@poadio/ui-elements 0.1.0 → 0.2.0

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.
Files changed (103) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +32 -0
  3. package/dist/accordion.d.ts +31 -0
  4. package/dist/accordion.d.ts.map +1 -0
  5. package/dist/accordion.js +67 -0
  6. package/dist/accordion.js.map +1 -0
  7. package/dist/combo.d.ts +88 -0
  8. package/dist/combo.d.ts.map +1 -0
  9. package/dist/combo.js +238 -0
  10. package/dist/combo.js.map +1 -0
  11. package/dist/confirm.d.ts +35 -0
  12. package/dist/confirm.d.ts.map +1 -0
  13. package/dist/confirm.js +94 -0
  14. package/dist/confirm.js.map +1 -0
  15. package/dist/datepicker.d.ts +146 -0
  16. package/dist/datepicker.d.ts.map +1 -0
  17. package/dist/datepicker.js +468 -0
  18. package/dist/datepicker.js.map +1 -0
  19. package/dist/declaration.d.ts +25 -0
  20. package/dist/declaration.d.ts.map +1 -0
  21. package/dist/declaration.js +35 -0
  22. package/dist/declaration.js.map +1 -0
  23. package/dist/dialog.d.ts +137 -0
  24. package/dist/dialog.d.ts.map +1 -0
  25. package/dist/dialog.js +174 -0
  26. package/dist/dialog.js.map +1 -0
  27. package/dist/element.d.ts +4 -0
  28. package/dist/element.d.ts.map +1 -1
  29. package/dist/element.js +5 -2
  30. package/dist/element.js.map +1 -1
  31. package/dist/index.d.ts +35 -2
  32. package/dist/index.d.ts.map +1 -1
  33. package/dist/index.js +20 -1
  34. package/dist/index.js.map +1 -1
  35. package/dist/menu.d.ts +121 -0
  36. package/dist/menu.d.ts.map +1 -0
  37. package/dist/menu.js +245 -0
  38. package/dist/menu.js.map +1 -0
  39. package/dist/meter.d.ts +1 -0
  40. package/dist/meter.d.ts.map +1 -1
  41. package/dist/meter.js +1 -2
  42. package/dist/meter.js.map +1 -1
  43. package/dist/multiselect.d.ts +133 -0
  44. package/dist/multiselect.d.ts.map +1 -0
  45. package/dist/multiselect.js +230 -0
  46. package/dist/multiselect.js.map +1 -0
  47. package/dist/option-list.d.ts +28 -0
  48. package/dist/option-list.d.ts.map +1 -0
  49. package/dist/option-list.js +31 -0
  50. package/dist/option-list.js.map +1 -0
  51. package/dist/segmented.d.ts +1 -0
  52. package/dist/segmented.d.ts.map +1 -1
  53. package/dist/segmented.js +1 -2
  54. package/dist/segmented.js.map +1 -1
  55. package/dist/select.d.ts +3 -6
  56. package/dist/select.d.ts.map +1 -1
  57. package/dist/select.js +8 -24
  58. package/dist/select.js.map +1 -1
  59. package/dist/services.d.ts +3 -0
  60. package/dist/services.d.ts.map +1 -0
  61. package/dist/services.js +10 -0
  62. package/dist/services.js.map +1 -0
  63. package/dist/slider.d.ts +1 -0
  64. package/dist/slider.d.ts.map +1 -1
  65. package/dist/slider.js +1 -2
  66. package/dist/slider.js.map +1 -1
  67. package/dist/split-button.d.ts +47 -0
  68. package/dist/split-button.d.ts.map +1 -0
  69. package/dist/split-button.js +64 -0
  70. package/dist/split-button.js.map +1 -0
  71. package/dist/stepper.d.ts +56 -0
  72. package/dist/stepper.d.ts.map +1 -0
  73. package/dist/stepper.js +69 -0
  74. package/dist/stepper.js.map +1 -0
  75. package/dist/tabs.d.ts +62 -0
  76. package/dist/tabs.d.ts.map +1 -0
  77. package/dist/tabs.js +118 -0
  78. package/dist/tabs.js.map +1 -0
  79. package/dist/toast.d.ts +79 -0
  80. package/dist/toast.d.ts.map +1 -0
  81. package/dist/toast.js +176 -0
  82. package/dist/toast.js.map +1 -0
  83. package/package.json +3 -3
  84. package/src/accordion.ts +80 -0
  85. package/src/combo.ts +220 -0
  86. package/src/confirm.ts +106 -0
  87. package/src/datepicker.ts +413 -0
  88. package/src/declaration.ts +37 -0
  89. package/src/dialog.ts +217 -0
  90. package/src/element.ts +7 -2
  91. package/src/index.ts +29 -2
  92. package/src/menu.ts +281 -0
  93. package/src/meter.ts +2 -1
  94. package/src/multiselect.ts +273 -0
  95. package/src/option-list.ts +51 -0
  96. package/src/segmented.ts +2 -1
  97. package/src/select.ts +14 -30
  98. package/src/services.ts +10 -0
  99. package/src/slider.ts +2 -1
  100. package/src/split-button.ts +76 -0
  101. package/src/stepper.ts +86 -0
  102. package/src/tabs.ts +129 -0
  103. package/src/toast.ts +203 -0
