@tangible/ui 0.2.27 → 0.2.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,453 @@
1
+ /**
2
+ * Vanilla modal: TUI's Modal for markup with no React behind it (Tangible
3
+ * Blocks, L&L templates, plain PHP). It wears the React Modal's classes and
4
+ * tokens, so token overrides (`--tui-modal-*`) and rules on the box and its
5
+ * slots reach both. The DOM differs in one place: the <dialog> is the
6
+ * full-viewport `.tui-modal` layer and paints the backdrop itself, so there is
7
+ * no `.tui-modal__backdrop` element to target.
8
+ *
9
+ * Built on the native <dialog> and `showModal()`, which already provides what
10
+ * the React Modal writes by hand: the rest of the page goes inert (the
11
+ * screen-reader escape `modal-review.md` flags), the dialog renders in the top
12
+ * layer (no portal, no z-index contest with wp-admin), and Escape fires
13
+ * `cancel`. This module adds what the platform leaves out:
14
+ *
15
+ * - delegated open/close triggers, so markup added after load works without re-init
16
+ * - backdrop-click dismissal, off by default for `role="alertdialog"` as in React
17
+ * - initial focus: `[autofocus]` / `[data-autofocus]`, else the first control that
18
+ * isn't an embed (focus inside a cross-origin player swallows Escape) or the ×
19
+ * - focus restored to the trigger, including in Safari, where clicking a button doesn't focus it
20
+ * - the body scroll lock (shared with the React Modal) and the enter/exit transition
21
+ * - media: `<audio>`/`<video>` pause on close, and `data-tui-modal-src` embeds load on
22
+ * open and unload on close, which stops a YouTube or Vimeo iframe without its JS API
23
+ * - console warnings for markup that leaves the dialog unnamed or unclosable
24
+ *
25
+ * Markup:
26
+ *
27
+ * <button type="button" data-tui-modal-open="intro-video">Watch</button>
28
+ *
29
+ * <dialog id="intro-video" class="tui-interface tui-modal" aria-labelledby="intro-video-title">
30
+ * <div class="tui-modal__dialog is-size-lg">
31
+ * <div class="tui-modal__head"><h2 id="intro-video-title">Intro</h2></div>
32
+ * <div class="tui-modal__body"><div class="tui-modal__body-inner">
33
+ * <iframe class="tui-modal__embed" title="Intro" data-tui-modal-src="https://www.youtube.com/embed/…?autoplay=1" …></iframe>
34
+ * </div></div>
35
+ * <div class="tui-modal__foot">
36
+ * <button type="button" class="tui-button" data-tui-modal-close>Close</button>
37
+ * </div>
38
+ * </div>
39
+ * </dialog>
40
+ *
41
+ * The inner `.tui-modal__dialog` box is required: a click on the <dialog>
42
+ * itself, outside the box, is a click on the backdrop. `.tui-interface` can sit
43
+ * on the <dialog> or any ancestor; the top layer changes paint order, not the cascade.
44
+ *
45
+ * Dialog attributes: `role="alertdialog"` (needs `aria-describedby` too),
46
+ * `data-tui-modal-backdrop="dismiss" | "static"` to override the role's default,
47
+ * and `data-tui-modal-restore-focus="<id>"` for where focus goes on close when the
48
+ * trigger won't survive it (a "Delete" whose confirm removes its row).
49
+ * A close × (`.tui-modal__close`) goes last in the box: it's the last tab stop,
50
+ * and takes initial focus only when it's the only control.
51
+ * The script keeps `data-state` at `open`, `closing` or `closed`.
52
+ *
53
+ * Anything that portals to <body> (a React Select, a third-party datepicker)
54
+ * renders under the top layer and is inert while a modal is open.
55
+ */
56
+ import { getTabbable, isTabbable } from '../utils/tabbable.js';
57
+ import { lockScroll, unlockScroll } from '../utils/scroll-lock.js';
58
+ const OPEN_ATTR = 'data-tui-modal-open';
59
+ const CLOSE_ATTR = 'data-tui-modal-close';
60
+ const BACKDROP_ATTR = 'data-tui-modal-backdrop';
61
+ const SRC_ATTR = 'data-tui-modal-src';
62
+ const RESTORE_ATTR = 'data-tui-modal-restore-focus';
63
+ // Takes initial focus only when nothing else can (#135). The React Modal
64
+ // applies the same rule through getInitialFocus's `lastResort`; this module
65
+ // keeps its own copy because it also skips embeds first.
66
+ const CLOSE_BUTTON_SELECTOR = '.tui-modal__close';
67
+ const BOX_SELECTOR = ':scope > .tui-modal__dialog';
68
+ // Focus inside a cross-origin embed sends keys to it, Escape included.
69
+ const EMBED_SELECTOR = 'iframe, object, embed, audio, video';
70
+ // The exit waits on the computed transition, so a stylesheet with a very long
71
+ // (or broken) duration can't hold a dialog open indefinitely.
72
+ const EXIT_MAX_MS = 1000;
73
+ /** Fired on the <dialog> after it opens. Bubbles, so one document listener covers every modal. */
74
+ export const MODAL_OPEN_EVENT = 'tui-modal-open';
75
+ /** Fired on the <dialog> after it closes, however it closed. Bubbles. */
76
+ export const MODAL_CLOSE_EVENT = 'tui-modal-close';
77
+ const openers = new WeakMap();
78
+ const exits = new WeakMap();
79
+ const warned = new WeakSet();
80
+ let pressTarget = null;
81
+ let releaseTarget = null;
82
+ let bindings = 0;
83
+ function warn(message) {
84
+ // Always on, unlike the React components' dev-only warnings: the people
85
+ // writing this markup have no dev build, and every warning here describes
86
+ // a dialog that's broken for someone.
87
+ console.warn(`[TUI modal] ${message}`);
88
+ }
89
+ // Managed = opened by this module and not yet finalized. Kept in the DOM, not
90
+ // in module state, so a second copy of the script on the page agrees with it.
91
+ function isManaged(dialog) {
92
+ const state = dialog.getAttribute('data-state');
93
+ return state === 'open' || state === 'closing';
94
+ }
95
+ function boxOf(dialog) {
96
+ return dialog.querySelector(BOX_SELECTOR);
97
+ }
98
+ function isDisabled(el) {
99
+ return el.matches(':disabled') || el.closest('[aria-disabled="true"]') !== null;
100
+ }
101
+ function resolve(target) {
102
+ if (typeof target !== 'string')
103
+ return target;
104
+ const el = document.getElementById(target);
105
+ if (el instanceof HTMLDialogElement)
106
+ return el;
107
+ warn(el
108
+ ? `#${target} is a <${el.tagName.toLowerCase()}>, not a <dialog>. ` +
109
+ 'The modal must be a <dialog> element.'
110
+ : `No element with id "${target}".`);
111
+ return null;
112
+ }
113
+ // IDs in an aria-labelledby/-describedby list that match nothing in the document.
114
+ function missingIds(list) {
115
+ return list.split(/\s+/).filter((id) => id && !document.getElementById(id));
116
+ }
117
+ function checkMarkup(dialog) {
118
+ if (warned.has(dialog))
119
+ return;
120
+ warned.add(dialog);
121
+ const name = `<dialog id="${dialog.id}">`;
122
+ const labelledBy = dialog.getAttribute('aria-labelledby');
123
+ const describedBy = dialog.getAttribute('aria-describedby');
124
+ if (labelledBy) {
125
+ // Unlike aria-describedby, a dangling aria-labelledby isn't ignored: it
126
+ // resolves to an empty name and overrides every other source (AccName 1.2 2B).
127
+ const missing = missingIds(labelledBy);
128
+ if (missing.length) {
129
+ warn(`${name} has aria-labelledby="${labelledBy}", but nothing has the id ` +
130
+ `${missing.map((id) => `"${id}"`).join(', ')}, so the dialog has no name. ` +
131
+ 'Give the heading that id.');
132
+ }
133
+ }
134
+ else if (!dialog.hasAttribute('aria-label')) {
135
+ warn(`${name} has no accessible name. Point aria-labelledby at its visible heading (WCAG 4.1.2).`);
136
+ }
137
+ if (describedBy && missingIds(describedBy).length) {
138
+ warn(`${name} has aria-describedby="${describedBy}", but not every id in it exists.`);
139
+ }
140
+ if (dialog.getAttribute('role') === 'alertdialog' && !describedBy) {
141
+ warn(`${name} is role="alertdialog" without aria-describedby. Point it at the message, ` +
142
+ 'or screen readers announce the heading and nothing about what is being confirmed.');
143
+ }
144
+ if (!boxOf(dialog)) {
145
+ warn(`${name} has no .tui-modal__dialog box as its child. The box is the visible dialog; ` +
146
+ 'without it the backdrop can\'t be told apart and backdrop clicks are ignored.');
147
+ }
148
+ const hasCloser = dialog.querySelector(`[${CLOSE_ATTR}], form[method="dialog"]`) ||
149
+ Array.from(document.querySelectorAll(`[${CLOSE_ATTR}]`)).some((el) => el.getAttribute(CLOSE_ATTR) === dialog.id);
150
+ if (!hasCloser) {
151
+ warn(`${name} has no close control. Touch screen-reader users have no Escape key; ` +
152
+ `add a button with ${CLOSE_ATTR}.`);
153
+ }
154
+ }
155
+ function dismissesOnBackdrop(dialog) {
156
+ const setting = dialog.getAttribute(BACKDROP_ATTR);
157
+ if (setting === 'dismiss')
158
+ return true;
159
+ if (setting === 'static')
160
+ return false;
161
+ // An alert dialog demands a response, and a stray click outside isn't one.
162
+ return dialog.getAttribute('role') !== 'alertdialog';
163
+ }
164
+ // Longest transition (duration + delay) on an element, in ms. The modal's
165
+ // transitions only exist under prefers-reduced-motion: no-preference, so with
166
+ // reduced motion this is 0 and the exit is immediate.
167
+ function transitionMs(el) {
168
+ const style = getComputedStyle(el);
169
+ const toMs = (value) => {
170
+ const n = parseFloat(value);
171
+ if (Number.isNaN(n))
172
+ return 0;
173
+ return value.trim().endsWith('ms') ? n : n * 1000;
174
+ };
175
+ const durations = style.transitionDuration.split(',');
176
+ const delays = style.transitionDelay.split(',');
177
+ return Math.max(0, ...durations.map((d, i) => toMs(d) + toMs(delays[i % delays.length] ?? '')));
178
+ }
179
+ // A timer from the computed transition rather than `transitionend`: the event
180
+ // never fires when nothing transitions, or when the stylesheet failed to load,
181
+ // and an exit that awaits it unguarded leaves the page stuck behind the dialog.
182
+ function waitForExit(dialog) {
183
+ const box = boxOf(dialog);
184
+ const ms = Math.min(EXIT_MAX_MS, Math.max(transitionMs(dialog), box ? transitionMs(box) : 0));
185
+ return ms > 0 ? new Promise((done) => setTimeout(done, ms)) : Promise.resolve();
186
+ }
187
+ function initialFocus(box) {
188
+ const preferred = box.querySelector('[autofocus], [data-autofocus]');
189
+ if (preferred && isTabbable(preferred, box))
190
+ return preferred;
191
+ const controls = getTabbable(box).filter((el) => !el.matches(EMBED_SELECTOR));
192
+ return controls.find((el) => !el.matches(CLOSE_BUTTON_SELECTOR)) ?? controls[0] ?? box;
193
+ }
194
+ /**
195
+ * Opens a modal. Returns false when the target can't be found or opened.
196
+ *
197
+ * `opener` is where focus returns on close. Delegated triggers pass themselves;
198
+ * from script, pass the control that asked, because Safari doesn't focus a
199
+ * button on click and `document.activeElement` can be stale.
200
+ */
201
+ export function open(target, opener) {
202
+ const dialog = resolve(target);
203
+ if (!dialog)
204
+ return false;
205
+ // Reopened mid-exit: cancel the exit instead of letting it close the dialog.
206
+ if (dialog.getAttribute('data-state') === 'closing') {
207
+ exits.delete(dialog);
208
+ if (opener)
209
+ openers.set(dialog, opener);
210
+ dialog.setAttribute('data-state', 'open');
211
+ dispatch(dialog, MODAL_OPEN_EVENT, { opener: openers.get(dialog) ?? null });
212
+ return true;
213
+ }
214
+ if (dialog.open && isManaged(dialog))
215
+ return true;
216
+ // Closed natively (a form, a script, Chrome's forced Escape) with its
217
+ // `close` event still queued: finish that session before starting this one.
218
+ if (isManaged(dialog))
219
+ finalize(dialog);
220
+ // Open but not ours: `<dialog open>` in the markup, or show() from a script.
221
+ // That's non-modal (the page stays live), so close it and open it properly.
222
+ if (dialog.open) {
223
+ warn(`<dialog id="${dialog.id}"> was already open, not as a modal. Drop the open attribute from the markup.`);
224
+ dialog.close();
225
+ }
226
+ checkMarkup(dialog);
227
+ try {
228
+ dialog.showModal();
229
+ }
230
+ catch (error) {
231
+ warn(`<dialog id="${dialog.id}"> couldn't open: ${error.message}`);
232
+ return false;
233
+ }
234
+ lockScroll();
235
+ const active = document.activeElement;
236
+ const returnTo = opener ?? (active instanceof HTMLElement && active !== document.body ? active : null);
237
+ openers.set(dialog, returnTo);
238
+ for (const el of dialog.querySelectorAll(`[${SRC_ATTR}]`)) {
239
+ if (!el.hasAttribute('src'))
240
+ el.setAttribute('src', el.getAttribute(SRC_ATTR) ?? '');
241
+ }
242
+ const box = boxOf(dialog) ?? dialog;
243
+ const initial = initialFocus(box);
244
+ // Nothing focusable inside: focus the box, which draws its own focus ring.
245
+ if (initial === box && !box.hasAttribute('tabindex'))
246
+ box.tabIndex = -1;
247
+ initial.focus();
248
+ // Flush the closed styles so the enter transition has a start point.
249
+ void dialog.offsetWidth;
250
+ dialog.setAttribute('data-state', 'open');
251
+ dispatch(dialog, MODAL_OPEN_EVENT, { opener: returnTo });
252
+ return true;
253
+ }
254
+ /**
255
+ * Closes a modal after its exit transition. The promise resolves when the
256
+ * exit ends: with the dialog closed, or still open if `open()` was called
257
+ * during the exit. A close already in progress returns the same promise.
258
+ */
259
+ export function close(target) {
260
+ const dialog = resolve(target);
261
+ if (!dialog?.open)
262
+ return Promise.resolve();
263
+ if (!isManaged(dialog)) {
264
+ dialog.close();
265
+ return Promise.resolve();
266
+ }
267
+ const pending = exits.get(dialog);
268
+ if (pending)
269
+ return pending;
270
+ dialog.setAttribute('data-state', 'closing');
271
+ const exit = waitForExit(dialog).then(() => {
272
+ if (exits.get(dialog) !== exit)
273
+ return; // reopened during the exit
274
+ dialog.close();
275
+ finalize(dialog);
276
+ });
277
+ exits.set(dialog, exit);
278
+ return exit;
279
+ }
280
+ function dispatch(dialog, type, detail) {
281
+ dialog.dispatchEvent(new CustomEvent(type, { bubbles: true, detail }));
282
+ }
283
+ // Everything that happens once a dialog has closed. Runs for our own close()
284
+ // and, via the native `close` event, for anything else that closes it: a
285
+ // `<form method="dialog">`, a script calling dialog.close(), or Chrome
286
+ // force-closing on a repeated Escape. Idempotent: the first call sets "closed".
287
+ function finalize(dialog) {
288
+ if (!isManaged(dialog))
289
+ return;
290
+ dialog.setAttribute('data-state', 'closed');
291
+ exits.delete(dialog);
292
+ for (const media of dialog.querySelectorAll('audio, video')) {
293
+ if (!media.paused)
294
+ media.pause();
295
+ }
296
+ // Unload each embed by dropping its src and re-inserting it, which gives
297
+ // it a fresh, empty browsing context. Pointing src at about:blank instead
298
+ // would add a history entry, so Back would "undo" the unload. Re-inserting
299
+ // keeps the element itself, so code holding a reference to it still works.
300
+ for (const el of dialog.querySelectorAll(`[${SRC_ATTR}][src]`)) {
301
+ el.removeAttribute('src');
302
+ const parent = el.parentNode;
303
+ const next = el.nextSibling;
304
+ el.remove();
305
+ parent?.insertBefore(el, next);
306
+ }
307
+ unlockScroll();
308
+ const opener = openers.get(dialog) ?? null;
309
+ openers.delete(dialog);
310
+ restoreFocus(dialog, opener);
311
+ dispatch(dialog, MODAL_CLOSE_EVENT, { opener, returnValue: dialog.returnValue });
312
+ }
313
+ // In order: the dialog's data-tui-modal-restore-focus target, the opener, then
314
+ // another trigger for this dialog. Each must still be in the document and take
315
+ // focus; a removed trigger's focus() is a silent no-op (#133).
316
+ function restoreFocus(dialog, opener) {
317
+ const restoreId = dialog.getAttribute(RESTORE_ATTR);
318
+ const candidates = [
319
+ restoreId ? document.getElementById(restoreId) : null,
320
+ opener,
321
+ ...Array.from(document.querySelectorAll(`[${OPEN_ATTR}]`)).filter((el) => el.getAttribute(OPEN_ATTR) === dialog.id),
322
+ ];
323
+ for (const el of candidates) {
324
+ if (!el?.isConnected || el === document.body)
325
+ continue;
326
+ el.focus();
327
+ if (document.activeElement === el)
328
+ return;
329
+ }
330
+ // Opened from script with nothing focused: there was nowhere to return to.
331
+ if (!opener && !restoreId)
332
+ return;
333
+ warn(`Focus had nowhere to return when <dialog id="${dialog.id}"> closed: its trigger is gone ` +
334
+ `or can't take focus, so focus fell to <body> (WCAG 2.4.3). Set ${RESTORE_ATTR}="<id>" ` +
335
+ 'on the dialog to name an element that will still be there.');
336
+ }
337
+ // A submit button or link keeps its own action (submitting the form,
338
+ // following the link); the dialog closes alongside it.
339
+ function keepsDefault(el) {
340
+ if (el.matches('a[href], input[type="submit"]'))
341
+ return true;
342
+ return el instanceof HTMLButtonElement && el.type === 'submit' && el.form !== null;
343
+ }
344
+ function onPointerDown(event) {
345
+ pressTarget = event.target;
346
+ releaseTarget = null;
347
+ }
348
+ function onPointerUp(event) {
349
+ releaseTarget = event.target;
350
+ }
351
+ function onClick(event) {
352
+ const pressed = pressTarget;
353
+ const released = releaseTarget;
354
+ pressTarget = releaseTarget = null;
355
+ const target = event.target;
356
+ if (!(target instanceof Element))
357
+ return;
358
+ const trigger = target.closest(`[${OPEN_ATTR}]`);
359
+ if (trigger) {
360
+ if (isDisabled(trigger))
361
+ return;
362
+ event.preventDefault();
363
+ open(trigger.getAttribute(OPEN_ATTR) ?? '', trigger);
364
+ return;
365
+ }
366
+ const closer = target.closest(`[${CLOSE_ATTR}]`);
367
+ if (closer) {
368
+ if (isDisabled(closer))
369
+ return;
370
+ const id = closer.getAttribute(CLOSE_ATTR);
371
+ const dialog = id || closer.closest('dialog');
372
+ if (!dialog) {
373
+ warn(`A [${CLOSE_ATTR}] control is outside any <dialog>. Give it the dialog's id as its value.`);
374
+ return;
375
+ }
376
+ if (!keepsDefault(closer))
377
+ event.preventDefault();
378
+ void close(dialog);
379
+ return;
380
+ }
381
+ // Backdrop: the click hit the <dialog> itself, not the box inside it. The
382
+ // press and the release must both have landed there too, or a selection
383
+ // dragged out of (or into) the box would close the dialog. Since the click
384
+ // target is their common ancestor, a drag between the two reports the <dialog>.
385
+ if (target instanceof HTMLDialogElement &&
386
+ isManaged(target) &&
387
+ pressed === target &&
388
+ released === target &&
389
+ boxOf(target) !== null &&
390
+ dismissesOnBackdrop(target) &&
391
+ !onScrollbar(target, event)) {
392
+ void close(target);
393
+ }
394
+ }
395
+ // The <dialog> scrolls a tall box, so its scrollbar is part of the "backdrop"
396
+ // element. offsetX/Y past clientWidth/Height is the scrollbar. (jsdom has no
397
+ // layout, so a zero size means "unknown", not "everything is scrollbar".)
398
+ function onScrollbar(dialog, event) {
399
+ const { clientWidth, clientHeight } = dialog;
400
+ return ((clientWidth > 0 && event.offsetX >= clientWidth) ||
401
+ (clientHeight > 0 && event.offsetY >= clientHeight));
402
+ }
403
+ // Escape: run the animated close instead of the native instant one.
404
+ function onCancel(event) {
405
+ const dialog = event.target;
406
+ if (!(dialog instanceof HTMLDialogElement) || !isManaged(dialog))
407
+ return;
408
+ // Chrome makes a repeated Escape uncancelable; the native close then runs and
409
+ // the `close` listener cleans up.
410
+ if (!event.cancelable)
411
+ return;
412
+ event.preventDefault();
413
+ void close(dialog);
414
+ }
415
+ // The `close` event is queued as a task, so it can arrive after the dialog has
416
+ // been reopened. Finalizing then would strip the new session's state and leave
417
+ // an open modal with no managed Escape, backdrop or visible box.
418
+ function onNativeClose(event) {
419
+ const dialog = event.target;
420
+ if (dialog instanceof HTMLDialogElement && !dialog.open)
421
+ finalize(dialog);
422
+ }
423
+ /**
424
+ * Wires up `data-tui-modal-open` / `data-tui-modal-close`, the backdrop and
425
+ * Escape for the whole document. Listeners are delegated, so markup added
426
+ * later needs no second call. Calls are counted: the listeners come off when
427
+ * every caller has run its teardown.
428
+ *
429
+ * The standalone script (`vanilla/modal.min.js`) calls this itself.
430
+ */
431
+ export function init() {
432
+ if (bindings++ === 0) {
433
+ // `cancel` and `close` don't bubble, so they're caught on the way down.
434
+ document.addEventListener('pointerdown', onPointerDown, true);
435
+ document.addEventListener('pointerup', onPointerUp, true);
436
+ document.addEventListener('click', onClick);
437
+ document.addEventListener('cancel', onCancel, true);
438
+ document.addEventListener('close', onNativeClose, true);
439
+ }
440
+ let released = false;
441
+ return () => {
442
+ if (released)
443
+ return;
444
+ released = true;
445
+ if (--bindings > 0)
446
+ return;
447
+ document.removeEventListener('pointerdown', onPointerDown, true);
448
+ document.removeEventListener('pointerup', onPointerUp, true);
449
+ document.removeEventListener('click', onClick);
450
+ document.removeEventListener('cancel', onCancel, true);
451
+ document.removeEventListener('close', onNativeClose, true);
452
+ };
453
+ }
@@ -0,0 +1 @@
1
+ (()=>{var j=Object.defineProperty;var z=(e,t)=>{for(var n in t)j(e,n,{get:t[n],enumerable:!0})};var D={};z(D,{MODAL_CLOSE_EVENT:()=>V,MODAL_OPEN_EVENT:()=>L,close:()=>p,init:()=>H,open:()=>X});var K=["[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(e,t){if(e.matches(":disabled")||e.closest("[inert]"))return!1;if(typeof e.checkVisibility=="function")return e.checkVisibility({visibilityProperty:!0});for(let n=e;n&&n!==t;n=n.parentElement){if(n.hidden)return!1;let o=getComputedStyle(n);if(o.display==="none"||n===e&&o.visibility==="hidden")return!1}return!0}function x(e){return Array.from(e.querySelectorAll(K)).filter(t=>h(t,e))}var $="tui-modal-open",b="tuiScrollLock";function C(){return Number(document.body.dataset[b]??0)||0}function k(){document.body.dataset[b]=String(C()+1),document.body.classList.add($)}function w(){let e=C()-1;if(e>0){document.body.dataset[b]=String(e);return}delete document.body.dataset[b],document.body.classList.remove($)}var g="data-tui-modal-open",u="data-tui-modal-close",Y="data-tui-modal-backdrop",M="data-tui-modal-src",_="data-tui-modal-restore-focus",J=".tui-modal__close",Q=":scope > .tui-modal__dialog",Z="iframe, object, embed, audio, video",ee=1e3,L="tui-modal-open",V="tui-modal-close",f=new WeakMap,m=new WeakMap,O=new WeakSet,y=null,E=null,P=0;function s(e){console.warn(`[TUI modal] ${e}`)}function c(e){let t=e.getAttribute("data-state");return t==="open"||t==="closing"}function T(e){return e.querySelector(Q)}function N(e){return e.matches(":disabled")||e.closest('[aria-disabled="true"]')!==null}function G(e){if(typeof e!="string")return e;let t=document.getElementById(e);return t instanceof HTMLDialogElement?t:(s(t?`#${e} is a <${t.tagName.toLowerCase()}>, not a <dialog>. The modal must be a <dialog> element.`:`No element with id "${e}".`),null)}function B(e){return e.split(/\s+/).filter(t=>t&&!document.getElementById(t))}function te(e){if(O.has(e))return;O.add(e);let t=`<dialog id="${e.id}">`,n=e.getAttribute("aria-labelledby"),o=e.getAttribute("aria-describedby");if(n){let r=B(n);r.length&&s(`${t} has aria-labelledby="${n}", but nothing has the id ${r.map(a=>`"${a}"`).join(", ")}, so the dialog has no name. Give the heading that id.`)}else e.hasAttribute("aria-label")||s(`${t} has no accessible name. Point aria-labelledby at its visible heading (WCAG 4.1.2).`);o&&B(o).length&&s(`${t} has aria-describedby="${o}", but not every id in it exists.`),e.getAttribute("role")==="alertdialog"&&!o&&s(`${t} 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(e)||s(`${t} 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.`),e.querySelector(`[${u}], form[method="dialog"]`)||Array.from(document.querySelectorAll(`[${u}]`)).some(r=>r.getAttribute(u)===e.id)||s(`${t} has no close control. Touch screen-reader users have no Escape key; add a button with ${u}.`)}function ne(e){let t=e.getAttribute(Y);return t==="dismiss"?!0:t==="static"?!1:e.getAttribute("role")!=="alertdialog"}function R(e){let t=getComputedStyle(e),n=r=>{let a=parseFloat(r);return Number.isNaN(a)?0:r.trim().endsWith("ms")?a:a*1e3},o=t.transitionDuration.split(","),i=t.transitionDelay.split(",");return Math.max(0,...o.map((r,a)=>n(r)+n(i[a%i.length]??"")))}function oe(e){let t=T(e),n=Math.min(ee,Math.max(R(e),t?R(t):0));return n>0?new Promise(o=>setTimeout(o,n)):Promise.resolve()}function ie(e){let t=e.querySelector("[autofocus], [data-autofocus]");if(t&&h(t,e))return t;let n=x(e).filter(o=>!o.matches(Z));return n.find(o=>!o.matches(J))??n[0]??e}function X(e,t){let n=G(e);if(!n)return!1;if(n.getAttribute("data-state")==="closing")return m.delete(n),t&&f.set(n,t),n.setAttribute("data-state","open"),v(n,L,{opener:f.get(n)??null}),!0;if(n.open&&c(n))return!0;c(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()),te(n);try{n.showModal()}catch(l){return s(`<dialog id="${n.id}"> couldn't open: ${l.message}`),!1}k();let o=document.activeElement,i=t??(o instanceof HTMLElement&&o!==document.body?o:null);f.set(n,i);for(let l of n.querySelectorAll(`[${M}]`))l.hasAttribute("src")||l.setAttribute("src",l.getAttribute(M)??"");let r=T(n)??n,a=ie(r);return a===r&&!r.hasAttribute("tabindex")&&(r.tabIndex=-1),a.focus(),n.offsetWidth,n.setAttribute("data-state","open"),v(n,L,{opener:i}),!0}function p(e){let t=G(e);if(!t?.open)return Promise.resolve();if(!c(t))return t.close(),Promise.resolve();let n=m.get(t);if(n)return n;t.setAttribute("data-state","closing");let o=oe(t).then(()=>{m.get(t)===o&&(t.close(),A(t))});return m.set(t,o),o}function v(e,t,n){e.dispatchEvent(new CustomEvent(t,{bubbles:!0,detail:n}))}function A(e){if(!c(e))return;e.setAttribute("data-state","closed"),m.delete(e);for(let n of e.querySelectorAll("audio, video"))n.paused||n.pause();for(let n of e.querySelectorAll(`[${M}][src]`)){n.removeAttribute("src");let o=n.parentNode,i=n.nextSibling;n.remove(),o?.insertBefore(n,i)}w();let t=f.get(e)??null;f.delete(e),re(e,t),v(e,V,{opener:t,returnValue:e.returnValue})}function re(e,t){let n=e.getAttribute(_),o=[n?document.getElementById(n):null,t,...Array.from(document.querySelectorAll(`[${g}]`)).filter(i=>i.getAttribute(g)===e.id)];for(let i of o)if(!(!i?.isConnected||i===document.body)&&(i.focus(),document.activeElement===i))return;!t&&!n||s(`Focus had nowhere to return when <dialog id="${e.id}"> closed: its trigger is gone or can't take focus, so focus fell to <body> (WCAG 2.4.3). Set ${_}="<id>" on the dialog to name an element that will still be there.`)}function ae(e){return e.matches('a[href], input[type="submit"]')?!0:e instanceof HTMLButtonElement&&e.type==="submit"&&e.form!==null}function I(e){y=e.target,E=null}function q(e){E=e.target}function U(e){let t=y,n=E;y=E=null;let o=e.target;if(!(o instanceof Element))return;let i=o.closest(`[${g}]`);if(i){if(N(i))return;e.preventDefault(),X(i.getAttribute(g)??"",i);return}let r=o.closest(`[${u}]`);if(r){if(N(r))return;let l=r.getAttribute(u)||r.closest("dialog");if(!l){s(`A [${u}] control is outside any <dialog>. Give it the dialog's id as its value.`);return}ae(r)||e.preventDefault(),p(l);return}o instanceof HTMLDialogElement&&c(o)&&t===o&&n===o&&T(o)!==null&&ne(o)&&!se(o,e)&&p(o)}function se(e,t){let{clientWidth:n,clientHeight:o}=e;return n>0&&t.offsetX>=n||o>0&&t.offsetY>=o}function W(e){let t=e.target;!(t instanceof HTMLDialogElement)||!c(t)||e.cancelable&&(e.preventDefault(),p(t))}function F(e){let t=e.target;t instanceof HTMLDialogElement&&!t.open&&A(t)}function H(){P++===0&&(document.addEventListener("pointerdown",I,!0),document.addEventListener("pointerup",q,!0),document.addEventListener("click",U),document.addEventListener("cancel",W,!0),document.addEventListener("close",F,!0));let e=!1;return()=>{e||(e=!0,!(--P>0)&&(document.removeEventListener("pointerdown",I,!0),document.removeEventListener("pointerup",q,!0),document.removeEventListener("click",U),document.removeEventListener("cancel",W,!0),document.removeEventListener("close",F,!0)))}}var S=Symbol.for("tangible-ui/vanilla/modal"),d=globalThis;d[S]||(d[S]=D,H());d.TangibleUI=d.TangibleUI||{};d.TangibleUI.modal=d[S];})();