@poadio/ui-elements 0.0.0-stage → 0.1.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 (174) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/LICENSE +22 -0
  3. package/README.md +119 -2
  4. package/dist/avatar.d.ts +56 -0
  5. package/dist/avatar.d.ts.map +1 -0
  6. package/dist/avatar.js +49 -0
  7. package/dist/avatar.js.map +1 -0
  8. package/dist/badge.d.ts +26 -0
  9. package/dist/badge.d.ts.map +1 -0
  10. package/dist/badge.js +19 -0
  11. package/dist/badge.js.map +1 -0
  12. package/dist/button-group.d.ts +43 -0
  13. package/dist/button-group.d.ts.map +1 -0
  14. package/dist/button-group.js +63 -0
  15. package/dist/button-group.js.map +1 -0
  16. package/dist/button.d.ts +44 -0
  17. package/dist/button.d.ts.map +1 -0
  18. package/dist/button.js +29 -0
  19. package/dist/button.js.map +1 -0
  20. package/dist/checkbox.d.ts +32 -0
  21. package/dist/checkbox.d.ts.map +1 -0
  22. package/dist/checkbox.js +46 -0
  23. package/dist/checkbox.js.map +1 -0
  24. package/dist/chip.d.ts +37 -0
  25. package/dist/chip.d.ts.map +1 -0
  26. package/dist/chip.js +46 -0
  27. package/dist/chip.js.map +1 -0
  28. package/dist/colorpicker.d.ts +63 -0
  29. package/dist/colorpicker.d.ts.map +1 -0
  30. package/dist/colorpicker.js +164 -0
  31. package/dist/colorpicker.js.map +1 -0
  32. package/dist/define.d.ts +2 -0
  33. package/dist/define.d.ts.map +1 -0
  34. package/dist/define.js +4 -0
  35. package/dist/define.js.map +1 -0
  36. package/dist/divider.d.ts +15 -0
  37. package/dist/divider.d.ts.map +1 -0
  38. package/dist/divider.js +17 -0
  39. package/dist/divider.js.map +1 -0
  40. package/dist/dom.d.ts +20 -0
  41. package/dist/dom.d.ts.map +1 -0
  42. package/dist/dom.js +99 -0
  43. package/dist/dom.js.map +1 -0
  44. package/dist/element.d.ts +84 -0
  45. package/dist/element.d.ts.map +1 -0
  46. package/dist/element.js +166 -0
  47. package/dist/element.js.map +1 -0
  48. package/dist/field.d.ts +50 -0
  49. package/dist/field.d.ts.map +1 -0
  50. package/dist/field.js +90 -0
  51. package/dist/field.js.map +1 -0
  52. package/dist/floating.d.ts +134 -0
  53. package/dist/floating.d.ts.map +1 -0
  54. package/dist/floating.js +311 -0
  55. package/dist/floating.js.map +1 -0
  56. package/dist/i18n.d.ts +32 -0
  57. package/dist/i18n.d.ts.map +1 -0
  58. package/dist/i18n.js +49 -0
  59. package/dist/i18n.js.map +1 -0
  60. package/dist/icon.d.ts +37 -0
  61. package/dist/icon.d.ts.map +1 -0
  62. package/dist/icon.js +32 -0
  63. package/dist/icon.js.map +1 -0
  64. package/dist/index.d.ts +98 -0
  65. package/dist/index.d.ts.map +1 -0
  66. package/dist/index.js +89 -0
  67. package/dist/index.js.map +1 -0
  68. package/dist/inplace.d.ts +25 -0
  69. package/dist/inplace.d.ts.map +1 -0
  70. package/dist/inplace.js +61 -0
  71. package/dist/inplace.js.map +1 -0
  72. package/dist/mask.d.ts +76 -0
  73. package/dist/mask.d.ts.map +1 -0
  74. package/dist/mask.js +150 -0
  75. package/dist/mask.js.map +1 -0
  76. package/dist/message.d.ts +31 -0
  77. package/dist/message.d.ts.map +1 -0
  78. package/dist/message.js +28 -0
  79. package/dist/message.js.map +1 -0
  80. package/dist/meter.d.ts +42 -0
  81. package/dist/meter.d.ts.map +1 -0
  82. package/dist/meter.js +47 -0
  83. package/dist/meter.js.map +1 -0
  84. package/dist/number.d.ts +63 -0
  85. package/dist/number.d.ts.map +1 -0
  86. package/dist/number.js +72 -0
  87. package/dist/number.js.map +1 -0
  88. package/dist/password.d.ts +30 -0
  89. package/dist/password.d.ts.map +1 -0
  90. package/dist/password.js +47 -0
  91. package/dist/password.js.map +1 -0
  92. package/dist/popover.d.ts +62 -0
  93. package/dist/popover.d.ts.map +1 -0
  94. package/dist/popover.js +109 -0
  95. package/dist/popover.js.map +1 -0
  96. package/dist/progress.d.ts +48 -0
  97. package/dist/progress.d.ts.map +1 -0
  98. package/dist/progress.js +42 -0
  99. package/dist/progress.js.map +1 -0
  100. package/dist/radio.d.ts +44 -0
  101. package/dist/radio.d.ts.map +1 -0
  102. package/dist/radio.js +70 -0
  103. package/dist/radio.js.map +1 -0
  104. package/dist/rating.d.ts +52 -0
  105. package/dist/rating.d.ts.map +1 -0
  106. package/dist/rating.js +77 -0
  107. package/dist/rating.js.map +1 -0
  108. package/dist/segmented.d.ts +51 -0
  109. package/dist/segmented.d.ts.map +1 -0
  110. package/dist/segmented.js +68 -0
  111. package/dist/segmented.js.map +1 -0
  112. package/dist/select.d.ts +122 -0
  113. package/dist/select.d.ts.map +1 -0
  114. package/dist/select.js +201 -0
  115. package/dist/select.js.map +1 -0
  116. package/dist/skeleton.d.ts +19 -0
  117. package/dist/skeleton.d.ts.map +1 -0
  118. package/dist/skeleton.js +16 -0
  119. package/dist/skeleton.js.map +1 -0
  120. package/dist/slider.d.ts +76 -0
  121. package/dist/slider.d.ts.map +1 -0
  122. package/dist/slider.js +137 -0
  123. package/dist/slider.js.map +1 -0
  124. package/dist/switch.d.ts +32 -0
  125. package/dist/switch.d.ts.map +1 -0
  126. package/dist/switch.js +42 -0
  127. package/dist/switch.js.map +1 -0
  128. package/dist/tag.d.ts +27 -0
  129. package/dist/tag.d.ts.map +1 -0
  130. package/dist/tag.js +21 -0
  131. package/dist/tag.js.map +1 -0
  132. package/dist/toggle-button.d.ts +46 -0
  133. package/dist/toggle-button.d.ts.map +1 -0
  134. package/dist/toggle-button.js +39 -0
  135. package/dist/toggle-button.js.map +1 -0
  136. package/dist/tooltip.d.ts +48 -0
  137. package/dist/tooltip.d.ts.map +1 -0
  138. package/dist/tooltip.js +105 -0
  139. package/dist/tooltip.js.map +1 -0
  140. package/package.json +66 -4
  141. package/src/avatar.ts +78 -0
  142. package/src/badge.ts +26 -0
  143. package/src/button-group.ts +66 -0
  144. package/src/button.ts +44 -0
  145. package/src/checkbox.ts +57 -0
  146. package/src/chip.ts +54 -0
  147. package/src/colorpicker.ts +173 -0
  148. package/src/define.ts +4 -0
  149. package/src/divider.ts +22 -0
  150. package/src/dom.ts +102 -0
  151. package/src/element.ts +182 -0
  152. package/src/field.ts +91 -0
  153. package/src/floating.ts +316 -0
  154. package/src/i18n.ts +61 -0
  155. package/src/icon.ts +42 -0
  156. package/src/index.ts +101 -0
  157. package/src/inplace.ts +69 -0
  158. package/src/mask.ts +170 -0
  159. package/src/message.ts +37 -0
  160. package/src/meter.ts +63 -0
  161. package/src/number.ts +94 -0
  162. package/src/password.ts +59 -0
  163. package/src/popover.ts +118 -0
  164. package/src/progress.ts +62 -0
  165. package/src/radio.ts +84 -0
  166. package/src/rating.ts +91 -0
  167. package/src/segmented.ts +81 -0
  168. package/src/select.ts +242 -0
  169. package/src/skeleton.ts +24 -0
  170. package/src/slider.ts +144 -0
  171. package/src/switch.ts +52 -0
  172. package/src/tag.ts +29 -0
  173. package/src/toggle-button.ts +52 -0
  174. package/src/tooltip.ts +101 -0
