@apliteni/apliteni-ui 0.142.1 → 0.142.3

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 (41) 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 +2 -2
  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/topbar.css +8 -6
  17. package/src/components/account-nav.js +0 -37
  18. package/src/components/avatar.js +0 -53
  19. package/src/components/back.js +0 -57
  20. package/src/components/button-busy.js +0 -69
  21. package/src/components/command-palette.js +0 -471
  22. package/src/components/confirm.js +0 -131
  23. package/src/components/drawer.js +0 -169
  24. package/src/components/dropdown.js +0 -1055
  25. package/src/components/feedback.js +0 -171
  26. package/src/components/filter-bar.js +0 -86
  27. package/src/components/footer.js +0 -102
  28. package/src/components/index.js +0 -352
  29. package/src/components/loading.js +0 -127
  30. package/src/components/nav.js +0 -220
  31. package/src/components/overlay.js +0 -263
  32. package/src/components/pagination.js +0 -323
  33. package/src/components/segmented.js +0 -33
  34. package/src/components/shell.js +0 -511
  35. package/src/components/stat.js +0 -82
  36. package/src/components/success.js +0 -131
  37. package/src/components/table-values.js +0 -32
  38. package/src/components/tabs.js +0 -82
  39. package/src/components/toasts.js +0 -118
  40. package/src/components/tooltip.js +0 -347
  41. package/src/components/topbar.js +0 -270
