@tangible/ui 0.2.52 → 0.2.54

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 (43) hide show
  1. package/components/Accordion/Accordion.js +10 -4
  2. package/components/Checkbox/Checkbox.js +7 -2
  3. package/components/ColorPicker/ColorField.js +15 -4
  4. package/components/DatePicker/DatePicker.js +2 -1
  5. package/components/DatePicker/DateRangePicker.js +2 -1
  6. package/components/DatePicker/PickerTrigger.js +2 -1
  7. package/components/Field/Field.js +19 -0
  8. package/components/Pager/Pager.d.ts +2 -1
  9. package/components/Pager/Pager.js +3 -114
  10. package/components/Switch/Switch.js +2 -0
  11. package/components/index.d.ts +2 -0
  12. package/components/index.js +3 -0
  13. package/figma-tokens.json +1 -1
  14. package/icons/icons.svg +1 -1
  15. package/icons/sprite-version.js +1 -1
  16. package/icons/sprite.php +1 -1
  17. package/package.json +9 -1
  18. package/skills/building-with-tui/SKILL.md +48 -2
  19. package/styles/all.css +1 -1
  20. package/styles/all.expanded.css +65 -25
  21. package/styles/all.expanded.unlayered.css +65 -25
  22. package/styles/all.unlayered.css +1 -1
  23. package/styles/components/checkbox.scss +53 -12
  24. package/styles/components/color-picker.scss +4 -1
  25. package/styles/components/move-handle.scss +17 -5
  26. package/styles/core.css +1 -1
  27. package/styles/core.unlayered.css +1 -1
  28. package/styles/index.scss +14 -0
  29. package/tui-manifest.json +5 -3
  30. package/utils/focus-trap.js +9 -2
  31. package/utils/pager.d.ts +49 -0
  32. package/utils/pager.js +129 -0
  33. package/utils/self-labelling.d.ts +12 -0
  34. package/utils/self-labelling.js +18 -0
  35. package/utils/tabbable.d.ts +1 -1
  36. package/utils/tabbable.js +20 -5
  37. package/vanilla/accordion.d.ts +94 -0
  38. package/vanilla/accordion.js +317 -0
  39. package/vanilla/accordion.min.js +1 -0
  40. package/vanilla/modal.js +2 -2
  41. package/vanilla/modal.min.js +1 -1
  42. package/vanilla/styles.css +1 -1
  43. package/vanilla/styles.unlayered.css +1 -1
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Vanilla accordion: TUI's Accordion for markup with no React behind it
3
+ * (Tangible Blocks, L&L templates, plain PHP). Behaviour hangs off
4
+ * `data-tui-accordion-*` attributes, not classes, so the reference markup can
5
+ * wear the React Accordion's classes and tokens while a consumer with its own
6
+ * look (SearchSync's filter panels) adds only the attributes.
7
+ *
8
+ * What it owns, so server markup can't get it wrong:
9
+ *
10
+ * - `aria-expanded` on the trigger and `data-state` (`open` | `closed`) on the
11
+ * item, trigger and panel, kept in step
12
+ * - a closed panel is `inert` and `aria-hidden`, so Tab and screen readers
13
+ * skip what can't be seen (a grid-row collapse alone hides nothing, #255)
14
+ * - `id` and `aria-controls` filled in when the markup leaves them out
15
+ * - single mode closes the other items; `data-tui-accordion-collapsible` lets
16
+ * the open one close too (multiple mode always can), as in React
17
+ * - closing a panel that holds focus moves focus to its trigger
18
+ * - in single, non-collapsible mode the open header is `aria-disabled` (APG),
19
+ * still focusable and not painted disabled; an author's own `aria-disabled`
20
+ * is left alone
21
+ *
22
+ * Markup:
23
+ *
24
+ * <div class="tui-accordion" data-tui-accordion="single" data-tui-accordion-collapsible>
25
+ * <div class="tui-accordion__item" data-tui-accordion-item data-state="open">
26
+ * <h3 class="tui-accordion__heading">
27
+ * <button type="button" class="tui-accordion__trigger" data-tui-accordion-trigger>
28
+ * <span class="tui-accordion__trigger-content">Brand</span>
29
+ * <span class="tui-accordion__indicator" aria-hidden="true">…chevron…</span>
30
+ * </button>
31
+ * </h3>
32
+ * <div class="tui-accordion__panel" data-tui-accordion-panel>
33
+ * <div class="tui-accordion__panel-content">…</div>
34
+ * </div>
35
+ * </div>
36
+ * </div>
37
+ *
38
+ * `data-tui-accordion` is `single` (default) or `multiple`. An item starts open
39
+ * with `data-state="open"` on the item or `aria-expanded="true"` on its
40
+ * trigger. The trigger must be a <button>: Enter and Space come from the
41
+ * platform, and nothing here adds key handling. Put it in a heading at the
42
+ * level the page needs. A disabled trigger (`disabled` or
43
+ * `aria-disabled="true"`) doesn't toggle.
44
+ *
45
+ * The React Accordion puts `data-tui-accordion-trigger` on its triggers too, as
46
+ * a styling hook. Without `data-tui-accordion` and `data-tui-accordion-item`
47
+ * around them, this script ignores them, so the two can share a page.
48
+ *
49
+ * Each toggle fires `tui-accordion-toggle` on the item (bubbles), with
50
+ * `{ open, trigger, panel }`. State lives in the DOM, so two copies of the
51
+ * script on one page agree.
52
+ */
53
+ /** Fired on the item after it opens or closes. Bubbles. */
54
+ export declare const ACCORDION_TOGGLE_EVENT = "tui-accordion-toggle";
55
+ export type AccordionToggleEventDetail = {
56
+ open: boolean;
57
+ trigger: HTMLElement;
58
+ panel: HTMLElement;
59
+ };
60
+ /** An item, its trigger or its panel, or the id of any of them. */
61
+ export type AccordionTarget = string | Element;
62
+ /**
63
+ * Brings markup in line with its state: ids, `aria-controls`, `inert` on
64
+ * closed panels, and one open item in single mode. The standalone script runs
65
+ * it on the whole page at load; call it for markup added later. Toggling an
66
+ * item syncs it anyway, so this is about first paint.
67
+ */
68
+ export declare function sync(scope?: ParentNode): void;
69
+ /**
70
+ * Opens an item (closing its siblings in single mode). Returns false only
71
+ * when the target isn't an accordion item. Closing a sibling that holds focus
72
+ * moves focus to that sibling's trigger.
73
+ */
74
+ export declare function open(target: AccordionTarget): boolean;
75
+ /**
76
+ * Closes an item. Programmatic closes ignore `collapsible`, as React's
77
+ * controlled value does. Returns false only when the target isn't an item.
78
+ */
79
+ export declare function close(target: AccordionTarget): boolean;
80
+ /**
81
+ * Toggles an item the way a click on its trigger would (so a disabled or
82
+ * non-collapsible open item stays put). Returns the item's open state
83
+ * afterwards, or null when the target isn't an item.
84
+ */
85
+ export declare function toggle(target: AccordionTarget): boolean | null;
86
+ /**
87
+ * Wires every `data-tui-accordion` on the page through one delegated click
88
+ * listener, so markup added later works without another call (run `sync()` on
89
+ * it to fix its first paint). Calls are counted: the listener comes off when
90
+ * every caller has run its teardown.
91
+ *
92
+ * The standalone script (`vanilla/accordion.min.js`) calls this itself.
93
+ */
94
+ export declare function init(): () => void;
@@ -0,0 +1,317 @@
1
+ /**
2
+ * Vanilla accordion: TUI's Accordion for markup with no React behind it
3
+ * (Tangible Blocks, L&L templates, plain PHP). Behaviour hangs off
4
+ * `data-tui-accordion-*` attributes, not classes, so the reference markup can
5
+ * wear the React Accordion's classes and tokens while a consumer with its own
6
+ * look (SearchSync's filter panels) adds only the attributes.
7
+ *
8
+ * What it owns, so server markup can't get it wrong:
9
+ *
10
+ * - `aria-expanded` on the trigger and `data-state` (`open` | `closed`) on the
11
+ * item, trigger and panel, kept in step
12
+ * - a closed panel is `inert` and `aria-hidden`, so Tab and screen readers
13
+ * skip what can't be seen (a grid-row collapse alone hides nothing, #255)
14
+ * - `id` and `aria-controls` filled in when the markup leaves them out
15
+ * - single mode closes the other items; `data-tui-accordion-collapsible` lets
16
+ * the open one close too (multiple mode always can), as in React
17
+ * - closing a panel that holds focus moves focus to its trigger
18
+ * - in single, non-collapsible mode the open header is `aria-disabled` (APG),
19
+ * still focusable and not painted disabled; an author's own `aria-disabled`
20
+ * is left alone
21
+ *
22
+ * Markup:
23
+ *
24
+ * <div class="tui-accordion" data-tui-accordion="single" data-tui-accordion-collapsible>
25
+ * <div class="tui-accordion__item" data-tui-accordion-item data-state="open">
26
+ * <h3 class="tui-accordion__heading">
27
+ * <button type="button" class="tui-accordion__trigger" data-tui-accordion-trigger>
28
+ * <span class="tui-accordion__trigger-content">Brand</span>
29
+ * <span class="tui-accordion__indicator" aria-hidden="true">…chevron…</span>
30
+ * </button>
31
+ * </h3>
32
+ * <div class="tui-accordion__panel" data-tui-accordion-panel>
33
+ * <div class="tui-accordion__panel-content">…</div>
34
+ * </div>
35
+ * </div>
36
+ * </div>
37
+ *
38
+ * `data-tui-accordion` is `single` (default) or `multiple`. An item starts open
39
+ * with `data-state="open"` on the item or `aria-expanded="true"` on its
40
+ * trigger. The trigger must be a <button>: Enter and Space come from the
41
+ * platform, and nothing here adds key handling. Put it in a heading at the
42
+ * level the page needs. A disabled trigger (`disabled` or
43
+ * `aria-disabled="true"`) doesn't toggle.
44
+ *
45
+ * The React Accordion puts `data-tui-accordion-trigger` on its triggers too, as
46
+ * a styling hook. Without `data-tui-accordion` and `data-tui-accordion-item`
47
+ * around them, this script ignores them, so the two can share a page.
48
+ *
49
+ * Each toggle fires `tui-accordion-toggle` on the item (bubbles), with
50
+ * `{ open, trigger, panel }`. State lives in the DOM, so two copies of the
51
+ * script on one page agree.
52
+ */
53
+ const ROOT_ATTR = 'data-tui-accordion';
54
+ const COLLAPSIBLE_ATTR = 'data-tui-accordion-collapsible';
55
+ const ITEM_ATTR = 'data-tui-accordion-item';
56
+ const TRIGGER_ATTR = 'data-tui-accordion-trigger';
57
+ const PANEL_ATTR = 'data-tui-accordion-panel';
58
+ // Marks an aria-disabled this script set on a locked open header, so it can
59
+ // tell its own from an author's and take it off again.
60
+ const LOCKED_ATTR = 'data-tui-accordion-locked';
61
+ /** Fired on the item after it opens or closes. Bubbles. */
62
+ export const ACCORDION_TOGGLE_EVENT = 'tui-accordion-toggle';
63
+ const warned = new WeakSet();
64
+ let bindings = 0;
65
+ let uid = 0;
66
+ function warn(el, message) {
67
+ // Always on, as in the vanilla Modal: template authors have no dev build.
68
+ if (warned.has(el))
69
+ return;
70
+ warned.add(el);
71
+ console.warn(`[TUI accordion] ${message}`, el);
72
+ }
73
+ function ensureId(el, prefix) {
74
+ // Two copies of the module (an ESM import and the standalone script) each
75
+ // count from 0, so check the page rather than trusting the counter.
76
+ while (!el.id) {
77
+ const id = `tui-accordion-${prefix}-${++uid}`;
78
+ if (!document.getElementById(id))
79
+ el.id = id;
80
+ }
81
+ return el.id;
82
+ }
83
+ function directOf(item, attr) {
84
+ // The item's own part, not one from an accordion nested in its panel.
85
+ for (const el of item.querySelectorAll(`[${attr}]`)) {
86
+ if (el.closest(`[${ITEM_ATTR}]`) === item)
87
+ return el;
88
+ }
89
+ return null;
90
+ }
91
+ function partsOf(el) {
92
+ const item = el.closest(`[${ITEM_ATTR}]`);
93
+ if (!item) {
94
+ warn(el, `No [${ITEM_ATTR}] around this element. Each trigger and panel pair needs an item.`);
95
+ return null;
96
+ }
97
+ const trigger = directOf(item, TRIGGER_ATTR);
98
+ const panel = directOf(item, PANEL_ATTR);
99
+ if (!trigger || !panel) {
100
+ warn(item, `This item needs one [${TRIGGER_ATTR}] and one [${PANEL_ATTR}].`);
101
+ return null;
102
+ }
103
+ return { root: item.closest(`[${ROOT_ATTR}]`), item, trigger, panel };
104
+ }
105
+ /** Disabled by the author: a locked open header isn't. */
106
+ function isDisabled(trigger) {
107
+ return (trigger.matches(':disabled') ||
108
+ (trigger.getAttribute('aria-disabled') === 'true' && !trigger.hasAttribute(LOCKED_ATTR)));
109
+ }
110
+ function isOpen(parts) {
111
+ return parts.item.getAttribute('data-state') === 'open';
112
+ }
113
+ function isMultiple(root) {
114
+ return root?.getAttribute(ROOT_ATTR) === 'multiple';
115
+ }
116
+ /** Writes one item's state to every attribute that carries it. */
117
+ function apply({ root, item, trigger, panel }, open) {
118
+ const state = open ? 'open' : 'closed';
119
+ // APG: an open header whose panel can't collapse (single, not collapsible)
120
+ // is aria-disabled. Still focusable and unpainted; activating it does nothing.
121
+ const locked = open && !!root && !isMultiple(root) && !root.hasAttribute(COLLAPSIBLE_ATTR);
122
+ if (locked && !isDisabled(trigger)) {
123
+ trigger.setAttribute('aria-disabled', 'true');
124
+ trigger.setAttribute(LOCKED_ATTR, '');
125
+ }
126
+ else if (!locked && trigger.hasAttribute(LOCKED_ATTR)) {
127
+ trigger.removeAttribute('aria-disabled');
128
+ trigger.removeAttribute(LOCKED_ATTR);
129
+ }
130
+ // Focus inside a panel that's about to go inert would be stranded.
131
+ if (!open && panel.contains(document.activeElement))
132
+ trigger.focus();
133
+ item.setAttribute('data-state', state);
134
+ trigger.setAttribute('data-state', state);
135
+ // The Accordion styles paint disabled off :disabled or [data-disabled];
136
+ // mirror aria-disabled so an inert trigger doesn't look live.
137
+ trigger.toggleAttribute('data-disabled', isDisabled(trigger));
138
+ trigger.setAttribute('aria-expanded', String(open));
139
+ panel.setAttribute('data-state', state);
140
+ panel.inert = !open;
141
+ if (open)
142
+ panel.removeAttribute('aria-hidden');
143
+ else
144
+ panel.setAttribute('aria-hidden', 'true');
145
+ }
146
+ function wire(parts) {
147
+ const { trigger, panel } = parts;
148
+ if (!(trigger instanceof HTMLButtonElement)) {
149
+ warn(trigger, `[${TRIGGER_ATTR}] should be a <button>: anything else gets no keyboard activation.`);
150
+ }
151
+ else if (!trigger.hasAttribute('type')) {
152
+ // Inside a form, a type-less button submits it.
153
+ trigger.type = 'button';
154
+ }
155
+ trigger.setAttribute('aria-controls', ensureId(panel, 'panel'));
156
+ ensureId(trigger, 'trigger');
157
+ }
158
+ function itemsOf(root) {
159
+ return [...root.querySelectorAll(`[${ITEM_ATTR}]`)].filter((item) => item.closest(`[${ROOT_ATTR}]`) === root);
160
+ }
161
+ /**
162
+ * Brings markup in line with its state: ids, `aria-controls`, `inert` on
163
+ * closed panels, and one open item in single mode. The standalone script runs
164
+ * it on the whole page at load; call it for markup added later. Toggling an
165
+ * item syncs it anyway, so this is about first paint.
166
+ */
167
+ export function sync(scope = document) {
168
+ // A scope inside an accordion (a newly appended item) re-syncs its root,
169
+ // which is idempotent; roots below the scope sync too.
170
+ const outer = scope instanceof Element ? scope.closest(`[${ROOT_ATTR}]`) : null;
171
+ const roots = new Set([...(outer ? [outer] : []), ...scope.querySelectorAll(`[${ROOT_ATTR}]`)]);
172
+ for (const root of roots) {
173
+ let seenOpen = false;
174
+ for (const item of itemsOf(root)) {
175
+ const parts = partsOf(item);
176
+ if (!parts)
177
+ continue;
178
+ wire(parts);
179
+ let open = isOpen(parts) || parts.trigger.getAttribute('aria-expanded') === 'true';
180
+ if (open && !isMultiple(root)) {
181
+ if (seenOpen) {
182
+ warn(root, 'More than one item starts open in a single accordion; keeping the first.');
183
+ open = false;
184
+ }
185
+ seenOpen = true;
186
+ }
187
+ apply(parts, open);
188
+ }
189
+ }
190
+ }
191
+ function set(parts, open) {
192
+ if (isOpen(parts) === open)
193
+ return;
194
+ if (open && !isMultiple(parts.root) && parts.root) {
195
+ for (const item of itemsOf(parts.root)) {
196
+ if (item === parts.item)
197
+ continue;
198
+ const other = partsOf(item);
199
+ if (other && isOpen(other))
200
+ set(other, false);
201
+ }
202
+ }
203
+ wire(parts);
204
+ apply(parts, open);
205
+ const detail = { open, trigger: parts.trigger, panel: parts.panel };
206
+ parts.item.dispatchEvent(new CustomEvent(ACCORDION_TOGGLE_EVENT, { bubbles: true, detail }));
207
+ }
208
+ function resolve(target) {
209
+ const el = typeof target === 'string' ? document.getElementById(target) : target;
210
+ if (!el) {
211
+ console.warn(`[TUI accordion] No element with id "${String(target)}".`);
212
+ return null;
213
+ }
214
+ // A root isn't an item: resolving it would walk up to an outer accordion's item.
215
+ if (!el.matches(`[${ITEM_ATTR}], [${TRIGGER_ATTR}], [${PANEL_ATTR}]`)) {
216
+ console.warn('[TUI accordion] Pass an item, trigger or panel (or its id), not', el);
217
+ return null;
218
+ }
219
+ return partsOf(el);
220
+ }
221
+ /**
222
+ * Opens an item (closing its siblings in single mode). Returns false only
223
+ * when the target isn't an accordion item. Closing a sibling that holds focus
224
+ * moves focus to that sibling's trigger.
225
+ */
226
+ export function open(target) {
227
+ const parts = resolve(target);
228
+ if (!parts)
229
+ return false;
230
+ set(parts, true);
231
+ return true;
232
+ }
233
+ /**
234
+ * Closes an item. Programmatic closes ignore `collapsible`, as React's
235
+ * controlled value does. Returns false only when the target isn't an item.
236
+ */
237
+ export function close(target) {
238
+ const parts = resolve(target);
239
+ if (!parts)
240
+ return false;
241
+ set(parts, false);
242
+ return true;
243
+ }
244
+ /**
245
+ * Toggles an item the way a click on its trigger would (so a disabled or
246
+ * non-collapsible open item stays put). Returns the item's open state
247
+ * afterwards, or null when the target isn't an item.
248
+ */
249
+ export function toggle(target) {
250
+ const parts = resolve(target);
251
+ if (!parts)
252
+ return null;
253
+ activate(parts);
254
+ return isOpen(parts);
255
+ }
256
+ function activate(parts) {
257
+ if (isDisabled(parts.trigger))
258
+ return;
259
+ if (!isOpen(parts)) {
260
+ set(parts, true);
261
+ return;
262
+ }
263
+ // In single mode the open item stays open unless the accordion is collapsible.
264
+ const collapsible = isMultiple(parts.root) || parts.root?.hasAttribute(COLLAPSIBLE_ATTR);
265
+ if (collapsible || !parts.root)
266
+ set(parts, false);
267
+ }
268
+ // Marks a click as handled across copies of the module. The Symbol.for guard
269
+ // stops a second standalone script installing, but an ESM import plus the
270
+ // script still means two listeners, and a toggle isn't idempotent: the second
271
+ // would undo the first.
272
+ const HANDLED = Symbol.for('tangible-ui/vanilla/accordion/handled');
273
+ function onClick(event) {
274
+ if (event.defaultPrevented || !(event.target instanceof Element))
275
+ return;
276
+ const marked = event;
277
+ if (marked[HANDLED])
278
+ return;
279
+ const trigger = event.target.closest(`[${TRIGGER_ATTR}]`);
280
+ // The React Accordion stamps the same trigger attribute as a styling hook
281
+ // but has no item or root attributes: leave its triggers alone, silently.
282
+ if (!trigger || !trigger.closest(`[${ITEM_ATTR}]`) || !trigger.closest(`[${ROOT_ATTR}]`))
283
+ return;
284
+ const parts = partsOf(trigger);
285
+ if (!parts || parts.trigger !== trigger)
286
+ return;
287
+ marked[HANDLED] = true;
288
+ activate(parts);
289
+ }
290
+ /**
291
+ * Wires every `data-tui-accordion` on the page through one delegated click
292
+ * listener, so markup added later works without another call (run `sync()` on
293
+ * it to fix its first paint). Calls are counted: the listener comes off when
294
+ * every caller has run its teardown.
295
+ *
296
+ * The standalone script (`vanilla/accordion.min.js`) calls this itself.
297
+ */
298
+ export function init() {
299
+ if (bindings++ === 0) {
300
+ document.addEventListener('click', onClick);
301
+ if (document.readyState === 'loading') {
302
+ document.addEventListener('DOMContentLoaded', () => sync(), { once: true });
303
+ }
304
+ else {
305
+ sync();
306
+ }
307
+ }
308
+ let released = false;
309
+ return () => {
310
+ if (released)
311
+ return;
312
+ released = true;
313
+ if (--bindings > 0)
314
+ return;
315
+ document.removeEventListener('click', onClick);
316
+ };
317
+ }
@@ -0,0 +1 @@
1
+ (()=>{var _=Object.defineProperty;var C=(t,e)=>{for(var n in e)_(t,n,{get:e[n],enumerable:!0})};var $={};C($,{ACCORDION_TOGGLE_EVENT:()=>S,close:()=>G,init:()=>h,open:()=>B,sync:()=>M,toggle:()=>q});var l="data-tui-accordion",x="data-tui-accordion-collapsible",a="data-tui-accordion-item",u="data-tui-accordion-trigger",A="data-tui-accordion-panel",m="data-tui-accordion-locked",S="tui-accordion-toggle",y=new WeakSet,v=0,U=0;function T(t,e){y.has(t)||(y.add(t),console.warn(`[TUI accordion] ${e}`,t))}function I(t,e){for(;!t.id;){let n=`tui-accordion-${e}-${++U}`;document.getElementById(n)||(t.id=n)}return t.id}function O(t,e){for(let n of t.querySelectorAll(`[${e}]`))if(n.closest(`[${a}]`)===t)return n;return null}function b(t){let e=t.closest(`[${a}]`);if(!e)return T(t,`No [${a}] around this element. Each trigger and panel pair needs an item.`),null;let n=O(e,u),o=O(e,A);return!n||!o?(T(e,`This item needs one [${u}] and one [${A}].`),null):{root:e.closest(`[${l}]`),item:e,trigger:n,panel:o}}function L(t){return t.matches(":disabled")||t.getAttribute("aria-disabled")==="true"&&!t.hasAttribute(m)}function d(t){return t.item.getAttribute("data-state")==="open"}function E(t){return t?.getAttribute(l)==="multiple"}function k({root:t,item:e,trigger:n,panel:o},i){let s=i?"open":"closed",r=i&&!!t&&!E(t)&&!t.hasAttribute(x);r&&!L(n)?(n.setAttribute("aria-disabled","true"),n.setAttribute(m,"")):!r&&n.hasAttribute(m)&&(n.removeAttribute("aria-disabled"),n.removeAttribute(m)),!i&&o.contains(document.activeElement)&&n.focus(),e.setAttribute("data-state",s),n.setAttribute("data-state",s),n.toggleAttribute("data-disabled",L(n)),n.setAttribute("aria-expanded",String(i)),o.setAttribute("data-state",s),o.inert=!i,i?o.removeAttribute("aria-hidden"):o.setAttribute("aria-hidden","true")}function D(t){let{trigger:e,panel:n}=t;e instanceof HTMLButtonElement?e.hasAttribute("type")||(e.type="button"):T(e,`[${u}] should be a <button>: anything else gets no keyboard activation.`),e.setAttribute("aria-controls",I(n,"panel")),I(e,"trigger")}function R(t){return[...t.querySelectorAll(`[${a}]`)].filter(e=>e.closest(`[${l}]`)===t)}function M(t=document){let e=t instanceof Element?t.closest(`[${l}]`):null,n=new Set([...e?[e]:[],...t.querySelectorAll(`[${l}]`)]);for(let o of n){let i=!1;for(let s of R(o)){let r=b(s);if(!r)continue;D(r);let g=d(r)||r.trigger.getAttribute("aria-expanded")==="true";g&&!E(o)&&(i&&(T(o,"More than one item starts open in a single accordion; keeping the first."),g=!1),i=!0),k(r,g)}}}function f(t,e){if(d(t)===e)return;if(e&&!E(t.root)&&t.root)for(let o of R(t.root)){if(o===t.item)continue;let i=b(o);i&&d(i)&&f(i,!1)}D(t),k(t,e);let n={open:e,trigger:t.trigger,panel:t.panel};t.item.dispatchEvent(new CustomEvent(S,{bubbles:!0,detail:n}))}function p(t){let e=typeof t=="string"?document.getElementById(t):t;return e?e.matches(`[${a}], [${u}], [${A}]`)?b(e):(console.warn("[TUI accordion] Pass an item, trigger or panel (or its id), not",e),null):(console.warn(`[TUI accordion] No element with id "${String(t)}".`),null)}function B(t){let e=p(t);return e?(f(e,!0),!0):!1}function G(t){let e=p(t);return e?(f(e,!1),!0):!1}function q(t){let e=p(t);return e?(N(e),d(e)):null}function N(t){if(L(t.trigger))return;if(!d(t)){f(t,!0);return}(E(t.root)||t.root?.hasAttribute(x)||!t.root)&&f(t,!1)}var P=Symbol.for("tangible-ui/vanilla/accordion/handled");function w(t){if(t.defaultPrevented||!(t.target instanceof Element))return;let e=t;if(e[P])return;let n=t.target.closest(`[${u}]`);if(!n||!n.closest(`[${a}]`)||!n.closest(`[${l}]`))return;let o=b(n);!o||o.trigger!==n||(e[P]=!0,N(o))}function h(){v++===0&&(document.addEventListener("click",w),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>M(),{once:!0}):M());let t=!1;return()=>{t||(t=!0,!(--v>0)&&document.removeEventListener("click",w))}}var H=Symbol.for("tangible-ui/vanilla/accordion"),c=globalThis;c[H]||(c[H]=$,h());c.TangibleUI=c.TangibleUI||{};c.TangibleUI.accordion=c[H];})();
package/vanilla/modal.js CHANGED
@@ -53,7 +53,7 @@
53
53
  * Anything that portals to <body> (a React Select, a third-party datepicker)
