Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Detala serĉilo: nova interfaco por gastigo-kondiĉoj #314

Merged
merged 4 commits into from
Aug 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions core/static/js/forms.js
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,26 @@ $(function() {
$('#id_test_email').closest('.form-group').toggle($(this).val() === "test");
}).change();

/* dynamic (collapsible) form area management */
$('[id$="_form_element"].collapse').each(function() {
var $switch = $('[aria-controls='+this.id+']');
var toggler = function(state) {
$switch.attr('aria-expanded', state).children('.fa').each(function() {
var $this = $(this);
var label = $this.attr('aria-label');
$this.attr('aria-label', $this.data('aria-label-inactive'))
.data('aria-label-inactive', label);
if (state)
$this.addClass('fa-rotate-90');
else
$this.removeClass('fa-rotate-90');
window.setTimeout(function() { $this.parent().removeClass('initial'); }, 100);
});
};
$(this).on('show.bs.collapse hide.bs.collapse',
function(event) { toggler(event.type == 'show') });
});

/* form cancel button enhancement */
$('#id_form_cancel').each(function() {
this.setAttribute('data-default-href', this.getAttribute('href'));
Expand Down
5 changes: 3 additions & 2 deletions core/static/js/scripts.js
Original file line number Diff line number Diff line change
Expand Up @@ -523,11 +523,12 @@ function enableTooltips() {
function realignTooltip(tip, elem) {
var placement = getComputedStyle(elem).getPropertyValue('--tooltip-placement').trim()
|| elem.getAttribute('data-placement') || 'top';
var alt_placement = elem.getAttribute('data-alt-placement') == 'top' ? 'top' : 'bottom';
if (placement == 'left' && elem.getBoundingClientRect().left < 85) {
return 'bottom';
return alt_placement;
}
if (placement == 'right' && elem.getBoundingClientRect().right > window.outerWidth - 85) {
return 'bottom';
return alt_placement;
}
return placement;
}
Expand Down
69 changes: 64 additions & 5 deletions core/static/sass/_all.scss
Original file line number Diff line number Diff line change
Expand Up @@ -424,7 +424,7 @@ header:not(.hero) #subtitle {
box-shadow: 0px 1px 5px 0px darken($color-default-bg, 12%);
border-top: 0;

.form-group:first-of-type {
.form-group:not([id*="option_1"]):first-of-type {
margin-top: 15px;
}
}
Expand Down Expand Up @@ -1243,10 +1243,51 @@ p.tip {
width: 100%;
background-color: $color-gray-light;
}
#id_facilitations_form_element, #id_restrictions_form_element {
.checkbox-inline {
margin-left: 0px;
margin-right: 10px;
.divider-heading {
overflow: hidden;
text-align: center;
color: lighten($color-text, 15%);

&::before, &::after {
content: "";
display: inline-block;
position: relative;
vertical-align: middle;
width: 50%;
height: 3px;
border-top: 1px #ccc solid;
border-bottom: 1px #eee solid;
}
&.has-content {
&::before {
right: 1em;
margin-left: -50%;
}
&::after {
left: 1em;
margin-right: -50%;
}
&.as-label {
font-weight: 700;
color: $color-text;
}
}
}
.switch.btn-sm ~ .divider-heading {
padding-top: 4px;
width: calc(100% - 50px);
float: right;
}
.switch.btn-xs ~ .divider-heading {
padding-top: 2px;
width: calc(100% - 40px);
float: right;
}
.form-divider {
margin-bottom: 15px;

.switch:not(.initial) .fa {
transition: all 0.3s ease-in;
}
}

Expand Down Expand Up @@ -1304,6 +1345,14 @@ textarea {
min-height: 34px;
}
}
input[type="checkbox"], input[type="radio"] {
~ .select-marker {
display: none;
}
&:checked ~ .select-marker {
display: inline-block !important;
}
}

:invalid {
box-shadow: none;
Expand Down Expand Up @@ -1480,6 +1529,16 @@ textarea {
max-width: 60%;
}
}
.form-horizontal .form-divider-sm {
font-size: 12px;

.switch.btn-sm ~ .divider-heading {
padding-top: 6px;
}
.switch.btn-xs ~ .divider-heading {
padding-top: 3px;
}
}
}
/* MD */
@media (min-width: #{$BOOTSTRAP-MD}) {
Expand Down
3 changes: 3 additions & 0 deletions core/static/sass/_bootstrap_fixes.scss
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,9 @@ blockquote .table.small:before {
margin-top: 1px;
}
}
.input-group-addon {
font-size: 12px;
}
}
}
/* MD */
Expand Down
42 changes: 41 additions & 1 deletion hosting/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
PhoneNumberField as DjangoPhoneNumberField,
)

