@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,471 +0,0 @@
1
- import { SCORE, scoreCommand, rankCommands, rankGroups, paletteHotkey, norm } from '../logic/command-palette.js';
2
- export { SCORE, scoreCommand, rankCommands, rankGroups, paletteHotkey } from '../logic/command-palette.js';
3
- // Command palette — one overlay, a text box and a ranked list of things to run
4
- // or go to.
5
- //
6
- // container.innerHTML = commandPalette({ groups });
7
- // wireCommandPalette(container); // hotkey, ranking, keys, Esc, focus
8
- //
9
- // The kit ships the shell and the ranking and names no result kinds; a row goes
10
- // somewhere, runs something, or asks a confirm first. Inertness, Escape and the
11
- // focus trap come from ./overlay.js, the stack the drawer and the confirm share.
12
- // why: docs/components.md#the-command-palette
13
- import { esc, icon } from './index.js';
14
- import { OVERLAY_LAYER, adoptOverlay, popOverlay, pushOverlay, returnFocus, syncOverlays } from './overlay.js';
15
- import { safeUrl } from '../html.js';
16
- const cx = (...a) => a.filter(Boolean).join(' ');
17
-
18
- let _uid = 0;
19
- const nextId = (p = 'cmdk') => `${p}-${++_uid}`;
20
-
21
- // The three fields a query is matched against, written onto the row so the
22
- // wiring can re-rank what is already rendered without being handed the data a
23
- // second time. Three attributes and not one blob: the ranking weighs a name
24
- // above a note, and a row carrying `label description keywords` in one string
25
- // would have its description scored as if it were its name.
26
- function searchAttrs(it) {
27
- const keywords = (it.keywords || []).map(norm).filter(Boolean).join('|');
28
- return [
29
- `data-label="${esc(norm(it.label))}"`,
30
- keywords ? `data-keywords="${esc(keywords)}"` : '',
31
- it.description ? `data-desc="${esc(norm(it.description))}"` : '',
32
- ].filter(Boolean).join(' ');
33
- }
34
-
35
- /** The fields back out of a rendered row, in the shape scoreCommand() takes. */
36
- const fieldsOf = (el) => ({
37
- label: el.dataset.label || '',
38
- keywords: el.dataset.keywords ? el.dataset.keywords.split('|') : [],
39
- description: el.dataset.desc || '',
40
- });
41
-
42
- // A shortcut hint: 'g then i' or ['⌘', 'K'] or '⌘K'. Rendered as <kbd>, which is
43
- // what it is, and never as part of the item's accessible name — the row already
44
- // says what it does, and a screen reader reading "G then I" after every label is
45
- // noise a sighted reader can simply skip.
46
- function keysFor(shortcut) {
47
- if (!shortcut) return '';
48
- const keys = Array.isArray(shortcut) ? shortcut : [shortcut];
49
- return `<span class="ui-cmdk__keys" aria-hidden="true">`
50
- + keys.map((k) => `<kbd class="ui-cmdk__key">${esc(k)}</kbd>`).join('')
51
- + '</span>';
52
- }
53
-
54
- /**
55
- * One result row.
56
- *
57
- * Always a <div role="option">, never a link or a button: an option in a listbox
58
- * is reached with an arrow key and never with Tab, and both of the other tags
59
- * put every row into the page's tab order, where forty of them stand between a
60
- * reader and the rest of the palette. `href` is carried in data- and followed by
61
- * the wiring, which is also what makes Cmd+Enter open it in a tab.
62
- *
63
- * A destructive item that names no confirm is rendered DISABLED. The kit's rule
64
- * is that a delete asks first (docs/components.md#the-command-palette), and a
65
- * palette is the one surface where a reader is typing fast and choosing from a
66
- * list that reorders under them.
67
- */
68
- function paletteItem(it, uid, index, active) {
69
- const disabled = isRefused(it);
70
- const lead = it.icon ? `<span class="ui-cmdk__ic">${icon(it.icon)}</span>` : '';
71
- const desc = it.description
72
- ? `<span class="ui-cmdk__desc">${esc(it.description)}</span>` : '';
73
- const attrs = [
74
- // `is-danger` only while the row is actually offered: a destructive command
75
- // the palette refuses to run is an unavailable row, not a dangerous one, and
76
- // painting it in the danger signal would spend that signal on something
77
- // nothing can press.
78
- `class="${cx('ui-cmdk__item', it.danger && !disabled && 'is-danger', disabled && 'is-disabled', active && 'is-active')}"`,
79
- 'role="option"',
80
- 'tabindex="-1"',
81
- `id="${esc(uid)}-o${esc(index)}"`,
82
- 'data-cmdk-item',
83
- `data-i="${esc(index)}"`,
84
- searchAttrs(it),
85
- it.id != null ? `data-id="${esc(it.id)}"` : '',
86
- it.href && !disabled ? `data-href="${esc(safeUrl(it.href))}"` : '',
87
- it.confirm && !disabled ? `data-confirm-open="${esc(it.confirm)}"` : '',
88
- it.confirm && !disabled ? 'aria-haspopup="dialog"' : '',
89
- disabled ? 'aria-disabled="true"' : '',
90
- `aria-selected="${active ? 'true' : 'false'}"`,
91
- ].filter(Boolean).join(' ');
92
- const badge = it.badge ? `<span class="ui-cmdk__badge">${esc(it.badge)}</span>` : '';
93
- return `<div ${attrs}>${lead}`
94
- + `<span class="ui-cmdk__main"><span class="ui-cmdk__label">${esc(it.label)}</span>${desc}</span>`
95
- + `${badge}${keysFor(it.shortcut)}</div>`;
96
- }
97
-
98
- /**
99
- * A destructive item that names no confirm is refused: the kit's rule is that a
100
- * delete asks first, and the palette is the one surface where a reader is
101
- * typing fast and choosing from a list that reorders under them.
102
- */
103
- const isRefused = (it) => !!it.disabled || (!!it.danger && !it.confirm);
104
-
105
- /**
106
- * Where the active row starts: the first row Enter could run.
107
- *
108
- * The markup carries it, rather than waiting for the wiring to add it, so a
109
- * palette rendered open by a server already says which row Enter answers — and
110
- * the React component, which has no wiring step at all, renders the same thing.
111
- */
112
- function firstEnabledIndex(groups) {
113
- let n = 0;
114
- for (const g of groups || []) {
115
- for (const it of g.items || []) {
116
- if (!isRefused(it)) return n;
117
- n += 1;
118
- }
119
- }
120
- return -1;
121
- }
122
-
123
- /**
124
- * The inside of the listbox: the groups, in the caller's order.
125
- *
126
- * Exported on its own because a palette fed by a server re-renders THIS and not
127
- * the shell around it — the input keeps its value, its focus and its caret.
128
- */
129
- export function commandPaletteList(groups = [], { uid = nextId(), from = 0 } = {}) {
130
- let n = from;
131
- const activeAt = firstEnabledIndex(groups) + from;
132
- return groups.map((g, gi) => {
133
- const items = (g.items || []);
134
- if (!items.length) return '';
135
- const headId = g.label ? `${uid}-g${gi}` : null;
136
- const head = headId
137
- ? `<div class="ui-cmdk__group-head" id="${esc(headId)}">${esc(g.label)}</div>` : '';
138
- const rows = items.map((it) => paletteItem(it, uid, n, n++ === activeAt)).join('');
139
- return `<div class="ui-cmdk__group" role="group" data-cmdk-group data-i="${gi}"`
140
- + `${headId ? ` aria-labelledby="${esc(headId)}"` : ''}>${head}${rows}</div>`;
141
- }).join('');
142
- }
143
-
144
- /**
145
- * The public factory. Returns an HTML string; wire it with wireCommandPalette().
146
- *
147
- * `specimen` renders it open as a PICTURE — same markup, minus the data-cmdk
148
- * hook and aria-modal — so a documentation page can show three at once without
149
- * any of them owning the page's keyboard. Use `open` when it is real.
150
- *
151
- * @param {object} [o]
152
- * @param {Array} [o.groups] [{ label, items: [{ id, label, description, icon,
153
- * keywords, shortcut, badge, href, confirm, danger,
154
- * disabled }] }]
155
- * @param {Array} [o.items] a flat list — the same thing as one unlabelled group
156
- * @param {string} [o.label] accessible name of the dialog and the text box
157
- * @param {string} [o.placeholder] the text box's placeholder
158
- * @param {string} [o.query] the query it renders with
159
- * @param {string} [o.empty] what it says when nothing matches
160
- * @param {string} [o.density] 'compact' (default) | 'roomy'
161
- * @param {boolean} [o.hint] draw the key legend along the bottom
162
- * @param {boolean} [o.rank] false → the caller ranks, and is asked for results
163
- * @param {boolean} [o.hotkey] false → this one does not answer Cmd/Ctrl+K
164
- * @param {boolean} [o.open] render already-open, as a real dialog
165
- * @param {boolean} [o.specimen] render open as a picture of the dialog
166
- * @param {string} [o.id] root id a [data-cmdk-open] trigger targets
167
- * @returns {string} html
168
- */
169
- export function commandPalette({
170
- groups, items, label = 'Command palette',
171
- placeholder = 'Search or run a command…', query = '',
172
- empty = 'No matches', density = 'compact', hint = true,
173
- rank = true, hotkey = true, open = false, specimen = false, id,
174
- } = {}) {
175
- const uid = nextId();
176
- const given = groups && groups.length ? groups : [{ items: items || [] }];
177
- // Rendered with a query in it, the factory ranks — so a palette a server drew
178
- // against `?q=inv` and the same palette after a keystroke are the same list in
179
- // the same order, and a specimen of a ranked palette is not a hand-arrangement.
180
- const list = rank && query ? rankGroups(given, query) : given;
181
- const rows = list.reduce((n, g) => n + (g.items || []).length, 0);
182
- const activeAt = firstEnabledIndex(list);
183
- const inputId = `${uid}-q`;
184
- const listId = `${uid}-list`;
185
-
186
- const inputAttrs = [
187
- 'class="ui-cmdk__input"', 'type="text"', `id="${inputId}"`,
188
- 'role="combobox"', 'aria-autocomplete="list"', 'aria-expanded="true"',
189
- `aria-controls="${listId}"`, `aria-label="${esc(label)}"`,
190
- `placeholder="${esc(placeholder)}"`, `value="${esc(query)}"`,
191
- 'autocomplete="off"', 'autocorrect="off"', 'spellcheck="false"',
192
- activeAt >= 0 ? `aria-activedescendant="${uid}-o${activeAt}"` : '',
193
- 'data-cmdk-input',
194
- ].filter(Boolean).join(' ');
195
-
196
- const legend = hint
197
- ? '<div class="ui-cmdk__foot" aria-hidden="true">'
198
- + '<span><kbd class="ui-cmdk__key">↑</kbd><kbd class="ui-cmdk__key">↓</kbd> move</span>'
199
- + '<span><kbd class="ui-cmdk__key">↵</kbd> run</span>'
200
- + '<span><kbd class="ui-cmdk__key">esc</kbd> close</span>'
201
- + '</div>'
202
- : '';
203
-
204
- const rootCls = cx('ui-cmdk', density === 'roomy' && 'ui-cmdk--roomy', (open || specimen) && 'is-open');
205
- const rootAttrs = [
206
- `class="${rootCls}"`,
207
- specimen ? '' : 'data-cmdk',
208
- rank ? '' : 'data-cmdk-rank="off"',
209
- hotkey && !specimen ? 'data-cmdk-hotkey' : '',
210
- id ? `id="${esc(id)}"` : '',
211
- ].filter(Boolean).join(' ');
212
-
213
- return `<div ${rootAttrs}>`
214
- + '<div class="ui-cmdk__scrim" data-cmdk-scrim></div>'
215
- + `<div class="ui-cmdk__panel" role="dialog"${specimen ? '' : ' aria-modal="true"'}`
216
- + ` aria-label="${esc(label)}" tabindex="-1" data-cmdk-panel>`
217
- + '<div class="ui-cmdk__search">'
218
- + `<span class="ui-cmdk__search-ic" aria-hidden="true">${icon('search')}</span>`
219
- + `<input ${inputAttrs}>`
220
- + '</div>'
221
- + `<div class="ui-cmdk__list" id="${listId}" role="listbox" aria-label="${esc(label)} results" data-cmdk-list>`
222
- + commandPaletteList(list, { uid })
223
- + '</div>'
224
- + `<p class="ui-cmdk__empty" data-cmdk-empty${rows ? ' hidden' : ''}>${esc(empty)}</p>`
225
- + '<p class="ui-sr" role="status" aria-live="polite" data-cmdk-status></p>'
226
- + legend
227
- + '</div></div>';
228
- }
229
-
230
- // ---- Shared behaviour ----------------------------------------------------
231
- // Per-instance handlers attach once (guarded by a flag on the node); the
232
- // document-level hotkey and [data-cmdk-open] delegation attach once per
233
- // document. Safe to call repeatedly (Storybook re-renders).
234
-
235
- const inputOf = (root) => root.querySelector('[data-cmdk-input]');
236
- const listOf = (root) => root.querySelector('[data-cmdk-list]');
237
- const optionsOf = (root) => Array.from(root.querySelectorAll('[data-cmdk-item]'));
238
- const visibleOptions = (root) => optionsOf(root)
239
- .filter((el) => !el.hidden && el.getAttribute('aria-disabled') !== 'true');
240
-
241
- /** Mark one option active. DOM focus never moves: the text box keeps it. */
242
- function setActive(root, el) {
243
- for (const opt of optionsOf(root)) {
244
- const on = opt === el;
245
- opt.classList.toggle('is-active', on);
246
- opt.setAttribute('aria-selected', on ? 'true' : 'false');
247
- }
248
- const input = inputOf(root);
249
- if (!input) return;
250
- if (el) input.setAttribute('aria-activedescendant', el.id);
251
- else input.removeAttribute('aria-activedescendant');
252
- // A row scrolled out of the list is a row the reader cannot see they are on.
253
- if (el && typeof el.scrollIntoView === 'function') el.scrollIntoView({ block: 'nearest' });
254
- }
255
-
256
- const activeOf = (root) => root.querySelector('[data-cmdk-item].is-active');
257
-
258
- /**
259
- * Say how many results there are, once, politely.
260
- *
261
- * The count and not the rows: a palette re-ranks on every keystroke, and a live
262
- * region holding the rows would read the whole list out again on each one. The
263
- * row the reader is on is announced by aria-activedescendant instead, which is
264
- * the combobox pattern's own answer.
265
- */
266
- function announce(root, n) {
267
- const status = root.querySelector('[data-cmdk-status]');
268
- if (!status) return;
269
- const next = n === 0 ? 'No results' : `${n} result${n === 1 ? '' : 's'}`;
270
- if (status.textContent !== next) status.textContent = next;
271
- }
272
-
273
- /**
274
- * Re-rank what is rendered against what is typed.
275
- *
276
- * The rows are scored where they stand — the wiring reads each row's
277
- * `data-label`, `data-keywords` and `data-desc` rather than being handed the
278
- * items a second time, so a palette rendered by a server and one built in the
279
- * browser behave the same. Groups are carried by their best row, and the
280
- * caller's order breaks every tie, at both levels.
281
- */
282
- function applyQuery(root) {
283
- const list = listOf(root);
284
- const input = inputOf(root);
285
- if (!list || !input) return;
286
- const q = input.value;
287
- const ranking = root.getAttribute('data-cmdk-rank') !== 'off';
288
-
289
- let shown = 0;
290
- const groups = Array.from(list.querySelectorAll('[data-cmdk-group]'));
291
- for (const group of groups) {
292
- const rows = Array.from(group.querySelectorAll('[data-cmdk-item]'));
293
- const scored = rows.map((el, i) => ({
294
- el,
295
- i: Number(el.dataset.i ?? i),
296
- score: ranking ? scoreCommand(fieldsOf(el), q) : 1,
297
- }));
298
- for (const r of scored) {
299
- r.el.hidden = r.score === 0;
300
- if (r.score > 0) shown += 1;
301
- }
302
- const live = scored.filter((r) => r.score > 0);
303
- if (ranking) {
304
- live.sort((a, b) => b.score - a.score || a.i - b.i);
305
- for (const r of live) group.append(r.el);
306
- }
307
- group.hidden = live.length === 0;
308
- group.dataset.best = String(live.length ? live[0].score : 0);
309
- }
310
- if (ranking) {
311
- const live = groups.filter((g) => !g.hidden);
312
- live.sort((a, b) => Number(b.dataset.best) - Number(a.dataset.best)
313
- || Number(a.dataset.i) - Number(b.dataset.i));
314
- for (const g of live) list.append(g);
315
- }
316
-
317
- const emptyMsg = root.querySelector('[data-cmdk-empty]');
318
- if (emptyMsg) emptyMsg.hidden = shown > 0;
319
- announce(root, shown);
320
- setActive(root, visibleOptions(root)[0] || null);
321
- }
322
-
323
- /**
324
- * Hand the palette a new set of results.
325
- *
326
- * This is the seam a product feeds. Called with groups it renders them; called
327
- * with a string it takes the markup as it is, which is how a server-rendered
328
- * page answers its own `ui-command-query`. Either way the text box is untouched.
329
- */
330
- export function setPaletteResults(root, groups) {
331
- const list = listOf(root);
332
- if (!list) return;
333
- list.innerHTML = typeof groups === 'string' ? groups : commandPaletteList(groups, { uid: list.id.replace(/-list$/, '') });
334
- applyQuery(root);
335
- }
336
-
337
- /** Open it, remembering what to give focus back to. */
338
- export function openCommandPalette(root, returnFocusTo) {
339
- if (!root || root.classList.contains('is-open')) return;
340
- root.__cmdkReturn = returnFocusTo
341
- || (document.activeElement instanceof HTMLElement ? document.activeElement : null);
342
- root.classList.add('is-open');
343
- const panel = root.querySelector('[data-cmdk-panel]');
344
- pushOverlay(root, panel, () => closeCommandPalette(root), OVERLAY_LAYER.palette);
345
- const input = inputOf(root);
346
- // It opens empty. A palette that comes back holding the last query shows a
347
- // list that answers a question the reader has already finished asking, and
348
- // the first keystroke then appends to it.
349
- if (input) { input.value = ''; input.focus(); }
350
- applyQuery(root);
351
- }
352
-
353
- export function closeCommandPalette(root) {
354
- if (!root || !root.classList.contains('is-open')) return;
355
- root.classList.remove('is-open');
356
- const back = root.__cmdkReturn;
357
- root.__cmdkReturn = null;
358
- // A palette row can open a drawer, and the palette then closes over a drawer
359
- // that is holding the page inert — including whatever summoned the palette.
360
- // popOverlay is passed `back` so it can see that and open the drawer's panel.
361
- popOverlay(root, back);
362
- returnFocus(back, root.ownerDocument);
363
- }
364
-
365
- /**
366
- * Run what the reader chose.
367
- *
368
- * An item that names a confirm is left alone: its `data-confirm-open` is the
369
- * kit's own trigger, and the confirm opens ABOVE the palette on the shared
370
- * overlay stack, so Escape answers the question rather than closing the palette
371
- * underneath it.
372
- */
373
- function activate(root, el, e) {
374
- if (!el || el.getAttribute('aria-disabled') === 'true') return;
375
- const detail = { id: el.dataset.id, href: el.dataset.href || null, item: el };
376
- const newTab = !!(e && (e.metaKey || e.ctrlKey));
377
- const view = root.ownerDocument.defaultView;
378
- // The document's own constructor, not the global one: a page under test is a
379
- // second document, and an Event built by another realm's class is refused by it.
380
- root.dispatchEvent(new view.CustomEvent('ui-command', { detail, bubbles: true }));
381
- if (el.hasAttribute('data-confirm-open')) return; // confirm() takes it from here
382
- closeCommandPalette(root);
383
- const href = el.dataset.href;
384
- if (!href) return;
385
- if (newTab) view?.open(href, '_blank', 'noopener');
386
- else if (view) view.location.href = href;
387
- }
388
-
389
- function onKeydown(root, e) {
390
- const options = visibleOptions(root);
391
- const at = options.indexOf(activeOf(root));
392
- if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
393
- if (!options.length) return;
394
- e.preventDefault();
395
- const step = e.key === 'ArrowDown' ? 1 : -1;
396
- // Wrapping, because the list is short and a reader holding Down to see what
397
- // is at the end should not have to let go to get back to the top.
398
- const next = (at + step + options.length) % options.length;
399
- setActive(root, options[next]);
400
- } else if (e.key === 'Enter') {
401
- if (at === -1) return;
402
- e.preventDefault();
403
- activate(root, options[at], e);
404
- }
405
- // Escape is not handled here. overlay.js owns it for every overlay on the
406
- // page, so one Escape closes the one on top — the confirm this palette opened
407
- // before the palette itself.
408
- }
409
-
410
- export function wireCommandPalette(scope = document) {
411
- const root = scope === document ? document : scope;
412
- root.querySelectorAll('[data-cmdk]').forEach((cmdk) => {
413
- if (cmdk.__cmdkWired) return;
414
- cmdk.__cmdkWired = true;
415
-
416
- cmdk.querySelector('[data-cmdk-scrim]')?.addEventListener('click', () => closeCommandPalette(cmdk));
417
- const input = inputOf(cmdk);
418
- input?.addEventListener('input', () => {
419
- applyQuery(cmdk);
420
- if (cmdk.getAttribute('data-cmdk-rank') === 'off') {
421
- const view = cmdk.ownerDocument.defaultView;
422
- cmdk.dispatchEvent(new view.CustomEvent('ui-command-query', {
423
- detail: { query: input.value }, bubbles: true,
424
- }));
425
- }
426
- });
427
- cmdk.addEventListener('keydown', (e) => onKeydown(cmdk, e));
428
- // Pointer: hovering moves the active row the way every palette does, and the
429
- // click lands on mouseup like a menu item rather than on mousedown.
430
- listOf(cmdk)?.addEventListener('mousemove', (e) => {
431
- const row = e.target.closest?.('[data-cmdk-item]');
432
- if (row && !row.hidden && row !== activeOf(cmdk)) setActive(cmdk, row);
433
- });
434
- listOf(cmdk)?.addEventListener('click', (e) => {
435
- const row = e.target.closest?.('[data-cmdk-item]');
436
- if (row) activate(cmdk, row, e);
437
- });
438
-
439
- applyQuery(cmdk);
440
- adoptOverlay(cmdk, cmdk.querySelector('[data-cmdk-panel]'), () => closeCommandPalette(cmdk), OVERLAY_LAYER.palette);
441
- });
442
-
443
- const doc = scope === document ? document : (scope.ownerDocument || document);
444
- if (!doc.__cmdkGlobalWired) {
445
- doc.__cmdkGlobalWired = true;
446
- doc.addEventListener('click', (e) => {
447
- const opener = e.target.closest?.('[data-cmdk-open]');
448
- if (!opener) return;
449
- e.preventDefault();
450
- const target = doc.getElementById(opener.getAttribute('data-cmdk-open'));
451
- if (target) openCommandPalette(target, opener);
452
- });
453
- // Cmd/Ctrl+K opens the first palette on the page that asked for the key.
454
- // Ctrl+K alone is left to a text box the reader is typing in — it is
455
- // kill-to-end-of-line there on every platform — while Cmd+K is answered
456
- // wherever focus is, because it is nothing else's key.
457
- doc.addEventListener('keydown', (e) => {
458
- if (e.key !== 'k' && e.key !== 'K') return;
459
- if (!(e.metaKey || e.ctrlKey) || e.altKey || e.shiftKey) return;
460
- const cmdk = doc.querySelector('[data-cmdk][data-cmdk-hotkey]');
461
- if (!cmdk) return;
462
- const typing = doc.activeElement;
463
- const inField = typing && /^(INPUT|TEXTAREA)$/.test(typing.tagName) && !cmdk.contains(typing);
464
- if (inField && !e.metaKey) return;
465
- e.preventDefault();
466
- if (cmdk.classList.contains('is-open')) closeCommandPalette(cmdk);
467
- else openCommandPalette(cmdk, typing instanceof HTMLElement ? typing : null);
468
- });
469
- }
470
- syncOverlays(doc);
471
- }
@@ -1,131 +0,0 @@
1
- // Confirm — the kit's confirmation dialog: a question the page stops for.
2
- //
3
- // container.innerHTML = confirm({ title, body, confirmLabel, cancelLabel });
4
- // wireConfirm(container); // scrim/Esc/answers + focus trap
5
- //
6
- // A page trigger opens it by id: <button data-confirm-open="ID">. Answering is
7
- // the caller's job — a listener on [data-confirm-accept] is where the
8
- // destructive work goes — and focus opens on the SAFE answer, so a reader who
9
- // hits Enter out of habit keeps what they have.
10
- //
11
- // Inertness, Escape and the focus trap come from ./overlay.js: one stack for
12
- // every overlay on the page.
13
- import { button, esc } from './index.js';
14
- import { OVERLAY_LAYER, adoptOverlay, focusablesIn, popOverlay, pushOverlay, returnFocus, syncOverlays } from './overlay.js';
15
-
16
- const cx = (...a) => a.filter(Boolean).join(' ');
17
-
18
- // Module counter (never Date/random) → stable, unique ids for aria-labelledby.
19
- let _uid = 0;
20
- const nextId = (p = 'confirm') => `${p}-${++_uid}`;
21
-
22
- /**
23
- * The public factory. Returns an HTML string; wire it with wireConfirm().
24
- *
25
- * `specimen` renders open as a *picture* of the dialog — same markup, minus the
26
- * data-confirm hook and aria-modal, so no wiring and no key handler can reach
27
- * it. A documentation page shows several at once and none of them may own the
28
- * page or answer Escape: an answered specimen would erase itself with nothing to
29
- * bring it back, and three modal dialogs on one page trap the reader in the
30
- * first. Use `open` when the dialog is real.
31
- *
32
- * @param {object} [o]
33
- * @param {string} [o.title] the question — also the accessible name
34
- * @param {string} [o.body] the consequence — the accessible description
35
- * @param {string} [o.confirmLabel] the destructive answer (default 'Confirm')
36
- * @param {string} [o.cancelLabel] the safe answer (default 'Cancel')
37
- * @param {string} [o.variant] 'danger' (default) | 'primary'
38
- * @param {boolean} [o.open] render already-open, as a real dialog
39
- * @param {boolean} [o.specimen] render open as a picture of the dialog
40
- * @param {string} [o.id] root id a [data-confirm-open] trigger targets
41
- * @returns {string} html
42
- */
43
- export function confirm({
44
- title = 'Are you sure?', body = '', confirmLabel = 'Confirm', cancelLabel = 'Cancel',
45
- variant = 'danger', id, open = false, specimen = false,
46
- } = {}) {
47
- const titleId = nextId('confirm-title');
48
- const bodyId = body ? nextId('confirm-body') : null;
49
- const describedBy = bodyId ? ` aria-describedby="${bodyId}"` : '';
50
-
51
- // The safe answer comes FIRST in the DOM, so the trap's first stop and the
52
- // reader's first Tab both land on the answer that changes nothing.
53
- const cancelBtn = button({ label: cancelLabel, variant: 'ghost' })
54
- .replace('<button ', '<button data-confirm-cancel ');
55
- const acceptBtn = button({ label: confirmLabel, variant })
56
- .replace('<button ', '<button data-confirm-accept ');
57
-
58
- const rootCls = cx('ui-confirm', (open || specimen) && 'is-open');
59
- return `<div class="${rootCls}"${specimen ? '' : ' data-confirm'}${id ? ` id="${esc(id)}"` : ''}>`
60
- + `<div class="ui-confirm__scrim" data-confirm-scrim></div>`
61
- + `<div class="ui-confirm__panel" role="alertdialog"${specimen ? '' : ' aria-modal="true"'}`
62
- + ` aria-labelledby="${titleId}"${describedBy} tabindex="-1" data-confirm-panel>`
63
- + `<h2 class="ui-confirm__title" id="${titleId}">${esc(title)}</h2>`
64
- + (bodyId ? `<p class="ui-confirm__body" id="${bodyId}">${esc(body)}</p>` : '')
65
- + `<div class="ui-confirm__acts">${cancelBtn}${acceptBtn}</div>`
66
- + `</div></div>`;
67
- }
68
-
69
- // ---- Shared behaviour ----------------------------------------------------
70
- // Per-instance handlers are attached once (guarded by a flag on the node);
71
- // the [data-confirm-open] delegation is attached once per document. Safe to
72
- // call repeatedly (Storybook re-renders).
73
-
74
- export function openConfirm(root, returnFocusTo) {
75
- if (!root || root.classList.contains('is-open')) return;
76
- root.__confirmReturn = returnFocusTo
77
- || (document.activeElement instanceof HTMLElement ? document.activeElement : null);
78
- root.classList.add('is-open');
79
- const panel = root.querySelector('[data-confirm-panel]');
80
- pushOverlay(root, panel, () => closeConfirm(root), OVERLAY_LAYER.confirm);
81
- // The safe answer, else the first control, else the panel itself. Asked for by
82
- // name and not by position: DOM order puts the safe answer first today, and a
83
- // preference that only agrees with the order proves nothing about either.
84
- const safe = panel && (panel.querySelector('[data-confirm-cancel]') || focusablesIn(panel)[0]);
85
- (safe || panel)?.focus();
86
- }
87
-
88
- export function closeConfirm(root) {
89
- if (!root || !root.classList.contains('is-open')) return;
90
- root.classList.remove('is-open');
91
- const back = root.__confirmReturn;
92
- root.__confirmReturn = null;
93
- // The destructive work a caller hangs off [data-confirm-accept] usually deletes
94
- // the row the trigger stood in, so the trigger can be detached by now — and
95
- // focus() on a detached node is a silent no-op that strands the reader. So is
96
- // one that is still there but inert, which popOverlay is passed `back` to see.
97
- popOverlay(root, back);
98
- returnFocus(back, root.ownerDocument);
99
- }
100
-
101
- export function wireConfirm(scope = document) {
102
- const root = scope === document ? document : scope;
103
- root.querySelectorAll('[data-confirm]').forEach((cf) => {
104
- if (cf.__confirmWired) return;
105
- cf.__confirmWired = true;
106
-
107
- cf.querySelector('[data-confirm-scrim]')?.addEventListener('click', () => closeConfirm(cf));
108
- cf.querySelectorAll('[data-confirm-cancel],[data-confirm-accept]').forEach((btn) =>
109
- btn.addEventListener('click', () => closeConfirm(cf)));
110
-
111
- // Rendered with `open: true`, so nothing called openConfirm() and nothing
112
- // put it on the stack. Adopting it here is what makes its aria-modal true.
113
- adoptOverlay(cf, cf.querySelector('[data-confirm-panel]'), () => closeConfirm(cf), OVERLAY_LAYER.confirm);
114
- });
115
-
116
- const doc = scope === document ? document : (scope.ownerDocument || document);
117
- if (!doc.__confirmGlobalWired) {
118
- doc.__confirmGlobalWired = true;
119
- // Any [data-confirm-open="ID"] trigger opens the matching dialog.
120
- doc.addEventListener('click', (e) => {
121
- const opener = e.target.closest?.('[data-confirm-open]');
122
- if (!opener) return;
123
- e.preventDefault();
124
- const target = doc.getElementById(opener.getAttribute('data-confirm-open'));
125
- if (target) openConfirm(target, opener);
126
- });
127
- }
128
- // This runs on every re-render, which is the moment to notice that an overlay
129
- // was destroyed while it was open and hand the page back.
130
- syncOverlays(doc);
131
- }