wtforms-htmx-components 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,25 @@
1
+ """Ready-made interactive WTForms fields built on wtforms-htmx."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .combobox import ChipsWidget
6
+ from .combobox import ComboboxField
7
+ from .combobox import ComboboxMultiField
8
+ from .combobox import ComboboxSingleField
9
+ from .combobox import ComboboxWidget
10
+ from .combobox import ListboxWidget
11
+ from .combobox import QueryInputWidget
12
+ from .combobox import SingleChipWidget
13
+ from .validators import MaxItems
14
+
15
+ __all__ = [
16
+ "ChipsWidget",
17
+ "ComboboxField",
18
+ "ComboboxMultiField",
19
+ "ComboboxSingleField",
20
+ "ComboboxWidget",
21
+ "ListboxWidget",
22
+ "MaxItems",
23
+ "QueryInputWidget",
24
+ "SingleChipWidget",
25
+ ]
@@ -0,0 +1,756 @@
1
+ """Composite combobox fields.
2
+
3
+ Each combobox field is a FormField with its own inner form: a query
4
+ input, a search button, a suggestion listbox and a storage field. The
5
+ field's data is the stored value (single) or list (multi).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import functools
11
+ import itertools
12
+ from collections.abc import Callable
13
+ from collections.abc import Iterable
14
+ from types import SimpleNamespace
15
+ from typing import Any
16
+
17
+ from markupsafe import escape
18
+ from markupsafe import Markup
19
+ from wtforms import ButtonField
20
+ from wtforms import FormField
21
+ from wtforms import HiddenField
22
+ from wtforms import SelectChoice
23
+ from wtforms import SelectField
24
+ from wtforms import SelectMultipleField
25
+ from wtforms import StringField
26
+ from wtforms.utils import unset_value
27
+ from wtforms.validators import Disabled
28
+ from wtforms.validators import ReadOnly
29
+ from wtforms.validators import ValidationError
30
+ from wtforms.widgets import Button
31
+ from wtforms.widgets import html_params
32
+ from wtforms_htmx import HtmxForm
33
+ from wtforms_htmx.mutations import value_add
34
+ from wtforms_htmx.mutations import value_remove
35
+ from wtforms_htmx.mutations import value_set
36
+
37
+ from .validators import MaxItems
38
+
39
+
40
+ class QueryInputWidget:
41
+ """Render the search ``<input>`` with the ARIA combobox attributes.
42
+
43
+ ``aria-expanded`` is true when the listbox has choices. After a
44
+ click on a suggestion, the input gets ``autofocus``, so a no-JS page
45
+ reload puts the focus back on it.
46
+ """
47
+
48
+ def __call__(self, field: Any, **kwargs: Any) -> Markup:
49
+ listbox = field._form.suggestions
50
+ autofocus = kwargs.pop("autofocus", False) or bool(listbox.raw_data)
51
+ attrs: dict[str, Any] = {
52
+ "type": "text",
53
+ "name": field.name,
54
+ "id": field.id,
55
+ "value": field._value(),
56
+ "role": "combobox",
57
+ "aria-autocomplete": "list",
58
+ "aria-haspopup": "listbox",
59
+ "aria-controls": listbox.id,
60
+ "aria-expanded": "true" if listbox.choices else "false",
61
+ "autocomplete": "off",
62
+ }
63
+ if autofocus:
64
+ attrs["autofocus"] = True
65
+
66
+ attrs.update(kwargs)
67
+ return Markup(f"<input {html_params(**attrs)}>")
68
+
69
+
70
+ class ListboxWidget:
71
+ """Render the suggestions as a ``<ul role="listbox">``.
72
+
73
+ Each suggestion is a ``<li role="option">`` holding a submit button
74
+ rendered by the field's ``option_widget``. ``multi=True`` sets
75
+ ``aria-multiselectable="true"``. Override :meth:`render_option` to
76
+ change the markup of a suggestion.
77
+ """
78
+
79
+ def __init__(self, *, multi: bool = False) -> None:
80
+ self._multi = multi
81
+
82
+ def __call__(self, field: Any, **kwargs: Any) -> Markup:
83
+ attrs: dict[str, Any] = {"role": "listbox", "id": field.id}
84
+ if self._multi:
85
+ attrs["aria-multiselectable"] = "true"
86
+
87
+ attrs.update(kwargs)
88
+ items: list[str] = []
89
+ for opt in field:
90
+ button = functools.partial(opt, **opt._form.htmx_submit_attrs(opt))
91
+ items.append(self.render_option(opt, button))
92
+
93
+ return Markup(f"<ul {html_params(**attrs)}>{''.join(items)}</ul>")
94
+
95
+ def render_option(self, opt: Any, button: Callable[..., Markup]) -> str:
96
+ """Render one suggestion.
97
+
98
+ ``button`` renders the submit button that picks the suggestion.
99
+ It takes the button's ``label`` and HTML attributes.
100
+ """
101
+ li_attrs = html_params(role="option", data_value=opt.choice.value)
102
+ return f"<li {li_attrs}>{button(label=opt.choice.label)}</li>"
103
+
104
+
105
+ def _locked(field: Any) -> bool:
106
+ """Tell whether a storage field is read-only or disabled."""
107
+ return bool(field.flags.readonly or field.flags.disabled)
108
+
109
+
110
+ def _render_chip(
111
+ *,
112
+ name: str,
113
+ value: Any,
114
+ label: Any,
115
+ remove_button: Markup | str,
116
+ disabled: bool = False,
117
+ ) -> str:
118
+ """Render one chip: a label, a remove button and a hidden input."""
119
+ hidden = html_params(type="hidden", name=name, value=value, disabled=disabled)
120
+ return (
121
+ f"<span {html_params(data_value=value)}>"
122
+ f"<span>{escape(label)}</span>"
123
+ f"{remove_button}"
124
+ f"<input {hidden}>"
125
+ f"</span>"
126
+ )
127
+
128
+
129
+ def _default_remove_label(label: Any) -> str:
130
+ return f"Remove {label}"
131
+
132
+
133
+ class _ChipRenderer:
134
+ _remove_label: Callable[[Any], str]
135
+
136
+ def render_chip(self, field: Any, value: Any, label: Any, remove: Any) -> str:
137
+ """Render one chip.
138
+
139
+ ``remove`` is the button field that removes the value. Call it with
140
+ ``value`` and the button's ``label`` and HTML attributes. It is
141
+ ``None`` when the field is read-only or disabled.
142
+ """
143
+ button = (
144
+ ""
145
+ if remove is None
146
+ else remove(
147
+ value=value,
148
+ label="×",
149
+ id=False,
150
+ aria_label=self._remove_label(label),
151
+ )
152
+ )
153
+ return _render_chip(
154
+ name=field.name,
155
+ value=value,
156
+ label=label,
157
+ remove_button=button,
158
+ disabled=bool(field.flags.disabled),
159
+ )
160
+
161
+
162
+ class ChipsWidget(_ChipRenderer):
163
+ """Render the stored values of a multi combobox as chips.
164
+
165
+ Each chip has a label, a ``×`` remove button and a hidden input
166
+ that sends the value with the form. ``remove_label`` gives the
167
+ accessible name of the remove button from the chip's label. With the
168
+ ``readonly`` or ``disabled`` flag, the chips have no remove button,
169
+ and a disabled field does not send its values. Override
170
+ :meth:`render_chip` to change the markup of a chip.
171
+ """
172
+
173
+ def __init__(self, remove_label: Callable[[Any], str] | None = None) -> None:
174
+ self._remove_label = remove_label or _default_remove_label
175
+
176
+ def __call__(self, field: Any, **kwargs: Any) -> Markup:
177
+ attrs: dict[str, Any] = {"id": field.id}
178
+ attrs.update(kwargs)
179
+ remove = None if _locked(field) else field._form.remove
180
+ chips = [
181
+ self.render_chip(field, opt.data, opt.label.text, remove) for opt in field
182
+ ]
183
+ return Markup(f"<div {html_params(**attrs)}>{''.join(chips)}</div>")
184
+
185
+
186
+ class SingleChipWidget(_ChipRenderer):
187
+ """Render the value of a single combobox as one removable chip.
188
+
189
+ Without a value, it renders an empty hidden input. The chip's ``×``
190
+ clears the value. ``remove_label`` gives the accessible name of the
191
+ remove button from the chip's label. The library ships no CSS: hiding
192
+ the query input while a chip is shown is up to the application.
193
+ Override :meth:`render_chip` to change the markup of the chip.
194
+ """
195
+
196
+ def __init__(
197
+ self,
198
+ label_for: Callable[[Any], str],
199
+ remove_label: Callable[[Any], str] | None = None,
200
+ ) -> None:
201
+ self._label_for = label_for
202
+ self._remove_label = remove_label or _default_remove_label
203
+
204
+ def __call__(self, field: Any, **kwargs: Any) -> Markup:
205
+ attrs: dict[str, Any] = {"id": field.id}
206
+ attrs.update(kwargs)
207
+ if not field.data:
208
+ hidden = html_params(type="hidden", name=field.name, value="")
209
+ return Markup(f"<div {html_params(**attrs)}><input {hidden}></div>")
210
+
211
+ remove = None if _locked(field) else field._form.remove
212
+ chip = self.render_chip(field, field.data, self._label_for(field.data), remove)
213
+ return Markup(f"<div {html_params(**attrs)}>{chip}</div>")
214
+
215
+
216
+ class ComboboxWidget:
217
+ """Render the parts of a combobox in a ``<div>``.
218
+
219
+ The order is: the stored values, the query input, the search button
220
+ and the listbox. The chips of a multi combobox show before the query
221
+ input. Without ``search_label``, the search button is left out. A
222
+ read-only or disabled field renders its stored values only.
223
+ """
224
+
225
+ def __call__(self, field: Any, **kwargs: Any) -> Markup:
226
+ if field.flags.readonly or field.flags.disabled:
227
+ return Markup(f"<div {html_params(**kwargs)}>{field.value()}</div>")
228
+
229
+ search = field.search() if "search" in field.form else ""
230
+ return Markup(
231
+ f"<div {html_params(**kwargs)}>"
232
+ f"{field.value()}"
233
+ f"{field.query()}"
234
+ f"{search}"
235
+ f"{field.suggestions()}"
236
+ f"</div>"
237
+ )
238
+
239
+
240
+ def _pick_value(_form: Any, source: Any, target: Any) -> None:
241
+ """Write the source button's submitted value into the target."""
242
+ target.data = source.raw_data[0]
243
+
244
+
245
+ def _make_pick_label(label_for: Callable[[Any], str]) -> Callable[..., None]:
246
+ """Build a callback that writes the label of the source's value into the target."""
247
+
248
+ def _pick(_form: Any, source: Any, target: Any) -> None:
249
+ target.data = label_for(source.raw_data[0])
250
+
251
+ return _pick
252
+
253
+
254
+ def _make_single_choices(
255
+ suggest: Callable[[str, Any], Iterable[SelectChoice]],
256
+ label_for: Callable[[Any], str],
257
+ max_n: int,
258
+ close_on_match: bool,
259
+ allow_custom_value: bool,
260
+ custom_value_label: Callable[[str], str] | None,
261
+ ) -> Callable[..., list[SelectChoice]]:
262
+ """Build the choices callable of the single combobox suggestions.
263
+
264
+ No suggestions for an empty query, nor with close_on_match when the
265
+ query is the label of the stored value. With allow_custom_value, a
266
+ "create" choice for the raw query comes last.
267
+ """
268
+
269
+ def _choices(form: Any, _field: Any) -> list[SelectChoice]:
270
+ query = (form.query.data or "").strip()
271
+ if not query:
272
+ return []
273
+
274
+ if close_on_match and (value := form.value.data) and query == label_for(value):
275
+ return []
276
+
277
+ choices = list(itertools.islice(suggest(query, form._parent_form), max_n))
278
+ if allow_custom_value:
279
+ choices = _maybe_append_create(
280
+ choices, query, custom_value_label, extra_existing_labels=()
281
+ )
282
+
283
+ return choices
284
+
285
+ return _choices
286
+
287
+
288
+ def _make_multi_choices(
289
+ suggest: Callable[[str, Any], Iterable[SelectChoice]],
290
+ label_for: Callable[[Any], str],
291
+ max_n: int,
292
+ cap: int | None,
293
+ allow_custom_value: bool,
294
+ custom_value_label: Callable[[str], str] | None,
295
+ ) -> Callable[..., list[SelectChoice]]:
296
+ """Build the choices callable of the multi combobox suggestions.
297
+
298
+ Picked values are left out, and an empty query or a reached MaxItems
299
+ cap gives no suggestions. With allow_custom_value, a "create" choice
300
+ for the raw query comes last unless the query is already picked.
301
+ """
302
+
303
+ def _choices(form: Any, _field: Any) -> list[SelectChoice]:
304
+ query = (form.query.data or "").strip()
305
+ if not query:
306
+ return []
307
+
308
+ picked = list(form.value.data or [])
309
+ if cap is not None and len(picked) >= cap:
310
+ return []
311
+
312
+ gen = (c for c in suggest(query, form._parent_form) if c.value not in picked)
313
+ choices = list(itertools.islice(gen, max_n))
314
+ if allow_custom_value and query not in picked:
315
+ picked_labels = tuple(str(label_for(v)).lower() for v in picked)
316
+ choices = _maybe_append_create(
317
+ choices, query, custom_value_label, picked_labels
318
+ )
319
+
320
+ return choices
321
+
322
+ return _choices
323
+
324
+
325
+ def _maybe_append_create(
326
+ choices: list[SelectChoice],
327
+ query: str,
328
+ custom_value_label: Callable[[str], str] | None,
329
+ extra_existing_labels: tuple[str, ...],
330
+ ) -> list[SelectChoice]:
331
+ """Append a "create" choice for the query.
332
+
333
+ Skip it when the query matches the value or label of a choice, or one
334
+ of extra_existing_labels.
335
+ """
336
+ existing_values = {c.value for c in choices}
337
+ existing_labels = {str(c.label).lower() for c in choices}
338
+ if query in existing_values:
339
+ return choices
340
+
341
+ lower = query.lower()
342
+ if lower in existing_labels or lower in extra_existing_labels:
343
+ return choices
344
+
345
+ label = custom_value_label(query) if custom_value_label else query
346
+ return [*choices, SelectChoice(query, label)]
347
+
348
+
349
+ def _make_value_choices(
350
+ label_for: Callable[[Any], str],
351
+ ) -> Callable[..., list[SelectChoice]]:
352
+ """Build the choices callable of the chips: one choice per stored value."""
353
+
354
+ def _choices(_form: Any, field: Any) -> list[SelectChoice]:
355
+ return [SelectChoice(v, label_for(v)) for v in (field.data or [])]
356
+
357
+ return _choices
358
+
359
+
360
+ class ComboboxField(FormField):
361
+ """Base class of :class:`ComboboxSingleField` and :class:`ComboboxMultiField`.
362
+
363
+ Use it to recognize a combobox, for example in a field wrapper:
364
+ ``isinstance(field, ComboboxField)``.
365
+
366
+ :class:`~wtforms.validators.ReadOnly` and
367
+ :class:`~wtforms.validators.Disabled` work on the whole field: it
368
+ renders its stored values only, and the validation checks the stored
369
+ values, not the objects that ``coerce`` returns.
370
+ """
371
+
372
+ _storage_name: str = "value"
373
+
374
+ def _stored_values(self) -> list[str]:
375
+ return _values_list(self.form.value.data)
376
+
377
+ def _try_coerce(self, value: str) -> tuple[Any, bool]:
378
+ try:
379
+ return self._coerce(value), True
380
+ except (ValueError, TypeError):
381
+ return None, False
382
+
383
+ def process(
384
+ self,
385
+ formdata: Any,
386
+ data: Any = unset_value,
387
+ extra_filters: Any = None,
388
+ ) -> None:
389
+ # Resolve the default here so a scalar default gets wrapped too.
390
+ if data is unset_value:
391
+ try:
392
+ data = self.default()
393
+ except TypeError:
394
+ data = self.default
395
+
396
+ if isinstance(data, dict):
397
+ stored = data.get(self._storage_name)
398
+ elif data is not None:
399
+ stored = self._to_storage(data)
400
+ data = SimpleNamespace(**{self._storage_name: stored})
401
+ else:
402
+ stored = None
403
+
404
+ self._initial_values = _values_list(stored)
405
+ super().process(formdata, data, extra_filters)
406
+ # The storage widget reads the readonly and disabled flags, even when
407
+ # they are set on this field after construction.
408
+ getattr(self.form, self._storage_name).flags = self.flags
409
+
410
+ def populate_obj(self, obj: Any, name: str) -> None:
411
+ setattr(obj, name, self.data)
412
+
413
+ @property
414
+ def errors(self) -> list[str]:
415
+ return self._combobox_errors
416
+
417
+ def validate(self, form: Any, extra_validators: Iterable[Any] = ()) -> bool:
418
+ """Validate the inner form, then run the validators with the outer form."""
419
+ self._combobox_errors = []
420
+ valid = self.form.validate()
421
+ if not all(self._try_coerce(v)[1] for v in self._stored_values()):
422
+ self._combobox_errors.append(self.gettext("Not a valid choice."))
423
+
424
+ validators = itertools.chain(self.validators, extra_validators)
425
+ self._run_validation_chain(form, map(_composite_validator, validators))
426
+ return valid and not self._combobox_errors
427
+
428
+
429
+ def _values_list(stored: Any) -> list[str]:
430
+ """Return stored data as a list of values: one value, a list, or none."""
431
+ if not stored:
432
+ return []
433
+
434
+ if isinstance(stored, str):
435
+ return [stored]
436
+
437
+ return list(stored)
438
+
439
+
440
+ def _check_unchanged(_form: Any, field: ComboboxField) -> None:
441
+ if field._stored_values() != field._initial_values:
442
+ raise ValidationError(field.gettext("This field cannot be edited."))
443
+
444
+
445
+ def _check_not_posted(_form: Any, field: ComboboxField) -> None:
446
+ if getattr(field.form, field._storage_name).raw_data:
447
+ raise ValidationError(
448
+ field.gettext("This field is disabled and cannot have a value.")
449
+ )
450
+
451
+
452
+ def _composite_validator(validator: Any) -> Any:
453
+ """Replace ReadOnly and Disabled with checks on the stored values.
454
+
455
+ The originals compare ``data`` and ``object_data``, which a composite
456
+ field does not keep comparable.
457
+ """
458
+ if isinstance(validator, ReadOnly):
459
+ return _check_unchanged
460
+
461
+ if isinstance(validator, Disabled):
462
+ return _check_not_posted
463
+
464
+ return validator
465
+
466
+
467
+ class _InnerMeta:
468
+ """Meta of the inner forms: their fields have no validators to show inline.
469
+
470
+ The other htmx settings come from the form that holds the combobox.
471
+ """
472
+
473
+ htmx_inline_validation = False
474
+
475
+
476
+ def _query_render_kw(
477
+ placeholder: str | None, render_kw: dict[str, Any] | None
478
+ ) -> dict[str, Any] | None:
479
+ """Merge the placeholder into the query input's render_kw."""
480
+ if placeholder:
481
+ return {**(render_kw or {}), "placeholder": placeholder}
482
+
483
+ return render_kw
484
+
485
+
486
+ def _build_single_inner_form(
487
+ *,
488
+ choices_cb: Callable[..., list[SelectChoice]],
489
+ pick_label: Callable[..., None],
490
+ label_for: Callable[[Any], str],
491
+ placeholder: str | None,
492
+ search_label: str | None,
493
+ query_widget: Any,
494
+ listbox_widget: Any,
495
+ value_widget: Any,
496
+ query_render_kw: dict[str, Any] | None,
497
+ listbox_render_kw: dict[str, Any] | None,
498
+ value_render_kw: dict[str, Any] | None,
499
+ ) -> type[HtmxForm]:
500
+ """Construct the inner form class for a single combobox."""
501
+ query_render_kw = _query_render_kw(placeholder, query_render_kw)
502
+
503
+ attrs: dict[str, Any] = {
504
+ "query": StringField(render_kw=query_render_kw, widget=query_widget).triggers(
505
+ "suggestions"
506
+ ),
507
+ "suggestions": (
508
+ SelectField(
509
+ choices=choices_cb,
510
+ option_widget=Button(),
511
+ widget=listbox_widget,
512
+ validate_choice=False,
513
+ render_kw=listbox_render_kw,
514
+ )
515
+ .triggers("value", _pick_value)
516
+ .triggers("query", pick_label)
517
+ .triggers("suggestions")
518
+ ),
519
+ "value": HiddenField(widget=value_widget, render_kw=value_render_kw),
520
+ "remove": (
521
+ ButtonField("×")
522
+ .triggers("value", value_set(""))
523
+ .triggers("query", value_set(""))
524
+ .triggers("suggestions")
525
+ ),
526
+ }
527
+ if search_label is not None:
528
+ attrs["search"] = ButtonField(search_label).triggers("suggestions")
529
+
530
+ def post_process(self: Any, formdata: Any = None) -> None:
531
+ # Seed the query before the choices callables run again.
532
+ if not self.query.data and self.value.data:
533
+ self.query.data = label_for(self.value.data)
534
+
535
+ HtmxForm.post_process(self, formdata)
536
+
537
+ attrs["post_process"] = post_process
538
+
539
+ attrs["Meta"] = _InnerMeta
540
+ return type("_ComboboxSingleInnerForm", (HtmxForm,), attrs)
541
+
542
+
543
+ class ComboboxSingleField(ComboboxField):
544
+ """Single-value combobox.
545
+
546
+ Typing in the query input refreshes the suggestions. Clicking a
547
+ suggestion stores its value and shows its label. ``.data`` is the
548
+ stored value, for example ``"FR"``, or what ``coerce`` makes of it.
549
+ The validators get the form that holds the field, and their errors
550
+ show on the field.
551
+
552
+ See :doc:`/how-to/combobox` for the constructor parameters.
553
+ """
554
+
555
+ _storage_name = "value"
556
+
557
+ def _to_storage(self, data: Any) -> Any:
558
+ return self._value_for(data)
559
+
560
+ @property
561
+ def data(self) -> Any:
562
+ raw = self.form.value.data
563
+ if not raw:
564
+ return raw
565
+
566
+ return self._try_coerce(raw)[0]
567
+
568
+ def __init__(
569
+ self,
570
+ label: str | None = None,
571
+ *,
572
+ suggest: Callable[[str, Any], Iterable[SelectChoice]],
573
+ label_for: Callable[[Any], str] = str,
574
+ coerce: Callable[[str], Any] = str,
575
+ value_for: Callable[[Any], str] = str,
576
+ validators: list | None = None,
577
+ placeholder: str | None = None,
578
+ search_label: str | None = "Search",
579
+ max_suggestions: int = 10,
580
+ close_listbox_on_match: bool = True,
581
+ allow_custom_value: bool = False,
582
+ custom_value_label: Callable[[str], str] | None = None,
583
+ remove_label: Callable[[Any], str] | None = None,
584
+ query_widget: Any = None,
585
+ listbox_widget: Any = None,
586
+ value_widget: Any = None,
587
+ widget: Any = None,
588
+ query_render_kw: dict[str, Any] | None = None,
589
+ listbox_render_kw: dict[str, Any] | None = None,
590
+ value_render_kw: dict[str, Any] | None = None,
591
+ **kwargs: Any,
592
+ ) -> None:
593
+ inner_form_class = _build_single_inner_form(
594
+ choices_cb=_make_single_choices(
595
+ suggest,
596
+ label_for,
597
+ max_suggestions,
598
+ close_listbox_on_match,
599
+ allow_custom_value,
600
+ custom_value_label,
601
+ ),
602
+ pick_label=_make_pick_label(label_for),
603
+ label_for=label_for,
604
+ placeholder=placeholder,
605
+ search_label=search_label,
606
+ query_widget=query_widget or QueryInputWidget(),
607
+ listbox_widget=listbox_widget or ListboxWidget(),
608
+ value_widget=value_widget
609
+ or SingleChipWidget(label_for=label_for, remove_label=remove_label),
610
+ query_render_kw=query_render_kw,
611
+ listbox_render_kw=listbox_render_kw,
612
+ value_render_kw=value_render_kw,
613
+ )
614
+ super().__init__(inner_form_class, label=label, **kwargs)
615
+ self.validators = list(validators or [])
616
+ for validator in self.validators:
617
+ for flag, value in getattr(validator, "field_flags", {}).items():
618
+ setattr(self.flags, flag, value)
619
+
620
+ self._combobox_errors: list[str] = []
621
+ self._coerce = coerce
622
+ self._value_for = value_for
623
+ self._label_for = label_for
624
+ self.widget = widget or ComboboxWidget()
625
+
626
+
627
+ def _build_multi_inner_form(
628
+ *,
629
+ choices_cb: Callable[..., list[SelectChoice]],
630
+ value_choices_cb: Callable[..., list[SelectChoice]],
631
+ placeholder: str | None,
632
+ search_label: str | None,
633
+ query_widget: Any,
634
+ listbox_widget: Any,
635
+ chips_widget: Any,
636
+ query_render_kw: dict[str, Any] | None,
637
+ listbox_render_kw: dict[str, Any] | None,
638
+ chips_render_kw: dict[str, Any] | None,
639
+ ) -> type[HtmxForm]:
640
+ """Construct the inner form class for a multi combobox."""
641
+ query_render_kw = _query_render_kw(placeholder, query_render_kw)
642
+
643
+ attrs: dict[str, Any] = {
644
+ "query": StringField(render_kw=query_render_kw, widget=query_widget).triggers(
645
+ "suggestions"
646
+ ),
647
+ "value": SelectMultipleField(
648
+ choices=value_choices_cb,
649
+ widget=chips_widget,
650
+ validate_choice=False,
651
+ render_kw=chips_render_kw,
652
+ ),
653
+ "suggestions": (
654
+ SelectField(
655
+ choices=choices_cb,
656
+ option_widget=Button(),
657
+ widget=listbox_widget,
658
+ validate_choice=False,
659
+ render_kw=listbox_render_kw,
660
+ )
661
+ .triggers("value", value_add)
662
+ .triggers("query", value_set(""))
663
+ .triggers("suggestions")
664
+ ),
665
+ "remove": ButtonField("×").triggers("value", value_remove),
666
+ }
667
+ if search_label is not None:
668
+ attrs["search"] = ButtonField(search_label).triggers("suggestions")
669
+
670
+ attrs["Meta"] = _InnerMeta
671
+ return type("_ComboboxMultiInnerForm", (HtmxForm,), attrs)
672
+
673
+
674
+ class ComboboxMultiField(ComboboxField):
675
+ """Multi-value combobox.
676
+
677
+ Clicking a suggestion adds a chip, and a chip's ``×`` removes it.
678
+ Picked values are left out of the suggestions. ``.data`` is a list,
679
+ for example ``["FR", "JP"]``, or what ``coerce`` makes of each value.
680
+ The validators get the form that holds the field, and their errors
681
+ show on the field.
682
+
683
+ See :doc:`/how-to/combobox` for the constructor parameters.
684
+ """
685
+
686
+ _storage_name = "value"
687
+
688
+ def _to_storage(self, data: Any) -> Any:
689
+ if isinstance(data, str):
690
+ data = [data]
691
+
692
+ return [self._value_for(item) for item in data]
693
+
694
+ @property
695
+ def data(self) -> Any:
696
+ raw = self.form.value.data
697
+ if not raw:
698
+ return raw
699
+
700
+ coerced = (self._try_coerce(value) for value in raw)
701
+ return [item for item, ok in coerced if ok]
702
+
703
+ def __init__(
704
+ self,
705
+ label: str | None = None,
706
+ *,
707
+ suggest: Callable[[str, Any], Iterable[SelectChoice]],
708
+ label_for: Callable[[Any], str] = str,
709
+ coerce: Callable[[str], Any] = str,
710
+ value_for: Callable[[Any], str] = str,
711
+ validators: list | None = None,
712
+ placeholder: str | None = None,
713
+ search_label: str | None = "Search",
714
+ max_suggestions: int = 10,
715
+ allow_custom_value: bool = False,
716
+ custom_value_label: Callable[[str], str] | None = None,
717
+ remove_label: Callable[[Any], str] | None = None,
718
+ query_widget: Any = None,
719
+ listbox_widget: Any = None,
720
+ chips_widget: Any = None,
721
+ widget: Any = None,
722
+ query_render_kw: dict[str, Any] | None = None,
723
+ listbox_render_kw: dict[str, Any] | None = None,
724
+ chips_render_kw: dict[str, Any] | None = None,
725
+ **kwargs: Any,
726
+ ) -> None:
727
+ inner_form_class = _build_multi_inner_form(
728
+ choices_cb=_make_multi_choices(
729
+ suggest,
730
+ label_for,
731
+ max_suggestions,
732
+ MaxItems.tightest_cap(validators),
733
+ allow_custom_value,
734
+ custom_value_label,
735
+ ),
736
+ value_choices_cb=_make_value_choices(label_for),
737
+ placeholder=placeholder,
738
+ search_label=search_label,
739
+ query_widget=query_widget or QueryInputWidget(),
740
+ listbox_widget=listbox_widget or ListboxWidget(multi=True),
741
+ chips_widget=chips_widget or ChipsWidget(remove_label=remove_label),
742
+ query_render_kw=query_render_kw,
743
+ listbox_render_kw=listbox_render_kw,
744
+ chips_render_kw=chips_render_kw,
745
+ )
746
+ super().__init__(inner_form_class, label=label, **kwargs)
747
+ self.validators = list(validators or [])
748
+ for validator in self.validators:
749
+ for flag, value in getattr(validator, "field_flags", {}).items():
750
+ setattr(self.flags, flag, value)
751
+
752
+ self._combobox_errors: list[str] = []
753
+ self._coerce = coerce
754
+ self._value_for = value_for
755
+ self._label_for = label_for
756
+ self.widget = widget or ComboboxWidget()
File without changes
@@ -0,0 +1,54 @@
1
+ """Validators for list fields."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterable
6
+ from typing import Any
7
+
8
+ from wtforms.validators import ValidationError
9
+
10
+
11
+ class MaxItems:
12
+ """Check that a list field has at most ``max`` items.
13
+
14
+ Works with any field whose data supports :func:`len`, such as
15
+ :class:`~wtforms.fields.SelectMultipleField` or
16
+ :class:`~wtforms.fields.FieldList`. Empty data passes: add
17
+ :class:`~wtforms.validators.DataRequired` to require a value.
18
+ ``message`` can use the ``%(max)d`` placeholder. The default message
19
+ goes through the translations of the form.
20
+
21
+ :class:`~wtforms_htmx_components.ComboboxMultiField` also reads this
22
+ validator and shows no more suggestions once the cap is reached.
23
+ """
24
+
25
+ def __init__(self, max: int, message: str | None = None) -> None:
26
+ if max < 0:
27
+ raise ValueError("MaxItems(max=…) must be non-negative")
28
+
29
+ self.max = max
30
+ self.message = message
31
+
32
+ def __call__(self, form: Any, field: Any) -> None:
33
+ data = field.data
34
+ if not data:
35
+ return
36
+
37
+ if len(data) <= self.max:
38
+ return
39
+
40
+ message = self.message
41
+ if message is None:
42
+ message = field.ngettext(
43
+ "Pick at most %(max)d item.", "Pick at most %(max)d items.", self.max
44
+ )
45
+
46
+ message = message % {"max": self.max}
47
+
48
+ raise ValidationError(message)
49
+
50
+ @classmethod
51
+ def tightest_cap(cls, validators: Iterable[Any] | None) -> int | None:
52
+ """Return the smallest ``max`` across all ``MaxItems`` in ``validators``, or ``None``."""
53
+ caps = [v.max for v in validators or [] if isinstance(v, cls)]
54
+ return min(caps) if caps else None
@@ -0,0 +1,83 @@
1
+ Metadata-Version: 2.4
2
+ Name: wtforms-htmx-components
3
+ Version: 0.1.0
4
+ Summary: Ready-made interactive WTForms fields built on wtforms-htmx.
5
+ Keywords: wtforms,htmx,forms,validation,combobox
6
+ License-Expression: BSD-3-Clause
7
+ License-File: LICENSE.rst
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Environment :: Web Environment
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Classifier: Programming Language :: Python :: 3.15
19
+ Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
20
+ Requires-Dist: wtforms>=3.3.0,<4
21
+ Requires-Dist: wtforms-htmx>=0.1.0
22
+ Maintainer: Éloi Rivard
23
+ Maintainer-email: Éloi Rivard <eloi@yaal.coop>
24
+ Requires-Python: >=3.11
25
+ Project-URL: Documentation, https://wtforms-htmx-components.readthedocs.io/
26
+ Project-URL: Changes, https://wtforms-htmx-components.readthedocs.io/changes/
27
+ Project-URL: Source Code, https://github.com/yaal-coop/wtforms-htmx-components
28
+ Project-URL: Issue Tracker, https://github.com/yaal-coop/wtforms-htmx-components/issues
29
+ Description-Content-Type: text/markdown
30
+
31
+ # wtforms-htmx-components
32
+
33
+ Ready-made interactive [WTForms](https://wtforms.readthedocs.io/) fields
34
+ built on [wtforms-htmx](https://github.com/yaal-coop/wtforms-htmx).
35
+
36
+ **Status: alpha, work in progress.**
37
+
38
+ Each field packages a recipe of several triggers (typing, suggestions,
39
+ pick, store, chip) into a single `FormField` declaration. Available now:
40
+ the combobox, single and multi value, strict or with free-form values.
41
+
42
+ ## Installation
43
+
44
+ ```sh
45
+ pip install wtforms-htmx-components
46
+ ```
47
+
48
+ ## Example
49
+
50
+ ```python
51
+ from wtforms import SelectChoice
52
+ from wtforms import SubmitField
53
+ from wtforms_htmx import HtmxForm
54
+ from wtforms_htmx_components import ComboboxMultiField
55
+
56
+
57
+ def suggest(query, form):
58
+ q = query.lower()
59
+ return [SelectChoice(tag, tag) for tag in CATALOG if q in tag.lower()]
60
+
61
+
62
+ class TagsForm(HtmxForm):
63
+ tags = ComboboxMultiField("Tags", suggest=suggest)
64
+ save = SubmitField()
65
+ ```
66
+
67
+ Run the example app:
68
+
69
+ ```sh
70
+ uv sync --group example
71
+ uv run python -m examples
72
+ ```
73
+
74
+ Then open <http://127.0.0.1:5000/>.
75
+
76
+ ## Links
77
+
78
+ - Source: <https://github.com/yaal-coop/wtforms-htmx-components>
79
+ - Issues: <https://github.com/yaal-coop/wtforms-htmx-components/issues>
80
+
81
+ ## License
82
+
83
+ BSD-3-Clause. See `LICENSE.rst`.
@@ -0,0 +1,8 @@
1
+ wtforms_htmx_components/__init__.py,sha256=XWULxDxe7NUeu3RNCbFsDZ7852jjlD2E-kwc38JDcZI,656
2
+ wtforms_htmx_components/combobox.py,sha256=cmVboRa0hT9WPFCrYn4VfVOuiPdlK3Hwqlr3EG2bqHI,26106
3
+ wtforms_htmx_components/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ wtforms_htmx_components/validators.py,sha256=pMv19rcy9n8uc3QrUiY8pTplNJfq1iQq5RZDov_KScQ,1757
5
+ wtforms_htmx_components-0.1.0.dist-info/licenses/LICENSE.rst,sha256=_H3YS-sMh9nVxo79jXhnJ4h6vhp8Gzo6q4q-0SZhk7w,1475
6
+ wtforms_htmx_components-0.1.0.dist-info/WHEEL,sha256=1dD_GoEqEIxQ7VnrUExgdj_eExY4b4UgfR0iBlGKVac,80
7
+ wtforms_htmx_components-0.1.0.dist-info/METADATA,sha256=3BEvqozWhrclBiXh6dZkOmpKyfaWaxyJ8DFI47PAe74,2571
8
+ wtforms_htmx_components-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,28 @@
1
+ Copyright 2026 WTForms
2
+
3
+ Redistribution and use in source and binary forms, with or without
4
+ modification, are permitted provided that the following conditions are
5
+ met:
6
+
7
+ 1. Redistributions of source code must retain the above copyright
8
+ notice, this list of conditions and the following disclaimer.
9
+
10
+ 2. Redistributions in binary form must reproduce the above copyright
11
+ notice, this list of conditions and the following disclaimer in the
12
+ documentation and/or other materials provided with the distribution.
13
+
14
+ 3. Neither the name of the copyright holder nor the names of its
15
+ contributors may be used to endorse or promote products derived from
16
+ this software without specific prior written permission.
17
+
18
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
21
+ PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22
+ HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
24
+ TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
25
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
26
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
27
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.