from .widgets import TextWithDatalistInput
from .widgets import MultiNullBooleanSelects, TextWithDatalistInput


class StyledEmailField(models.EmailField):
Expand Down Expand Up @@ -226,3 +226,43 @@ def to_python(self, value):
defaults = {'form_class': SuggestiveModelChoiceFormField}
defaults.update(kwargs)
return super().formfield(**defaults)


class MultiNullBooleanFormField(forms.MultiValueField):
widget = MultiNullBooleanSelects

def __init__(
self, base_field, boolean_choices, *args,
label_prefix=lambda choice: None, **kwargs,
):
self.choices = list(base_field.choices)
if isinstance(base_field.choices, forms.models.ModelChoiceIterator):
self._single_choice_value = lambda choice: choice.value
else:
self._single_choice_value = lambda choice: choice
field_labels = {
self._single_choice_value(choice_value):
(choice_label, label_prefix(choice_value))
for choice_value, choice_label in self.choices
}
fields = [
forms.NullBooleanField(label=choice_label, required=False)
for _, choice_label in self.choices
]
super().__init__(
fields,
*args,
required=base_field.required,
require_all_fields=False,
widget=self.widget(field_labels, boolean_choices),
**kwargs)
self.empty_values = list(v for v in self.empty_values if v is not None)

def compress(self, data_list):
if not data_list:
data_list = [None] * len(self.choices)
# Each value of the data_list corresponds to a field.
return zip(
[self._single_choice_value(choice_value) for choice_value, _ in self.choices],
data_list
)
68 changes: 56 additions & 12 deletions hosting/filters/search.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
from django import forms
from django.db import models
from django.utils.translation import pgettext_lazy

import django_filters as filters

from ..fields import MultiNullBooleanFormField
from ..forms import SearchForm
from ..models import Condition, Place

Expand Down Expand Up @@ -39,6 +41,46 @@ def filter(self, qs, value):
return super().filter(qs, [tuple(value)])


class ModelMultipleChoiceIncludeExcludeFilter(filters.ModelMultipleChoiceFilter):
def __init__(self, boolean_choices, *args, label_prefix=lambda choice: None, **kwargs):
super().__init__(*args, **kwargs)
self.field_boolean_choices = boolean_choices
self.option_label_prefix = label_prefix

@property
def field(self):
if not hasattr(self, '_field'):
base_field = super().field

self._field = MultiNullBooleanFormField(
base_field=base_field,
label=base_field.label,
label_prefix=self.option_label_prefix,
boolean_choices=self.field_boolean_choices,
)

return self._field

def filter(self, qs, value):
value = list(value)
include = tuple(choice_value for choice_value, decision in value if decision is True)
exclude = tuple(choice_value for choice_value, decision in value if decision is False)
base_lookup_expr = self.lookup_expr

self.exclude = True
self.conjoined = False
self.lookup_expr = 'in'
if exclude:
qs = super().filter(qs, [exclude])
self.exclude = False
self.conjoined = True
self.lookup_expr = base_lookup_expr
if include:
qs = super().filter(qs, include)

return qs


class SearchFilterSet(filters.FilterSet):
class Meta:
model = Place
Expand Down Expand Up @@ -80,20 +122,22 @@ class Meta:
},
}

# Include only hosts who offer specific facilitations...
facilitations = filters.ModelMultipleChoiceFilter(
field_name='conditions',
conjoined=True,
queryset=(
Condition.objects.filter(restriction=False).order_by(Condition.active_name_field())
))

# Exclude hosts who indicated specific restrictions...
restrictions = ModelMultipleChoiceExcludeFilter(
conditions = ModelMultipleChoiceIncludeExcludeFilter(
field_name='conditions',
queryset=(
Condition.objects.filter(restriction=True).order_by(Condition.active_name_field())
))
Condition.objects.order_by('restriction', Condition.active_name_field())
),
boolean_choices=(
('false', pgettext_lazy("Imperative", "exclude")),
('unknown', pgettext_lazy("Imperative", "not important")),
('true', pgettext_lazy("Imperative", "include")),
),
label_prefix=lambda choice: (
pgettext_lazy("Condition type", "Restriction")
if choice.instance.restriction
else pgettext_lazy("Condition type", "Facilitation")
),
)

def __init__(self, data=None, *args, **kwargs):
if data is None:
Expand Down
28 changes: 20 additions & 8 deletions hosting/forms/listing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@
from django.utils.text import format_lazy
from django.utils.translation import gettext_lazy as _

from crispy_forms.bootstrap import InlineCheckboxes, PrependedText
from crispy_forms.bootstrap import PrependedText
from crispy_forms.helper import FormHelper

from ..widgets import ExpandedMultipleChoice, FormDivider


class SearchForm(forms.Form):

