@apliteni/apliteni-ui 0.142.1 → 0.142.4

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 (42) hide show
  1. package/README.md +24 -36
  2. package/guidelines/state-set.md +4 -4
  3. package/package.json +3 -3
  4. package/react/dist/index.css +7 -3
  5. package/react/dist/index.js +12 -5
  6. package/src/index.d.ts +13 -96
  7. package/src/index.js +17 -30
  8. package/src/styles/command-palette.css +9 -5
  9. package/src/styles/drawer.css +8 -0
  10. package/src/styles/dropdown.css +30 -8
  11. package/src/styles/feedback.css +1 -1
  12. package/src/styles/filter-bar.css +5 -2
  13. package/src/styles/input.css +14 -15
  14. package/src/styles/layout.css +5 -2
  15. package/src/styles/table.css +28 -2
  16. package/src/styles/tap-zone.css +9 -4
  17. package/src/styles/topbar.css +8 -6
  18. package/src/components/account-nav.js +0 -37
  19. package/src/components/avatar.js +0 -53
  20. package/src/components/back.js +0 -57
  21. package/src/components/button-busy.js +0 -69
  22. package/src/components/command-palette.js +0 -471
  23. package/src/components/confirm.js +0 -131
  24. package/src/components/drawer.js +0 -169
  25. package/src/components/dropdown.js +0 -1055
  26. package/src/components/feedback.js +0 -171
  27. package/src/components/filter-bar.js +0 -86
  28. package/src/components/footer.js +0 -102
  29. package/src/components/index.js +0 -352
  30. package/src/components/loading.js +0 -127
  31. package/src/components/nav.js +0 -220
  32. package/src/components/overlay.js +0 -263
  33. package/src/components/pagination.js +0 -323
  34. package/src/components/segmented.js +0 -33
  35. package/src/components/shell.js +0 -511
  36. package/src/components/stat.js +0 -82
  37. package/src/components/success.js +0 -131
  38. package/src/components/table-values.js +0 -32
  39. package/src/components/tabs.js +0 -82
  40. package/src/components/toasts.js +0 -118
  41. package/src/components/tooltip.js +0 -347
  42. package/src/components/topbar.js +0 -270