54
54
  * renders under the top layer and is inert while a modal is open.
55
55
  */
56
- import { getTabbable, isTabbable } from '../utils/tabbable.js';
56
+ import { getTabbable, isFocusTarget } from '../utils/tabbable.js';
57
57
  import { lockScroll, unlockScroll } from '../utils/scroll-lock.js';
58
58
  const OPEN_ATTR = 'data-tui-modal-open';
59
59
  const CLOSE_ATTR = 'data-tui-modal-close';
@@ -186,7 +186,7 @@ function waitForExit(dialog) {
186
186
  }
187
187
  function initialFocus(box) {
188
188
  const preferred = box.querySelector('[autofocus], [data-autofocus]');
189
- if (preferred && isTabbable(preferred, box))
189
+ if (preferred && isFocusTarget(preferred, box))
190
190
  return preferred;
191
191
  const controls = getTabbable(box).filter((el) => !el.matches(EMBED_SELECTOR));
192
192
  return controls.find((el) => !el.matches(CLOSE_BUTTON_SELECTOR)) ?? controls[0] ?? box;
@@ -1 +1 @@
1
- (()=>{var Y=Object.defineProperty;var J=(t,e)=>{for(var n in e)Y(t,n,{get:e[n],enumerable:!0})};var D={};J(D,{MODAL_CLOSE_EVENT:()=>j,MODAL_OPEN_EVENT:()=>y,close:()=>p,init:()=>S,open:()=>K});var Q=["[data-autofocus]","a[href]","area[href]","button:not([disabled])",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])","textarea:not([disabled])","iframe","audio[controls]","video[controls]",'[contenteditable]:not([contenteditable="false"])','[tabindex]:not([tabindex="-1"])'].join(",");function h(t,e){if(t.matches(":disabled")||t.closest("[inert]"))return!1;if(typeof t.checkVisibility=="function")return t.checkVisibility({visibilityProperty:!0});for(let n=t;n&&n!==e;n=n.parentElement){if(n.hidden)return!1;let o=getComputedStyle(n);if(o.display==="none"||n===t&&o.visibility==="hidden")return!1}return!0}function x(t){return Array.from(t.querySelectorAll(Q)).filter(e=>h(e,t))}var k="tui-modal-open",g="tuiScrollLock",C="--tui-scroll-lock-pad",w="--tui-scroll-lock-gutter",Z=["left","right"];function L(){return Number(document.body.dataset[g]??0)||0}function P(t){t.style.removeProperty(C);for(let e of Z)t.classList.remove(`tui-scroll-lock-pad-${e}`),t.style.removeProperty(`${w}-${e}`)}function _(){let t=document.body,e=L()===0;if(t.dataset[g]=String(L()+1),!e)return;P(t);let n=document.documentElement,o=n.clientWidth,r=t.getBoundingClientRect().left;t.classList.add(k);let i=n.clientWidth-o;if(i<=0)return;let l=t.getBoundingClientRect().left<r?"left":"right",a=parseFloat(getComputedStyle(t)[l==="left"?"paddingLeft":"paddingRight"])||0;t.style.setProperty(C,`${a+i}px`),t.style.setProperty(`${w}-${l}`,`${i}px`),t.classList.add(`tui-scroll-lock-pad-${l}`)}function O(){let t=document.body,e=L()-1;if(e>0){t.dataset[g]=String(e);return}delete t.dataset[g],t.classList.remove(k),P(t)}var b="data-tui-modal-open",c="data-tui-modal-close",tt="data-tui-modal-backdrop",M="data-tui-modal-src",R="data-tui-modal-restore-focus",et=".tui-modal__close",nt=":scope > .tui-modal__dialog",ot="iframe, object, embed, audio, video",it=1e3,y="tui-modal-open",j="tui-modal-close",m=new WeakMap,f=new WeakMap,B=new WeakSet,v=null,E=null,N=0;function s(t){console.warn(`[TUI modal] ${t}`)}function u(t){let e=t.getAttribute("data-state");return e==="open"||e==="closing"}function T(t){return t.querySelector(nt)}function I(t){return t.matches(":disabled")||t.closest('[aria-disabled="true"]')!==null}function z(t){if(typeof t!="string")return t;let e=document.getElementById(t);return e instanceof HTMLDialogElement?e:(s(e?`#${t} is a <${e.tagName.toLowerCase()}>, not a <dialog>. The modal must be a <dialog> element.`:`No element with id "${t}".`),null)}function q(t){return t.split(/\s+/).filter(e=>e&&!document.getElementById(e))}function rt(t){if(B.has(t))return;B.add(t);let e=`<dialog id="${t.id}">`,n=t.getAttribute("aria-labelledby"),o=t.getAttribute("aria-describedby");if(n){let i=q(n);i.length&&s(`${e} has aria-labelledby="${n}", but nothing has the id ${i.map(l=>`"${l}"`).join(", ")}, so the dialog has no name. Give the heading that id.`)}else t.hasAttribute("aria-label")||s(`${e} has no accessible name. Point aria-labelledby at its visible heading (WCAG 4.1.2).`);o&&q(o).length&&s(`${e} has aria-describedby="${o}", but not every id in it exists.`),t.getAttribute("role")==="alertdialog"&&!o&&s(`${e} is role="alertdialog" without aria-describedby. Point it at the message, or screen readers announce the heading and nothing about what is being confirmed.`),T(t)||s(`${e} has no .tui-modal__dialog box as its child. The box is the visible dialog; without it the backdrop can't be told apart and backdrop clicks are ignored.`),t.querySelector(`[${c}], form[method="dialog"]`)||Array.from(document.querySelectorAll(`[${c}]`)).some(i=>i.getAttribute(c)===t.id)||s(`${e} has no close control. Touch screen-reader users have no Escape key; add a button with ${c}.`)}function lt(t){let e=t.getAttribute(tt);return e==="dismiss"?!0:e==="static"?!1:t.getAttribute("role")!=="alertdialog"}function F(t){let e=getComputedStyle(t),n=i=>{let l=parseFloat(i);return Number.isNaN(l)?0:i.trim().endsWith("ms")?l:l*1e3},o=e.transitionDuration.split(","),r=e.transitionDelay.split(",");return Math.max(0,...o.map((i,l)=>n(i)+n(r[l%r.length]??"")))}function st(t){let e=T(t),n=Math.min(it,Math.max(F(t),e?F(e):0));return n>0?new Promise(o=>setTimeout(o,n)):Promise.resolve()}function at(t){let e=t.querySelector("[autofocus], [data-autofocus]");if(e&&h(e,t))return e;let n=x(t).filter(o=>!o.matches(ot));return n.find(o=>!o.matches(et))??n[0]??t}function K(t,e){let n=z(t);if(!n)return!1;if(n.getAttribute("data-state")==="closing")return f.delete(n),e&&m.set(n,e),n.setAttribute("data-state","open"),A(n,y,{opener:m.get(n)??null}),!0;if(n.open&&u(n))return!0;u(n)&&H(n),n.open&&(s(`<dialog id="${n.id}"> was already open, not as a modal. Drop the open attribute from the markup.`),n.close()),rt(n);try{n.showModal()}catch(a){return s(`<dialog id="${n.id}"> couldn't open: ${a.message}`),!1}_();let o=document.activeElement,r=e??(o instanceof HTMLElement&&o!==document.body?o:null);m.set(n,r);for(let a of n.querySelectorAll(`[${M}]`))a.hasAttribute("src")||a.setAttribute("src",a.getAttribute(M)??"");let i=T(n)??n,l=at(i);return l===i&&!i.hasAttribute("tabindex")&&(i.tabIndex=-1),l.focus(),n.offsetWidth,n.setAttribute("data-state","open"),A(n,y,{opener:r}),!0}function p(t){let e=z(t);if(!e?.open)return Promise.resolve();if(!u(e))return e.close(),Promise.resolve();let n=f.get(e);if(n)return n;e.setAttribute("data-state","closing");let o=st(e).then(()=>{f.get(e)===o&&(e.close(),H(e))});return f.set(e,o),o}function A(t,e,n){t.dispatchEvent(new CustomEvent(e,{bubbles:!0,detail:n}))}function H(t){if(!u(t))return;t.setAttribute("data-state","closed"),f.delete(t);for(let n of t.querySelectorAll("audio, video"))n.paused||n.pause();for(let n of t.querySelectorAll(`[${M}][src]`)){n.removeAttribute("src");let o=n.parentNode,r=n.nextSibling;n.remove(),o?.insertBefore(n,r)}O();let e=m.get(t)??null;m.delete(t),ct(t,e),A(t,j,{opener:e,returnValue:t.returnValue})}function ct(t,e){let n=t.getAttribute(R),o=[n?document.getElementById(n):null,e,...Array.from(document.querySelectorAll(`[${b}]`)).filter(r=>r.getAttribute(b)===t.id)];for(let r of o)if(!(!r?.isConnected||r===document.body)&&(r.focus(),document.activeElement===r))return;!e&&!n||s(`Focus had nowhere to return when <dialog id="${t.id}"> closed: its trigger is gone or can't take focus, so focus fell to <body> (WCAG 2.4.3). Set ${R}="<id>" on the dialog to name an element that will still be there.`)}function ut(t){return t.matches('a[href], input[type="submit"]')?!0:t instanceof HTMLButtonElement&&t.type==="submit"&&t.form!==null}function W(t){v=t.target,E=null}function U(t){E=t.target}function V(t){let e=v,n=E;v=E=null;let o=t.target;if(!(o instanceof Element))return;let r=o.closest(`[${b}]`);if(r){if(I(r))return;t.preventDefault(),K(r.getAttribute(b)??"",r);return}let i=o.closest(`[${c}]`);if(i){if(I(i))return;let a=i.getAttribute(c)||i.closest("dialog");if(!a){s(`A [${c}] control is outside any <dialog>. Give it the dialog's id as its value.`);return}ut(i)||t.preventDefault(),p(a);return}o instanceof HTMLDialogElement&&u(o)&&e===o&&n===o&&T(o)!==null&&lt(o)&&!dt(o,t)&&p(o)}function dt(t,e){let{clientWidth:n,clientHeight:o}=t;return n>0&&e.offsetX>=n||o>0&&e.offsetY>=o}function G(t){let e=t.target;!(e instanceof HTMLDialogElement)||!u(e)||t.cancelable&&(t.preventDefault(),p(e))}function X(t){let e=t.target;e instanceof HTMLDialogElement&&!e.open&&H(e)}function S(){N++===0&&(document.addEventListener("pointerdown",W,!0),document.addEventListener("pointerup",U,!0),document.addEventListener("click",V),document.addEventListener("cancel",G,!0),document.addEventListener("close",X,!0));let t=!1;return()=>{t||(t=!0,!(--N>0)&&(document.removeEventListener("pointerdown",W,!0),document.removeEventListener("pointerup",U,!0),document.removeEventListener("click",V),document.removeEventListener("cancel",G,!0),document.removeEventListener("close",X,!0)))}}var $=Symbol.for("tangible-ui/vanilla/modal"),d=globalThis;d[$]||(d[$]=D,S());d.TangibleUI=d.TangibleUI||{};d.TangibleUI.modal=d[$];})();
1
+ (()=>{var Q=Object.defineProperty;var Z=(t,e)=>{for(var n in e)Q(t,n,{get:e[n],enumerable:!0})};var S={};Z(S,{MODAL_CLOSE_EVENT:()=>K,MODAL_OPEN_EVENT:()=>M,close:()=>p,init:()=>H,open:()=>J});var $=["a[href]","area[href]","button:not([disabled])",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])","textarea:not([disabled])","iframe","audio[controls]","video[controls]",'[contenteditable]:not([contenteditable="false"])','[tabindex]:not([tabindex="-1"])'].join(",");function x(t,e){if(t.matches(":disabled")||t.closest("[inert]"))return!1;if(typeof t.checkVisibility=="function")return t.checkVisibility({visibilityProperty:!0});for(let n=t;n&&n!==e;n=n.parentElement){if(n.hidden)return!1;let o=getComputedStyle(n);if(o.display==="none"||n===t&&o.visibility==="hidden")return!1}return!0}function k(t,e){return(t.matches($)||t.hasAttribute("tabindex"))&&x(t,e)}function tt(t){let e=t.getAttribute("tabindex");return e!==null&&Number.parseInt(e,10)<0}function C(t){return Array.from(t.querySelectorAll($)).filter(e=>!tt(e)&&x(e,t))}var w="tui-modal-open",g="tuiScrollLock",P="--tui-scroll-lock-pad",O="--tui-scroll-lock-gutter",et=["left","right"];function h(){return Number(document.body.dataset[g]??0)||0}function _(t){t.style.removeProperty(P);for(let e of et)t.classList.remove(`tui-scroll-lock-pad-${e}`),t.style.removeProperty(`${O}-${e}`)}function R(){let t=document.body,e=h()===0;if(t.dataset[g]=String(h()+1),!e)return;_(t);let n=document.documentElement,o=n.clientWidth,i=t.getBoundingClientRect().left;t.classList.add(w);let r=n.clientWidth-o;if(r<=0)return;let l=t.getBoundingClientRect().left<i?"left":"right",a=parseFloat(getComputedStyle(t)[l==="left"?"paddingLeft":"paddingRight"])||0;t.style.setProperty(P,`${a+r}px`),t.style.setProperty(`${O}-${l}`,`${r}px`),t.classList.add(`tui-scroll-lock-pad-${l}`)}function B(){let t=document.body,e=h()-1;if(e>0){t.dataset[g]=String(e);return}delete t.dataset[g],t.classList.remove(w),_(t)}var b="data-tui-modal-open",c="data-tui-modal-close",nt="data-tui-modal-backdrop",L="data-tui-modal-src",N="data-tui-modal-restore-focus",ot=".tui-modal__close",rt=":scope > .tui-modal__dialog",it="iframe, object, embed, audio, video",lt=1e3,M="tui-modal-open",K="tui-modal-close",m=new WeakMap,f=new WeakMap,I=new WeakSet,y=null,E=null,q=0;function s(t){console.warn(`[TUI modal] ${t}`)}function u(t){let e=t.getAttribute("data-state");return e==="open"||e==="closing"}function T(t){return t.querySelector(rt)}function F(t){return t.matches(":disabled")||t.closest('[aria-disabled="true"]')!==null}function Y(t){if(typeof t!="string")return t;let e=document.getElementById(t);return e instanceof HTMLDialogElement?e:(s(e?`#${t} is a <${e.tagName.toLowerCase()}>, not a <dialog>. The modal must be a <dialog> element.`:`No element with id "${t}".`),null)}function W(t){return t.split(/\s+/).filter(e=>e&&!document.getElementById(e))}function st(t){if(I.has(t))return;I.add(t);let e=`<dialog id="${t.id}">`,n=t.getAttribute("aria-labelledby"),o=t.getAttribute("aria-describedby");if(n){let r=W(n);r.length&&s(`${e} has aria-labelledby="${n}", but nothing has the id ${r.map(l=>`"${l}"`).join(", ")}, so the dialog has no name. Give the heading that id.`)}else t.hasAttribute("aria-label")||s(`${e} has no accessible name. Point aria-labelledby at its visible heading (WCAG 4.1.2).`);o&&W(o).length&&s(`${e} has aria-describedby="${o}", but not every id in it exists.`),t.getAttribute("role")==="alertdialog"&&!o&&s(`${e} is role="alertdialog" without aria-describedby. Point it at the message, or screen readers announce the heading and nothing about what is being confirmed.`),T(t)||s(`${e} has no .tui-modal__dialog box as its child. The box is the visible dialog; without it the backdrop can't be told apart and backdrop clicks are ignored.`),t.querySelector(`[${c}], form[method="dialog"]`)||Array.from(document.querySelectorAll(`[${c}]`)).some(r=>r.getAttribute(c)===t.id)||s(`${e} has no close control. Touch screen-reader users have no Escape key; add a button with ${c}.`)}function at(t){let e=t.getAttribute(nt);return e==="dismiss"?!0:e==="static"?!1:t.getAttribute("role")!=="alertdialog"}function U(t){let e=getComputedStyle(t),n=r=>{let l=parseFloat(r);return Number.isNaN(l)?0:r.trim().endsWith("ms")?l:l*1e3},o=e.transitionDuration.split(","),i=e.transitionDelay.split(",");return Math.max(0,...o.map((r,l)=>n(r)+n(i[l%i.length]??"")))}function ct(t){let e=T(t),n=Math.min(lt,Math.max(U(t),e?U(e):0));return n>0?new Promise(o=>setTimeout(o,n)):Promise.resolve()}function ut(t){let e=t.querySelector("[autofocus], [data-autofocus]");if(e&&k(e,t))return e;let n=C(t).filter(o=>!o.matches(it));return n.find(o=>!o.matches(ot))??n[0]??t}function J(t,e){let n=Y(t);if(!n)return!1;if(n.getAttribute("data-state")==="closing")return f.delete(n),e&&m.set(n,e),n.setAttribute("data-state","open"),v(n,M,{opener:m.get(n)??null}),!0;if(n.open&&u(n))return!0;u(n)&&A(n),n.open&&(s(`<dialog id="${n.id}"> was already open, not as a modal. Drop the open attribute from the markup.`),n.close()),st(n);try{n.showModal()}catch(a){return s(`<dialog id="${n.id}"> couldn't open: ${a.message}`),!1}R();let o=document.activeElement,i=e??(o instanceof HTMLElement&&o!==document.body?o:null);m.set(n,i);for(let a of n.querySelectorAll(`[${L}]`))a.hasAttribute("src")||a.setAttribute("src",a.getAttribute(L)??"");let r=T(n)??n,l=ut(r);return l===r&&!r.hasAttribute("tabindex")&&(r.tabIndex=-1),l.focus(),n.offsetWidth,n.setAttribute("data-state","open"),v(n,M,{opener:i}),!0}function p(t){let e=Y(t);if(!e?.open)return Promise.resolve();if(!u(e))return e.close(),Promise.resolve();let n=f.get(e);if(n)return n;e.setAttribute("data-state","closing");let o=ct(e).then(()=>{f.get(e)===o&&(e.close(),A(e))});return f.set(e,o),o}function v(t,e,n){t.dispatchEvent(new CustomEvent(e,{bubbles:!0,detail:n}))}function A(t){if(!u(t))return;t.setAttribute("data-state","closed"),f.delete(t);for(let n of t.querySelectorAll("audio, video"))n.paused||n.pause();for(let n of t.querySelectorAll(`[${L}][src]`)){n.removeAttribute("src");let o=n.parentNode,i=n.nextSibling;n.remove(),o?.insertBefore(n,i)}B();let e=m.get(t)??null;m.delete(t),dt(t,e),v(t,K,{opener:e,returnValue:t.returnValue})}function dt(t,e){let n=t.getAttribute(N),o=[n?document.getElementById(n):null,e,...Array.from(document.querySelectorAll(`[${b}]`)).filter(i=>i.getAttribute(b)===t.id)];for(let i of o)if(!(!i?.isConnected||i===document.body)&&(i.focus(),document.activeElement===i))return;!e&&!n||s(`Focus had nowhere to return when <dialog id="${t.id}"> closed: its trigger is gone or can't take focus, so focus fell to <body> (WCAG 2.4.3). Set ${N}="<id>" on the dialog to name an element that will still be there.`)}function mt(t){return t.matches('a[href], input[type="submit"]')?!0:t instanceof HTMLButtonElement&&t.type==="submit"&&t.form!==null}function V(t){y=t.target,E=null}function G(t){E=t.target}function X(t){let e=y,n=E;y=E=null;let o=t.target;if(!(o instanceof Element))return;let i=o.closest(`[${b}]`);if(i){if(F(i))return;t.preventDefault(),J(i.getAttribute(b)??"",i);return}let r=o.closest(`[${c}]`);if(r){if(F(r))return;let a=r.getAttribute(c)||r.closest("dialog");if(!a){s(`A [${c}] control is outside any <dialog>. Give it the dialog's id as its value.`);return}mt(r)||t.preventDefault(),p(a);return}o instanceof HTMLDialogElement&&u(o)&&e===o&&n===o&&T(o)!==null&&at(o)&&!ft(o,t)&&p(o)}function ft(t,e){let{clientWidth:n,clientHeight:o}=t;return n>0&&e.offsetX>=n||o>0&&e.offsetY>=o}function j(t){let e=t.target;!(e instanceof HTMLDialogElement)||!u(e)||t.cancelable&&(t.preventDefault(),p(e))}function z(t){let e=t.target;e instanceof HTMLDialogElement&&!e.open&&A(e)}function H(){q++===0&&(document.addEventListener("pointerdown",V,!0),document.addEventListener("pointerup",G,!0),document.addEventListener("click",X),document.addEventListener("cancel",j,!0),document.addEventListener("close",z,!0));let t=!1;return()=>{t||(t=!0,!(--q>0)&&(document.removeEventListener("pointerdown",V,!0),document.removeEventListener("pointerup",G,!0),document.removeEventListener("click",X),document.removeEventListener("cancel",j,!0),document.removeEventListener("close",z,!0)))}}var D=Symbol.for("tangible-ui/vanilla/modal"),d=globalThis;d[D]||(d[D]=S,H());d.TangibleUI=d.TangibleUI||{};d.TangibleUI.modal=d[D];})();