package/dist/toast.js ADDED
@@ -0,0 +1,176 @@
1
+ /**
2
+ * poadToast.success('Deployed', 'api v1.4 is live'); n'importe où dans la page
3
+ * poadToast({ severity: 'warn', summary: 'Careful', life: 8000 });
4
+ * <poad-toast position="bottom-right" show-progress></poad-toast> facultatif : où et comment les montrer
5
+ *
6
+ * Toasts : le pendant de `PoadToastService` + `<poad-toast>` d'ui-angular. `poadToast` est une fonction (elle ajoute un
7
+ * message) et une file (`createToastStore` d'ui-core) : `add`, `success`, `info`, `warn`, `error`, `remove`,
8
+ * `clear(key?)`, `messages()`, `subscribe()`. `<poad-toast>` montre les messages de sa clé (`toast-key`) :
9
+ * synchronisation avec la file, doublons (`prevent-duplicates`), trop-plein (`max-visible`), durée de vie, pause au
10
+ * survol, sortie animée — machine `toast` d'ui-core. Un message ajouté à la file par défaut sans `<poad-toast>` sans clé
11
+ * dans la page en fait poser un en fin de `body` (en haut à droite). Une autre file : `createPoadToastService()` et la
12
+ * propriété `service`. Évènements : `close` (detail : le message fermé), `toastclick`. Même DOM, mêmes classes, même
13
+ * ARIA (`role="status"` / `alert`, `aria-live`) que `poad-toast`. Style : `toast.css` (et `icon.css`, `button.css`).
14
+ */
15
+ import { TOAST_LIFE, TOAST_MAX_VISIBLE, TOAST_OUT_MS, createToastStore, toastForKey, toastIcon, toastItemProps, toastLife, toastPause, toastResume, toastRootClass, toastSync, } from '@poadio/ui-core';
16
+ import { button } from './button.js';
17
+ import { h } from './dom.js';
18
+ import { PoadElement } from './element.js';
19
+ import { icon } from './icon.js';
20
+ import { servicePrefix } from './services.js';
21
+ function service(onAdd) {
22
+ const store = createToastStore(() => Date.now());
23
+ const add = (m) => { const out = store.add(m); onAdd?.(); return out; };
24
+ const sev = (severity) => (summary, detail, opts = {}) => add({ severity, summary, detail, ...opts });
25
+ return Object.assign(add, {
26
+ add, messages: store.messages, remove: store.remove, clear: store.clear, subscribe: store.subscribe,
27
+ success: sev('success'), info: sev('info'), warn: sev('warn'), error: sev('error'),
28
+ });
29
+ }
30
+ /** Une autre file de toasts (la bibliothèque en a une par défaut : `poadToast`). */
31
+ export const createPoadToastService = () => service();
32
+ /** `<poad-toast>` sans clé connectés à la file par défaut. */
33
+ const defaultHosts = new Set();
34
+ /** La file par défaut ; sans `<poad-toast>` qui la montre, le premier message en fait poser un. */
35
+ export const poadToast = service(() => {
36
+ const tag = `${servicePrefix()}-toast`;
37
+ if (typeof document === 'undefined' || defaultHosts.size || !customElements.get(tag))
38
+ return;
39
+ document.body.append(document.createElement(tag));
40
+ });
41
+ export class PoadToastElement extends PoadElement {
42
+ static props = {
43
+ position: 'string', toastKey: 'string', life: 'number', maxVisible: 'number', preventDuplicates: 'boolean', showProgress: 'boolean', zIndex: 'string',
44
+ };
45
+ static functions = ['service', 'renderItem'];
46
+ items = [];
47
+ known = new Set();
48
+ timers = new Map();
49
+ subscribed = null;
50
+ unsubscribe = null;
51
+ get queue() { return this.service ?? poadToast; }
52
+ disconnectedCallback() {
53
+ super.disconnectedCallback();
54
+ defaultHosts.delete(this);
55
+ this.unsubscribe?.();
56
+ this.unsubscribe = null;
57
+ this.subscribed = null;
58
+ this.timers.forEach(clearTimeout);
59
+ this.timers.clear();
60
+ this.items = [];
61
+ this.known.clear();
62
+ }
63
+ updated() {
64
+ const queue = this.queue;
65
+ if (queue === poadToast && !this.toastKey)
66
+ defaultHosts.add(this);
67
+ else
68
+ defaultHosts.delete(this);
69
+ if (queue === this.subscribed)
70
+ return;
71
+ this.unsubscribe?.();
72
+ this.subscribed = queue;
73
+ this.unsubscribe = queue.subscribe(() => this.sync());
74
+ this.sync();
75
+ }
76
+ clearTimer(id) {
77
+ const t = this.timers.get(id);
78
+ if (t)
79
+ clearTimeout(t);
80
+ this.timers.delete(id);
81
+ }
82
+ animateOut(msg, notify) {
83
+ const it = this.items.find((x) => x.msg === msg);
84
+ if (!it || it.state === 'out')
85
+ return;
86
+ this.clearTimer(msg.id);
87
+ this.items = this.items.map((x) => (x.msg === msg ? { ...x, state: 'out' } : x));
88
+ this.update();
89
+ setTimeout(() => {
90
+ this.items = this.items.filter((x) => x.msg !== msg);
91
+ this.known.delete(msg.id);
92
+ this.update();
93
+ if (notify)
94
+ this.queue.remove(msg);
95
+ this.emit('close', msg);
96
+ }, TOAST_OUT_MS);
97
+ }
98
+ arm(it) {
99
+ this.clearTimer(it.msg.id);
100
+ this.timers.set(it.msg.id, setTimeout(() => this.animateOut(it.msg, true), it.remaining));
101
+ }
102
+ sync() {
103
+ const queue = this.queue;
104
+ const r = toastSync(this.items, toastForKey(queue.messages(), this.toastKey), this.known, {
105
+ life: this.life ?? TOAST_LIFE, maxVisible: this.maxVisible ?? TOAST_MAX_VISIBLE, preventDuplicates: this.preventDuplicates, now: Date.now(),
106
+ });
107
+ for (const m of r.rejected)
108
+ queue.remove(m);
109
+ const fresh = r.items.filter((it) => !this.items.includes(it));
110
+ if (fresh.length) {
111
+ fresh.forEach((it) => this.known.add(it.msg.id));
112
+ this.items = [...this.items, ...fresh];
113
+ this.update();
114
+ for (const it of fresh)
115
+ if (r.arm.includes(it.msg))
116
+ this.arm(it);
117
+ }
118
+ for (const d of r.dismiss)
119
+ this.animateOut(d.msg, d.notify);
120
+ }
121
+ hover(m, on) {
122
+ const it = this.items.find((x) => x.msg === m);
123
+ if (it) {
124
+ if (on)
125
+ this.pause(it);
126
+ else
127
+ this.resume(it);
128
+ }
129
+ }
130
+ pause(it) {
131
+ const next = toastPause(it, Date.now());
132
+ if (next === it)
133
+ return;
134
+ this.clearTimer(it.msg.id);
135
+ this.items = this.items.map((x) => (x === it ? next : x));
136
+ this.update();
137
+ }
138
+ resume(it) {
139
+ const next = toastResume(it, Date.now());
140
+ if (next === it)
141
+ return;
142
+ this.items = this.items.map((x) => (x === it ? next : x));
143
+ this.update();
144
+ this.arm(next);
145
+ }
146
+ render() {
147
+ const { t } = this.i18n();
148
+ const registry = this.icons();
149
+ const life = this.life ?? TOAST_LIFE;
150
+ return h('div', { class: toastRootClass(this.position ?? 'top-right'), style: { zIndex: this.zIndex ?? 'var(--poad-z-overlay)' } }, this.items.map((it) => {
151
+ const a = toastItemProps(it.msg, it.state === 'out');
152
+ const close = () => this.animateOut(it.msg, true);
153
+ const m = it.msg;
154
+ return h('div', {
155
+ class: a.className, role: a.role, 'aria-live': a['aria-live'], onmouseenter: () => this.hover(m, true),
156
+ onmouseleave: () => this.hover(m, false), onclick: () => this.emit('toastclick', m),
157
+ }, [
158
+ this.renderItem ? this.renderItem(m, close) : [
159
+ icon(registry, toastIcon(m), { size: 16, class: 'poad-toast__icon' }),
160
+ h('div', { class: 'poad-toast__text' }, [
161
+ m.summary && h('b', {}, m.summary),
162
+ m.detail && h('span', {}, m.detail),
163
+ !!m.actions?.length && h('div', { class: 'poad-toast__actions' }, m.actions.map((ac) => button({ size: 'sm', variant: 'text', severity: ac.severity || 'primary' }, { type: 'button', onclick: (e) => { e.stopPropagation(); ac.click(m); } }, ac.label))),
164
+ ]),
165
+ m.closable !== false && h('button', {
166
+ type: 'button', class: 'poad-toast__close', 'aria-label': t('common.close'), onclick: (e) => { e.stopPropagation(); close(); },
167
+ }, icon(registry, 'x', { size: 14 })),
168
+ ],
169
+ this.showProgress && !m.sticky && h('i', {
170
+ class: 'poad-toast__progress', style: { animationDuration: `${toastLife(m, life)}ms`, animationPlayState: it.paused ? 'paused' : 'running' },
171
+ }),
172
+ ]);
173
+ }));
174
+ }
175
+ }
176
+ //# sourceMappingURL=toast.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"toast.js","sourceRoot":"","sources":["../src/toast.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,EACL,UAAU,EAAE,iBAAiB,EAAE,YAAY,EAAE,gBA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C,CAAC,eAAe,EAAE,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;qBAC3I,EAAE,IAAI,CAAC,QAAQ,EAAE,GAAG,EAAE,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,CAAC;iBACtC;gBACD,IAAI,CAAC,YAAY,IAAI,CAAC,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC,GAAG,EAAE;oBACvC,KAAK,EAAE,sBAAsB,EAAE,KAAK,EAAE,EAAE,iBAAiB,EAAE,GAAG,SAAS,CAAC,CAAC,EAAE,IAAI,CAAC,IAAI,EAAE,kBAAkB,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS,EAAE;iBAC7I,CAAC;aACH,CAAC,CAAC;QACL,CAAC,CAAC,CAAC,CAAC;IACN,CAAC"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@poadio/ui-elements",
3
- "version": "0.1.0",
4
- "description": "Framework-free web components of the poad UI library (<poad-switch>, <poad-button>, <poad-field>, <poad-select>, named icons, badge, tag, chip, avatar, divider, skeleton, progress, meter, message, checkbox, radio, toggle button, segmented, button group) built on @poadio/ui-core (state machines, shared CSS, message catalogue). Light DOM (one CSS for every renderer), form-associated through ElementInternals, safe to import on a server. For vanilla pages, Svelte, Solid or server-rendered HTML.",
3
+ "version": "0.2.0",
4
+ "description": "Framework-free web components of the poad UI library (<poad-switch>, <poad-button>, <poad-field>, <poad-select>, named icons, badge, tag, chip, avatar, divider, skeleton, progress, meter, message, checkbox, radio, toggle button, segmented, button group, fields, tooltip, popover, colorpicker, tabs, accordion, stepper, menu, split button, multiselect, combo, datepicker, dialog, drawer, poadConfirm(), poadToast()) built on @poadio/ui-core (state machines, shared CSS, message catalogue). Light DOM (one CSS for every renderer), form-associated through ElementInternals, safe to import on a server. For vanilla pages, Svelte, Solid or server-rendered HTML.",
5
5
  "license": "MIT",