@@ -1,220 +0,0 @@
1
- // Navigation — the kit's primary wayfinding primitives. `nav({ variant })`
2
- // dispatches to sidebarNav(), navTabs() and breadcrumbs(), each also exported
3
- // directly: the three share tokens and classes but almost no markup, so a single
4
- // options bag would mean wildly different fields per variant.
5
- //
6
- // These are NAVIGATION controls, not tab panels — so tabs render as
7
- // <nav> + <a aria-current="page">, not role="tablist" (that is what segmented()
8
- // is for). wireNav() opens sidebar groups and reveals the current route link.
9
- import { esc, icon } from './index.js';
10
- import { playEntrance } from '../motion.js';
11
- import { safeUrl } from '../html.js';
12
- import { observeNavFit, revealCurrentNav, revealFocusedNav } from '../logic/nav.js';
13
- const cx = (...a) => a.filter(Boolean).join(' ');
14
-
15
- // Unique-per-render ids so a section heading can label its own list. Module
16
- // counter (never Date/random) — matches field()'s nextId() in index.js.
17
- let _uid = 0;
18
- const nextId = (p = 'nav') => `${p}-${++_uid}`;
19
-
20
- // A trailing counter/badge on a nav item. `badge` is a number, a string, or
21
- // { text, tone }. Tones map to the badge token set (accent | live | neutral…).
22
- const badgeText = (badge) => {
23
- if (badge == null || badge === '') return '';
24
- const text = typeof badge === 'object' ? badge.text : badge;
25
- return text == null || text === '' ? '' : String(text);
26
- };
27
-
28
- function navBadge(badge) {
29
- const text = badgeText(badge);
30
- if (!text) return '';
31
- const tone = typeof badge === 'object' && badge.tone ? badge.tone : 'neutral';
32
- return `<span class="${esc(cx('ui-nav__badge', `is-${tone}`))}">${esc(text)}</span>`;
33
- }
34
-
35
- // An item's accessible name. It is emitted at every width, not only when
36
- // `collapsed`, so a shell may fold `.ui-nav__label` out of view in CSS and keep
37
- // the icon named. An always-on name overrides the row's own text, so the badge
38
- // has to be spelled into it — otherwise "Pending 3" narrows to "Pending". The
39
- // `title` tooltip is for the collapsed rail only — a narrow touch device has no
40
- // hover to show it with, and the badge is folded away there too.
41
- const leafName = (label, collapsed, badge) => {
42
- const count = badgeText(badge);
43
- const name = esc(count ? `${label} ${count}` : label);
44
- return ` aria-label="${name}"${collapsed ? ` title="${name}"` : ''}`;
45
- };
46
-
47
- // One sidebar leaf: a link (or a plain, aria-disabled span). `collapsed` also
48
- // hides the label visually, leaving the icon hoverable.
49
- function sideLeaf(it, active, { collapsed, sub, current = 'page' } = {}) {
50
- const on = it.id != null && it.id === active;
51
- const disabled = !!it.disabled;
52
- const label = it.label || '';
53
- const lead = it.icon ? `<span class="ui-nav__ic">${icon(it.icon)}</span>` : '';
54
- const text = `<span class="ui-nav__label">${esc(label)}</span>`;
55
- const badge = navBadge(it.badge);
56
- const cls = cx('ui-nav__item', sub && 'ui-nav__item--sub', on && 'is-active', it.danger && 'is-danger', disabled && 'is-disabled');
57
- const name = leafName(label, collapsed, it.badge);
58
- if (disabled) {
59
- return `<li><span class="${cls}" aria-disabled="true"${name}>${lead}${text}${badge}</span></li>`;
60
- }
61
- const attrs = [
62
- `class="${cls}"`,
63
- `href="${esc(safeUrl(it.href || '#' + (it.id ?? '')))}"`,
64
- it.target ? `target="${esc(it.target)}"` : '',
65
- on ? `aria-current="${current}"` : '',
66
- name.trim(),
67
- ].filter(Boolean).join(' ');
68
- return `<li><a ${attrs}>${lead}${text}${badge}</a></li>`;
69
- }
70
-
71
- // A collapsible group: a toggle button (aria-expanded/-controls) over a nested
72
- // list. It opens and closes the same way on the folded rail: forcing it shut
73
- // there hid the current page's own row and left the toggle announcing a list
74
- // nobody could reach.
75
- function sideGroup(it, active, { collapsed, current } = {}) {
76
- const listId = nextId('nav-grp');
77
- const childActive = (it.items || []).some((c) => c.id != null && c.id === active);
78
- const open = it.open != null ? !!it.open : childActive;
79
- const lead = it.icon ? `<span class="ui-nav__ic">${icon(it.icon)}</span>` : '';
80
- const label = it.label || '';
81
- const text = `<span class="ui-nav__label">${esc(label)}</span>`;
82
- const kids = (it.items || []).map((c) => sideLeaf(c, active, { collapsed, sub: true, current })).join('');
83
- const name = leafName(label, collapsed);
84
- const btn =
85
- `<button type="button" class="${cx('ui-nav__item', 'ui-nav__toggle', childActive && 'is-current')}"` +
86
- ` data-nav-toggle aria-expanded="${open ? 'true' : 'false'}" aria-controls="${listId}"${name}>` +
87
- `${lead}${text}<span class="ui-nav__caret" aria-hidden="true"></span></button>`;
88
- return `<li class="${cx('ui-nav__group', open && 'is-open')}">${btn}` +
89
- `<ul class="ui-nav__sub" id="${listId}"${open ? '' : ' hidden'}>${kids}</ul></li>`;
90
- }
91
-
92
- function sideItem(it, active, opts) {
93
- return (it.items && it.items.length) ? sideGroup(it, active, opts) : sideLeaf(it, active, opts);
94
- }
95
-
96
- // Sidebar nav. Pass `sections` ([{ label, items }]) or a flat `items` list.
97
- // items/section items: { id, label, icon?, href?, target?, badge?, danger?,
98
- // disabled?, items?, open? } (items ⇒ collapsible group)
99
- // active id of the current item (gets aria-current="page")
100
- // activeIs 'page', or 'section' when the page on screen sits below the active
101
- // row: the row then carries aria-current="true", because "page" would
102
- // announce the list as the page the reader is on
103
- // collapsed icon-only rail; every item is aria-labelled at every width, and
104
- // collapsed adds the hover tooltip on top
105
- // footer trusted HTML pinned below a divider (e.g. a sign-out link)
106
- // ariaLabel accessible name for the <nav> landmark
107
- export function sidebarNav({
108
- sections, items, active, activeIs = 'page', collapsed = false, footer = '', ariaLabel = 'Sidebar', id,
109
- } = {}) {
110
- const current = activeIs === 'section' ? 'true' : 'page';
111
- const blocks = (sections && sections.length)
112
- ? sections
113
- : [{ items: items || [] }];
114
- const body = blocks.map((sec) => {
115
- const capId = sec.label ? nextId('nav-cap') : '';
116
- const cap = sec.label
117
- ? `<div class="ui-nav__cap" id="${capId}"${collapsed ? ' aria-hidden="true"' : ''}>${esc(sec.label)}</div>`
118
- : '';
119
- const list = `<ul class="ui-nav__list"${capId ? ` aria-labelledby="${capId}"` : ''}>` +
120
- (sec.items || []).map((it) => sideItem(it, active, { collapsed, current })).join('') + `</ul>`;
121
- return `<div class="ui-nav__section">${cap}${list}</div>`;
122
- }).join('');
123
- const foot = footer ? `<div class="ui-nav__foot">${footer}</div>` : '';
124
- return `<nav class="${cx('ui-nav', 'ui-nav--side', collapsed && 'is-collapsed')}"` +
125
- ` aria-label="${esc(ariaLabel)}"${id ? ` id="${esc(id)}"` : ''}>${body}${foot}</nav>`;
126
- }
127
-
128
- // Horizontal page tabs — links, not a tablist. `variant` picks the active
129
- // affordance: 'underline' (default) or 'pill'.
130
- // items { id, label, href?, target?, badge?, disabled? }
131
- // active id of the current tab (aria-current="page")
132
- export function navTabs({
133
- items = [], active, variant = 'underline', ariaLabel = 'Tabs', id,
134
- } = {}) {
135
- const tabs = items.map((it) => {
136
- const on = it.id != null && it.id === active;
137
- const badge = navBadge(it.badge);
138
- const inner = `<span class="ui-nav__tab-label">${esc(it.label)}</span>${badge}`;
139
- if (it.disabled) {
140
- return `<span class="ui-nav__tab is-disabled" aria-disabled="true">${inner}</span>`;
141
- }
142
- const attrs = [
143
- `class="${cx('ui-nav__tab', on && 'is-active')}"`,
144
- `href="${esc(safeUrl(it.href || '#' + (it.id ?? '')))}"`,
145
- it.target ? `target="${esc(it.target)}"` : '',
146
- on ? 'aria-current="page"' : '',
147
- ].filter(Boolean).join(' ');
148
- return `<a ${attrs}>${inner}</a>`;
149
- }).join('');
150
- return `<nav class="${esc(cx('ui-nav', 'ui-nav--tabs', `is-${variant}`))}"` +
151
- ` aria-label="${esc(ariaLabel)}"${id ? ` id="${esc(id)}"` : ''}>${tabs}</nav>`;
152
- }
153
-
154
- // Breadcrumb trail. The last crumb is the current page (aria-current="page",
155
- // rendered as text). Earlier crumbs link when they carry an `href`.
156
- // items { label, href?, target?, icon? }
157
- export function breadcrumbs({ items = [], ariaLabel = 'Breadcrumb', id } = {}) {
158
- const last = items.length - 1;
159
- const crumbs = items.map((it, i) => {
160
- const lead = it.icon ? `<span class="ui-nav__ic">${icon(it.icon)}</span>` : '';
161
- const label = `<span class="ui-nav__crumb-label">${esc(it.label)}</span>`;
162
- const inner = `${lead}${label}`;
163
- const isLast = i === last;
164
- const cell = (!isLast && it.href)
165
- ? `<a class="ui-nav__crumb" href="${esc(safeUrl(it.href))}"${it.target ? ` target="${esc(it.target)}"` : ''}>${inner}</a>`
166
- : `<span class="${cx('ui-nav__crumb', isLast && 'is-current')}"${isLast ? ' aria-current="page"' : ''}>${inner}</span>`;
167
- return `<li class="ui-nav__crumb-item">${cell}</li>`;
168
- }).join('');
169
- return `<nav class="ui-nav ui-nav--crumbs" aria-label="${esc(ariaLabel)}"${id ? ` id="${esc(id)}"` : ''}>` +
170
- `<ol class="ui-nav__crumbs">${crumbs}</ol></nav>`;
171
- }
172
-
173
- // Umbrella dispatcher — the one thing to import when the variant is data-driven.
174
- export function nav({ variant = 'sidebar', ...opts } = {}) {
175
- if (variant === 'tabs') return navTabs(opts);
176
- if (variant === 'breadcrumbs') return breadcrumbs(opts);
177
- return sidebarNav(opts);
178
- }
179
-
180
- // ---- Behaviour -----------------------------------------------------------
181
- // Toggle a sidebar group's `.is-open` and its button's aria-expanded, and
182
- // show/hide the nested list. Idempotent and event-delegated, so it's safe to
183
- // call repeatedly (Storybook re-renders).
184
- let _navGlobalWired = false;
185
-
186
- function toggleGroup(btn) {
187
- const li = btn.closest('.ui-nav__group');
188
- const list = document.getElementById(btn.getAttribute('aria-controls'));
189
- const open = btn.getAttribute('aria-expanded') === 'true';
190
- btn.setAttribute('aria-expanded', open ? 'false' : 'true');
191
- if (li) li.classList.toggle('is-open', !open);
192
- if (list) {
193
- if (open) list.setAttribute('hidden', '');
194
- else { list.removeAttribute('hidden'); playEntrance(list); }
195
- }
196
- }
197
-
198
- const fitObservers = new Map();
199
- export function wireNav(root = document) {
200
- for (const [nav, stop] of fitObservers) {
201
- if (!nav.isConnected) { stop(); fitObservers.delete(nav); }
202
- }
203
- root.querySelectorAll('.ui-nav--tabs').forEach((nav) => {
204
- if (!fitObservers.has(nav)) fitObservers.set(nav, observeNavFit(nav));
205
- revealCurrentNav(nav);
206
- });
207
- // Per-collapsed-rail behaviour would go here; groups use one delegated handler.
208
- if (_navGlobalWired) return;
209
- _navGlobalWired = true;
210
- // A tab row scrolls its own focused link clear of its edge, so the ring the link
211
- // draws is not cut off by the scroll box. Delegated, because the links come and go.
212
- document.addEventListener('focusin', (e) => {
213
- const row = e.target.closest && e.target.closest('.ui-nav--tabs');
214
- if (row) revealFocusedNav(row, e.target);
215
- });
216
- document.addEventListener('click', (e) => {
217
- const btn = e.target.closest && e.target.closest('[data-nav-toggle]');
218
- if (btn) { e.preventDefault(); toggleGroup(btn); }
219
- });
220
- }
@@ -1,263 +0,0 @@
1
- // Overlay primitives — the page state the kit's modal surfaces share. Drawer and Confirm
2
- // are the same problem twice: content over a scrim that owns the keyboard until it is
3
- // answered. What is inert, which overlay Escape talks to and where Tab may go are
4
- // properties of the *page*, so they are answered here from one stack per document rather
5
- // than from either component's own storage. Internal — not re-exported from src/index.js.
6
-
7
- // What each overlay paints on today: a drawer at `--z-overlay` (styles/drawer.css), a
8
- // command palette one above it (styles/command-palette.css) and a confirm above both
9
- // (styles/confirm.css). Three steps and not two, because at equal levels paint order falls
10
- // back to document order and the overlay that owns the keyboard is then not reliably the
11
- // one the reader can see. A palette is summoned deliberately and must be seen, so it goes
12
- // over a drawer that was already open; a confirm is a question about whatever is under it,
13
- // so it goes over both. Absolute values, not ranks, so a sheet that moves and a table that
14
- // did not is a failed test — stories/overlay-css.test.js holds all three.
15
- export const OVERLAY_LAYER = { drawer: 100, palette: 101, confirm: 102 };
16
-
17
- const FOCUSABLE = [
18
- 'a[href]', 'button:not([disabled])', 'input:not([disabled])',
19
- 'select:not([disabled])', 'textarea:not([disabled])',
20
- '[tabindex]:not([tabindex="-1"])',
21
- ].join(',');
22
-
23
- // Per document, not per module: JSDOM tests and Storybook iframes each get their
24
- // own page, and one global stack would let one page's overlays decide another's.
25
- // stack open overlays, bottom → top: { root, panel, dismiss, layer }
26
- // marked what the current top hid, with the state to give back
27
- const pages = new WeakMap();
28
- function pageOf(doc) {
29
- let page = pages.get(doc);
30
- if (!page) { page = { stack: [], marked: [], keys: false }; pages.set(doc, page); }
31
- return page;
32
- }
33
-
34
- // Focusable to the *browser*, not merely matching the selector. A control in a closed
35
- // overlay, an inert subtree or a hidden ancestor is skipped by the real tab order, so a
36
- // trap that counts it wraps at an element focus never reaches.
37
- function reachable(el) {
38
- for (let n = el; n && n.nodeType === 1; n = n.parentElement) {
39
- if (n.inert || n.hasAttribute('inert') || n.hasAttribute('hidden')) return false;
40
- const overlayRoot = n.hasAttribute('data-drawer') || n.hasAttribute('data-confirm')
41
- || n.hasAttribute('data-cmdk');
42
- if (overlayRoot && !n.classList.contains('is-open')) return false;
43
- }
44
- // Browsers can answer the rest properly; JSDOM has no layout and no such method.
45
- return typeof el.checkVisibility !== 'function'
46
- || el.checkVisibility({ visibilityProperty: true, contentVisibilityAuto: true });
47
- }
48
-
49
- // Focusable controls inside the panel, in DOM order.
50
- export function focusablesIn(panel) {
51
- return Array.from(panel.querySelectorAll(FOCUSABLE)).filter(reachable);
52
- }
53
-
54
- // Hide everything *outside* `root` from AT + the tab order: walk through a shadow
55
- // host when present, then to body, and mark each
56
- // ancestor's other children. Scrim and panel live inside the root so they stay
57
- // interactive; a drawer under an aria-modal alertdialog is outside it and must not be.
58
- function mark(page, doc, root) {
59
- let node = root;
60
- while (node && node !== doc.body) {
61
- const tree = node.getRootNode();
62
- const parent = node.parentElement || (tree.host ? tree : null);
63
- if (!parent) break;
64
- for (const sib of parent.children) {
65
- if (sib === node) continue;
66
- page.marked.push([sib, sib.getAttribute('aria-hidden'), sib.hasAttribute('inert')]);
67
- sib.setAttribute('aria-hidden', 'true');
68
- sib.setAttribute('inert', '');
69
- sib.inert = true;
70
- }
71
- node = parent.host || parent;
72
- }
73
- }
74
-
75
- function unmark(page) {
76
- for (let i = page.marked.length - 1; i >= 0; i--) {
77
- const [el, ariaHidden, hadInert] = page.marked[i];
78
- if (ariaHidden == null) el.removeAttribute('aria-hidden');
79
- else el.setAttribute('aria-hidden', ariaHidden);
80
- if (!hadInert) { el.removeAttribute('inert'); el.inert = false; }
81
- }
82
- page.marked = [];
83
- }
84
-
85
- // Recompute the page from the stack — never replay a snapshot taken when an overlay
86
- // opened, because by the time it closes that snapshot describes a page that has moved on.
87
- // Roots torn down while open drop out here.
88
- function sync(doc) {
89
- const page = pageOf(doc);
90
- for (let i = page.stack.length - 1; i >= 0; i--) {
91
- if (!page.stack[i].root.isConnected) page.stack.splice(i, 1);
92
- }
93
- unmark(page);
94
- const top = page.stack[page.stack.length - 1];
95
- if (top) mark(page, doc, top.root);
96
- }
97
-
98
- // One keydown owner per document. Escape closes the single topmost overlay and
99
- // Tab is trapped in that one's panel, so the answer never turns on which
100
- // component registered a listener first or on where focus happens to be.
101
- function ownKeys(page, doc) {
102
- if (page.keys) return;
103
- page.keys = true;
104
- doc.addEventListener('keydown', (e) => {
105
- const top = page.stack[page.stack.length - 1];
106
- if (!top) return;
107
- if (e.key === 'Escape') {
108
- if (top.dismiss) { e.preventDefault(); top.dismiss(); }
109
- } else if (e.key === 'Tab') {
110
- trapTab(top.panel, e);
111
- }
112
- });
113
- }
114
-
115
- // Node.DOCUMENT_POSITION_PRECEDING, without reaching for a global Node that a
116
- // document-scoped module has no business assuming is there.
117
- const PRECEDING = 2;
118
-
119
- // One way onto the stack. `where` picks the slot; everything after it — the
120
- // duplicate guard, the key owner, the recompute — is the same either way. Every
121
- // entry carries its layer, so the comparisons in the slot pickers never meet undefined.
122
- function place(root, panel, dismiss, layer, where) {
123
- const doc = root.ownerDocument;
124
- const page = pageOf(doc);
125
- if (page.stack.some((e) => e.root === root)) return;
126
- page.stack.splice(where(page), 0, { root, panel, dismiss, layer });
127
- ownKeys(page, doc);
128
- sync(doc);
129
- }
130
-
131
- // The layer this root actually paints on. In a browser the live z-index is the truth, so
132
- // a consumer who moves an overlay in their own stylesheet gets the keyboard on the layer
133
- // they can see. JSDOM hands back declared text rather than a number, so under test the
134
- // passed constant stands — `auto` must not read as 0, and anything unparseable falls
135
- // through.
136
- function paintedLayer(root, layer) {
137
- const painted = root.ownerDocument.defaultView?.getComputedStyle(root)?.zIndex;
138
- const live = painted ? Number(painted) : NaN;
139
- return Number.isFinite(live) ? live : layer;
140
- }
141
-
142
- /**
143
- * Put an overlay on the page. `dismiss` is what Escape calls — pass null for one
144
- * that refuses to be dismissed, and Escape then does nothing rather than falling
145
- * through to the overlay underneath.
146
- *
147
- * It goes on top of everything it paints over, and under anything painted above
148
- * it. Opening is history the stack can order by, but only within a layer: an
149
- * overlay opened under one already on screen — a drawer opened from a palette
150
- * row, a palette opened while a confirm is up — is not the one the reader is
151
- * looking at, and giving it Escape and the Tab trap would put the keyboard on a
152
- * surface that is covered.
153
- */
154
- export function pushOverlay(root, panel, dismiss, layer) {
155
- const level = paintedLayer(root, layer);
156
- place(root, panel, dismiss, level, (page) => {
157
- const at = page.stack.findIndex((e) => e.layer > level);
158
- return at === -1 ? page.stack.length : at;
159
- });
160
- }
161
-
162
- /**
163
- * Take on a root that arrived already open — markup rendered with `open: true`, which
164
- * nobody called open…() for. Without this its aria-modal is a claim the page contradicts.
165
- * It goes in by PAINT ORDER, because wiring has no history to order by; document position
166
- * separates two overlays on the same layer, where the later root paints on top (CSS 2.2
167
- * Appendix E, steps 8 and 9). A root that renders closed is left alone.
168
- */
169
- export function adoptOverlay(root, panel, dismiss, layer) {
170
- if (!root.classList.contains('is-open')) return;
171
- const level = paintedLayer(root, layer);
172
- place(root, panel, dismiss, level, (page) => {
173
- const at = page.stack.findIndex((e) => e.layer > level
174
- || (e.layer === level && (e.root.compareDocumentPosition(root) & PRECEDING)));
175
- return at === -1 ? page.stack.length : at;
176
- });
177
- }
178
-
179
- // Where an overlay puts focus when it opens: the first stop inside its panel,
180
- // else the panel itself. One rule serves all three, because the kit's own markup
181
- // puts each one's opening target first — a drawer's first control, the palette's
182
- // text box, and the confirm's safe answer, which its panel renders before the
183
- // destructive one.
184
- function initialFocus(panel) {
185
- return (panel && focusablesIn(panel)[0]) || panel;
186
- }
187
-
188
- // What `el` can actually be handed focus, or null when nothing can take it. An
189
- // overlay stays open while the page carries on, so by the time it closes the
190
- // element it came from may be detached — look for whatever inherited its identity
191
- // in the re-render — or sitting in a subtree that a lower overlay has just made
192
- // inert again, where focus() is a silent no-op. <body> is null too: with no
193
- // tabindex it cannot be focused either, and `activeElement === body` is what
194
- // having no focus looks like, which is what an overlay summoned by its hotkey out
195
- // of a page nobody had touched yet records as the place it came from.
196
- function focusTarget(el, doc) {
197
- const live = el && !el.isConnected && el.id ? doc?.getElementById(el.id) : el;
198
- if (!live || !live.isConnected || live === live.ownerDocument.body) return null;
199
- return reachable(live) && typeof live.focus === 'function' ? live : null;
200
- }
201
-
202
- /**
203
- * Take an overlay off the page, wherever in the stack it sits. `opener` is what
204
- * the caller is about to hand focus back to, which this has to see: one overlay
205
- * can close over another that is still open, and the opener is then out on a page
206
- * that lower overlay is holding inert. Nobody would place focus at all, and the
207
- * reader would be left on <body> looking at a panel that holds neither the
208
- * keyboard nor the Tab trap — so open the panel now on top where it opens.
209
- */
210
- export function popOverlay(root, opener) {
211
- const doc = root.ownerDocument;
212
- const page = pageOf(doc);
213
- const at = page.stack.findIndex((e) => e.root === root);
214
- if (at !== -1) page.stack.splice(at, 1);
215
- sync(doc);
216
- const top = page.stack[page.stack.length - 1];
217
- if (top && opener && !focusTarget(opener, doc)) initialFocus(top.panel)?.focus();
218
- }
219
-
220
- /**
221
- * Recompute from what is still on the page. The wiring calls this, and the
222
- * wiring runs on every re-render, so an overlay destroyed while open cannot
223
- * leave the page inert with no node left to hand it back.
224
- */
225
- export function syncOverlays(doc = document) {
226
- sync(doc);
227
- }
228
-
229
- /**
230
- * Hand focus back to `el`. The overlay was open while the page carried on, so
231
- * the element it came from may be detached by now — and focus() on a detached
232
- * node is a silent no-op that leaves the reader with no place on the page. Look
233
- * for whatever inherited its identity in the re-render, then give up to the page.
234
- *
235
- * With another overlay still open, the only place worth having focus is inside
236
- * it: an opener that overlay is holding inert cannot take focus at all, popOverlay
237
- * has already opened the panel now on top for exactly that case, and <body> behind
238
- * a live modal is not somewhere to give up to.
239
- */
240
- export function returnFocus(el, doc) {
241
- if (doc && pageOf(doc).stack.length) { focusTarget(el, doc)?.focus(); return; }
242
- const live = el && !el.isConnected && el.id ? doc?.getElementById(el.id) : el;
243
- if (live && live.isConnected && typeof live.focus === 'function') { live.focus(); return; }
244
- doc?.body?.focus?.();
245
- }
246
-
247
- // Trap Tab within the panel while open; wrap at both ends, and pull focus back
248
- // in when it has fallen outside the panel altogether.
249
- export function trapTab(panel, e) {
250
- if (e.key !== 'Tab' || !panel) return;
251
- const items = focusablesIn(panel);
252
- if (!items.length) { e.preventDefault(); panel.focus(); return; }
253
- const first = items[0];
254
- const last = items[items.length - 1];
255
- const active = panel.getRootNode().activeElement || panel.ownerDocument.activeElement;
256
- if (!panel.contains(active)) {
257
- e.preventDefault(); (e.shiftKey ? last : first).focus();
258
- } else if (e.shiftKey && (active === first || active === panel)) {
259
- e.preventDefault(); last.focus();
260
- } else if (!e.shiftKey && active === last) {
261
- e.preventDefault(); first.focus();
262
- }
263
- }