@@ -1,1055 +0,0 @@
1
- import { dropdownMatch, dropdownFiltering, dropdownAvail, dropdownStop } from '../logic/dropdown.js';
2
- export { dropdownMatch, dropdownFiltering, dropdownAvail } from '../logic/dropdown.js';
3
- // Dropdown — the kit's one popover-list primitive. A trigger opens a panel of
4
- // item rows; two flavours share the same panel and the same open/close JS:
5
- //
6
- // variant: 'select' → role="listbox" / role="option", value shown in trigger
7
- // variant: 'menu' → role="menu" / role="menuitem", action list
8
- //
9
- // The name is deliberate: `menu` implies actions only and `select` implies a
10
- // form control bound to a value, and this factory is the umbrella both are
11
- // specialisations of. The topbar's version switcher and account menu are thin
12
- // consumers of the SAME wiring, so there is one open/close/Esc/keyboard
13
- // implementation in the kit.
14
- //
15
- // container.innerHTML = dropdown({ label: 'version:', value: '…', items });
16
- // wireDropdown(container); // or let wireTopbar() do it
17
- import { esc, icon } from './index.js';
18
- import { safeUrl } from '../html.js';
19
- import { avatar } from './avatar.js';
20
- // The fade's own length, read off the stylesheet rather than copied. why: src/motion.js
21
- import { transitionMs, prefersReducedMotion } from '../motion.js';
22
- import {
23
- DD_MENU_FLOOR, filterPanelRow, filterPanelFit, dropdownHeightFit, dropdownLift, dropdownReveal, dropdownRest, dropdownSnap, dropdownViewportFit, ddViewOf, ddGap, ddMin, ddViewWidth, ddLifted, DD_EXIT_SLACK_MS, ddWriteCeiling, ddInFilterRow,
24
- } from '../logic/dropdown-placement.js';
25
- export {
26
- DD_MENU_FLOOR, filterPanelRow, filterPanelFit, dropdownHeightFit, dropdownLift, dropdownReveal, dropdownRest, dropdownSnap, dropdownViewportFit,
27
- } from '../logic/dropdown-placement.js';
28
- const cx = (...a) => a.filter(Boolean).join(' ');
29
-
30
- // A trailing status badge. `badge` is the text shown, in the case it is written
31
- // ("Live"), or { text, tone }; a string reading "live" in any case takes the live tone.
32
- function ddBadge(badge) {
33
- if (!badge) return '';
34
- const text = typeof badge === 'string' ? badge : badge.text;
35
- let tone = typeof badge === 'string' ? '' : (badge.tone || '');
36
- if (!tone) tone = /^live$/i.test(text) ? 'live'
37
- : /^(?:off|unset|disabled|archive|archived)$/i.test(text) ? 'state' : 'neutral';
38
- return `<span class="${esc(cx('ui-dropdown__badge', `is-${tone}`))}">${esc(text)}</span>`;
39
- }
40
-
41
- // One item row. `listbox` picks role=option (selectable) vs role=menuitem (action).
42
- function ddItem(it, listbox, ext) {
43
- if (it === '---' || it.separator) return `<div class="ui-dropdown__sep" role="separator"${ext?.filtering ? ' hidden' : ''}></div>`;
44
- const disabled = !!it.disabled;
45
- const selected = !!it.selected;
46
- const role = listbox ? 'option' : 'menuitem';
47
- const asLink = !!it.href && !disabled && !listbox;
48
- const tag = asLink ? 'a' : 'div';
49
- const lead = it.avatar ? avatar(it.avatar) : it.icon ? `<span class="ui-dropdown__ic">${icon(it.icon)}</span>` : '';
50
- const desc = it.description ? `<span class="ui-dropdown__desc">${esc(it.description)}</span>` : '';
51
- const main = `<span class="ui-dropdown__main"><span class="ui-dropdown__label">${esc(it.label)}</span>${desc}</span>`;
52
- const badge = ddBadge(it.badge);
53
- const tick = listbox ? `<span class="ui-dropdown__tick" aria-hidden="true">${icon('check')}</span>` : '';
54
- const attrs = [
55
- `class="${esc(cx('ui-dropdown__item', selected && 'is-selected', disabled && 'is-disabled', it.danger && 'is-danger'))}"`,
56
- 'data-dd-item',
57
- `role="${role}"`,
58
- 'tabindex="-1"',
59
- it.value != null ? `data-value="${esc(it.value)}"` : '',
60
- listbox ? `aria-selected="${selected ? 'true' : 'false'}"` : '',
61
- disabled ? 'aria-disabled="true"' : '',
62
- asLink ? `href="${esc(safeUrl(it.href))}"` : '',
63
- asLink && it.target ? `target="${esc(it.target)}"` : '',
64
- ext?.id ? `id="${esc(ext.id)}"` : '',
65
- ext?.hidden ? 'hidden' : '',
66
- ].filter(Boolean).join(' ');
67
- return `<${tag} ${attrs}>${lead}${main}${badge}${tick}</${tag}>`;
68
- }
69
-
70
- // Render a flat item list or grouped sections ([{ label, items }]). `sx` is the
71
- // search variant's context; the plain dropdown passes none and its markup is
72
- // unchanged.
73
- function ddBody({ items, sections }, listbox, sx) {
74
- const one = (it) => ddItem(it, listbox, sx && ddRowExt(it, sx));
75
- if (sections && sections.length) {
76
- return sections.map((s) => {
77
- const head = s.label ? `<div class="ui-dropdown__group" role="presentation">${esc(s.label)}</div>` : '';
78
- const gone = sx && dropdownFiltering(sx.q)
79
- && !(s.items || []).some((it) => ddIsRow(it) && dropdownMatch(it.label, sx.q));
80
- return `<div class="ui-dropdown__section" role="group"${s.label ? ` aria-label="${esc(s.label)}"` : ''}${gone ? ' hidden' : ''}>${head}${(s.items || []).map(one).join('')}</div>`;
81
- }).join('');
82
- }
83
- return (items || []).map(one).join('');
84
- }
85
-
86
- // ---- Search --------------------------------------------------------------
87
- // The match is a substring of the label, anywhere in it, ignoring case and
88
- // accents; rows keep their order. The factory and the wiring both ask
89
- // dropdownMatch(), so a preset query and a typed one hide the same rows.
90
- // why: docs/components.md#a-dropdown-with-a-search-field
91
- // NFD takes the mark off é or ö; ł, ø, đ and the rest are letters of their own
92
- // with nothing to take off, so they are mapped by hand.
93
- const ddIsRow = (it) => it && it !== '---' && !it.separator;
94
-
95
- let _ddSeq = 0;
96
-
97
- // "Search 214 people": the size of the whole set, in the placeholder and in the field's
98
- // name. `count: true` counts the rows, less a "No one" row, which is not a person.
99
- // why: docs/components.md#a-dropdown-with-a-search-field
100
- function ddCount(count, rows) {
101
- if (count == null || count === false) return null;
102
- const n = count === true ? rows.filter((it) => ddIsRow(it) && !it.avatar?.empty).length : Number(count);
103
- return Number.isFinite(n) && n >= 0 ? n : null;
104
- }
105
-
106
- function ddSearchContext(search, id, rows) {
107
- const o = search === true ? {} : search;
108
- const n = ddCount(o.count, rows);
109
- const counted = n == null ? null : `Search ${n} ${o.noun || 'people'}`;
110
- return {
111
- base: id || `ui-dd-${++_ddSeq}`,
112
- n: 0,
113
- q: o.query || '',
114
- label: o.label || counted,
115
- placeholder: o.placeholder || counted || 'Search',
116
- empty: o.empty || 'No match for “{q}”',
117
- hint: o.hint || 'Check the spelling, or try fewer letters.',
118
- };
119
- }
120
-
121
- function ddRowExt(it, sx) {
122
- if (!ddIsRow(it)) return { filtering: dropdownFiltering(sx.q) };
123
- return { id: `${sx.base}-opt-${sx.n++}`, hidden: !dropdownMatch(it.label, sx.q) };
124
- }
125
-
126
- // The no-match state. A function replacer, so a `$&` typed into the field is
127
- // text rather than a replacement pattern.
128
- function ddNone(empty, hint, q) {
129
- return `<span class="ui-dropdown__none-title">${esc(empty.replace('{q}', () => q.trim()))}</span>`
130
- + `<span class="ui-dropdown__none-hint">${esc(hint)}</span>`;
131
- }
132
-
133
- // The field is a combobox that owns the list; the rows stay options, and the
134
- // one Enter would pick is named by aria-activedescendant, so focus never
135
- // leaves the field while the reader types.
136
- function ddSearchBody({ items, sections }, sx, name, scroll) {
137
- const listId = `${sx.base}-list`;
138
- const rows = ddBody({ items, sections }, true, sx);
139
- const flat = (sections ? sections.flatMap((s) => s.items || []) : (items || [])).filter(ddIsRow);
140
- const shown = flat.some((it) => dropdownMatch(it.label, sx.q));
141
- // The cap property and not `max-height`: an inline height outranks the sheet's
142
- // min() and would put the panel back past the viewport edge. #489
143
- const cap = scroll && scroll !== true
144
- ? ` style="--ui-dropdown-cap:${typeof scroll === 'number' ? scroll + 'px' : esc(scroll)}"` : '';
145
- const input = [
146
- 'class="ui-dropdown__search-input"', 'type="text"', 'role="combobox"',
147
- 'aria-autocomplete="list"', 'aria-expanded="true"', `aria-controls="${esc(listId)}"`,
148
- `aria-label="${esc(sx.label || `Search ${name}`)}"`, `placeholder="${esc(sx.placeholder)}"`,
149
- 'autocomplete="off"', 'spellcheck="false"', 'data-dd-search',
150
- sx.q ? `value="${esc(sx.q)}"` : '',
151
- ].filter(Boolean).join(' ');
152
- return `<div class="ui-dropdown__search">`
153
- + `<span class="ui-dropdown__search-ic" aria-hidden="true">${icon('search')}</span><input ${input}></div>`
154
- + `<div class="ui-dropdown__list" role="listbox" id="${esc(listId)}" aria-label="${esc(name)}"${cap}>${rows}</div>`
155
- + `<div class="ui-dropdown__none" role="status" data-dd-none data-dd-empty="${esc(sx.empty)}" data-dd-hint="${esc(sx.hint)}">`
156
- + `${shown || !dropdownFiltering(sx.q) ? '' : ddNone(sx.empty, sx.hint, sx.q)}</div>`;
157
- }
158
-
159
- /**
160
- * The public factory. Returns an HTML string; wire it with wireDropdown().
161
- *
162
- * @param {object} [o]
163
- * @param {string} [o.label] muted prefix in the trigger (e.g. "version:")
164
- * @param {string} [o.value] current value shown in the trigger
165
- * @param {string} [o.placeholder] shown when there is no value
166
- * @param {string} [o.variant] 'select' (listbox) | 'menu' (inferred from items)
167
- * @param {Array} [o.items] [{ label, value?, description?, icon?, avatar?, badge?, selected?, disabled?, href?, danger? }]
168
- * @param {Array} [o.sections] [{ label, items }] — grouped alternative to items
169
- * @param {string} [o.foot] content for a pinned block at the panel's bottom edge,
170
- * drawn as `.ui-dropdown__foot` — raw HTML, so escape your own text
171
- * @param {string} [o.header] raw HTML pinned to the top of the panel, unwrapped
172
- * @param {string} [o.footer] raw HTML pinned to the bottom of the panel, unwrapped
173
- * @param {string} [o.align] 'start' (default) | 'end' — the edge the panel hugs
174
- * @param {string} [o.direction] 'down' (default) | 'up' | 'auto' — the way it opens
175
- * @param {boolean} [o.portal] mount the panel on <body>, for a clipping or sticky ancestor
176
- * @param {boolean|number} [o.scroll] true, or a maxHeight in px, to cap and scroll
177
- * @param {boolean} [o.open] render already-open (handy for screenshots)
178
- * @param {boolean} [o.disabled] the trigger is off: no stop, no panel, the kit's
179
- * unavailable paint. #580
180
- * @param {string} [o.ariaLabel] accessible name for the panel and trigger
181
- * @param {boolean|object} [o.search] true, or { placeholder, label, empty, hint, query, count, noun } —
182
- * a field above the rows that filters them; `empty` may carry {q}; `count` (a number, or
183
- * true to count the rows) puts the size of the set in the placeholder and the field's
184
- * name, "Search 214 people", and `noun` replaces "people"
185
- * @returns {string} html
186
- */
187
- export function dropdown({
188
- label, value, placeholder = 'Select…', variant, items, sections,
189
- foot = '', header = '', footer = '', triggerContent, triggerClass = '', chevron = true,
190
- align = 'start', direction = 'down', portal = false,
191
- scroll = false, open = false, disabled = false, ariaLabel, id, panelClass = '', search = false,
192
- } = {}) {
193
- const flat = sections ? sections.flatMap((s) => s.items || []) : (items || []);
194
- const isSelect = variant === 'select' || (variant == null && flat.some((it) => it && (it.selected || it.value != null)));
195
- const listRole = isSelect ? 'listbox' : 'menu';
196
- const cur = value != null ? value : (isSelect ? (flat.find((it) => it && it.selected)?.label) : null);
197
- const sx = search ? ddSearchContext(search, id, flat) : null;
198
- const name = ariaLabel || (label ? String(label).replace(/:\s*$/, '') : '') || 'Options';
199
-
200
- // A picker of people: the trigger leads with the chosen row's mark, and with no value
201
- // a dashed ring beside the placeholder. why: docs/components.md#avatar
202
- const marked = isSelect && flat.some((it) => it && it.avatar);
203
- const chosen = marked && cur != null ? flat.find((it) => it && it.label === cur) : null;
204
- const lead = marked && (chosen?.avatar || cur == null) ? avatar(chosen?.avatar ?? { empty: true }) : '';
205
- const trig = triggerContent != null
206
- ? triggerContent
207
- : `${lead}${label ? `<span class="ui-dropdown__pre">${esc(label)}</span>` : ''}` +
208
- `<span class="${esc(cx('ui-dropdown__value', marked && cur == null && 'is-placeholder'))}">${esc(cur != null ? cur : placeholder)}</span>`;
209
- const triggerAttrs = [
210
- `class="${esc(cx('ui-dropdown__trigger', triggerClass))}"`,
211
- 'type="button"',
212
- 'data-dropdown-trigger',
213
- `aria-haspopup="${sx ? 'dialog' : listRole}"`,
214
- `aria-expanded="${open ? 'true' : 'false'}"`,
215
- // The attribute, not aria-disabled: a dropdown's trigger carries no message a
216
- // reader has to stop on, so it leaves the tab order the way .ui-btn's does.
217
- disabled ? 'disabled' : '',
218
- ariaLabel && triggerContent != null ? `aria-label="${esc(ariaLabel)}"` : '',
219
- ].filter(Boolean).join(' ');
220
-
221
- // `is-open` beside `open` because the descendant selector the panel normally
222
- // takes its open state from stops matching once wireDropdown() portals it.
223
- const panelAttrs = [
224
- `class="${esc(cx(
225
- 'ui-dropdown__panel',
226
- align === 'end' && 'is-end',
227
- direction === 'up' && 'is-up',
228
- scroll && !sx && 'is-scroll',
229
- sx && 'ui-dropdown__panel--search',
230
- portal && 'ui-dropdown__panel--portal',
231
- portal && open && 'is-open',
232
- panelClass,
233
- ))}"`,
234
- 'data-dropdown-panel',
235
- // With search the panel holds a field and a list, which a listbox may not.
236
- `role="${sx ? 'dialog' : listRole}"`,
237
- sx ? `aria-label="${esc(name)}"` : (ariaLabel ? `aria-label="${esc(ariaLabel)}"` : ''),
238
- // The cap property and not `max-height`: an inline height outranks the
239
- // sheet's min() and would put the panel back past the viewport edge. #489
240
- scroll && scroll !== true && !sx
241
- ? `style="--ui-dropdown-cap:${typeof scroll === 'number' ? scroll + 'px' : esc(scroll)}"` : '',
242
- ].filter(Boolean).join(' ');
243
-
244
- // The block the sheet bleeds to the panel's bottom edge. It sits OUTSIDE the
245
- // unwrapped `footer`, because the block that bleeds is the one that has to
246
- // touch the edge. why: docs/components.md#the-dropdown-panel
247
- const footBlock = foot ? `<div class="ui-dropdown__foot">${foot}</div>` : '';
248
-
249
- const ddAttrs = 'data-dropdown'
250
- + (isSelect ? ' data-dropdown-select' : '')
251
- + (direction === 'auto' ? ' data-dropdown-direction="auto"' : '')
252
- + (portal ? ' data-dropdown-portal' : '');
253
-
254
- return `<div class="${esc(cx('ui-dropdown', open && 'open'))}" ${ddAttrs}${id ? ` id="${esc(id)}"` : ''}>` +
255
- `<button ${triggerAttrs}>${trig}${chevron ? '<span class="ui-dropdown__chevron" aria-hidden="true"></span>' : ''}</button>` +
256
- `<div ${panelAttrs}>${header}`
257
- + `${sx ? ddSearchBody({ items, sections }, sx, name, scroll) : ddBody({ items, sections }, isSelect)}`
258
- + `${footer}${footBlock}</div>` +
259
- `</div>`;
260
- }
261
-
262
- // ---- Shared behaviour ----------------------------------------------------
263
- // One implementation for every dropdown in the kit — the generic component AND
264
- // the topbar's version switcher / account menu (they emit the same data hooks:
265
- // [data-dropdown] > [data-dropdown-trigger] + [data-dropdown-panel], toggling
266
- // `.open` on the container so each keeps its own visual CSS).
267
- //
268
- // Per-instance trigger + keyboard handlers are attached once (guarded by a flag
269
- // on the element). Document-level click-outside + Esc are attached once per
270
- // document. Safe to call repeatedly (e.g. Storybook re-renders).
271
-
272
- // Every wired container, so the close handlers can reach a dropdown wherever it
273
- // was drawn: `document.querySelectorAll` enters no shadow root and sees no other
274
- // document. A Set and not a WeakSet, because this has to be walked.
275
- // why: docs/components.md#the-dropdown-panel
276
- const _ddAll = new Set();
277
- // One pair of close handlers per document that holds a dropdown, the same way
278
- // wireShell() listens once per document it is handed.
279
- const _ddWiredDocs = new WeakSet();
280
-
281
- /** Where a portalled panel goes: the top of the tree its trigger lives in. A
282
- * shadow root is its own top — moving the panel out to the page's <body> would
283
- * leave every style scoped to that root behind. */
284
- const ddHostOf = (node) => {
285
- const root = node.getRootNode ? node.getRootNode() : node.ownerDocument;
286
- return root.nodeType === 9 ? root.body : root;
287
- };
288
-
289
- // A portalled panel is no longer a descendant of its container, so everything
290
- // below asks the container for its panel rather than querying inside it.
291
- const ddPanelOf = (dd) => dd.__ddPanel || dd.querySelector('[data-dropdown-panel]');
292
-
293
- // A trigger the sheet paints off. The kit paints both spellings unavailable, so
294
- // the wiring refuses both: the native attribute keeps the browser from
295
- // dispatching anything, but an aria-disabled trigger is still a keyboard stop,
296
- // and a click or an Enter on it reached openDropdown() until #580's round two.
297
- // ddItemsOf() above refuses an aria-disabled ROW the same way.
298
- // why: docs/foundations.md#colour-and-contrast
299
- const ddTriggerOff = (dd) => {
300
- const trigger = dd.querySelector('[data-dropdown-trigger]');
301
- return !!trigger && (trigger.disabled === true || trigger.getAttribute('aria-disabled') === 'true');
302
- };
303
-
304
- function ddItemsOf(dd) {
305
- const panel = ddPanelOf(dd);
306
- if (!panel) return [];
307
- return Array.from(panel.querySelectorAll('[data-dd-item]'))
308
- .filter((el) => el.getAttribute('aria-disabled') !== 'true' && !el.hidden);
309
- }
310
-
311
- // ---- Search wiring ---------------------------------------------------------
312
- // why: docs/components.md#a-dropdown-with-a-search-field
313
- const ddSearchOf = (dd) => ddPanelOf(dd)?.querySelector('[data-dd-search]') || null;
314
- const ddActiveOf = (dd) => ddPanelOf(dd)?.querySelector('[data-dd-item].is-active') || null;
315
- const ddComposing = (e) => e.isComposing || e.keyCode === 229;
316
-
317
- // Mark the row Enter would pick and keep it inside the list's scroll box,
318
- // without scrolling the page the way scrollIntoView() would.
319
- function ddSetActive(dd, row) {
320
- const search = ddSearchOf(dd);
321
- if (!search) return;
322
- ddActiveOf(dd)?.classList.remove('is-active');
323
- if (!row) { search.removeAttribute('aria-activedescendant'); return; }
324
- row.classList.add('is-active');
325
- search.setAttribute('aria-activedescendant', row.id);
326
- const list = row.closest('.ui-dropdown__list');
327
- if (!list || !list.clientHeight) return;
328
- const top = row.offsetTop - list.offsetTop;
329
- if (top < list.scrollTop) list.scrollTop = top;
330
- else if (top + row.offsetHeight > list.scrollTop + list.clientHeight) list.scrollTop = top + row.offsetHeight - list.clientHeight;
331
- }
332
-
333
- function ddFilter(dd) {
334
- const panel = ddPanelOf(dd);
335
- const search = ddSearchOf(dd);
336
- if (!panel || !search) return;
337
- const q = search.value;
338
- let shown = 0;
339
- panel.querySelectorAll('[data-dd-item]').forEach((row) => {
340
- row.hidden = !dropdownMatch((row.querySelector('.ui-dropdown__label') || row).textContent, q);
341
- if (!row.hidden) shown += 1;
342
- });
343
- panel.querySelectorAll('.ui-dropdown__sep').forEach((el) => { el.hidden = dropdownFiltering(q); });
344
- panel.querySelectorAll('.ui-dropdown__section').forEach((el) => { el.hidden = !el.querySelector('[data-dd-item]:not([hidden])'); });
345
- const none = panel.querySelector('[data-dd-none]');
346
- if (none) {
347
- none.innerHTML = shown || !dropdownFiltering(q) ? ''
348
- : ddNone(none.getAttribute('data-dd-empty') || '', none.getAttribute('data-dd-hint') || '', q);
349
- }
350
- ddSetActive(dd, ddItemsOf(dd)[0] || null);
351
- }
352
-
353
- // Every open starts from the whole list. Reset here rather than on close, so
354
- // a panel fading out after a pick does not flash back to every row.
355
- function ddResetSearch(dd, panel, search) {
356
- search.value = '';
357
- ddFilter(dd);
358
- panel.style.minWidth = '';
359
- // Hold the width the whole list needs, so the panel does not narrow as rows go.
360
- if (panel.offsetWidth) panel.style.minWidth = `${panel.offsetWidth}px`;
361
- }
362
-
363
- /** Write the fit onto the panel, and say whether any of the three numbers moved.
364
- * All three, because the stylesheet reads all three; it falls back to the
365
- * trigger's width when they are unset, so a panel opened before this runs is
366
- * bounded rather than unbounded.
367
- *
368
- * A number that has not changed is not written again, which is what stops the
369
- * observers below from answering their own writes: a fit landing on the same
370
- * three numbers mutates nothing, so it reports nothing. */
371
- function ddWriteFit(panel, fit) {
372
- let moved = false;
373
- for (const prop of ['room', 'shift', 'floor']) {
374
- const name = `--ui-filter-panel-${prop}`;
375
- const next = `${fit[prop]}px`;
376
- if (panel.style.getPropertyValue(name) === next) continue;
377
- panel.style.setProperty(name, next);
378
- moved = true;
379
- }
380
- return moved;
381
- }
382
-
383
- /** Fit a panel just opened, or leave it alone outside a filter row. */
384
- function ddFitFilterPanel(dd, panel) {
385
- const fit = filterPanelFit(dd);
386
- if (!fit || !panel?.style) return false;
387
- return ddWriteFit(panel, fit);
388
- }
389
-
390
- /** Measure an open menu again where its row now puts it. The fit it was opened
391
- * with can describe a row that no longer exists — a menu opened at 1280 and left
392
- * open at 390 kept a 1102px room and stood 11px off the page — or a place in that
393
- * row the chip has since left. A search panel's inline `min-width` was read at
394
- * the old width too, and inline beats the sheet, so it is read again off the
395
- * newly bounded box; only when the fit moved, because re-reading it is itself a
396
- * write.
397
- * why: docs/components.md#a-filter-row-holds-its-panels */
398
- function ddRefitFilterPanel(dd, panel) {
399
- const fit = panel?.style ? filterPanelFit(dd) : null;
400
- if (!fit || !ddWriteFit(panel, fit)) return;
401
- if (!panel.style.minWidth) return;
402
- panel.style.minWidth = '';
403
- if (panel.offsetWidth) panel.style.minWidth = `${panel.offsetWidth}px`;
404
- }
405
-
406
- /** Is this node inside some dropdown panel? Both fits write to a panel and to
407
- * nothing else, so a change inside one is never news — and a panel is
408
- * `position: absolute`, so nothing in it can move a chip along its row. Any
409
- * panel, not only the one being fitted: two open menus in one row would
410
- * otherwise answer each other a mutation at a time, and so did two <Dropdown>s
411
- * on a page, until the browser gate timed out.
412
- * why: docs/components.md#a-filter-row-holds-its-panels
413
- * why: docs/components.md#the-dropdown-panel */
414
- function ddOurs(node) {
415
- const el = node?.nodeType === 1 ? node : node?.parentElement;
416
- return !!el?.closest?.('[data-dropdown-panel]');
417
- }
418
-
419
- /**
420
- * Watch what the fit is measured from, and fit the menu again when it changes.
421
- *
422
- * Two inputs, two watchers. The row's width is one, observed rather than taken
423
- * from `resize`, which fires before an animating row has settled. Where the chip
424
- * sits along the row is the other, and it moves while the row keeps both of its
425
- * dimensions: re-labelling the chip in front of an open menu at 390px slid this
426
- * one 27.97px and took the menu 27.97px out of its row. So the boxes laid out in
427
- * the row are observed too — a chip is moved by the size of the ones in front of
428
- * it — and the mutation that moved it is watched for the frame before any of it
429
- * is laid out.
430
- *
431
- * Why those two cover the arithmetic, and the one case they do not:
432
- * why: docs/components.md#a-filter-row-holds-its-panels
433
- */
434
- function ddWatchRow(dd, panel) {
435
- ddUnwatchRow(dd);
436
- const row = filterPanelRow(dd);
437
- const view = dd.ownerDocument?.defaultView;
438
- if (!row) return;
439
- const refit = () => { if (dd.classList.contains('open')) ddRefitFilterPanel(dd, panel); };
440
- if (typeof view?.ResizeObserver === 'function') {
441
- // observe() reports each current box at once, which the fit was just written
442
- // from, so the first round writes nothing.
443
- const ro = new view.ResizeObserver(refit);
444
- ro.observe(row);
445
- for (const kid of row.children) ro.observe(kid);
446
- dd.__ddRowFit = ro;
447
- }
448
- if (typeof view?.MutationObserver !== 'function') return;
449
- const mo = new view.MutationObserver((records) => {
450
- if (records.every((m) => ddOurs(m.target))) return;
451
- // A chip added or removed brings a box the observer above is not watching yet.
452
- if (dd.__ddRowFit && records.some((m) => m.type === 'childList')) {
453
- for (const kid of row.children) dd.__ddRowFit.observe(kid);
454
- }
455
- refit();
456
- });
457
- /* characterData as well as the two structural kinds: a chip's printed value
458
- replaced is a text node changed, with no child list and no attribute moving
459
- with it — which is what a React re-render of that value arrives as too.
460
- Attributes, because a class is how a chip changes shape; subtree, because the
461
- text that sets a chip's width is inside it. */
462
- mo.observe(row, { subtree: true, childList: true, attributes: true, characterData: true });
463
- dd.__ddRowMo = mo;
464
- }
465
-
466
- function ddUnwatchRow(dd) {
467
- dd.__ddRowFit?.disconnect();
468
- dd.__ddRowFit = null;
469
- dd.__ddRowMo?.disconnect();
470
- dd.__ddRowMo = null;
471
- }
472
-
473
- /* ---- Following a panel's anchor --------------------------------------------
474
- * A position change need not resize anything and no event reports one, so the CAUSE
475
- * is watched instead: the DOM change that moved the trigger. Measured on the first
476
- * answer to #572, a flex row told to end-align its children left a panel at
477
- * 237.6…477.6 on a 390px screen and an ancestor scrolled sideways left one at
478
- * −108…132; a ResizeObserver sees neither. The limit, and why no end event is
479
- * taken for the middle of an animation, is stated with the rule.
480
- * why: docs/components.md#the-dropdown-panel */
481
-
482
- function ddSizeHeight(dd, panel) {
483
- if (!panel?.style) return;
484
- /* Decided when the panel opens and kept while the page or the body scrolls under it,
485
- * so the panel does not grow or shrink under the reader. A resize, or the next open,
486
- * decides again. A portalled panel follows its trigger instead, so it is measured
487
- * again where the trigger now is. A lifted one follows its trigger at the height it
488
- * opened at. why: docs/components.md#the-dropdown-panel */
489
- if (dd.__ddSized && !dd.__ddPanel) return;
490
- const avail = dropdownHeightFit(dd, panel);
491
- if (avail == null) return;
492
- // Infinity means the floor could not be met even by spending the whole inset:
493
- // the property is removed rather than written, so the sheet's own fallback — the
494
- // viewport less the edge inset, not a trigger-sized sliver — takes over. why:
495
- // dropdownAvail(), src/logic/dropdown.js
496
- //
497
- // `.is-unbounded` marks a panel the room cannot hold. It keeps its cap, and the
498
- // page, not the panel, is the way to the rows past the fold. why: src/styles/dropdown.css
499
- panel.classList.toggle('is-unbounded', !Number.isFinite(avail));
500
- // A number that has not changed is not written again, the way the width fit's
501
- // own write is guarded: a mutation inside the row that moved nothing vertically
502
- // would otherwise answer its own write, over and over, through the document
503
- // observer below. why: dropdownViewportFit()'s own "moved" guard, same file
504
- const next = Number.isFinite(avail) ? `${avail}px` : '';
505
- if (panel.style.getPropertyValue('--ui-dropdown-avail') !== next) {
506
- if (next) panel.style.setProperty('--ui-dropdown-avail', next);
507
- else panel.style.removeProperty('--ui-dropdown-avail');
508
- }
509
- dropdownSnap(dd, panel);
510
- }
511
-
512
- /** Fit a panel again where it now is, whichever placement it uses. */
513
- function ddPlace(dd) {
514
- const panel = dd.__ddPanel || ddPanelOf(dd);
515
- if (dd.__ddPanel) {
516
- ddResolveDirection(dd, panel);
517
- positionPortalPanel(dd, panel);
518
- }
519
- else if (ddLifted(panel)) { if (dd.classList.contains('open')) dropdownLift(dd, panel); }
520
- else ddFitViewport(dd, ddPanelOf(dd));
521
- ddSizeHeight(dd, panel);
522
- }
523
-
524
- /* How long the settle fallback waits: past --dur-slow (400ms), the longest motion
525
- * the kit ships, plus the same slack. A motion longer than this is answered by its
526
- * own end event; this timer is for the end event that never comes.
527
- * why: src/tokens/tokens.css */
528
- const DD_SETTLE_MS = 450;
529
-
530
- /**
531
- * Hold a closing anchored menu's open geometry until its fade has finished.
532
- *
533
- * `.open` stops matching in the frame the menu closes; the fade does not — the
534
- * panel transitions opacity over --dur-med. Dropping the width there left a 240px
535
- * menu painted as a 48px column of single letters: #549 on the way out. The timer
536
- * is the way out of a transitionend that never comes.
537
- * why: src/styles/filter-bar.css
538
- */
539
- function ddHoldClose(dd, panel) {
540
- ddCancelClose(dd, panel);
541
- panel.classList.add('is-closing');
542
- let done = false;
543
- const finish = () => {
544
- if (done) return;
545
- done = true;
546
- dd.__ddClosing = null;
547
- panel.classList.remove('is-closing');
548
- panel.style.minWidth = '';
549
- for (const prop of ['room', 'shift', 'floor']) {
550
- panel.style.removeProperty(`--ui-filter-panel-${prop}`);
551
- }
552
- };
553
- // Only the panel's own fade: a row's background transition bubbles here too.
554
- const onEnd = (e) => { if (e.target === panel && e.propertyName === 'opacity') stop(); };
555
- const timer = setTimeout(() => stop(), transitionMs(panel) + DD_EXIT_SLACK_MS);
556
- function stop() {
557
- panel.removeEventListener('transitionend', onEnd);
558
- clearTimeout(timer);
559
- finish();
560
- }
561
- panel.addEventListener('transitionend', onEnd);
562
- // Re-opened mid-fade: the wait is abandoned, so it cannot clear a fit the new
563
- // open has already written.
564
- dd.__ddClosing = () => {
565
- done = true;
566
- dd.__ddClosing = null;
567
- panel.removeEventListener('transitionend', onEnd);
568
- clearTimeout(timer);
569
- panel.classList.remove('is-closing');
570
- };
571
- }
572
-
573
- function ddCancelClose(dd, panel) {
574
- if (dd.__ddClosing) dd.__ddClosing();
575
- else panel?.classList?.remove('is-closing');
576
- }
577
-
578
- // Keep the configured side separate from the side resolved for this opening.
579
- function ddResolveDirection(dd, panel) {
580
- const auto = dd.getAttribute('data-dropdown-direction') === 'auto';
581
- if (!auto && !dd.__ddPanel) return;
582
- const trigger = dd.querySelector('[data-dropdown-trigger]');
583
- if (!trigger || typeof trigger.getBoundingClientRect !== 'function') return;
584
- const t = trigger.getBoundingClientRect();
585
- const below = ddViewOf(panel).innerHeight - t.bottom;
586
- if (auto) {
587
- ddSetUp(panel, below < panel.offsetHeight + ddGap(panel) && t.top > below);
588
- return;
589
- }
590
- const up = dd.__ddPreferredUp;
591
- const room = (up ? t.top : below) - ddGap(panel);
592
- const opposite = (up ? below : t.top) - ddGap(panel);
593
- // Short content or a smaller consumer cap needs less than the usual floor.
594
- const needed = Math.min(ddMin(panel), panel.offsetHeight);
595
- ddSetUp(panel, room < needed && opposite > room ? !up : up);
596
- }
597
-
598
- /* Change the side without a transition: the shut panel's transform would otherwise
599
- * be running when `is-open` arrives, and the open would retarget it from the wrong
600
- * side. */
601
- function ddSetUp(panel, up) {
602
- if (panel.classList.contains('is-up') === up) return;
603
- const held = panel.style.transition;
604
- panel.style.transition = 'none';
605
- panel.classList.toggle('is-up', up);
606
- ddViewOf(panel).getComputedStyle(panel).transform;
607
- panel.style.transition = held;
608
- }
609
-
610
- /**
611
- * Keep a panel in place inside its view, by moving it along the inline axis.
612
- *
613
- * `translate` and not `left`, `right` or a margin: an absolutely positioned box is
614
- * shrink-to-fit, so its width is measured against the room left between its own
615
- * offsets, and a shift written as one of those offsets changes the width the shift
616
- * was calculated from. A transform moves no layout, so the number stays true. The
617
- * entry travel keeps `transform` to itself, and the property is off the panel's
618
- * transition list, so a panel already open lands at once rather than sliding.
619
- *
620
- * A portalled panel is placed by positionPortalPanel(), which writes its edges in
621
- * viewport coordinates and clamps them there.
622
- * why: docs/components.md#the-dropdown-panel
623
- */
624
- function ddFitViewport(dd, panel) {
625
- if (!panel?.style || dd?.__ddPanel === panel || ddInFilterRow(panel) || ddLifted(panel)) return;
626
- ddWriteCeiling(panel);
627
- const fit = dropdownViewportFit(panel);
628
- if (!fit) return;
629
- panel.style.translate = fit.shift ? `${fit.shift}px` : '';
630
- }
631
-
632
- // Nothing lays a portalled panel out any more, so these four inline values are
633
- // its layout. Inline, so no rule in any sheet can pin the opposite edge.
634
- function positionPortalPanel(dd, panel) {
635
- const trigger = dd.querySelector('[data-dropdown-trigger]');
636
- if (!trigger || typeof trigger.getBoundingClientRect !== 'function') return;
637
- const view = ddViewOf(panel);
638
- const t = trigger.getBoundingClientRect();
639
- const gap = ddGap(panel);
640
- const s = panel.style;
641
- if (panel.classList.contains('is-up')) {
642
- s.top = 'auto';
643
- s.bottom = `${view.innerHeight - t.top + gap}px`;
644
- } else {
645
- s.bottom = 'auto';
646
- s.top = `${t.bottom + gap}px`;
647
- }
648
- /* The inline axis is fitted rather than mirrored. Both of these edges put a
649
- 240px panel off the screen from a trigger near the one it is anchored to, and
650
- #572 is that: the fit is asked with the box this function is about to write,
651
- because the panel's own is still where the last call left it. */
652
- const end = panel.classList.contains('is-end');
653
- ddWriteCeiling(panel);
654
- const width = panel.getBoundingClientRect().width;
655
- const left = end ? t.right - width : t.left;
656
- const shift = dropdownViewportFit(panel, { left, width })?.shift || 0;
657
- if (end) {
658
- s.left = 'auto';
659
- s.right = `${ddViewWidth(panel) - t.right - shift}px`;
660
- } else {
661
- s.right = 'auto';
662
- s.left = `${t.left + shift}px`;
663
- }
664
- }
665
-
666
- // A portalled panel outlives the container that owned it — a re-render replaces
667
- // the container and the old panel has nothing pointing at it. Swept in the host
668
- // it was put in, which is the tree the new container is in too.
669
- function sweepOrphanPanels(host) {
670
- host.querySelectorAll(':scope > [data-dropdown-panel][data-dropdown-portal]')
671
- .forEach((p) => { if (!p.__ddOwner || !p.__ddOwner.isConnected) p.remove(); });
672
- }
673
-
674
- function closeDropdown(dd) {
675
- if (!dd.classList.contains('open')) return;
676
- dd.classList.remove('open');
677
- const panel = ddPanelOf(dd);
678
- panel?.classList.remove('is-open');
679
- ddUnwatchRow(dd);
680
- /* A search panel carries the width it was opened at as an inline `min-width`,
681
- * and inline beats any sheet. Inside a filter row that leaves a SHUT panel wider
682
- * than its trigger, which is #467. Cleared here, and ddResetSearch() writes it
683
- * again on the next open — except for an anchored menu, which gives the pin and
684
- * the fit back at the END of its fade, both being its open geometry. A portalled
685
- * panel is never fitted, so it has none to hold. why: ddHoldClose() */
686
- if (panel?.style && !dd.__ddPanel && filterPanelRow(dd)) ddHoldClose(dd, panel);
687
- else if (panel?.style && dd.closest?.('.ui-filter-bar')) panel.style.minWidth = '';
688
- dd.querySelector('[data-dropdown-trigger]')?.setAttribute('aria-expanded', 'false');
689
- /* The anchor may have moved while the panel was open, and a shut panel is laid
690
- out: its box goes on counting towards the page's scrollable width. One reading
691
- on the way out, so a panel left behind at 237.6…477.6 does not keep the page
692
- 478px wide with nothing open. why: ddPlace() */
693
- if (panel) ddFitViewport(dd, panel);
694
- if (panel) dropdownRest(dd, panel, false);
695
- }
696
-
697
- /** Every wired dropdown still in a tree, the ones in frames and shadow roots
698
- * included. Disconnected containers are dropped as they are passed, with a collapse
699
- * still waiting for a scroll, which would otherwise hold them until the next one. */
700
- function ddLive() {
701
- const out = [];
702
- for (const dd of _ddAll) {
703
- if (dd.isConnected) out.push(dd);
704
- else {
705
- dd.__ddRest?.();
706
- _ddAll.delete(dd);
707
- }
708
- }
709
- return out;
710
- }
711
-
712
- function closeAllDropdowns(except) {
713
- for (const dd of ddLive()) if (dd !== except && dd.classList.contains('open')) closeDropdown(dd);
714
- }
715
-
716
- function openDropdown(dd, focusIdx) {
717
- // Every way in goes through here — the trigger's click, the Enter the browser
718
- // turns into one, and the arrows — so one refusal covers them all. #580
719
- if (ddTriggerOff(dd)) return;
720
- closeAllDropdowns(dd);
721
- const panel = ddPanelOf(dd);
722
- const search = ddSearchOf(dd);
723
- if (panel) {
724
- // An earlier close may still be holding its geometry; this open owns it now.
725
- ddCancelClose(dd, panel);
726
- dropdownRest(dd, panel, true);
727
- ddResolveDirection(dd, panel);
728
- if (dd.__ddPanel) { positionPortalPanel(dd, panel); panel.classList.add('is-open'); }
729
- /* Both fits, because each one answers for the panels the other declines:
730
- filterPanelFit() is null outside a filter chip, and dropdownViewportFit()
731
- is null inside a filter row, whose own row already bounds its panels.
732
- why: docs/components.md#a-filter-row-holds-its-panels */
733
- else { ddFitFilterPanel(dd, panel); ddWatchRow(dd, panel); ddFitViewport(dd, panel); }
734
- if (!dd.__ddPanel && !ddInFilterRow(panel)) dropdownLift(dd, panel);
735
- dd.__ddSized = false;
736
- ddSizeHeight(dd, panel);
737
- dd.__ddSized = true;
738
- }
739
- // The body was scrolled to show the panel: a row taking focus must not scroll it
740
- // again to the row alone.
741
- const keep = panel && dropdownReveal(dd, panel) ? { preventScroll: true } : undefined;
742
- dd.classList.add('open');
743
- /* After `open`, and after the fit: ddResetSearch() pins the width it reads off
744
- * the panel, and the rule that widens a filter menu only applies once the
745
- * panel is open. Reading first pinned 50px inline, which beats any stylesheet
746
- * — a searchable chip in a filter row kept the 74px menu #549 reported, while
747
- * React, whose effects already ran in this order, gave 240px for the same
748
- * markup. why: src/styles/filter-bar.css */
749
- if (panel && search) ddResetSearch(dd, panel, search);
750
- dd.querySelector('[data-dropdown-trigger]')?.setAttribute('aria-expanded', 'true');
751
- // With search, focus goes to the field however the panel was opened, and
752
- // the selected row (or the first) is the one Enter would pick.
753
- if (search) {
754
- const items = ddItemsOf(dd);
755
- ddSetActive(dd, items.find((el) => el.getAttribute('aria-selected') === 'true') || items[0] || null);
756
- search.focus(keep);
757
- return;
758
- }
759
- if (focusIdx != null) {
760
- const items = ddItemsOf(dd);
761
- const sel = items.findIndex((el) => el.getAttribute('aria-selected') === 'true');
762
- (items[focusIdx === 'selected' && sel >= 0 ? sel : (focusIdx === 'selected' ? 0 : focusIdx)] || items[0])?.focus(keep);
763
- }
764
- }
765
-
766
- // Single-select: reflect the picked option into aria-selected + the trigger value.
767
- function selectOption(dd, item) {
768
- if (!dd.hasAttribute('data-dropdown-select')) return;
769
- // Every enabled row, the ones a search query has hidden included.
770
- ddPanelOf(dd)?.querySelectorAll('[data-dd-item]:not([aria-disabled="true"])')
771
- .forEach((el) => el.setAttribute('aria-selected', el === item ? 'true' : 'false'));
772
- ddPanelOf(dd)?.querySelectorAll('[data-dd-item].is-selected').forEach((el) => el.classList.remove('is-selected'));
773
- item.classList.add('is-selected');
774
- const valueEl = dd.querySelector('[data-dropdown-trigger] .ui-dropdown__value');
775
- const label = item.querySelector('.ui-dropdown__label');
776
- if (valueEl && label) valueEl.textContent = label.textContent;
777
- // A picker of people carries the row's mark up into the trigger.
778
- const mark = item.querySelector(':scope > .ui-avatar');
779
- const lead = dd.querySelector('[data-dropdown-trigger] > .ui-avatar');
780
- if (mark && lead) lead.replaceWith(mark.cloneNode(true));
781
- else if (mark) dd.querySelector('[data-dropdown-trigger]')?.prepend(mark.cloneNode(true));
782
- else lead?.remove();
783
- valueEl?.classList.remove('is-placeholder');
784
- }
785
-
786
- // Click-outside, Escape and the repositioning sweep, registered once per document
787
- // that holds a dropdown — the same shape wireShell()'s listen() has, and for the
788
- // same reason: a frame is its own document and a listener on the page's never
789
- // fires there. why: docs/components.md#the-dropdown-panel
790
- function ddListen(doc) {
791
- if (!doc || _ddWiredDocs.has(doc)) return;
792
- _ddWiredDocs.add(doc);
793
- doc.addEventListener('click', () => closeAllDropdowns());
794
- doc.addEventListener('keydown', (e) => {
795
- if (e.key !== 'Escape' || ddComposing(e)) return;
796
- const open = ddLive().find((dd) => dd.classList.contains('open') && dd.ownerDocument === doc);
797
- if (open) { closeDropdown(open); open.querySelector('[data-dropdown-trigger]')?.focus(); }
798
- });
799
- /* Viewport coordinates go stale the moment anything scrolls, and an in-place
800
- panel's fit is measured against the view as much as a portalled one's: a
801
- trigger slid from x=260 to x=10 inside a row that scrolls sideways left its
802
- panel at −108…132, with the first row's label off the screen. Capture, so a
803
- scroll inside the rail the panel was lifted out of, or inside that row, counts
804
- too. why: docs/components.md#the-dropdown-panel */
805
- const reposition = () => {
806
- for (const dd of ddLive()) if (dd.classList.contains('open')) ddPlace(dd);
807
- };
808
- /* The fallback re-fit, for a view with no ResizeObserver. Not taken as well where
809
- * ddWatchRow() is watching: a `resize` event is the worse measurement of the two.
810
- * why: docs/components.md#a-filter-row-holds-its-panels */
811
- const refit = () => {
812
- for (const dd of ddLive()) {
813
- if (dd.classList.contains('open') && !dd.__ddPanel && !dd.__ddRowFit) {
814
- ddRefitFilterPanel(dd, ddPanelOf(dd));
815
- }
816
- }
817
- };
818
- /* The shut ones, which the sweep above does not reach and which no reader is
819
- looking at: a shut panel is laid out, so a panel fitted at 1280 and left shut
820
- at 375 keeps the page scrolling sideways with nothing open. A shut PORTALLED
821
- panel is not one of them — `position: fixed` puts it in no page's scrollable
822
- width. why: docs/components.md#the-dropdown-panel */
823
- const refitInPlace = () => {
824
- for (const dd of ddLive()) {
825
- if (!dd.__ddPanel && !dd.classList.contains('open')) ddFitViewport(dd, ddPanelOf(dd));
826
- }
827
- };
828
- // The two together, which is every panel that owes anybody an answer.
829
- const follow = () => { reposition(); refitInPlace(); };
830
- const view = doc.defaultView;
831
- if (!view) return;
832
- /* Both states on a scroll, not the open one alone: a shut panel is laid out, so
833
- an ancestor scrolled back to where it started left one at 258…498 on a 390px
834
- screen with nothing open — #501's page width, in the state the open sweep
835
- cannot reach. React's half has always answered both; this is that answer.
836
- why: docs/components.md#the-dropdown-panel */
837
- view.addEventListener('scroll', follow, true);
838
- /* A resize decides the placement again, a panel that was not lifted included: a
839
- Drawer that held the panel at 844 tall cannot at 320. Lifted first, because the
840
- height is measured from the placement, and the body is then scrolled to show what
841
- the new placement needs, as it is on an open. why: openDropdown() */
842
- const replace = () => {
843
- for (const dd of ddLive()) {
844
- dd.__ddSized = false;
845
- if (!dd.classList.contains('open')) continue;
846
- const panel = ddPanelOf(dd);
847
- if (panel && !dd.__ddPanel && !ddInFilterRow(panel)) dropdownLift(dd, panel);
848
- ddPlace(dd);
849
- // Held again at the new height while the page scrolls, as after an open.
850
- dd.__ddSized = true;
851
- if (panel) dropdownReveal(dd, panel);
852
- }
853
- };
854
- view.addEventListener('resize', replace);
855
- view.addEventListener('resize', refit);
856
- view.addEventListener('resize', refitInPlace);
857
- /* Where motion leaves a trigger, read once it has stopped. The style write that
858
- starts a transition is a mutation measured in the frame it lands, when the
859
- trigger has not moved yet: one given `transition: transform 200ms` and then
860
- translated 220px left its panel 240px outside the view for good, not for 200ms.
861
- The end events answer that, and one timer per document answers the end event
862
- that never comes — a cancelled transition's, or one on a box this document
863
- never hears from. Armed when motion starts and cleared before it is armed
864
- again, so one is pending at a time, and a fired one walks ddLive(), which has
865
- already dropped whatever was removed meanwhile. The frames in between are what
866
- this declines: the reader is owed the final position, not a measurement per
867
- frame per panel. why: docs/components.md#the-dropdown-panel */
868
- let settling = null;
869
- const settle = () => {
870
- clearTimeout(settling);
871
- settling = setTimeout(() => { settling = null; follow(); }, DD_SETTLE_MS);
872
- };
873
- view.addEventListener('transitionend', follow, true);
874
- view.addEventListener('animationend', follow, true);
875
- view.addEventListener('transitionstart', settle, true);
876
- view.addEventListener('animationstart', settle, true);
877
- if (typeof view.MutationObserver === 'function' && doc.documentElement) {
878
- const mo = new view.MutationObserver((records) => {
879
- if (records.every((m) => ddOurs(m.target))) return;
880
- follow();
881
- });
882
- /* characterData as well as the two structural kinds: growing a sibling TEXT
883
- NODE moves a trigger along a flex row without changing one observed box, and
884
- neither a child list nor an attribute changes with it. 39 characters of 10px
885
- monospace in front of a menu carried both layers' panels from 8…248 to
886
- 236.8…476.8 and left the page 477px wide. A change inside any panel is still
887
- skipped, text included: ddOurs() reads a text node's parent.
888
- why: docs/components.md#the-dropdown-panel */
889
- mo.observe(doc.documentElement, {
890
- subtree: true, childList: true, attributes: true, characterData: true,
891
- });
892
- }
893
- }
894
-
895
- export function wireDropdown(root = document) {
896
- const scope = root === document ? document : root;
897
- scope.querySelectorAll('[data-dropdown]').forEach((dd) => {
898
- if (dd.__ddWired) return;
899
- dd.__ddWired = true;
900
- _ddAll.add(dd);
901
- ddListen(dd.ownerDocument);
902
- const trigger = dd.querySelector('[data-dropdown-trigger]');
903
- const panel = dd.querySelector('[data-dropdown-panel]');
904
- if (!trigger) return;
905
-
906
- // Portal: lift the panel onto <body>. An ancestor whose overflow is not
907
- // `visible` clips it on both axes, and one that is `position: sticky` opens
908
- // a stacking context whatever z-index the panel carries — the app rail is
909
- // both at once. why: docs/components.md#the-dropdown-panel
910
- if (panel && dd.hasAttribute('data-dropdown-portal')) {
911
- // The tree the trigger is in, not the page's: a panel lifted out of a
912
- // frame or a shadow root into the top document leaves its stylesheet and
913
- // its close handler behind. why: docs/components.md#the-dropdown-panel
914
- const host = ddHostOf(dd);
915
- sweepOrphanPanels(host);
916
- panel.setAttribute('data-dropdown-portal', '');
917
- panel.__ddOwner = dd;
918
- dd.__ddPreferredUp = panel.classList.contains('is-up');
919
- dd.__ddPanel = panel;
920
- host.appendChild(panel);
921
- if (dd.classList.contains('open')) {
922
- ddResolveDirection(dd, panel);
923
- positionPortalPanel(dd, panel);
924
- panel.classList.add('is-open');
925
- }
926
- }
927
-
928
- // A panel rendered already-open never passes through openDropdown(), so its
929
- // fit has to be taken here too — otherwise a story or a server-rendered bar
930
- // keeps the fallback width and #549 survives in exactly the place a
931
- // default-open menu makes most visible.
932
- if (panel && !dd.__ddPanel && dd.classList.contains('open')) {
933
- ddFitFilterPanel(dd, panel);
934
- ddWatchRow(dd, panel);
935
- }
936
- if (panel && dd.classList.contains('open')) {
937
- if (!dd.__ddPanel && !ddInFilterRow(panel)) dropdownLift(dd, panel);
938
- ddSizeHeight(dd, panel);
939
- dd.__ddSized = true;
940
- }
941
- else if (panel) dropdownRest(dd, panel, false, 0);
942
-
943
- trigger.addEventListener('click', (e) => {
944
- e.stopPropagation();
945
- if (dd.classList.contains('open')) closeDropdown(dd);
946
- else openDropdown(dd);
947
- });
948
-
949
- if (panel) {
950
- // Clicks inside the panel shouldn't reach the document close handler;
951
- // activating an item selects (single-select) + closes.
952
- panel.addEventListener('click', (e) => {
953
- e.stopPropagation();
954
- const item = e.target.closest('[data-dd-item]');
955
- if (!item || item.getAttribute('aria-disabled') === 'true') return;
956
- selectOption(dd, item);
957
- closeDropdown(dd);
958
- trigger.focus();
959
- });
960
- const field = panel.querySelector('[data-dd-search]');
961
- if (field) {
962
- field.addEventListener('input', () => ddFilter(dd));
963
- // The pointer moves the pick too, so Enter takes the row under it. A
964
- // move to the same point is the browser's own after a scroll, not the
965
- // reader's, and would snatch the pick from the arrows.
966
- let at = '';
967
- panel.addEventListener('mousemove', (e) => {
968
- const here = `${e.clientX},${e.clientY}`;
969
- if (here === at) return;
970
- at = here;
971
- const row = e.target.closest('[data-dd-item]');
972
- if (row && row.getAttribute('aria-disabled') !== 'true' && !row.classList.contains('is-active')) ddSetActive(dd, row);
973
- });
974
- }
975
- }
976
-
977
- const onKeydown = (e) => {
978
- const open = dd.classList.contains('open');
979
- const onTrigger = e.target === trigger;
980
- const search = ddSearchOf(dd);
981
- // While an IME is composing, its keys commit or steer the text, not the
982
- // list. Safari's committing Enter carries keyCode 229, not isComposing.
983
- if (e.target === search && ddComposing(e)) return;
984
- if (search && open) {
985
- // Arrows walk the rows still showing; focus stays in the field.
986
- if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
987
- e.preventDefault();
988
- const items = ddItemsOf(dd);
989
- if (!items.length) return;
990
- const i = items.indexOf(ddActiveOf(dd));
991
- const next = e.key === 'ArrowDown' ? (i + 1) % items.length : (i <= 0 ? items.length - 1 : i - 1);
992
- ddSetActive(dd, items[next]);
993
- return;
994
- }
995
- if (e.target === search && e.key === 'Enter') { e.preventDefault(); ddActiveOf(dd)?.click(); return; }
996
- // Home and End move the caret in a text field; they are not the list's.
997
- if (e.target === search && (e.key === 'Home' || e.key === 'End')) return;
998
- }
999
- if ((e.key === 'ArrowDown' || e.key === 'ArrowUp') && (onTrigger || open)) {
1000
- e.preventDefault();
1001
- if (!open) return openDropdown(dd, e.key === 'ArrowDown' ? 0 : 'selected');
1002
- const items = ddItemsOf(dd);
1003
- const i = items.indexOf(document.activeElement);
1004
- const next = e.key === 'ArrowDown' ? (i + 1) % items.length : (i - 1 + items.length) % items.length;
1005
- items[next < 0 ? 0 : next]?.focus();
1006
- } else if (e.key === 'Home' && open) {
1007
- e.preventDefault(); ddItemsOf(dd)[0]?.focus();
1008
- } else if (e.key === 'End' && open) {
1009
- e.preventDefault(); const it = ddItemsOf(dd); it[it.length - 1]?.focus();
1010
- dropdownReveal(dd, ddPanelOf(dd));
1011
- } else if ((e.key === 'Enter' || e.key === ' ') && open && e.target.matches('[data-dd-item]')) {
1012
- e.preventDefault(); e.target.click();
1013
- } else if (e.key === 'Escape' && open) {
1014
- e.preventDefault(); e.stopPropagation(); closeDropdown(dd); trigger.focus();
1015
- } else if (e.key === 'Tab' && open) {
1016
- closeDropdown(dd);
1017
- }
1018
- };
1019
-
1020
- dd.addEventListener('keydown', onKeydown);
1021
- if (dd.__ddPanel) {
1022
- // A portalled panel is no longer inside the container, so a keystroke on
1023
- // an item never bubbles to it. Bound here only, or it would fire twice.
1024
- dd.__ddPanel.addEventListener('keydown', onKeydown);
1025
- // It is also placed once, on open, and a trigger whose box changes after
1026
- // that — a webfont arriving, a longer label — leaves it adrift. Scroll
1027
- // and resize do not see a reflow; this does.
1028
- if (typeof ResizeObserver === 'function') {
1029
- new ResizeObserver(() => {
1030
- if (dd.classList.contains('open')) positionPortalPanel(dd, dd.__ddPanel);
1031
- }).observe(trigger);
1032
- }
1033
- } else if (panel && !ddInFilterRow(panel)) {
1034
- /* And an in-place panel is fitted here, before anything is clicked, because
1035
- a shut panel is laid out and a laid-out box counts towards the page's
1036
- scrollable width. The two boxes the fit is measured from are both watched:
1037
- the trigger, because the edge an end-aligned panel hangs from is the
1038
- trigger's, and the panel, because its own width is the other half of the
1039
- sum. The view's observer and not the module's: a panel in a frame is laid
1040
- out in that frame. A filter row's panels are skipped outright rather than
1041
- watched for a fit that declines them: that row is their bound, and
1042
- ddWatchRow() is the observer they get instead.
1043
- why: docs/components.md#the-dropdown-panel */
1044
- ddFitViewport(dd, panel);
1045
- const view = dd.ownerDocument?.defaultView;
1046
- if (typeof view?.ResizeObserver === 'function') {
1047
- // Writing a translate moves no layout, so a fit cannot report itself back.
1048
- const ro = new view.ResizeObserver(() => ddFitViewport(dd, panel));
1049
- ro.observe(trigger);
1050
- ro.observe(panel);
1051
- }
1052
- }
1053
- });
1054
-
1055
- }