@@ -0,0 +1,57 @@
1
+ /**
2
+ * <poad-checkbox label="PostGIS" name="ext" value="postgis" checked></poad-checkbox> <poad-checkbox label="All" indeterminate></poad-checkbox>
3
+ *
4
+ * Machine `checkbox` de @poadio/ui-core (gestes refusés désactivée ou en lecture seule, `aria-checked` à trois valeurs,
5
+ * état partiel qui cède au premier geste, comme une case native) ; même DOM, mêmes classes, même ARIA que
6
+ * `poad-checkbox` d'ui-angular. Propriétés `checked` et `indeterminate` ; évènements `input` / `change` (detail : la
7
+ * valeur) aux seuls gestes. Formulaire : `name`, `value` (défaut `on`), `required`. Style : `checkbox.css`.
8
+ */
9
+ import { checkboxControlProps, checkboxLabelProps, checkboxMark, checkboxRootClasses, checkboxTransition, type CheckboxState } from '@poadio/ui-core';
10
+ import { h } from './dom.js';
11
+ import { PoadFormElement } from './element.js';
12
+ import { icon } from './icon.js';
13
+
14
+ export class PoadCheckboxElement extends PoadFormElement {
15
+ static override props = {
16
+ checked: 'boolean', indeterminate: 'boolean', disabled: 'boolean', readonly: 'boolean', invalid: 'boolean', label: 'string', ariaLabel: 'string',
17
+ name: 'string', value: 'string', required: 'boolean',
18
+ } as const;
19
+ declare checked?: boolean;
20
+ declare indeterminate?: boolean;
21
+ declare disabled?: boolean;
22
+ declare readonly?: boolean;
23
+ declare invalid?: boolean;
24
+ declare label?: string;
25
+ declare ariaLabel: string | null;
26
+ declare name?: string;
27
+ declare value?: string;
28
+ declare required?: boolean;
29
+ protected readonly resetProps = ['checked', 'indeterminate'];
30
+
31
+ protected formValue() {
32
+ return { value: this.checked ? (this.value ?? 'on') : null, missing: !this.checked };
33
+ }
34
+ protected render() {
35
+ const state: CheckboxState = { checked: !!this.checked, indeterminate: !!this.indeterminate, disabled: this.inactive, readonly: !!this.readonly };
36
+ const element = { id: this.uid, label: this.label ?? '', ariaLabel: this.ariaLabel ?? '', invalid: this.invalid };
37
+ const control = checkboxControlProps(state, element);
38
+ const label = checkboxLabelProps(element);
39
+ const mark = checkboxMark(state);
40
+ const toggle = () => {
41
+ const next = checkboxTransition(state, { type: 'toggle' });
42
+ if (next === state) return; // désactivée ou en lecture seule : le socle refuse le geste
43
+ this.indeterminate = next.indeterminate;
44
+ this.checked = next.checked;
45
+ this.changed(next.checked);
46
+ };
47
+ return h('span', { class: ['poad-checkbox', checkboxRootClasses(state, element)] }, [
48
+ h('button', {
49
+ type: 'button', role: control.role, id: control.id, 'aria-checked': control['aria-checked'], disabled: control.disabled,
50
+ 'aria-labelledby': control['aria-labelledby'], 'aria-label': control['aria-label'], 'aria-invalid': control['aria-invalid'], onclick: toggle,
51
+ }, h('span', { class: 'poad-checkbox__box' },
52
+ mark === 'dash' ? h('span', { class: 'poad-checkbox__dash' }) : mark === 'check' && icon(this.icons(), 'check', { size: 11, strokeWidth: 3.2 }))),
53
+ label && h('label', { id: label.id, for: label.for, class: 'poad-checkbox__label' }, this.label),
54
+ this.content,
55
+ ]);
56
+ }
57
+ }
package/src/chip.ts ADDED
@@ -0,0 +1,54 @@
1
+ /**
2
+ * <poad-chip label="Paris" removable></poad-chip> <poad-chip label="Mine" clickable selected></poad-chip>
3
+ * <poad-chip label="szu" avatar-text="SZ"></poad-chip> <poad-chip label="Lyon" icon="map-pin" severity="info" size="sm"></poad-chip>
4
+ *
5
+ * Puce : classes, attributs et gestes de @poadio/ui-core (`chipClasses`, `chipProps`, `chipKeyAction`) — même DOM que
6
+ * `poad-chip` d'ui-angular. Évènements : `remove` (bouton ×, Retour arrière, Suppr sur une puce retirable) et `press`
7
+ * (clic, Entrée, Espace sur une puce cliquable) ; rien quand elle est désactivée. Le `click` natif, lui, remonte
8
+ * toujours : écouter `press`. Bouton de retrait nommé par le catalogue (`display.removeChip`). Style : `chip.css`.
9
+ */
10
+ import { chipClasses, chipClickAction, chipIconSize, chipKeyAction, chipProps, chipShowRemove, type ButtonSeverity } from '@poadio/ui-core';
11
+ import { avatar } from './avatar.js';
12
+ import { h } from './dom.js';
13
+ import { PoadElement } from './element.js';
14
+ import { icon } from './icon.js';
15
+
16
+ export class PoadChipElement extends PoadElement {
17
+ static override props = {
18
+ label: 'string', icon: 'string', image: 'string', avatarText: 'string', removable: 'boolean', selected: 'boolean', disabled: 'boolean',
19
+ clickable: 'boolean', size: 'string', severity: 'string',
20
+ } as const;
21
+ declare label?: string;
22
+ declare icon?: string;
23
+ declare image?: string | null;
24
+ declare avatarText?: string;
25
+ declare removable?: boolean;
26
+ declare selected?: boolean;
27
+ declare disabled?: boolean;
28
+ declare clickable?: boolean;
29
+ declare size?: 'sm' | 'md';
30
+ declare severity?: ButtonSeverity | null;
31
+
32
+ protected render() {
33
+ const attrs = chipProps(this);
34
+ const label = this.label ?? '';
35
+ return h('span', {
36
+ class: chipClasses(this), role: attrs.role, tabindex: attrs.tabindex, 'aria-pressed': attrs['aria-pressed'], 'aria-disabled': attrs['aria-disabled'],
37
+ onclick: (e: MouseEvent) => { if (chipClickAction(this)) this.emit('press', e); },
38
+ onkeydown: (e: KeyboardEvent) => {
39
+ const action = chipKeyAction(this, e.key);
40
+ if (!action) return;
41
+ e.preventDefault();
42
+ this.emit(action === 'remove' ? 'remove' : 'press', e);
43
+ },
44
+ }, [
45
+ this.image || this.avatarText ? avatar(this.icons(), { class: 'poad-chip__avatar', src: this.image, text: this.avatarText, size: 'sm' })
46
+ : this.icon && icon(this.icons(), this.icon, { size: chipIconSize(this) }),
47
+ h('span', { class: 'poad-chip__label' }, [label, this.content]),
48
+ chipShowRemove(this) && h('button', {
49
+ type: 'button', class: 'poad-chip__rm', 'aria-label': this.i18n().t('display.removeChip', { label }), tabindex: -1,
50
+ onclick: (e: MouseEvent) => { e.stopPropagation(); if (!this.disabled) this.emit('remove'); },
51
+ }, icon(this.icons(), 'x', { size: 11, strokeWidth: 2.4 })),
52
+ ]);
53
+ }
54
+ }
@@ -0,0 +1,173 @@
1
+ /**
2
+ * <poad-colorpicker name="accent" value="#3b82f6" format="hex" alpha clearable aria-label="Accent"></poad-colorpicker>
3
+ * <poad-colorpicker value="#3b82f6" inline></poad-colorpicker> sans panneau flottant
4
+ *
5
+ * Valeur = texte CSS (`format` : `hex` | `rgb` | `hsl`, opacité avec `alpha`). Panneau : zone saturation / luminosité,
6
+ * barres teinte (et opacité), pipette (`EyeDropper` si le navigateur l'a), champs HEX / R / G / B (/ A), palette
7
+ * (`presets`, propriété). Clavier : flèches sur les poignées (Maj = ×10). Logique : `colorpicker` d'ui-core ; panneau
8
+ * dans la couche flottante interne, fermé par Échap ou un appui extérieur, le focus revient au déclencheur. Même DOM,
9
+ * mêmes classes, même ARIA que `poad-colorpicker` d'ui-angular. Propriété `value` ; évènements `input` / `change`
10
+ * (detail : la couleur, `null` effacée), `openchange`. Formulaire : `name`, `required`. Style : `colorpicker.css`,
11
+ * `floating.css`, `icon.css`.
12
+ */
13
+ import {
14
+ COLORPICKER_PLACEMENTS, COLOR_PRESETS, colorpickerCanOpen, colorpickerDismiss, colorpickerFraction, colorpickerFromAlpha, colorpickerFromChannel,
15
+ colorpickerFromEyedropper, colorpickerFromHex, colorpickerFromPreset, colorpickerHsv, colorpickerKey, colorpickerPoint, colorpickerPresetSelected,
16
+ colorpickerRootClasses, colorpickerTriggerProps, colorpickerView, colorpickerWrite, type ColorFormat, type ColorHsva, type ColorpickerPart,
17
+ } from '@poadio/ui-core';
18
+ import { h, type Child } from './dom.js';
19
+ import { PoadFormElement } from './element.js';
20
+ import { FloatingTracker, Listening, listenOutside } from './floating.js';
21
+ import { icon } from './icon.js';
22
+
23
+ type EyeDropperCtor = new () => { open(): Promise<{ sRGBHex: string }> };
24
+
25
+ export class PoadColorpickerElement extends PoadFormElement {
26
+ static override props = {
27
+ value: 'string', format: 'string', alpha: 'boolean', inline: 'boolean', presets: 'json', placeholder: 'string', clearable: 'boolean', invalid: 'boolean',
28
+ disabled: 'boolean', size: 'string', ariaLabel: 'string', name: 'string', required: 'boolean',
29
+ } as const;
30
+ declare value?: string | null;
31
+ declare format?: ColorFormat;
32
+ declare alpha?: boolean;
33
+ declare inline?: boolean;
34
+ declare presets?: readonly string[];
35
+ declare placeholder?: string;
36
+ declare clearable?: boolean;
37
+ declare invalid?: boolean;
38
+ declare disabled?: boolean;
39
+ declare size?: 'sm' | 'md' | 'lg';
40
+ declare ariaLabel: string | null;
41
+ declare name?: string;
42
+ declare required?: boolean;
43
+ protected readonly resetProps = ['value'];
44
+ private local: ColorHsva | null = null;
45
+ private opened = false;
46
+ private readonly tracker = new FloatingTracker(() => this.update());
47
+ private readonly outside = new Listening(() => listenOutside(() => [this.find('.cp-trigger'), this.find('.poad-floating')], () => this.setOpen(false)));
48
+
49
+ private find<E extends HTMLElement>(selector: string): E | null {
50
+ return this.querySelector<E>(`:scope > .poad-colorpicker ${selector}`);
51
+ }
52
+ private get hsv() {
53
+ return colorpickerHsv(this.value ?? null, this.local);
54
+ }
55
+ private setOpen(next: boolean) {
56
+ if (next === this.opened) return;
57
+ if (next && !colorpickerCanOpen({ open: this.opened, disabled: this.inactive })) return;
58
+ this.opened = next;
59
+ this.update();
60
+ this.emit('openchange', next);
61
+ if (!next) this.find('.cp-trigger')?.focus();
62
+ }
63
+ private set(hsv: ColorHsva | null) {
64
+ if (!hsv) return;
65
+ this.local = hsv;
66
+ const s = colorpickerWrite(hsv, this.format ?? 'hex', !!this.alpha, this.value ?? null);
67
+ if (s === null) return this.update();
68
+ this.value = s;
69
+ this.changed(s);
70
+ }
71
+ private drag(e: PointerEvent, part: ColorpickerPart) {
72
+ const el = e.currentTarget as HTMLElement;
73
+ if (this.inactive) return;
74
+ e.preventDefault();
75
+ const r = el.getBoundingClientRect();
76
+ let latest = this.hsv;
77
+ const upd = (ev: { clientX: number; clientY: number }) => {
78
+ const f = colorpickerFraction(ev.clientX, ev.clientY, r);
79
+ latest = colorpickerPoint(part, f.x, f.y, latest);
80
+ this.set(latest);
81
+ };
82
+ upd(e);
83
+ const up = () => { window.removeEventListener('pointermove', upd); window.removeEventListener('pointerup', up); };
84
+ window.addEventListener('pointermove', upd); window.addEventListener('pointerup', up);
85
+ el.focus();
86
+ }
87
+ private readonly onKey = (e: KeyboardEvent) => { if (this.opened && colorpickerDismiss({ type: 'keydown', key: e.key }).action === 'close') this.setOpen(false); };
88
+ protected formValue() {
89
+ return { value: this.value || null, missing: !this.value };
90
+ }
91
+ override disconnectedCallback(): void {
92
+ super.disconnectedCallback();
93
+ this.tracker.sync(null, null);
94
+ this.outside.toggle(false);
95
+ }
96
+ protected render() {
97
+ const { t, text, locale } = this.i18n();
98
+ const registry = this.icons();
99
+ const hsv = this.hsv, alpha = !!this.alpha;
100
+ const view = colorpickerView(hsv, alpha);
101
+ const percent = (v: number) => new Intl.NumberFormat(locale, { style: 'percent', maximumFractionDigits: 0 }).format(v);
102
+ const slider = (part: ColorpickerPart, props: Record<string, unknown>, children: Child) => h('div', {
103
+ tabindex: 0, role: 'slider', ...props, onpointerdown: (e: PointerEvent) => this.drag(e, part),
104
+ onkeydown: (e: KeyboardEvent) => { const next = colorpickerKey(part, e.key, e.shiftKey, this.hsv); if (next) { e.preventDefault(); this.set(next); } },
105
+ }, children);
106
+ const hex = (e: Event) => this.set(colorpickerFromHex((e.target as HTMLInputElement).value));
107
+ const presets = this.presets ?? COLOR_PRESETS;
108
+ const panel = [
109
+ slider('sv', {
110
+ class: 'cp-sv', style: { backgroundColor: view.hueCss }, 'aria-label': t('field.saturationBrightness'),
111
+ 'aria-valuetext': t('field.saturationBrightnessValue', { saturation: percent(view.saturation), brightness: percent(view.brightness) }),
112
+ }, h('span', { class: 'cp-sv__thumb', style: { left: `${view.sv.left}%`, top: `${view.sv.top}%`, background: view.opaqueCss } })),
113
+ h('div', { class: 'cp-bars' }, [
114
+ h('button', {
115
+ type: 'button', class: 'cp-eye', style: { visibility: typeof window !== 'undefined' && 'EyeDropper' in window ? 'visible' : 'hidden' },
116
+ title: t('field.eyedropper'), 'aria-label': t('field.eyedropper'),
117
+ onclick: async () => {
118
+ try {
119
+ const ED = (window as unknown as { EyeDropper?: EyeDropperCtor }).EyeDropper;
120
+ if (ED) this.set(colorpickerFromEyedropper((await new ED().open()).sRGBHex, this.hsv));
121
+ } catch { /* annulé */ }
122
+ },
123
+ }, icon(registry, 'crosshair', { size: 14 })),
124
+ h('div', { class: 'cp-sliders' }, [
125
+ slider('hue', { class: 'cp-bar cp-bar--hue', 'aria-label': t('field.hue'), 'aria-valuemin': 0, 'aria-valuemax': 360, 'aria-valuenow': view.hueNow },
126
+ h('span', { class: 'cp-bar__thumb', style: { left: `${view.hue}%`, background: view.hueCss } })),
127
+ alpha && slider('alpha', { class: 'cp-bar cp-bar--alpha', 'aria-label': t('field.opacity'), 'aria-valuemin': 0, 'aria-valuemax': 100, 'aria-valuenow': view.alphaNow }, [
128
+ h('i', { class: 'cp-bar__grad', style: { background: `linear-gradient(to right, transparent, ${view.opaqueCss})` } }),
129
+ h('span', { class: 'cp-bar__thumb', style: { left: `${view.alpha}%`, background: view.css } }),
130
+ ]),
131
+ ]),
132
+ ]),
133
+ h('div', { class: 'cp-fields' }, [
134
+ h('label', [h('span', 'HEX'), h('input', { type: 'text', value: view.hex, spellcheck: 'false', onblur: hex, onkeydown: (e: KeyboardEvent) => { if (e.key === 'Enter') hex(e); } })]),
135
+ (['r', 'g', 'b'] as const).map((c) => h('label', [h('span', c.toUpperCase()), h('input', {
136
+ type: 'number', min: 0, max: 255, value: String(view.rgb[c]), oninput: (e: Event) => this.set(colorpickerFromChannel(view.rgb, c, (e.target as HTMLInputElement).value)),
137
+ })])),
138
+ alpha && h('label', [h('span', 'A'), h('input', {
139
+ type: 'number', min: 0, max: 100, value: String(view.alphaNow), oninput: (e: Event) => this.set(colorpickerFromAlpha(hsv, (e.target as HTMLInputElement).value)),
140
+ })]),
141
+ ]),
142
+ presets.length > 0 && h('div', { class: 'cp-presets', role: 'listbox', 'aria-label': t('field.presets') }, presets.map((p) => {
143
+ const on = colorpickerPresetSelected(p, view.rgb);
144
+ return h('button', { type: 'button', role: 'option', 'aria-selected': String(on), class: on ? 'is-on' : undefined, style: { background: p }, title: p, onclick: () => this.set(colorpickerFromPreset(p)) });
145
+ })),
146
+ ];
147
+ const tr = colorpickerTriggerProps({ open: this.opened, invalid: this.invalid });
148
+ const current = this.value || null;
149
+ return h('div', { class: ['poad-colorpicker', colorpickerRootClasses({ open: this.opened, disabled: this.inactive, invalid: this.invalid, inline: this.inline, size: this.size ?? 'md' })] },
150
+ this.inline ? h('div', { class: 'poad-colorpicker-panel cp-panel is-inline' }, panel) : [
151
+ h('button', {
152
+ type: 'button', class: 'cp-trigger', disabled: this.inactive, 'aria-expanded': tr['aria-expanded'], 'aria-haspopup': tr['aria-haspopup'],
153
+ 'aria-label': this.ariaLabel || t('field.color'), 'aria-invalid': tr['aria-invalid'], onclick: () => this.setOpen(!this.opened), onkeydown: this.onKey,
154
+ }, [
155
+ h('span', { class: 'cp-swatch', style: { background: view.css } }, h('i')),
156
+ h('span', { class: ['cp-val', { 'is-ph': !current }] }, current || text(this.placeholder, 'field.colorPlaceholder')),
157
+ this.clearable && current && !this.inactive && h('span', {
158
+ class: 'cp-clear', role: 'button', 'aria-label': t('common.clear'),
159
+ onclick: (e: MouseEvent) => { e.stopPropagation(); this.local = null; this.value = null; this.changed(null); },
160
+ }, icon(registry, 'x', { size: 12 })),
161
+ icon(registry, 'chevron-down', { size: 13, class: 'cp-chev' }),
162
+ ]),
163
+ this.opened && h('div', { class: 'poad-floating', style: this.tracker.style },
164
+ h('div', { class: 'poad-colorpicker-panel cp-panel', role: 'dialog', 'aria-label': t('field.colorPicker'), onkeydown: this.onKey }, panel)),
165
+ ]);
166
+ }
167
+ protected override updated(): void {
168
+ super.updated();
169
+ const floating = this.opened && !this.inline;
170
+ this.tracker.sync(floating ? this.find('.cp-trigger') : null, floating ? this.find('.poad-floating') : null, { candidates: COLORPICKER_PLACEMENTS, offset: 0, shift: true });
171
+ this.outside.toggle(floating);
172
+ }
173
+ }
package/src/define.ts ADDED
@@ -0,0 +1,4 @@
1
+ /** `import '@poadio/ui-elements/define'` : enregistre les éléments sous leurs noms par défaut (`<poad-switch>`…). */
2
+ import { defineElements } from './index.js';
3
+
4
+ defineElements();
package/src/divider.ts ADDED
@@ -0,0 +1,22 @@
1
+ /**
2
+ * <poad-divider></poad-divider> <poad-divider align="left">Section</poad-divider> <poad-divider vertical dashed></poad-divider>
3
+ *
4
+ * Séparateur : classes et attributs de @poadio/ui-core (`dividerClasses`, `dividerProps`) — même DOM que
5
+ * `poad-divider` d'ui-angular (`role="separator"`, contenu dans `.poad-divider__txt`). Propriété `text` : le texte en
6
+ * données. Style : `@poadio/ui-core/divider.css`.
7
+ */
8
+ import { dividerClasses, dividerProps } from '@poadio/ui-core';
9
+ import { h } from './dom.js';
10
+ import { PoadElement } from './element.js';
11
+
12
+ export class PoadDividerElement extends PoadElement {
13
+ static override props = { vertical: 'boolean', dashed: 'boolean', align: 'string', text: 'string' } as const;
14
+ declare vertical?: boolean;
15
+ declare dashed?: boolean;
16
+ declare align?: 'left' | 'center' | 'right';
17
+ declare text?: string;
18
+
19
+ protected render() {
20
+ return h('div', { class: dividerClasses(this), ...dividerProps(this) }, h('span', { class: 'poad-divider__txt' }, [this.text, this.content]));
21
+ }
22
+ }
package/src/dom.ts ADDED
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Rendu des composants web : `h(tag, props, enfants)` décrit le DOM voulu, `patch(parent, enfants)` y amène le DOM
3
+ * réel en RÉUTILISANT les nœuds en place (même balise à la même position) — le focus, la sélection d'un champ et les
4
+ * écouteurs survivent à un nouveau rendu. Pas de clés : les listes de la bibliothèque sont courtes et stables.
5
+ *
6
+ * Un enfant peut être un nœud du DOM existant (contenu de l'application capturé par un élément) : il est posé à sa
7
+ * place tel quel, jamais modifié. Interne au paquet.
8
+ */
9
+ export interface VNode {
10
+ readonly tag: string;
11
+ readonly props: Props;
12
+ readonly children: readonly Child[];
13
+ }
14
+ export type Props = Readonly<Record<string, unknown>>;
15
+ export type Child = VNode | Node | string | number | null | undefined | false | readonly Child[];
16
+
17
+ export function h(tag: string, props?: Props | Child, children?: Child): VNode {
18
+ const hasProps = props != null && typeof props === 'object' && !Array.isArray(props) && !('tag' in props) && !('nodeType' in props);
19
+ const kids = hasProps ? children : (props as Child);
20
+ return { tag, props: hasProps ? (props as Props) : {}, children: kids === undefined ? [] : [kids] };
21
+ }
22
+
23
+ const SVG = 'http://www.w3.org/2000/svg';
24
+ /** Nœuds créés par `patch` : seuls ceux-là sont réutilisés (le contenu de l'application n'est jamais modifié). */
25
+ const owned = new WeakSet<Node>();
26
+ const applied = new WeakMap<Element, Props>();
27
+ const handlers = new WeakMap<Element, Record<string, EventListener>>();
28
+
29
+ // Pas `'tag' in c` seul : nos éléments ont une méthode `tag()` — un <poad-…> écrit par l'application est un nœud du DOM.
30
+ const isVNode = (c: unknown): c is VNode => typeof c === 'object' && c !== null && !('nodeType' in c) && 'tag' in c;
31
+ function flat(children: readonly Child[], out: (VNode | Node | string)[] = []): (VNode | Node | string)[] {
32
+ for (const c of children) {
33
+ if (c == null || c === false || c === '') continue;
34
+ if (Array.isArray(c)) flat(c, out);
35
+ else out.push(typeof c === 'number' ? String(c) : (c as VNode | Node | string));
36
+ }
37
+ return out;
38
+ }
39
+
40
+ export const classOf = (value: unknown): string =>
41
+ Array.isArray(value) ? value.map(classOf).filter(Boolean).join(' ')
42
+ : value && typeof value === 'object' ? Object.entries(value).filter(([, on]) => on).map(([k]) => k).join(' ')
43
+ : value ? String(value) : '';
44
+
45
+ const kebab = (s: string) => s.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`);
46
+ const styleOf = (value: unknown): string =>
47
+ value && typeof value === 'object' ? Object.entries(value).filter(([, v]) => v != null && v !== '').map(([k, v]) => `${kebab(k)}: ${v}`).join('; ') : String(value ?? '');
48
+
49
+ function setProp(el: Element, key: string, value: unknown, previous: unknown) {
50
+ if (key === 'ref') return void (typeof value === 'function' && value(el));
51
+ if (key.startsWith('on') && key.length > 2) {
52
+ const type = key.slice(2).toLowerCase();
53
+ const table = handlers.get(el) ?? {};
54
+ handlers.set(el, table);
55
+ if (!table[type] && typeof value === 'function') el.addEventListener(type, (e) => table[type]?.(e));
56
+ table[type] = value as EventListener;
57
+ return;
58
+ }
59
+ // Propriétés vivantes : le contenu d'un <svg>, la valeur d'un champ (pas l'attribut, qui n'est que la valeur de départ).
60
+ if (key === 'innerHTML' || (key === 'value' && (el.localName === 'input' || el.localName === 'textarea'))) {
61
+ if ((el as unknown as Record<string, unknown>)[key] !== value) (el as unknown as Record<string, unknown>)[key] = value ?? '';
62
+ return;
63
+ }
64
+ if (Object.is(value, previous) && key !== 'class') return;
65
+ const text = key === 'class' ? classOf(value) : key === 'style' ? styleOf(value) : value;
66
+ if (text == null || text === false || ((key === 'class' || key === 'style') && text === '')) el.removeAttribute(key);
67
+ else el.setAttribute(key, text === true ? '' : String(text));
68
+ }
69
+
70
+ function update(el: Element, vnode: VNode) {
71
+ const before = applied.get(el) ?? {};
72
+ for (const key of Object.keys(before)) if (!(key in vnode.props)) setProp(el, key, undefined, before[key]);
73
+ for (const [key, value] of Object.entries(vnode.props)) setProp(el, key, value, before[key]);
74
+ applied.set(el, vnode.props);
75
+ if (!('innerHTML' in vnode.props)) patch(el, vnode.children);
76
+ }
77
+
78
+ function create(vnode: VNode, svg: boolean): Element {
79
+ const el = svg || vnode.tag === 'svg' ? document.createElementNS(SVG, vnode.tag) : document.createElement(vnode.tag);
80
+ owned.add(el);
81
+ return el;
82
+ }
83
+
84
+ /** Amène les enfants de `parent` à `children`, en réutilisant ceux qui conviennent. */
85
+ export function patch(parent: Element, children: readonly Child[]): void {
86
+ const wanted = flat(children);
87
+ const svg = parent.namespaceURI === SVG;
88
+ wanted.forEach((want, i) => {
89
+ const here = parent.childNodes[i] ?? null;
90
+ if (typeof want === 'string') {
91
+ if (here && owned.has(here) && here.nodeType === 3) { if (here.nodeValue !== want) here.nodeValue = want; return; }
92
+ const text = document.createTextNode(want);
93
+ owned.add(text);
94
+ parent.insertBefore(text, here);
95
+ } else if (isVNode(want)) {
96
+ let el = here && owned.has(here) && (here as Element).localName === want.tag ? (here as Element) : null;
97
+ if (!el) parent.insertBefore((el = create(want, svg)), here);
98
+ update(el, want);
99
+ } else if (here !== want) parent.insertBefore(want, here);
100
+ });
101
+ while (parent.childNodes.length > wanted.length) parent.lastChild!.remove();
102
+ }
package/src/element.ts ADDED
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Base des composants web : attributs ↔ propriétés, rendu en DOM LÉGER, langue, participation aux formulaires.
3
+ *
4
+ * - Chaque propriété déclarée (`static props`) a son attribut en kebab-case (`labelPosition` ↔ `label-position`) ;
5
+ * l'attribut fixe la propriété, la propriété ne réécrit pas l'attribut. Types : `string`, `number`, `boolean`
6
+ * (présent = vrai, `"false"` = faux, absent = défaut du composant), `json` (tableaux et objets : `options='[…]'` ;
7
+ * ce qui n'est pas du JSON reste une chaîne : `value="d"`).
8
+ * - Rendu synchrone : changer une propriété redessine l'élément tout de suite (`patch` réutilise les nœuds). Le
9
+ * contenu de l'application (enfants écrits dans la page) est capturé à la première connexion et reposé à sa place.
10
+ * - `aria-label` posé sur l'élément est lu puis RETIRÉ de l'hôte (sans rôle, il n'y nommerait rien) et porté par le
11
+ * contrôle intérieur.
12
+ * - Sans DOM (Node, rendu serveur), le module se charge : la classe de base est alors une classe vide.
13
+ */
14
+ import type { IconRegistry } from '@poadio/ui-core';
15
+ import { patch, type Child } from './dom.js';
16
+ import { iconRegistry, track, uiI18nOf, type UiI18nValue } from './i18n.js';
17
+
18
+ export type PropType = 'string' | 'number' | 'boolean' | 'json';
19
+ const Base = (typeof HTMLElement === 'undefined' ? class {} : HTMLElement) as typeof HTMLElement;
20
+ const kebab = (s: string) => s.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`);
21
+ let ids = 0;
22
+
23
+ function parse(type: PropType, value: string | null): unknown {
24
+ if (value === null) return undefined;
25
+ if (type === 'boolean') return value !== 'false';
26
+ if (type === 'number') return Number(value);
27
+ if (type === 'json') {
28
+ try { return JSON.parse(value); } catch { return value; } // value="d" : une chaîne telle quelle
29
+ }
30
+ return value;
31
+ }
32
+
33
+ /**
34
+ * Données d'un élément de DÉCLARATION lu par son groupe (`<poad-radio>`, `<poad-avatar>`) : chaque propriété, sinon
35
+ * son attribut (élément pas encore défini).
36
+ */
37
+ export function declared<T>(el: Element, props: Readonly<Record<string, PropType>>): T {
38
+ return Object.fromEntries(Object.entries(props).map(([name, type]) =>
39
+ [name, (el as unknown as Record<string, unknown>)[name] ?? parse(type, el.getAttribute(kebab(name)))])) as T;
40
+ }
41
+
42
+ export abstract class PoadElement extends Base {
43
+ static props: Readonly<Record<string, PropType>> = {};
44
+ /** Préfixe des balises de cette définition (`poad` → `<poad-radio>`), posé par `defineElements`. */
45
+ static prefix = 'poad';
46
+ static get observedAttributes(): string[] {
47
+ return Object.keys(this.props).map(kebab);
48
+ }
49
+ /** Déclare les propriétés (accesseurs) d'une classe d'élément : appelé par `defineElements`. */
50
+ static install(): void {
51
+ for (const name of Object.keys(this.props)) {
52
+ if (Object.prototype.hasOwnProperty.call(this.prototype, name)) continue;
53
+ Object.defineProperty(this.prototype, name, {
54
+ configurable: true,
55
+ get(this: PoadElement) { return this.propValues[name]; },
56
+ set(this: PoadElement, value: unknown) { this.propValues[name] = value; this.update(); },
57
+ });
58
+ }
59
+ }
60
+
61
+ protected propValues: Record<string, unknown> = {};
62
+ /** Contenu écrit par l'application, capturé à la première connexion. */
63
+ protected content: Node[] | null = null;
64
+ /** Identifiant stable de l'instance, pour les liens `for` / `aria-*`. */
65
+ protected readonly uid = `poad-el-${++ids}`;
66
+ private removing = false;
67
+
68
+ connectedCallback(): void {
69
+ // Défini avant que la page soit lue (script classique en tête) : les enfants ne sont pas encore là.
70
+ if (!this.content && this.ownerDocument.readyState === 'loading') {
71
+ this.ownerDocument.addEventListener('DOMContentLoaded', () => this.isConnected && this.connectedCallback(), { once: true });
72
+ return;
73
+ }
74
+ // Propriétés posées avant la définition de l'élément : elles masquent les accesseurs, on les rejoue.
75
+ for (const name of Object.keys((this.constructor as typeof PoadElement).props)) {
76
+ if (!Object.prototype.hasOwnProperty.call(this, name)) continue;
77
+ const value = (this as unknown as Record<string, unknown>)[name];
78
+ delete (this as unknown as Record<string, unknown>)[name];
79
+ (this as unknown as Record<string, unknown>)[name] = value;
80
+ }
81
+ this.content ??= this.capture();
82
+ track(this, true);
83
+ this.update();
84
+ }
85
+ disconnectedCallback(): void {
86
+ track(this, false);
87
+ }
88
+ attributeChangedCallback(attr: string, _old: string | null, value: string | null): void {
89
+ if (this.removing) return;
90
+ const props = (this.constructor as typeof PoadElement).props;
91
+ const name = Object.keys(props).find((p) => kebab(p) === attr)!;
92
+ (this as unknown as Record<string, unknown>)[name] = parse(props[name]!, value);
93
+ }
94
+
95
+ /** Contenu de l'application : par défaut, tous les enfants. */
96
+ protected capture(): Node[] {
97
+ return [...this.childNodes];
98
+ }
99
+ /** Le DOM voulu, à partir des propriétés. */
100
+ protected abstract render(): Child;
101
+ /** Après chaque rendu (formulaire, liens vers le contenu de l'application). */
102
+ protected updated(): void {}
103
+
104
+ update(): void {
105
+ if (!this.isConnected || !this.content) return;
106
+ // Retiré ici, pas dans attributeChangedCallback : pendant la mise à niveau, retirer un attribut ferait sauter au
107
+ // navigateur l'attribut suivant (options="…" après aria-label="…").
108
+ if (this.hasAttribute('aria-label')) {
109
+ this.removing = true;
110
+ this.removeAttribute('aria-label');
111
+ this.removing = false;
112
+ }
113
+ patch(this, [this.render()]);
114
+ this.updated();
115
+ }
116
+ protected emit(type: string, detail?: unknown): boolean {
117
+ return this.dispatchEvent(new CustomEvent(type, { detail, bubbles: true, composed: true }));
118
+ }
119
+ protected i18n(): UiI18nValue {
120
+ return uiI18nOf(this);
121
+ }
122
+ protected icons(): IconRegistry {
123
+ return iconRegistry();
124
+ }
125
+ /** Balise d'un autre élément de la même définition : `tag('radio')` → `poad-radio`. */
126
+ protected tag(name: string): string {
127
+ return `${(this.constructor as typeof PoadElement).prefix}-${name}`;
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Élément qui porte une valeur de formulaire (interrupteur, case, radios, bascule, choix segmenté, liste) :
133
+ * ElementInternals — valeur soumise (`name`), désactivation par un `<fieldset disabled>`, remise à zéro du formulaire
134
+ * (retour aux attributs), validité (`required`). Sans ElementInternals (vieux navigateur), rien de tout cela, le reste
135
+ * fonctionne.
136
+ */
137
+ export abstract class PoadFormElement extends PoadElement {
138
+ static formAssociated = true;
139
+ protected internals: ElementInternals | null = typeof this.attachInternals === 'function' ? this.attachInternals() : null;
140
+ private formDisabled = false;
141
+
142
+ /** Valeur soumise (`null` : rien), et si elle manque alors que `required` est posé. */
143
+ protected abstract formValue(): { readonly value: string | FormData | null; readonly missing: boolean };
144
+ /** Propriétés remises à leur attribut par `form.reset()`. */
145
+ protected abstract readonly resetProps: readonly string[];
146
+
147
+ get form(): HTMLFormElement | null { return this.internals?.form ?? null; }
148
+ get validity(): ValidityState | undefined { return this.internals?.validity; }
149
+ get validationMessage(): string { return this.internals?.validationMessage ?? ''; }
150
+ checkValidity(): boolean { return this.internals?.checkValidity() ?? true; }
151
+ reportValidity(): boolean { return this.internals?.reportValidity() ?? true; }
152
+
153
+ /** Désactivé par sa propriété ou par un `<fieldset disabled>` parent. */
154
+ protected get inactive(): boolean {
155
+ return !!this.propValues['disabled'] || this.formDisabled;
156
+ }
157
+ formDisabledCallback(disabled: boolean): void {
158
+ this.formDisabled = disabled;
159
+ this.update();
160
+ }
161
+ formResetCallback(): void {
162
+ const props = (this.constructor as typeof PoadElement).props;
163
+ for (const name of this.resetProps) (this as unknown as Record<string, unknown>)[name] = parse(props[name]!, this.getAttribute(kebab(name)));
164
+ }
165
+ protected override updated(): void {
166
+ // jsdom et les navigateurs anciens : ElementInternals absent ou sans formulaire.
167
+ if (typeof this.internals?.setFormValue !== 'function') return;
168
+ const { value, missing } = this.formValue();
169
+ this.internals.setFormValue(value);
170
+ // Message du navigateur, dans sa langue (aucun texte de la bibliothèque) : celui d'un champ requis vide.
171
+ if (missing && this.propValues['required']) {
172
+ const probe = document.createElement('input');
173
+ probe.required = true;
174
+ this.internals.setValidity({ valueMissing: true }, probe.validationMessage || ' ');
175
+ } else this.internals.setValidity({});
176
+ }
177
+ /** Nouvelle valeur choisie par l'utilisateur : `input` puis `change`, comme un contrôle natif. */
178
+ protected changed(detail: unknown): void {
179
+ this.emit('input', detail);
180
+ this.emit('change', detail);
181
+ }
182
+ }