6
6
  "author": "poad — Stéphane Zuccatti",
7
7
  "type": "module",
@@ -37,7 +37,7 @@
37
37
  "i18n:check": "node ../../tools/check-i18n.mjs ui-elements"
38
38
  },
39
39
  "dependencies": {
40
- "@poadio/ui-core": "^0.1.0"
40
+ "@poadio/ui-core": "^0.2.0"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@types/node": "^24.0.0",
@@ -0,0 +1,80 @@
1
+ /**
2
+ * <poad-accordion value="db">
3
+ * <poad-accordion-panel value="db" header="Database" icon="database">…contenu…</poad-accordion-panel>
4
+ * <poad-accordion-panel value="net" header="Network" disabled>…</poad-accordion-panel>
5
+ * </poad-accordion>
6
+ * <poad-accordion multiple value='["db"]'>…</poad-accordion>
7
+ *
8
+ * Accordéon : machine `accordion` de @poadio/ui-core (un panneau ouvert, ou plusieurs avec `multiple` ; ↓ ↑ Début Fin
9
+ * entre en-têtes ; attributs `aria-expanded` / `region` ; panneau fermé `inert`). Les `<poad-accordion-panel>` sont
10
+ * des DÉCLARATIONS (sans `value`, un panneau vaut son rang : `"0"`, `"1"`…). Propriété `value` (valeur d'un panneau, un
11
+ * tableau en `multiple`, ou `null`) ; évènement `change` (detail : la nouvelle valeur) quand l'utilisateur ouvre ou
12
+ * ferme. Même DOM, mêmes classes, même ARIA que `poad-accordion` d'ui-angular. Style : `accordion.css`, `icon.css`.
13
+ */
14
+ import {
15
+ accordionHeaderProps, accordionIsOpen, accordionKeydown, accordionPanelClasses, accordionRegionProps, accordionRootClasses, accordionSet, type AccordionValue,
16
+ } from '@poadio/ui-core';
17
+ import { PoadDeclarationElement, declarations } from './declaration.js';
18
+ import { h } from './dom.js';
19
+ import { PoadElement } from './element.js';
20
+ import { icon } from './icon.js';
21
+
22
+ export interface AccordionPanelData {
23
+ readonly value?: string;
24
+ readonly header?: string;
25
+ readonly icon?: string;
26
+ readonly disabled?: boolean;
27
+ }
28
+
29
+ /** Déclaration d'un panneau dans un `<poad-accordion>` ; ses enfants sont son contenu. */
30
+ export class PoadAccordionPanelElement extends PoadDeclarationElement {
31
+ static override props = { value: 'string', header: 'string', icon: 'string', disabled: 'boolean' } as const;
32
+ }
33
+
34
+ export class PoadAccordionElement extends PoadElement {
35
+ static override props = { value: 'json', multiple: 'boolean', expandIcon: 'string', flush: 'boolean' } as const;
36
+ declare value?: string | string[] | null;
37
+ declare multiple?: boolean;
38
+ declare expandIcon?: string;
39
+ declare flush?: boolean;
40
+
41
+ protected render() {
42
+ const registry = this.icons();
43
+ const panels = declarations<AccordionPanelData>(this, this.content, this.tag('accordion-panel'), PoadAccordionPanelElement.props);
44
+ const keyOf = (p: AccordionPanelData, i: number) => p.value ?? String(i);
45
+ const toggle = (p: AccordionPanelData, i: number) => {
46
+ if (p.disabled) return;
47
+ const v = keyOf(p, i);
48
+ const open = !accordionIsOpen(this.value, v);
49
+ const next = accordionSet((this.value ?? null) as AccordionValue, v, open, this.multiple);
50
+ if (next === this.value) return;
51
+ this.value = next as string | string[] | null;
52
+ this.emit('change', next);
53
+ };
54
+ const onkeydown = (e: KeyboardEvent, i: number) => {
55
+ const to = accordionKeydown(panels.map((p) => ({ disabled: !!p.data.disabled })), i, e.key);
56
+ if (to === null) return;
57
+ e.preventDefault();
58
+ this.querySelectorAll<HTMLElement>(':scope > .poad-accordion > .poad-accordion-panel > h3 > button')[to]?.focus();
59
+ };
60
+ return h('div', { class: ['poad-accordion', accordionRootClasses(this.flush)] }, panels.map(({ data: p, content }, i) => {
61
+ const id = `${this.uid}-acc-${i}`;
62
+ const open = accordionIsOpen(this.value, keyOf(p, i));
63
+ const hd = accordionHeaderProps(id, open, !!p.disabled);
64
+ const rg = accordionRegionProps(id, open);
65
+ return h('div', { class: ['poad-accordion-panel', accordionPanelClasses(open, !!p.disabled)] }, [
66
+ h('h3', { class: 'poad-acc__h' }, h('button', {
67
+ type: 'button', class: 'poad-acc__hd', id: hd.id, 'aria-expanded': hd['aria-expanded'], 'aria-controls': hd['aria-controls'], disabled: hd.disabled,
68
+ onclick: () => toggle(p, i), onkeydown: (e: KeyboardEvent) => onkeydown(e, i),
69
+ }, [
70
+ icon(registry, this.expandIcon ?? 'chevron-right', { size: 13, class: 'poad-acc__chev' }),
71
+ p.icon && icon(registry, p.icon, { size: 14 }),
72
+ h('span', { class: 'poad-acc__title' }, p.header ?? ''),
73
+ h('span', { class: 'poad-acc__extra' }),
74
+ ])),
75
+ h('div', { class: 'poad-acc__wrap', role: rg.role, id: rg.id, 'aria-labelledby': rg['aria-labelledby'], inert: rg.inert },
76
+ h('div', { class: 'poad-acc__inner' }, h('div', { class: 'poad-acc__bd' }, content))),
77
+ ]);
78
+ }));
79
+ }
80
+ }
package/src/combo.ts ADDED
@@ -0,0 +1,220 @@
1
+ /**
2
+ * <poad-combo name="city" placeholder="City…" min-length="2" force-selection suggestions='[{"label":"Lyon"},{"label":"Lens"}]'></poad-combo>
3
+ * combo.suggestions = async (query) => (await fetch(`/cities?q=${query}`)).json(); une source qui cherche
4
+ * <poad-combo multiple dropdown suggestions='["Concrete","Steel","Wood"]'></poad-combo>
5
+ *
6
+ * Saisie avec suggestions (« autocomplete ») : machine `combo` de @poadio/ui-core (filtre sans accents ni casse, clavier
7
+ * ↓ ↑ Entrée Échap Tab et Retour arrière en choix multiple, choix, sortie du champ — texte libre ou `force-selection` —,
8
+ * attributs `combobox` / `listbox`). `suggestions` : un tableau (filtré ici) ou, en propriété, une fonction de la requête
9
+ * qui rend un tableau ou une promesse (la dernière réponse gagne). Propriété `value` : texte libre (chaîne), suggestion
10
+ * (objet) ou, en `multiple`, tableau (puces). Évènements : `change` (et `input`) quand l'utilisateur choisit, efface ou
11
+ * quitte le champ ; en texte libre, `input` seul à chaque frappe (la valeur suit) ; `search` (detail : la requête),
12
+ * `openchange`. Formulaire : `name` (le libellé ; une entrée par puce en `multiple`), `required`. Même DOM, mêmes
13
+ * classes, même ARIA que `poad-combo` d'ui-angular. Styles : `combo.css`, `icon.css`, `floating.css`.
14
+ */
15
+ import {
16
+ SELECT_PLACEMENTS, comboBlur, comboFilter, comboInput, comboInputProps, comboIsSelected, comboKeydown, comboLabel, comboOptionProps, comboPick, comboResults,
17
+ comboRootClasses, comboTextOf, comboValues,
18
+ } from '@poadio/ui-core';
19
+ import { classOf, h } from './dom.js';
20
+ import { PoadFormElement } from './element.js';
21
+ import { FloatingTracker, Listening, listenOutside } from './floating.js';
22
+ import { icon } from './icon.js';
23
+
24
+ export type PoadComboSource = readonly unknown[] | ((query: string) => readonly unknown[] | Promise<readonly unknown[]>);
25
+
26
+ export class PoadComboElement extends PoadFormElement {
27
+ static override props = {
28
+ value: 'json', suggestions: 'json', optionLabel: 'string', minLength: 'number', delay: 'number', dropdown: 'boolean', forceSelection: 'boolean',
29
+ multiple: 'boolean', clearable: 'boolean', readonly: 'boolean', disabled: 'boolean', invalid: 'boolean', placeholder: 'string', emptyMessage: 'string',
30
+ size: 'string', panelMaxHeight: 'number', ariaLabel: 'string', name: 'string', required: 'boolean',
31
+ } as const;
32
+ static override functions = ['renderOption'] as const;
33
+ declare value?: unknown;
34
+ declare suggestions?: PoadComboSource;
35
+ /** Chemin du libellé d'une suggestion objet (défaut `label`). */
36
+ declare optionLabel?: string;
37
+ declare minLength?: number;
38
+ /** Délai avant la recherche (ms, défaut 250). */
39
+ declare delay?: number;
40
+ declare dropdown?: boolean;
41
+ declare forceSelection?: boolean;
42
+ declare multiple?: boolean;
43
+ declare clearable?: boolean;
44
+ declare readonly?: boolean;
45
+ declare disabled?: boolean;
46
+ declare invalid?: boolean;
47
+ declare placeholder?: string;
48
+ declare emptyMessage?: string;
49
+ declare size?: 'sm' | 'md' | 'lg';
50
+ declare panelMaxHeight?: number;
51
+ declare ariaLabel: string | null;
52
+ declare name?: string;
53
+ declare required?: boolean;
54
+ /** Rendu d'une suggestion. */
55
+ declare renderOption?: (option: unknown, context: { readonly selected: boolean; readonly index: number; readonly label: string }) => string | Node;
56
+ protected readonly resetProps = ['value'];
57
+
58
+ private text = '';
59
+ /** Valeur dont le texte du champ est tiré (choix unique) : une autre valeur posée par la page récrit le texte. */
60
+ private shown: unknown = undefined;
61
+ private open = false;
62
+ private loading = false;
63
+ private items: readonly unknown[] = [];
64
+ private active = -1;
65
+ private width = 0;
66
+ private timer: ReturnType<typeof setTimeout> | null = null;
67
+ private seq = 0;
68
+ private readonly tracker = new FloatingTracker(() => this.update());
69
+ private readonly outside = new Listening(() => listenOutside(() => [this], () => this.close()));
70
+
71
+ private get path() { return this.optionLabel ?? 'label'; }
72
+ private get values() { return comboValues(this.value, !!this.multiple); }
73
+ private input(): HTMLInputElement | null { return this.querySelector<HTMLInputElement>(':scope > .poad-combo input.st__input'); }
74
+
75
+ protected formValue() {
76
+ if (this.multiple) {
77
+ const values = this.values;
78
+ if (!this.name || !values.length) return { value: null, missing: !values.length };
79
+ const data = new FormData();
80
+ for (const v of values) data.append(this.name, comboLabel(v, this.path));
81
+ return { value: data, missing: false };
82
+ }
83
+ const text = comboTextOf(this.value, this.path);
84
+ return { value: text || null, missing: !text };
85
+ }
86
+ override disconnectedCallback(): void {
87
+ super.disconnectedCallback();
88
+ if (this.timer) clearTimeout(this.timer);
89
+ this.open = false;
90
+ this.tracker.sync(null, null);
91
+ this.outside.toggle(false);
92
+ }
93
+
94
+ private write(next: unknown, commit = true) {
95
+ if (!this.multiple) this.shown = next;
96
+ this.value = next;
97
+ if (commit) this.changed(next); else this.emit('input', next);
98
+ }
99
+ private setOpen(next: boolean) {
100
+ if (next === this.open) return;
101
+ this.open = next;
102
+ if (next) this.width = this.querySelector(':scope > .poad-combo > .st')?.getBoundingClientRect().width ?? 0;
103
+ this.update();
104
+ this.emit('openchange', next);
105
+ }
106
+ private close() {
107
+ if (!this.open) return;
108
+ this.active = -1;
109
+ this.setOpen(false);
110
+ }
111
+ private async search(q: string) {
112
+ this.emit('search', q);
113
+ const my = ++this.seq;
114
+ const source = this.suggestions ?? [];
115
+ let res: readonly unknown[] = [];
116
+ if (typeof source === 'function') {
117
+ this.loading = true;
118
+ this.update();
119
+ try { res = await source(q); } catch { res = []; } finally { if (my === this.seq) { this.loading = false; this.update(); } }
120
+ } else res = comboFilter(source, q, this.path);
121
+ if (my !== this.seq) return;
122
+ this.items = res;
123
+ this.active = comboResults(res.length).active;
124
+ if (!this.open) this.setOpen(true); else this.update();
125
+ }
126
+ private onInput(v: string) {
127
+ this.text = v;
128
+ // texte libre : la valeur suit la frappe (évènement `input` seul, comme un champ natif)
129
+ if (!this.multiple && !this.forceSelection) this.write(v || null, false);
130
+ if (comboInput(v, this.minLength ?? 1) === 'close') { this.close(); this.update(); return; }
131
+ if (this.timer) clearTimeout(this.timer);
132
+ this.timer = setTimeout(() => void this.search(v), this.delay ?? 250);
133
+ }
134
+ private pick(o: unknown) {
135
+ const r = comboPick(this.value, o, { multiple: this.multiple, labelPath: this.path });
136
+ this.text = r.text;
137
+ if (r.changed) this.write(r.value);
138
+ this.close();
139
+ this.update();
140
+ }
141
+ private onBlur() {
142
+ const r = comboBlur(this.value, this.text, { forceSelection: this.forceSelection, multiple: this.multiple, labelPath: this.path });
143
+ if (!r) return;
144
+ if (r.text !== undefined) this.text = r.text;
145
+ if ('value' in r) this.write(r.value);
146
+ this.update();
147
+ }
148
+ private readonly onKeydown = (e: KeyboardEvent) => {
149
+ const values = this.values;
150
+ const r = comboKeydown({ open: this.open, active: this.active, count: this.items.length, multiple: !!this.multiple, text: this.text, valuesCount: values.length }, e.key);
151
+ if (r.preventDefault) e.preventDefault();
152
+ const a = r.action;
153
+ if (a.type === 'search') void this.search(this.text);
154
+ else if (a.type === 'move') { this.active = a.active; this.update(); }
155
+ else if (a.type === 'pick') this.pick(this.items[a.index]);
156
+ else if (a.type === 'close') this.close();
157
+ else if (a.type === 'remove-last') this.write(values.slice(0, -1));
158
+ };
159
+ protected override updated(): void {
160
+ super.updated();
161
+ const pane = this.open ? this.querySelector<HTMLElement>(':scope > .poad-combo > .poad-combo-pane') : null;
162
+ this.tracker.sync(pane ? this.querySelector<HTMLElement>(':scope > .poad-combo > .st') : null, pane, { candidates: SELECT_PLACEMENTS, offset: 4, shift: true });
163
+ this.outside.toggle(this.open);
164
+ }
165
+
166
+ protected render() {
167
+ const { t, text: tx } = this.i18n();
168
+ const registry = this.icons();
169
+ const multiple = !!this.multiple;
170
+ // valeur posée par la page (choix unique) → texte du champ
171
+ if (!multiple && this.value !== this.shown) { this.shown = this.value; this.text = comboTextOf(this.value, this.path); }
172
+ const values = this.values;
173
+ const listId = `${this.uid}-list`;
174
+ const ia = comboInputProps({ open: this.open, listId, active: this.active, invalid: this.invalid });
175
+ const disabled = this.inactive;
176
+ const input = h('input', {
177
+ class: 'st__input', role: ia.role, placeholder: multiple && values.length ? '' : (this.placeholder ?? ''), value: this.text, disabled,
178
+ readonly: !multiple && this.readonly, autocomplete: 'off', spellcheck: 'false', 'aria-autocomplete': ia['aria-autocomplete'], 'aria-expanded': ia['aria-expanded'],
179
+ 'aria-controls': ia['aria-controls'], 'aria-activedescendant': ia['aria-activedescendant'], 'aria-invalid': multiple ? undefined : ia['aria-invalid'],
180
+ 'aria-label': this.ariaLabel || undefined, oninput: (e: Event) => this.onInput((e.target as HTMLInputElement).value), onkeydown: this.onKeydown,
181
+ onblur: () => this.onBlur(),
182
+ });
183
+ const clear = (e: MouseEvent) => { e.stopPropagation(); this.text = ''; this.write(multiple ? [] : null); this.close(); this.update(); };
184
+ const removeAt = (i: number, e: MouseEvent) => { e.stopPropagation(); if (disabled) return; this.write(values.filter((_, k) => k !== i)); };
185
+ return h('div', { class: ['poad-combo', comboRootClasses({ open: this.open, disabled, invalid: this.invalid, size: this.size ?? 'md' })] }, [
186
+ h('div', { class: ['st', { 'st--multi': multiple }], onclick: () => this.input()?.focus() }, [
187
+ multiple ? h('span', { class: 'st__chips' }, [
188
+ values.map((v, i) => h('span', { class: 'st__chip' }, [
189
+ comboLabel(v, this.path),
190
+ h('button', { type: 'button', tabindex: -1, 'aria-label': t('common.remove'), onclick: (e: MouseEvent) => removeAt(i, e) }, icon(registry, 'x', { size: 10 })),
191
+ ])),
192
+ input,
193
+ ]) : input,
194
+ this.loading && icon(registry, 'loader', { size: 14, spin: true, class: 'st__spin' }),
195
+ this.clearable && (this.text || values.length > 0) && !disabled && h('button', {
196
+ type: 'button', class: 'st__clear', tabindex: -1, 'aria-label': t('common.clear'), onclick: clear,
197
+ }, icon(registry, 'x', { size: 12 })),
198
+ this.dropdown && h('button', {
199
+ type: 'button', class: 'st__dd', tabindex: -1, 'aria-label': t('select.showSuggestions'),
200
+ onclick: (e: MouseEvent) => {
201
+ e.stopPropagation();
202
+ if (disabled) return;
203
+ if (this.open) { this.close(); return; }
204
+ this.input()?.focus();
205
+ void this.search('');
206
+ },
207
+ }, icon(registry, 'chevron-down', { size: 13, class: 'st__chev' })),
208
+ ]),
209
+ this.open && h('div', { class: 'poad-floating poad-combo-pane', style: this.tracker.style }, h('div', { class: 'sp', style: { minWidth: `${this.width}px` } },
210
+ h('ul', { class: 'cb__list', role: 'listbox', id: listId, style: { maxHeight: `${this.panelMaxHeight ?? 260}px` } },
211
+ this.items.length ? this.items.map((o, i) => {
212
+ const op = comboOptionProps(listId, i, i === this.active, comboIsSelected(this.value, o, multiple));
213
+ return h('li', {
214
+ role: op.role, id: op.id, class: classOf(op.classes) || undefined, 'aria-selected': op['aria-selected'],
215
+ onmousedown: (e: MouseEvent) => e.preventDefault(), onmouseenter: () => { this.active = i; this.update(); }, onclick: () => this.pick(o),
216
+ }, this.renderOption ? this.renderOption(o, { selected: op.classes['is-on'], index: i, label: comboLabel(o, this.path) }) : comboLabel(o, this.path));
217
+ }) : !this.loading && h('li', { class: 'sp__empty' }, tx(this.emptyMessage, 'select.noSuggestions'))))),
218
+ ]);
219
+ }
220
+ }
package/src/confirm.ts ADDED
@@ -0,0 +1,106 @@
1
+ /**
2
+ * const ok = await poadConfirm({ header: 'Delete?', message: 'This cannot be undone.', severity: 'danger', requireTyping: 'prod' });
3
+ *
4
+ * Confirmation : le pendant de `PoadConfirmService` d'ui-angular, en une fonction. `poadConfirm(options)` rend une
5
+ * promesse de `true` (accepté) ou `false` (refusé, croix, Échap, fond) et appelle `accept` / `reject` s'ils sont
6
+ * donnés. Elle se sert d'un `<poad-confirm-dialog>` de la page : le premier connecté, sinon un élément créé à la
7
+ * première demande en fin de `body` et gardé (préfixe de balise : celui du premier `defineElements()`). Une seule
8
+ * confirmation à la fois : une nouvelle demande refuse la précédente. Décisions : `confirm*` d'ui-core (configuration
9
+ * de la boîte — même conteneur que `<poad-dialog>` —, sévérité du bouton, icône, saisie exigée). `message` : un texte ou
10
+ * un nœud du DOM. Styles : `dialog.css`, `button.css`, `field.css`, `icon.css`.
11
+ */
12
+ import { confirmAcceptSeverity, confirmCanAccept, confirmClasses, confirmDialogConfig, confirmIcon, inputClasses, type ConfirmOptions } from '@poadio/ui-core';
13
+ import { button } from './button.js';
14
+ import { DialogLayer } from './dialog.js';
15
+ import { h } from './dom.js';
16
+ import { PoadElement } from './element.js';
17
+ import { icon } from './icon.js';
18
+ import { servicePrefix } from './services.js';
19
+
20
+ export interface PoadConfirmOptions extends ConfirmOptions {
21
+ /** Texte, ou nœud du DOM. */
22
+ readonly message?: string | Node;
23
+ readonly accept?: () => void;
24
+ readonly reject?: () => void;
25
+ }
26
+
27
+ interface Pending {
28
+ readonly options: PoadConfirmOptions;
29
+ readonly resolve: (ok: boolean) => void;
30
+ }
31
+
32
+ export class PoadConfirmDialogElement extends PoadElement {
33
+ private pending: Pending | null = null;
34
+ private current: Pending | null = null;
35
+ private open = false;
36
+ private typed = '';
37
+ private readonly layer = new DialogLayer(this);
38
+
39
+ /** Ouvre la confirmation ; rend la réponse de l'utilisateur. */
40
+ confirm(options: PoadConfirmOptions): Promise<boolean> {
41
+ return new Promise<boolean>((resolve) => {
42
+ this.current?.resolve(false); // une seule à la fois : la précédente est refusée
43
+ this.current = this.pending = { options, resolve };
44
+ this.typed = '';
45
+ this.open = true;
46
+ this.update();
47
+ });
48
+ }
49
+ private settle(ok: boolean) {
50
+ const p = this.current;
51
+ if (!p) return;
52
+ this.current = null;
53
+ this.open = false;
54
+ this.update();
55
+ (ok ? p.options.accept : p.options.reject)?.();
56
+ p.resolve(ok);
57
+ }
58
+ override disconnectedCallback(): void {
59
+ super.disconnectedCallback();
60
+ this.layer.dispose();
61
+ this.settle(false);
62
+ }
63
+ protected render() {
64
+ const o = this.pending?.options;
65
+ if (!o) return null;
66
+ const { t, text } = this.i18n();
67
+ const registry = this.icons();
68
+ const name = confirmIcon(o);
69
+ const accept = { severity: confirmAcceptSeverity(o), disabled: !confirmCanAccept(o, this.typed) } as const;
70
+ return this.layer.render({
71
+ config: confirmDialogConfig(o, t('overlay.confirmHeader')), open: this.open, titleId: `${this.uid}-title`, t, icons: registry,
72
+ onClose: () => this.settle(false),
73
+ body: h('div', { class: ['poad-confirm', confirmClasses(o)] }, [
74
+ h('div', { class: 'poad-confirm__row' }, [
75
+ name && icon(registry, name, { size: 20, class: 'poad-confirm__icon' }),
76
+ h('div', { class: 'poad-confirm__msg' }, h('div', {}, o.message ?? '')),
77
+ ]),
78
+ o.requireTyping && h('label', { class: 'poad-confirm__typing' }, [
79
+ h('span', {}, text(o.requireTypingLabel || undefined, 'overlay.typeToConfirm', { text: o.requireTyping })),
80
+ h('input', {
81
+ class: ['poad-input', inputClasses({ mono: true })], value: this.typed, placeholder: o.requireTyping, autocomplete: 'off', spellcheck: 'false',
82
+ oninput: (e: Event) => { this.typed = (e.target as HTMLInputElement).value; this.update(); },
83
+ }),
84
+ ]),
85
+ ]),
86
+ footer: [
87
+ o.rejectVisible !== false && button({ severity: 'secondary' }, { type: 'button', onclick: () => this.settle(false) }, o.rejectLabel || t('common.cancel')),
88
+ button(accept, { type: 'button', onclick: () => this.settle(true) }, [o.acceptIcon && icon(registry, o.acceptIcon, { size: 14 }), o.acceptLabel || t('common.confirm')]),
89
+ ],
90
+ });
91
+ }
92
+ protected override updated(): void {
93
+ this.layer.sync();
94
+ }
95
+ }
96
+
97
+ /** Demande une confirmation : `true` si l'utilisateur accepte. Navigateur seulement. */
98
+ export function poadConfirm(options: PoadConfirmOptions): Promise<boolean> {
99
+ const tag = `${servicePrefix()}-confirm-dialog`;
100
+ let el = document.querySelector(tag) as PoadConfirmDialogElement | null;
101
+ if (!el) {
102
+ el = document.createElement(tag) as PoadConfirmDialogElement;
103
+ document.body.append(el);
104
+ }
105
+ return el.confirm(options);
106
+ }