Expand All @@ -25,32 +27,42 @@ def __init__(self, *args, **kwargs):
self.helper['max_guest'].wrap(
PrependedText,
format_lazy('<span class="addon-fw-3">{text}</span>', text=_("guests")),
wrapper_class='form-group-sm')
wrapper_class=self.helper.wrapper_class)
self.fields['max_night'].widget.attrs['min'] = 0
self.fields['max_night'].label = (
format_lazy('<span class="sr-only">{text}</span>', text=_("At least this many"))
)
self.helper['max_night'].wrap(
PrependedText,
format_lazy('<span class="addon-fw-3">{text}</span>', text=_("nights")),
wrapper_class='form-group-sm')
wrapper_class=self.helper.wrapper_class)
self.fields['contact_before'].widget.attrs['min'] = 1
self.fields['contact_before'].label = _("Available within")
self.helper['contact_before'].wrap(
PrependedText,
format_lazy('<span class="addon-fw-3">{text}</span>', text=_("days")),
wrapper_class='form-group-sm')
wrapper_class=self.helper.wrapper_class)

self.fields['available'].initial = True
self.fields['available'].label = _("Place to sleep")
for bool_field in ('available', 'tour_guide', 'have_a_drink'):
self.fields[bool_field].extra_label = self.fields[bool_field].label
self.fields[bool_field].label = _("Yes")

self.fields['facilitations'].label = _("Show hosts with such facilitation")
self.helper['facilitations'].wrap(InlineCheckboxes, wrapper_class='form-group-sm')
self.fields['restrictions'].label = _("Don't show hosts with such restriction")
self.helper['restrictions'].wrap(InlineCheckboxes, wrapper_class='form-group-sm')
self.helper.layout.insert(
self.helper.layout.fields.index('conditions'),
FormDivider(
title=self.fields['conditions'].label,
collapse_field_name='conditions',
collapsed=True,
wrapper_class="form-divider-sm",
)
)
self.helper['conditions'].wrap(
ExpandedMultipleChoice,
wrapper_class=self.helper.wrapper_class,
collapsed=True,
option_hover_css_classes={'true': "btn-success", 'false': "btn-danger"})

def clean(self):
cleaned_data = super().clean()
Expand Down
11 changes: 7 additions & 4 deletions hosting/forms/places.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from core.auth import AuthRole
from core.models import SiteConfiguration
from core.utils import join_lazy, mark_safe_lazy, sort_by
from hosting.widgets import FormDivider
from maps import SRID
from maps.widgets import MapboxGlWidget

Expand Down Expand Up @@ -85,7 +86,7 @@ def __init__(self, *args, **kwargs):
self.helper = FormHelper(self)
self.fields['state_province'].widget.attrs['autocomplete'] = 'region'
# Combine the postcode and the city fields together in one line.
postcode_field_index = self._meta.fields.index('postcode')
postcode_field_index = self.helper.layout.fields.index('postcode')
self.helper[postcode_field_index:postcode_field_index+2].wrap_together(Div, css_class='row')
self.helper['postcode'].wrap(Field, wrapper_class='col-xxs-12 col-xs-4')
self.helper['city'].wrap(Field, wrapper_class='col-xxs-12 col-xs-8')
Expand All @@ -94,9 +95,11 @@ def __init__(self, *args, **kwargs):
# Bigger input area for the address by default.
self.fields['address'].widget.attrs['rows'] = 2
self.fields['address'].widget.attrs['autocomplete'] = 'street-address'
# Combine the count fields together in one line (index is shifted because of postcode+city layout change).
max_guests_field_index = self._meta.fields.index('max_guest')
self.helper[max_guests_field_index-1:max_guests_field_index+2].wrap_together(Div, css_class='row')
# Split address details from the description and conditions.
self.helper.layout.insert(self.helper.layout.fields.index('max_guest'), FormDivider())
# Combine the count fields together in one line.
max_guests_field_index = self.helper.layout.fields.index('max_guest')
self.helper[max_guests_field_index:max_guests_field_index+3].wrap_together(Div, css_class='row')
for field, field_icon in {'max_guest': 'fa-street-view', 'max_night': 'fa-regular fa-moon'}.items():
self.helper[field].wrap(
PrependedText,
Expand Down
2 changes: 1 addition & 1 deletion hosting/migrations/0066_hosting_conditions.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ class Migration(migrations.Migration):
migrations.AddField(
model_name='condition',
name='restriction',
field=models.BooleanField(default=True, help_text='Marked = limitation for the guests, unmarked = facilitation for the guests.', verbose_name='is a limitation'),
field=models.BooleanField(default=True, help_text='Marked = restriction for the guests, unmarked = facilitation for the guests.', verbose_name='is a limitation'),
),

migrations.RunPython(update_existing_conditions, revert_existing_conditions),
Expand Down
Loading