@apliteni/apliteni-ui 0.142.0 → 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 (46) 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/logic/account-nav.js +9 -0
  9. package/src/logic/code.js +75 -0
  10. package/src/logic/dropdown-placement.js +671 -0
  11. package/src/logic/feedback.js +16 -0
  12. package/src/logic/theme.js +5 -0
  13. package/src/styles/command-palette.css +9 -5
  14. package/src/styles/drawer.css +8 -0
  15. package/src/styles/dropdown.css +30 -8
  16. package/src/styles/feedback.css +1 -1
  17. package/src/styles/filter-bar.css +5 -2
  18. package/src/styles/input.css +14 -15
  19. package/src/styles/layout.css +5 -2
  20. package/src/styles/table.css +28 -2
  21. package/src/styles/topbar.css +8 -6
  22. package/src/components/account-nav.js +0 -44
  23. package/src/components/avatar.js +0 -53
  24. package/src/components/back.js +0 -57
  25. package/src/components/button-busy.js +0 -69
  26. package/src/components/command-palette.js +0 -471
  27. package/src/components/confirm.js +0 -131
  28. package/src/components/drawer.js +0 -169
  29. package/src/components/dropdown.js +0 -1713
  30. package/src/components/feedback.js +0 -182
  31. package/src/components/filter-bar.js +0 -86
  32. package/src/components/footer.js +0 -102
  33. package/src/components/index.js +0 -424
  34. package/src/components/loading.js +0 -127
  35. package/src/components/nav.js +0 -220
  36. package/src/components/overlay.js +0 -263
  37. package/src/components/pagination.js +0 -323
  38. package/src/components/segmented.js +0 -33
  39. package/src/components/shell.js +0 -511
  40. package/src/components/stat.js +0 -82
  41. package/src/components/success.js +0 -131
  42. package/src/components/table-values.js +0 -32
  43. package/src/components/tabs.js +0 -82
  44. package/src/components/toasts.js +0 -118
  45. package/src/components/tooltip.js +0 -347
  46. package/src/components/topbar.js +0 -269
@@ -1,1713 +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
- const cx = (...a) => a.filter(Boolean).join(' ');
23
-
24
- // A trailing status badge. `badge` is the text shown, in the case it is written
25
- // ("Live"), or { text, tone }; a string reading "live" in any case takes the live tone.
26
- function ddBadge(badge) {
27
- if (!badge) return '';
28
- const text = typeof badge === 'string' ? badge : badge.text;
29
- let tone = typeof badge === 'string' ? '' : (badge.tone || '');
30
- if (!tone) tone = /^live$/i.test(text) ? 'live'
31
- : /^(?:off|unset|disabled|archive|archived)$/i.test(text) ? 'state' : 'neutral';
32
- return `<span class="${esc(cx('ui-dropdown__badge', `is-${tone}`))}">${esc(text)}</span>`;
33
- }
34
-
35
- // One item row. `listbox` picks role=option (selectable) vs role=menuitem (action).
36
- function ddItem(it, listbox, ext) {
37
- if (it === '---' || it.separator) return `<div class="ui-dropdown__sep" role="separator"${ext?.filtering ? ' hidden' : ''}></div>`;
38
- const disabled = !!it.disabled;
39
- const selected = !!it.selected;
40
- const role = listbox ? 'option' : 'menuitem';
41
- const asLink = !!it.href && !disabled && !listbox;
42
- const tag = asLink ? 'a' : 'div';
43
- const lead = it.avatar ? avatar(it.avatar) : it.icon ? `<span class="ui-dropdown__ic">${icon(it.icon)}</span>` : '';
44
- const desc = it.description ? `<span class="ui-dropdown__desc">${esc(it.description)}</span>` : '';
45
- const main = `<span class="ui-dropdown__main"><span class="ui-dropdown__label">${esc(it.label)}</span>${desc}</span>`;
46
- const badge = ddBadge(it.badge);
47
- const tick = listbox ? `<span class="ui-dropdown__tick" aria-hidden="true">${icon('check')}</span>` : '';
48
- const attrs = [
49
- `class="${esc(cx('ui-dropdown__item', selected && 'is-selected', disabled && 'is-disabled', it.danger && 'is-danger'))}"`,
50
- 'data-dd-item',
51
- `role="${role}"`,
52
- 'tabindex="-1"',
53
- it.value != null ? `data-value="${esc(it.value)}"` : '',
54
- listbox ? `aria-selected="${selected ? 'true' : 'false'}"` : '',
55
- disabled ? 'aria-disabled="true"' : '',
56
- asLink ? `href="${esc(safeUrl(it.href))}"` : '',
57
- asLink && it.target ? `target="${esc(it.target)}"` : '',
58
- ext?.id ? `id="${esc(ext.id)}"` : '',
59
- ext?.hidden ? 'hidden' : '',
60
- ].filter(Boolean).join(' ');
61
- return `<${tag} ${attrs}>${lead}${main}${badge}${tick}</${tag}>`;
62
- }
63
-
64
- // Render a flat item list or grouped sections ([{ label, items }]). `sx` is the
65
- // search variant's context; the plain dropdown passes none and its markup is
66
- // unchanged.
67
- function ddBody({ items, sections }, listbox, sx) {
68
- const one = (it) => ddItem(it, listbox, sx && ddRowExt(it, sx));
69
- if (sections && sections.length) {
70
- return sections.map((s) => {
71
- const head = s.label ? `<div class="ui-dropdown__group" role="presentation">${esc(s.label)}</div>` : '';
72
- const gone = sx && dropdownFiltering(sx.q)
73
- && !(s.items || []).some((it) => ddIsRow(it) && dropdownMatch(it.label, sx.q));
74
- return `<div class="ui-dropdown__section" role="group"${s.label ? ` aria-label="${esc(s.label)}"` : ''}${gone ? ' hidden' : ''}>${head}${(s.items || []).map(one).join('')}</div>`;
75
- }).join('');
76
- }
77
- return (items || []).map(one).join('');
78
- }
79
-
80
- // ---- Search --------------------------------------------------------------
81
- // The match is a substring of the label, anywhere in it, ignoring case and
82
- // accents; rows keep their order. The factory and the wiring both ask
83
- // dropdownMatch(), so a preset query and a typed one hide the same rows.
84
- // why: docs/components.md#a-dropdown-with-a-search-field
85
- // NFD takes the mark off é or ö; ł, ø, đ and the rest are letters of their own
86
- // with nothing to take off, so they are mapped by hand.
87
- const ddIsRow = (it) => it && it !== '---' && !it.separator;
88
-
89
- let _ddSeq = 0;
90
-
91
- // "Search 214 people": the size of the whole set, in the placeholder and in the field's
92
- // name. `count: true` counts the rows, less a "No one" row, which is not a person.
93
- // why: docs/components.md#a-dropdown-with-a-search-field
94
- function ddCount(count, rows) {
95
- if (count == null || count === false) return null;
96
- const n = count === true ? rows.filter((it) => ddIsRow(it) && !it.avatar?.empty).length : Number(count);
97
- return Number.isFinite(n) && n >= 0 ? n : null;
98
- }
99
-
100
- function ddSearchContext(search, id, rows) {
101
- const o = search === true ? {} : search;
102
- const n = ddCount(o.count, rows);
103
- const counted = n == null ? null : `Search ${n} ${o.noun || 'people'}`;
104
- return {
105
- base: id || `ui-dd-${++_ddSeq}`,
106
- n: 0,
107
- q: o.query || '',
108
- label: o.label || counted,
109
- placeholder: o.placeholder || counted || 'Search',
110
- empty: o.empty || 'No match for “{q}”',
111
- hint: o.hint || 'Check the spelling, or try fewer letters.',
112
- };
113
- }
114
-
115
- function ddRowExt(it, sx) {
116
- if (!ddIsRow(it)) return { filtering: dropdownFiltering(sx.q) };
117
- return { id: `${sx.base}-opt-${sx.n++}`, hidden: !dropdownMatch(it.label, sx.q) };
118
- }
119
-
120
- // The no-match state. A function replacer, so a `$&` typed into the field is
121
- // text rather than a replacement pattern.
122
- function ddNone(empty, hint, q) {
123
- return `<span class="ui-dropdown__none-title">${esc(empty.replace('{q}', () => q.trim()))}</span>`
124
- + `<span class="ui-dropdown__none-hint">${esc(hint)}</span>`;
125
- }
126
-
127
- // The field is a combobox that owns the list; the rows stay options, and the
128
- // one Enter would pick is named by aria-activedescendant, so focus never
129
- // leaves the field while the reader types.
130
- function ddSearchBody({ items, sections }, sx, name, scroll) {
131
- const listId = `${sx.base}-list`;
132
- const rows = ddBody({ items, sections }, true, sx);
133
- const flat = (sections ? sections.flatMap((s) => s.items || []) : (items || [])).filter(ddIsRow);
134
- const shown = flat.some((it) => dropdownMatch(it.label, sx.q));
135
- // The cap property and not `max-height`: an inline height outranks the sheet's
136
- // min() and would put the panel back past the viewport edge. #489
137
- const cap = scroll && scroll !== true
138
- ? ` style="--ui-dropdown-cap:${typeof scroll === 'number' ? scroll + 'px' : esc(scroll)}"` : '';
139
- const input = [
140
- 'class="ui-dropdown__search-input"', 'type="text"', 'role="combobox"',
141
- 'aria-autocomplete="list"', 'aria-expanded="true"', `aria-controls="${esc(listId)}"`,
142
- `aria-label="${esc(sx.label || `Search ${name}`)}"`, `placeholder="${esc(sx.placeholder)}"`,
143
- 'autocomplete="off"', 'spellcheck="false"', 'data-dd-search',
144
- sx.q ? `value="${esc(sx.q)}"` : '',
145
- ].filter(Boolean).join(' ');
146
- return `<div class="ui-dropdown__search">`
147
- + `<span class="ui-dropdown__search-ic" aria-hidden="true">${icon('search')}</span><input ${input}></div>`
148
- + `<div class="ui-dropdown__list" role="listbox" id="${esc(listId)}" aria-label="${esc(name)}"${cap}>${rows}</div>`
149
- + `<div class="ui-dropdown__none" role="status" data-dd-none data-dd-empty="${esc(sx.empty)}" data-dd-hint="${esc(sx.hint)}">`
150
- + `${shown || !dropdownFiltering(sx.q) ? '' : ddNone(sx.empty, sx.hint, sx.q)}</div>`;
151
- }
152
-
153
- /**
154
- * The public factory. Returns an HTML string; wire it with wireDropdown().
155
- *
156
- * @param {object} [o]
157
- * @param {string} [o.label] muted prefix in the trigger (e.g. "version:")
158
- * @param {string} [o.value] current value shown in the trigger
159
- * @param {string} [o.placeholder] shown when there is no value
160
- * @param {string} [o.variant] 'select' (listbox) | 'menu' (inferred from items)
161
- * @param {Array} [o.items] [{ label, value?, description?, icon?, avatar?, badge?, selected?, disabled?, href?, danger? }]
162
- * @param {Array} [o.sections] [{ label, items }] — grouped alternative to items
163
- * @param {string} [o.foot] content for a pinned block at the panel's bottom edge,
164
- * drawn as `.ui-dropdown__foot` — raw HTML, so escape your own text
165
- * @param {string} [o.header] raw HTML pinned to the top of the panel, unwrapped
166
- * @param {string} [o.footer] raw HTML pinned to the bottom of the panel, unwrapped
167
- * @param {string} [o.align] 'start' (default) | 'end' — the edge the panel hugs
168
- * @param {string} [o.direction] 'down' (default) | 'up' | 'auto' — the way it opens
169
- * @param {boolean} [o.portal] mount the panel on <body>, for a clipping or sticky ancestor
170
- * @param {boolean|number} [o.scroll] true, or a maxHeight in px, to cap and scroll
171
- * @param {boolean} [o.open] render already-open (handy for screenshots)
172
- * @param {boolean} [o.disabled] the trigger is off: no stop, no panel, the kit's
173
- * unavailable paint. #580
174
- * @param {string} [o.ariaLabel] accessible name for the panel and trigger
175
- * @param {boolean|object} [o.search] true, or { placeholder, label, empty, hint, query, count, noun } —
176
- * a field above the rows that filters them; `empty` may carry {q}; `count` (a number, or
177
- * true to count the rows) puts the size of the set in the placeholder and the field's
178
- * name, "Search 214 people", and `noun` replaces "people"
179
- * @returns {string} html
180
- */
181
- export function dropdown({
182
- label, value, placeholder = 'Select…', variant, items, sections,
183
- foot = '', header = '', footer = '', triggerContent, triggerClass = '', chevron = true,
184
- align = 'start', direction = 'down', portal = false,
185
- scroll = false, open = false, disabled = false, ariaLabel, id, panelClass = '', search = false,
186
- } = {}) {
187
- const flat = sections ? sections.flatMap((s) => s.items || []) : (items || []);
188
- const isSelect = variant === 'select' || (variant == null && flat.some((it) => it && (it.selected || it.value != null)));
189
- const listRole = isSelect ? 'listbox' : 'menu';
190
- const cur = value != null ? value : (isSelect ? (flat.find((it) => it && it.selected)?.label) : null);
191
- const sx = search ? ddSearchContext(search, id, flat) : null;
192
- const name = ariaLabel || (label ? String(label).replace(/:\s*$/, '') : '') || 'Options';
193
-
194
- // A picker of people: the trigger leads with the chosen row's mark, and with no value
195
- // a dashed ring beside the placeholder. why: docs/components.md#avatar
196
- const marked = isSelect && flat.some((it) => it && it.avatar);
197
- const chosen = marked && cur != null ? flat.find((it) => it && it.label === cur) : null;
198
- const lead = marked && (chosen?.avatar || cur == null) ? avatar(chosen?.avatar ?? { empty: true }) : '';
199
- const trig = triggerContent != null
200
- ? triggerContent
201
- : `${lead}${label ? `<span class="ui-dropdown__pre">${esc(label)}</span>` : ''}` +
202
- `<span class="${esc(cx('ui-dropdown__value', marked && cur == null && 'is-placeholder'))}">${esc(cur != null ? cur : placeholder)}</span>`;
203
- const triggerAttrs = [
204
- `class="${esc(cx('ui-dropdown__trigger', triggerClass))}"`,
205
- 'type="button"',
206
- 'data-dropdown-trigger',
207
- `aria-haspopup="${sx ? 'dialog' : listRole}"`,
208
- `aria-expanded="${open ? 'true' : 'false'}"`,
209
- // The attribute, not aria-disabled: a dropdown's trigger carries no message a
210
- // reader has to stop on, so it leaves the tab order the way .ui-btn's does.
211
- disabled ? 'disabled' : '',
212
- ariaLabel && triggerContent != null ? `aria-label="${esc(ariaLabel)}"` : '',
213
- ].filter(Boolean).join(' ');
214
-
215
- // `is-open` beside `open` because the descendant selector the panel normally
216
- // takes its open state from stops matching once wireDropdown() portals it.
217
- const panelAttrs = [
218
- `class="${esc(cx(
219
- 'ui-dropdown__panel',
220
- align === 'end' && 'is-end',
221
- direction === 'up' && 'is-up',
222
- scroll && !sx && 'is-scroll',
223
- sx && 'ui-dropdown__panel--search',
224
- portal && 'ui-dropdown__panel--portal',
225
- portal && open && 'is-open',
226
- panelClass,
227
- ))}"`,
228
- 'data-dropdown-panel',
229
- // With search the panel holds a field and a list, which a listbox may not.
230
- `role="${sx ? 'dialog' : listRole}"`,
231
- sx ? `aria-label="${esc(name)}"` : (ariaLabel ? `aria-label="${esc(ariaLabel)}"` : ''),
232
- // The cap property and not `max-height`: an inline height outranks the
233
- // sheet's min() and would put the panel back past the viewport edge. #489
234
- scroll && scroll !== true && !sx
235
- ? `style="--ui-dropdown-cap:${typeof scroll === 'number' ? scroll + 'px' : esc(scroll)}"` : '',
236
- ].filter(Boolean).join(' ');
237
-
238
- // The block the sheet bleeds to the panel's bottom edge. It sits OUTSIDE the
239
- // unwrapped `footer`, because the block that bleeds is the one that has to
240
- // touch the edge. why: docs/components.md#the-dropdown-panel
241
- const footBlock = foot ? `<div class="ui-dropdown__foot">${foot}</div>` : '';
242
-
243
- const ddAttrs = 'data-dropdown'
244
- + (isSelect ? ' data-dropdown-select' : '')
245
- + (direction === 'auto' ? ' data-dropdown-direction="auto"' : '')
246
- + (portal ? ' data-dropdown-portal' : '');
247
-
248
- return `<div class="${esc(cx('ui-dropdown', open && 'open'))}" ${ddAttrs}${id ? ` id="${esc(id)}"` : ''}>` +
249
- `<button ${triggerAttrs}>${trig}${chevron ? '<span class="ui-dropdown__chevron" aria-hidden="true"></span>' : ''}</button>` +
250
- `<div ${panelAttrs}>${header}`
251
- + `${sx ? ddSearchBody({ items, sections }, sx, name, scroll) : ddBody({ items, sections }, isSelect)}`
252
- + `${footer}${footBlock}</div>` +
253
- `</div>`;
254
- }
255
-
256
- // ---- Shared behaviour ----------------------------------------------------
257
- // One implementation for every dropdown in the kit — the generic component AND
258
- // the topbar's version switcher / account menu (they emit the same data hooks:
259
- // [data-dropdown] > [data-dropdown-trigger] + [data-dropdown-panel], toggling
260
- // `.open` on the container so each keeps its own visual CSS).
261
- //
262
- // Per-instance trigger + keyboard handlers are attached once (guarded by a flag
263
- // on the element). Document-level click-outside + Esc are attached once per
264
- // document. Safe to call repeatedly (e.g. Storybook re-renders).
265
-
266
- // Every wired container, so the close handlers can reach a dropdown wherever it
267
- // was drawn: `document.querySelectorAll` enters no shadow root and sees no other
268
- // document. A Set and not a WeakSet, because this has to be walked.
269
- // why: docs/components.md#the-dropdown-panel
270
- const _ddAll = new Set();
271
- // One pair of close handlers per document that holds a dropdown, the same way
272
- // wireShell() listens once per document it is handed.
273
- const _ddWiredDocs = new WeakSet();
274
-
275
- /** Where a portalled panel goes: the top of the tree its trigger lives in. A
276
- * shadow root is its own top — moving the panel out to the page's <body> would
277
- * leave every style scoped to that root behind. */
278
- const ddHostOf = (node) => {
279
- const root = node.getRootNode ? node.getRootNode() : node.ownerDocument;
280
- return root.nodeType === 9 ? root.body : root;
281
- };
282
-
283
- /** The window a box is measured in. A panel in a frame is laid out against the
284
- * frame's viewport, not the top page's. */
285
- const ddViewOf = (node) => node.ownerDocument?.defaultView || window;
286
-
287
- // The trigger-to-panel offset is --ui-dropdown-gap in src/styles/dropdown.css.
288
- // This is the fallback for a document that has not loaded the sheet;
289
- // src/components/dropdown.test.js pins the two to each other.
290
- const DD_GAP = 9;
291
-
292
- // A portalled panel is no longer a descendant of its container, so everything
293
- // below asks the container for its panel rather than querying inside it.
294
- const ddPanelOf = (dd) => dd.__ddPanel || dd.querySelector('[data-dropdown-panel]');
295
-
296
- // A trigger the sheet paints off. The kit paints both spellings unavailable, so
297
- // the wiring refuses both: the native attribute keeps the browser from
298
- // dispatching anything, but an aria-disabled trigger is still a keyboard stop,
299
- // and a click or an Enter on it reached openDropdown() until #580's round two.
300
- // ddItemsOf() above refuses an aria-disabled ROW the same way.
301
- // why: docs/foundations.md#colour-and-contrast
302
- const ddTriggerOff = (dd) => {
303
- const trigger = dd.querySelector('[data-dropdown-trigger]');
304
- return !!trigger && (trigger.disabled === true || trigger.getAttribute('aria-disabled') === 'true');
305
- };
306
-
307
- function ddGap(panel) {
308
- const declared = parseFloat(ddViewOf(panel).getComputedStyle(panel).getPropertyValue('--ui-dropdown-gap'));
309
- return Number.isFinite(declared) ? declared : DD_GAP;
310
- }
311
-
312
- // The least a panel keeps between itself and the edge of its view. The number is
313
- // --ui-dropdown-edge in src/styles/dropdown.css, and this is the fallback for a
314
- // document that has not loaded the sheet, as DD_GAP is for the offset.
315
- const DD_EDGE = 8;
316
-
317
- function ddEdge(panel) {
318
- const declared = parseFloat(ddViewOf(panel).getComputedStyle(panel).getPropertyValue('--ui-dropdown-edge'));
319
- return Number.isFinite(declared) ? declared : DD_EDGE;
320
- }
321
-
322
- // The room a panel that opens down keeps between its end and the end of the Modal
323
- // or Drawer body that holds it, so its shadow fades before the body clips it. The
324
- // number is --ui-dropdown-shade in src/styles/dropdown.css.
325
- const DD_SHADE = 48;
326
-
327
- function ddShade(panel) {
328
- const declared = parseFloat(ddViewOf(panel).getComputedStyle(panel).getPropertyValue('--ui-dropdown-shade'));
329
- return Number.isFinite(declared) ? declared : DD_SHADE;
330
- }
331
-
332
- // The least height a capped panel keeps, below which it would rather spend the
333
- // edge inset than shrink further. The number is --ui-dropdown-min in
334
- // src/styles/dropdown.css. #489
335
- const DD_MIN = 120;
336
-
337
- function ddMin(panel) {
338
- const declared = parseFloat(ddViewOf(panel).getComputedStyle(panel).getPropertyValue('--ui-dropdown-min'));
339
- return Number.isFinite(declared) ? declared : DD_MIN;
340
- }
341
-
342
- /** The width a panel has to stay inside: the LAYOUT viewport, which is what both
343
- * `position: fixed` and a page's scrollable width are measured against. A classic
344
- * scrollbar is in `innerWidth` and not in the box either of those means, so an
345
- * end-anchored panel written from `innerWidth` sat a scrollbar's width inside its
346
- * trigger. The fallback is for a view that lays nothing out, JSDOM among them. */
347
- const ddViewWidth = (panel) => {
348
- const view = ddViewOf(panel);
349
- return view.document?.documentElement?.clientWidth || view.innerWidth || 0;
350
- };
351
-
352
- function ddItemsOf(dd) {
353
- const panel = ddPanelOf(dd);
354
- if (!panel) return [];
355
- return Array.from(panel.querySelectorAll('[data-dd-item]'))
356
- .filter((el) => el.getAttribute('aria-disabled') !== 'true' && !el.hidden);
357
- }
358
-
359
- // ---- Search wiring ---------------------------------------------------------
360
- // why: docs/components.md#a-dropdown-with-a-search-field
361
- const ddSearchOf = (dd) => ddPanelOf(dd)?.querySelector('[data-dd-search]') || null;
362
- const ddActiveOf = (dd) => ddPanelOf(dd)?.querySelector('[data-dd-item].is-active') || null;
363
- const ddComposing = (e) => e.isComposing || e.keyCode === 229;
364
-
365
- // Mark the row Enter would pick and keep it inside the list's scroll box,
366
- // without scrolling the page the way scrollIntoView() would.
367
- function ddSetActive(dd, row) {
368
- const search = ddSearchOf(dd);
369
- if (!search) return;
370
- ddActiveOf(dd)?.classList.remove('is-active');
371
- if (!row) { search.removeAttribute('aria-activedescendant'); return; }
372
- row.classList.add('is-active');
373
- search.setAttribute('aria-activedescendant', row.id);
374
- const list = row.closest('.ui-dropdown__list');
375
- if (!list || !list.clientHeight) return;
376
- const top = row.offsetTop - list.offsetTop;
377
- if (top < list.scrollTop) list.scrollTop = top;
378
- else if (top + row.offsetHeight > list.scrollTop + list.clientHeight) list.scrollTop = top + row.offsetHeight - list.clientHeight;
379
- }
380
-
381
- function ddFilter(dd) {
382
- const panel = ddPanelOf(dd);
383
- const search = ddSearchOf(dd);
384
- if (!panel || !search) return;
385
- const q = search.value;
386
- let shown = 0;
387
- panel.querySelectorAll('[data-dd-item]').forEach((row) => {
388
- row.hidden = !dropdownMatch((row.querySelector('.ui-dropdown__label') || row).textContent, q);
389
- if (!row.hidden) shown += 1;
390
- });
391
- panel.querySelectorAll('.ui-dropdown__sep').forEach((el) => { el.hidden = dropdownFiltering(q); });
392
- panel.querySelectorAll('.ui-dropdown__section').forEach((el) => { el.hidden = !el.querySelector('[data-dd-item]:not([hidden])'); });
393
- const none = panel.querySelector('[data-dd-none]');
394
- if (none) {
395
- none.innerHTML = shown || !dropdownFiltering(q) ? ''
396
- : ddNone(none.getAttribute('data-dd-empty') || '', none.getAttribute('data-dd-hint') || '', q);
397
- }
398
- ddSetActive(dd, ddItemsOf(dd)[0] || null);
399
- }
400
-
401
- // Every open starts from the whole list. Reset here rather than on close, so
402
- // a panel fading out after a pick does not flash back to every row.
403
- function ddResetSearch(dd, panel, search) {
404
- search.value = '';
405
- ddFilter(dd);
406
- panel.style.minWidth = '';
407
- // Hold the width the whole list needs, so the panel does not narrow as rows go.
408
- if (panel.offsetWidth) panel.style.minWidth = `${panel.offsetWidth}px`;
409
- }
410
-
411
- /* The kit's menu floor, the one `.ui-dropdown__panel` writes. The stylesheets
412
- * carry the same number; stories/filter-bar-fit.test.js reads all of them and
413
- * fails when one drifts. why: src/styles/dropdown.css */
414
- export const DD_MENU_FLOOR = 240;
415
-
416
- /** The floor a panel asks for in the sheet, or null. A separate name from the
417
- * floor this fit writes back: one that read its own output would pin a menu at
418
- * whatever a narrow row once allowed. why: src/styles/filter-bar.css */
419
- function ddPanelAsk(panel) {
420
- const view = panel?.ownerDocument?.defaultView;
421
- if (!panel || typeof view?.getComputedStyle !== 'function') return null;
422
- const asked = Number.parseFloat(view.getComputedStyle(panel).getPropertyValue('--ui-filter-panel-ask'));
423
- return Number.isFinite(asked) && asked > 0 ? asked : null;
424
- }
425
-
426
- /** The `.ui-dropdown__panel` inside a dropdown, by class rather than by data
427
- * attribute: the fit's subjects are the panels the stylesheet's rules match, and
428
- * filter-panel-fit.test.js hands this function hand-made elements. */
429
- const ddFitPanelOf = (dd) => (typeof dd?.querySelector === 'function'
430
- ? dd.querySelector('.ui-dropdown__panel') : null);
431
-
432
- /**
433
- * The filter row an anchored menu is measured inside, or null outside one.
434
- *
435
- * Two panels in a row are anchored at a trigger of their own: a chip's values, and
436
- * the add control's catalogue, which says so by asking for a width. The slide
437
- * filterPanelFit() computes is measured from that trigger's offset along the row,
438
- * which is arithmetic for either. A panel anchored to the row itself is neither,
439
- * and sizes itself.
440
- *
441
- * Published because `<Dropdown>` asks the same question — the same row to observe,
442
- * the same panels to hold through a close — and a second copy of this rule would
443
- * drift from the stylesheet. why: src/styles/filter-bar.css
444
- *
445
- * @param {Element} dd a `.ui-dropdown` that may be inside a filter row
446
- * @returns {Element|null} the `.ui-filter-bar` this menu's fit is measured in
447
- */
448
- export function filterPanelRow(dd) {
449
- if (typeof dd?.closest !== 'function') return null;
450
- const chip = dd.closest('.ui-filter-bar__chip');
451
- if (chip) return chip.closest('.ui-filter-bar');
452
- return ddPanelAsk(ddFitPanelOf(dd)) ? dd.closest('.ui-filter-bar') : null;
453
- }
454
-
455
- /**
456
- * Where a filter chip's menu may sit. #484 bounds the panel to its trigger, so a
457
- * chip printing its value alone (#536) left a 48px menu breaking words
458
- * mid-letter — #549. An OPEN panel takes the floor instead and slides along the
459
- * row when the room on the side it opens from is short; shut, it keeps the
460
- * trigger's width, which is why #467 needs no measuring at all.
461
- *
462
- * A panel is anchored at one edge of its dropdown — its inline end when it
463
- * carries `is-end` — so room is measured from that edge and the slide goes the
464
- * other way. Measuring an end-anchored panel forwards put one off the page.
465
- * why: docs/components.md#a-filter-row-holds-its-panels
466
- *
467
- * A menu that is not a chip's takes this arithmetic by asking, on its own panel,
468
- * for a width: `--ui-filter-panel-ask`. why: src/styles/filter-bar.css
469
- *
470
- * @param {Element} dd a `.ui-dropdown` that may be inside a filter row
471
- * @param {number} [floor] the width to reach for; the panel's own ask, else the kit's
472
- * @returns {{room: number, shift: number, floor: number, end: boolean}|null}
473
- */
474
- export function filterPanelFit(dd, floor) {
475
- const panel = ddFitPanelOf(dd);
476
- // Which menus are this function's subjects is filterPanelRow()'s question.
477
- const bar = filterPanelRow(dd);
478
- if (!bar || typeof bar.getBoundingClientRect !== 'function') return null;
479
- const row = bar.getBoundingClientRect();
480
- const box = dd.getBoundingClientRect();
481
- const end = !!panel?.classList?.contains('is-end');
482
- // A row narrower than the floor decides the width; nothing may leave the row.
483
- const want = Math.min(floor ?? ddPanelAsk(panel) ?? DD_MENU_FLOOR, row.width);
484
- const ahead = end
485
- ? Math.max(0, box.right - row.left) // an end-anchored panel grows backwards
486
- : Math.max(0, row.right - box.left);
487
- const slack = end
488
- ? Math.max(0, row.right - box.right) // …and slides towards the row's end
489
- : Math.max(0, box.left - row.left);
490
- const shift = Math.min(slack, Math.max(0, want - ahead));
491
- return { room: ahead + shift, shift, floor: want, end };
492
- }
493
-
494
- /** Write the fit onto the panel, and say whether any of the three numbers moved.
495
- * All three, because the stylesheet reads all three; it falls back to the
496
- * trigger's width when they are unset, so a panel opened before this runs is
497
- * bounded rather than unbounded.
498
- *
499
- * A number that has not changed is not written again, which is what stops the
500
- * observers below from answering their own writes: a fit landing on the same
501
- * three numbers mutates nothing, so it reports nothing. */
502
- function ddWriteFit(panel, fit) {
503
- let moved = false;
504
- for (const prop of ['room', 'shift', 'floor']) {
505
- const name = `--ui-filter-panel-${prop}`;
506
- const next = `${fit[prop]}px`;
507
- if (panel.style.getPropertyValue(name) === next) continue;
508
- panel.style.setProperty(name, next);
509
- moved = true;
510
- }
511
- return moved;
512
- }
513
-
514
- /** Fit a panel just opened, or leave it alone outside a filter row. */
515
- function ddFitFilterPanel(dd, panel) {
516
- const fit = filterPanelFit(dd);
517
- if (!fit || !panel?.style) return false;
518
- return ddWriteFit(panel, fit);
519
- }
520
-
521
- /** Measure an open menu again where its row now puts it. The fit it was opened
522
- * with can describe a row that no longer exists — a menu opened at 1280 and left
523
- * open at 390 kept a 1102px room and stood 11px off the page — or a place in that
524
- * row the chip has since left. A search panel's inline `min-width` was read at
525
- * the old width too, and inline beats the sheet, so it is read again off the
526
- * newly bounded box; only when the fit moved, because re-reading it is itself a
527
- * write.
528
- * why: docs/components.md#a-filter-row-holds-its-panels */
529
- function ddRefitFilterPanel(dd, panel) {
530
- const fit = panel?.style ? filterPanelFit(dd) : null;
531
- if (!fit || !ddWriteFit(panel, fit)) return;
532
- if (!panel.style.minWidth) return;
533
- panel.style.minWidth = '';
534
- if (panel.offsetWidth) panel.style.minWidth = `${panel.offsetWidth}px`;
535
- }
536
-
537
- /** Is this node inside some dropdown panel? Both fits write to a panel and to
538
- * nothing else, so a change inside one is never news — and a panel is
539
- * `position: absolute`, so nothing in it can move a chip along its row. Any
540
- * panel, not only the one being fitted: two open menus in one row would
541
- * otherwise answer each other a mutation at a time, and so did two <Dropdown>s
542
- * on a page, until the browser gate timed out.
543
- * why: docs/components.md#a-filter-row-holds-its-panels
544
- * why: docs/components.md#the-dropdown-panel */
545
- function ddOurs(node) {
546
- const el = node?.nodeType === 1 ? node : node?.parentElement;
547
- return !!el?.closest?.('[data-dropdown-panel]');
548
- }
549
-
550
- /**
551
- * Watch what the fit is measured from, and fit the menu again when it changes.
552
- *
553
- * Two inputs, two watchers. The row's width is one, observed rather than taken
554
- * from `resize`, which fires before an animating row has settled. Where the chip
555
- * sits along the row is the other, and it moves while the row keeps both of its
556
- * dimensions: re-labelling the chip in front of an open menu at 390px slid this
557
- * one 27.97px and took the menu 27.97px out of its row. So the boxes laid out in
558
- * the row are observed too — a chip is moved by the size of the ones in front of
559
- * it — and the mutation that moved it is watched for the frame before any of it
560
- * is laid out.
561
- *
562
- * Why those two cover the arithmetic, and the one case they do not:
563
- * why: docs/components.md#a-filter-row-holds-its-panels
564
- */
565
- function ddWatchRow(dd, panel) {
566
- ddUnwatchRow(dd);
567
- const row = filterPanelRow(dd);
568
- const view = dd.ownerDocument?.defaultView;
569
- if (!row) return;
570
- const refit = () => { if (dd.classList.contains('open')) ddRefitFilterPanel(dd, panel); };
571
- if (typeof view?.ResizeObserver === 'function') {
572
- // observe() reports each current box at once, which the fit was just written
573
- // from, so the first round writes nothing.
574
- const ro = new view.ResizeObserver(refit);
575
- ro.observe(row);
576
- for (const kid of row.children) ro.observe(kid);
577
- dd.__ddRowFit = ro;
578
- }
579
- if (typeof view?.MutationObserver !== 'function') return;
580
- const mo = new view.MutationObserver((records) => {
581
- if (records.every((m) => ddOurs(m.target))) return;
582
- // A chip added or removed brings a box the observer above is not watching yet.
583
- if (dd.__ddRowFit && records.some((m) => m.type === 'childList')) {
584
- for (const kid of row.children) dd.__ddRowFit.observe(kid);
585
- }
586
- refit();
587
- });
588
- /* characterData as well as the two structural kinds: a chip's printed value
589
- replaced is a text node changed, with no child list and no attribute moving
590
- with it — which is what a React re-render of that value arrives as too.
591
- Attributes, because a class is how a chip changes shape; subtree, because the
592
- text that sets a chip's width is inside it. */
593
- mo.observe(row, { subtree: true, childList: true, attributes: true, characterData: true });
594
- dd.__ddRowMo = mo;
595
- }
596
-
597
- function ddUnwatchRow(dd) {
598
- dd.__ddRowFit?.disconnect();
599
- dd.__ddRowFit = null;
600
- dd.__ddRowMo?.disconnect();
601
- dd.__ddRowMo = null;
602
- }
603
-
604
- /* ---- Following a panel's anchor --------------------------------------------
605
- * A position change need not resize anything and no event reports one, so the CAUSE
606
- * is watched instead: the DOM change that moved the trigger. Measured on the first
607
- * answer to #572, a flex row told to end-align its children left a panel at
608
- * 237.6…477.6 on a 390px screen and an ancestor scrolled sideways left one at
609
- * −108…132; a ResizeObserver sees neither. The limit, and why no end event is
610
- * taken for the middle of an animation, is stated with the rule.
611
- * why: docs/components.md#the-dropdown-panel */
612
-
613
- /**
614
- * How tall a panel may be: the room between its trigger and the viewport edge,
615
- * from dropdownAvail() in src/logic/dropdown.js — one calculation, so the
616
- * vanilla wiring and the React `<Dropdown>` cannot disagree about where a panel
617
- * ends. Measured from the trigger, not the panel, the way dropdownViewportFit()
618
- * is measured from the panel and not the trigger: each is the box the number it
619
- * answers actually depends on. `null` when there is nothing to measure.
620
- * why: docs/components.md#the-dropdown-panel
621
- *
622
- * @param {Element} dd the `[data-dropdown]` container the trigger lives in
623
- * @param {Element} panel a `[data-dropdown-panel]`, for its gap/edge/min and its
624
- * `is-up` direction
625
- */
626
- export function dropdownHeightFit(dd, panel) {
627
- const trigger = dd?.querySelector?.('[data-dropdown-trigger]');
628
- if (!trigger || typeof trigger.getBoundingClientRect !== 'function' || !panel) return null;
629
- const t = trigger.getBoundingClientRect();
630
- const view = ddViewOf(panel);
631
- // Inside a scrolling body the panel may take the body less its field: dropdownReveal()
632
- // scrolls the body to show it, so the room is the body's, not what is left under the
633
- // trigger now. A lifted panel is measured against the viewport, as a portalled one is.
634
- const fit = ddLifted(panel) ? null : ddBodyFit(dd, panel);
635
- if (fit && !fit.lift) return fit.room;
636
- // A lifted panel is measured from where the body is about to bring its trigger.
637
- const by = ddLifted(panel) && !ddUp(panel) ? dd.__ddLiftBy || 0 : 0;
638
- return dropdownAvail({
639
- anchorTop: t.top - by,
640
- anchorBottom: t.bottom - by,
641
- viewport: view.innerHeight,
642
- gap: ddGap(panel),
643
- inset: ddEdge(panel),
644
- min: ddMin(panel),
645
- up: ddUp(panel),
646
- });
647
- }
648
-
649
- /* A panel the wiring lifted out of a body too short to hold it: `position: fixed`, so
650
- * it opens over the body the way a portalled panel does. The value is the side it
651
- * opens on. why: docs/components.md#the-dropdown-panel */
652
- const ddLifted = (panel) => typeof panel?.hasAttribute === 'function' && panel.hasAttribute('data-dd-lifted');
653
- const ddUp = (panel) => (ddLifted(panel)
654
- ? panel.getAttribute('data-dd-lifted') === 'up'
655
- : !!panel?.classList?.contains('is-up'));
656
-
657
- /** Every ancestor that scrolls the block axis, from a wrapper to the Modal or Drawer
658
- * body round it, with the part of them a reader can see: their padding boxes clipped
659
- * to each other and to the viewport. `el` is the one whose end is that part's end,
660
- * which is the one that has to scroll. `height` is the least any of them shows, which
661
- * is the room a panel has whatever they are scrolled to. `null` for a portalled panel
662
- * (it is not inside them), a filter row (its row already bounds its panels) and a
663
- * trigger with none. */
664
- function ddScrollBox(dd, panel) {
665
- if (dd.__ddPanel || ddInFilterRow(panel)) return null;
666
- const view = ddViewOf(panel);
667
- const els = [];
668
- let top = 0;
669
- let bottom = view.innerHeight;
670
- let height = view.innerHeight;
671
- let el = null;
672
- for (let at = dd.parentElement; at && at !== at.ownerDocument.body; at = at.parentElement) {
673
- const overflow = view.getComputedStyle(at).overflowY;
674
- if (overflow !== 'auto' && overflow !== 'scroll') continue;
675
- const start = at.getBoundingClientRect().top + at.clientTop;
676
- const end = start + at.clientHeight;
677
- els.push(at);
678
- top = Math.max(top, start);
679
- if (end <= bottom) { bottom = end; el = at; }
680
- height = Math.min(height, at.clientHeight);
681
- }
682
- if (!els.length || !(bottom > top)) return null;
683
- return { el: el || els[0], els, top, bottom, height };
684
- }
685
-
686
- /* The top of what has to stay in view over the panel: the field's label when the
687
- * trigger has one above it, so the reader still sees what the list is for. */
688
- function ddAnchorTop(dd, t) {
689
- const label = dd.closest?.('.ui-field')?.querySelector(':scope > .ui-field__label');
690
- const top = label?.getBoundingClientRect?.().top;
691
- return Number.isFinite(top) && top < t.top ? top : t.top;
692
- }
693
-
694
- /* The height a panel's rows ask for, uncapped: its own box plus whatever it and its
695
- * list hold past their ends. */
696
- function ddContentHeight(panel) {
697
- let h = panel.offsetHeight + panel.scrollHeight - panel.clientHeight;
698
- const list = panel.querySelector?.('.ui-dropdown__list');
699
- if (list) h += list.scrollHeight - list.clientHeight;
700
- return h;
701
- }
702
-
703
- /**
704
- * How a panel fits the body it opens in. The body has to hold the field's label and
705
- * trigger, the gap, the panel and the room under it. That room is 48px where the body
706
- * can spare it, so the shadow fades before the body clips it, and it is spent down to
707
- * the 8px edge where the body cannot. Where even then the body cannot hold the floor
708
- * (or the whole list, when that is shorter), the panel is lifted out of the body.
709
- * Measured from the heights alone, so the answer is the same however far the body is
710
- * scrolled. `null` with no scrolling body.
711
- */
712
- function ddBodyFit(dd, panel) {
713
- const trigger = dd.querySelector('[data-dropdown-trigger]');
714
- const box = ddScrollBox(dd, panel);
715
- if (!box || !trigger) return null;
716
- const t = trigger.getBoundingClientRect();
717
- const edge = ddEdge(panel);
718
- const gap = ddGap(panel);
719
- const need = Math.min(ddMin(panel), ddContentHeight(panel));
720
- if (ddUp(panel)) {
721
- const room = box.height - 2 * edge - t.height - gap;
722
- return room >= need ? { box, end: edge, room, anchor: t.top } : { box, lift: true };
723
- }
724
- const anchor = ddAnchorTop(dd, t);
725
- const spare = box.height - edge - (t.bottom - anchor) - gap - need;
726
- const end = Math.max(edge, Math.min(ddShade(panel), spare));
727
- const room = box.height - edge - (t.bottom - anchor) - gap - end;
728
- return room >= need ? { box, end, room, anchor } : { box, lift: true };
729
- }
730
-
731
- /**
732
- * Lift an open panel out of a body too short to hold it, or put a lifted one back.
733
- * A lifted panel is `position: fixed` against the viewport and opens over the body,
734
- * below its trigger or, where the viewport has more room above, over it, the way a
735
- * portalled panel opens. It follows its trigger while the body scrolls. Call it with
736
- * the panel open and laid out, before sizing it. Returns whether the panel is lifted.
737
- * why: docs/components.md#the-dropdown-panel
738
- */
739
- export function dropdownLift(dd, panel) {
740
- if (!dd || !panel?.style || dd.__ddPanel) return false;
741
- const lift = !!ddBodyFit(dd, panel)?.lift;
742
- if (!lift) {
743
- if (ddLifted(panel)) {
744
- panel.removeAttribute('data-dd-lifted');
745
- for (const side of ['top', 'bottom', 'left', 'right']) panel.style.removeProperty(side);
746
- panel.style.removeProperty('inline-size');
747
- }
748
- return false;
749
- }
750
- dd.__ddLiftBy = ddLiftPlan(dd, panel);
751
- ddPlaceLifted(dd, panel);
752
- return true;
753
- }
754
-
755
- /* How far the body scrolls to give a lifted panel that opens down the viewport's room
756
- * under its trigger: no further than the field's label reaching the body's top, and no
757
- * further than the panel needs. 0 for a panel that opens up. The label stays in view,
758
- * where a panel lifted over it would cover it. */
759
- function ddLiftPlan(dd, panel) {
760
- const trigger = dd.querySelector('[data-dropdown-trigger]');
761
- const box = ddScrollBox(dd, panel);
762
- if (!trigger || !box || panel.classList.contains('is-up')) return 0;
763
- const t = trigger.getBoundingClientRect();
764
- const edge = ddEdge(panel);
765
- const rise = Math.max(0, ddAnchorTop(dd, t) - edge - box.top);
766
- const want = Math.min(ddContentHeight(panel), ddCeilingOf(panel));
767
- const over = t.bottom + ddGap(panel) + want + edge - ddViewOf(panel).innerHeight;
768
- return Math.max(0, Math.min(rise, Math.ceil(over)));
769
- }
770
-
771
- /* The tallest a panel may be before the room has a say: the cap a consumer asked for,
772
- * which under a search field is the list's and the field over it, or the standard cap. */
773
- function ddCeilingOf(panel) {
774
- const view = ddViewOf(panel);
775
- const list = panel.querySelector?.('.ui-dropdown__list');
776
- const own = parseFloat((list || panel).style?.getPropertyValue('--ui-dropdown-cap'));
777
- if (Number.isFinite(own)) return own + (list ? panel.offsetHeight - list.offsetHeight : 0);
778
- const max = parseFloat(view.getComputedStyle(panel).getPropertyValue('--ui-dropdown-max'));
779
- return Number.isFinite(max) ? max : Infinity;
780
- }
781
-
782
- function ddPlaceLifted(dd, panel) {
783
- const trigger = dd.querySelector('[data-dropdown-trigger]');
784
- if (!trigger) return;
785
- const view = ddViewOf(panel);
786
- const t = trigger.getBoundingClientRect();
787
- const gap = ddGap(panel);
788
- // Below is counted after the body has scrolled the field up (ddLiftPlan()).
789
- const below = view.innerHeight - t.bottom - gap + (dd.__ddLiftBy || 0);
790
- const above = t.top - gap;
791
- // The configured side, unless it cannot hold the floor and the other side has more.
792
- const configured = panel.classList.contains('is-up');
793
- const mine = configured ? above : below;
794
- const other = configured ? below : above;
795
- const up = mine < Math.min(ddMin(panel), ddContentHeight(panel)) && other > mine ? !configured : configured;
796
- const s = panel.style;
797
- s.translate = '';
798
- if (panel.getAttribute('data-dd-lifted') !== (up ? 'up' : 'down')) {
799
- const held = s.transition;
800
- s.transition = 'none';
801
- panel.setAttribute('data-dd-lifted', up ? 'up' : 'down');
802
- view.getComputedStyle(panel).transform;
803
- s.transition = held;
804
- }
805
- ddWriteCeiling(panel);
806
- if (dd.parentElement?.classList.contains('ui-field')) s.inlineSize = `${t.width}px`;
807
- const width = panel.getBoundingClientRect().width;
808
- const end = panel.classList.contains('is-end');
809
- const shift = dropdownViewportFit(panel, { left: end ? t.right - width : t.left, width })?.shift || 0;
810
- const left = (end ? t.right - width : t.left) + shift;
811
- s.right = 'auto';
812
- s.left = `${left}px`;
813
- if (up) { s.top = 'auto'; s.bottom = `${view.innerHeight - t.top + gap}px`; }
814
- else { s.bottom = 'auto'; s.top = `${t.bottom + gap}px`; }
815
- /* An ancestor with a transform holds a fixed box too, and then the numbers above are
816
- * read from its corner. Measured and taken back, so the panel lands where they say. */
817
- const r = panel.getBoundingClientRect();
818
- if (!(r.width > 0)) return;
819
- const dx = r.left - left;
820
- const dy = up ? r.bottom - (t.top - gap) : r.top - (t.bottom + gap);
821
- if (Math.abs(dx) > 0.5) s.left = `${left - dx}px`;
822
- if (Math.abs(dy) > 0.5) {
823
- if (up) s.bottom = `${view.innerHeight - t.top + gap + dy}px`;
824
- else s.top = `${t.bottom + gap - dy}px`;
825
- }
826
- }
827
-
828
- /**
829
- * Scroll the body an open panel sits in the least distance that shows the whole
830
- * panel, the room under it and the field's label over it (dropdownHeightFit() makes
831
- * the panel no taller than that). A body that already shows them does not move. A
832
- * wrapper inside the body that does not scroll is passed over: the ancestor whose end
833
- * is the end of what the reader sees is the one scrolled. Instant under
834
- * `prefers-reduced-motion`. Returns the distance scrolled.
835
- * why: docs/components.md#the-dropdown-panel
836
- */
837
- export function dropdownReveal(dd, panel) {
838
- const by = ddRevealOnce(dd, panel);
839
- /* A shut panel is held 6px off its place and the body cannot scroll past where
840
- * it ends, so the first scroll falls up to 6px short. One more look once the
841
- * panel has settled. */
842
- if (by && panel.style) {
843
- setTimeout(() => { if (dd.classList.contains('open')) ddRevealOnce(dd, panel); },
844
- transitionMs(panel) + DD_EXIT_SLACK_MS);
845
- }
846
- return by;
847
- }
848
-
849
- /* A body cannot scroll past the end of what it holds, and a panel is the last thing
850
- * in it: the panel's own bottom is the end. Without more below it, the room the
851
- * reveal keeps cannot be reached at the end of the body. The sheet draws a 1px spot
852
- * at the distance written here, below the trigger. `end` is that room: the body's,
853
- * or on a page the 8px edge, which the page's own fit keeps, so opening a panel on a
854
- * page that does not scroll makes it scroll by nothing. why: src/styles/dropdown.css */
855
- function ddReserveEnd(dd, panel, end) {
856
- if (!dd.style || ddUp(panel) || ddLifted(panel)) return;
857
- const next = `${ddGap(panel) + panel.offsetHeight + end - 1}px`;
858
- if (dd.style.getPropertyValue('--ui-dropdown-reach') !== next) dd.style.setProperty('--ui-dropdown-reach', next);
859
- }
860
-
861
- /* A shut panel is still laid out, and a box that is laid out counts towards the scroll
862
- * of what holds it: the end of a Modal or Drawer body, or of a page, scrolled to blank
863
- * space as tall as the panel. So a shut panel is collapsed, once its fade is over, and
864
- * its room under it goes with it. The body cannot scroll past where it ends, so
865
- * collapsing under a reader who is looking at that room would slide the field down by
866
- * the whole of it: the box stays until the reader has scrolled out of the room, and the
867
- * field never moves. The panel is given its box back before anything measures it.
868
- * why: docs/components.md#the-dropdown-panel */
869
- function ddScrollerOf(dd, panel) {
870
- return ddScrollBox(dd, panel)?.el ?? dd.ownerDocument.scrollingElement;
871
- }
872
-
873
- function ddCollapse(dd, panel) {
874
- const scroller = ddScrollerOf(dd, panel);
875
- const before = scroller?.scrollTop ?? 0;
876
- const reach = dd.style?.getPropertyValue('--ui-dropdown-reach') ?? '';
877
- panel.setAttribute('data-dd-shut', '');
878
- dd.style?.removeProperty('--ui-dropdown-reach');
879
- if (!scroller || scroller.scrollTop === before) return true;
880
- panel.removeAttribute('data-dd-shut');
881
- if (reach) dd.style.setProperty('--ui-dropdown-reach', reach);
882
- if (typeof scroller.scrollTo === 'function') scroller.scrollTo({ top: before, behavior: 'instant' });
883
- else scroller.scrollTop = before;
884
- return false;
885
- }
886
-
887
- /**
888
- * Give a panel its box while it is open, and take the box away once it has shut and
889
- * its fade is over. Returns a function that cancels a collapse still waiting.
890
- * Does nothing for a portalled panel, which is `position: fixed` and adds no scroll,
891
- * and for a panel in a filter row, which its row already bounds.
892
- * why: docs/components.md#the-dropdown-panel
893
- *
894
- * @param {Element} dd the `[data-dropdown]` container
895
- * @param {Element} panel its `[data-dropdown-panel]`
896
- * @param {boolean} open whether the panel is opening (`true`) or has shut (`false`)
897
- * @param {number} [wait] ms to wait before collapsing; the panel's own fade by default
898
- */
899
- export function dropdownRest(dd, panel, open, wait) {
900
- if (!dd || !panel?.style || dd.__ddPanel || ddInFilterRow(panel)) return () => {};
901
- dd.__ddRest?.();
902
- if (open) {
903
- panel.removeAttribute('data-dd-shut');
904
- return () => {};
905
- }
906
- let timer = null;
907
- let off = null;
908
- const cancel = () => {
909
- clearTimeout(timer);
910
- off?.();
911
- dd.__ddRest = null;
912
- };
913
- const attempt = () => {
914
- const done = !dd.isConnected || dd.classList.contains('open') || ddCollapse(dd, panel);
915
- if (done) cancel();
916
- return done;
917
- };
918
- const start = () => {
919
- timer = null;
920
- if (attempt()) return;
921
- const scroller = ddScrollerOf(dd, panel);
922
- const target = scroller === dd.ownerDocument.scrollingElement ? ddViewOf(panel) : scroller;
923
- target.addEventListener('scroll', attempt, { passive: true });
924
- off = () => target.removeEventListener('scroll', attempt);
925
- };
926
- dd.__ddRest = cancel;
927
- const ms = wait ?? transitionMs(panel) + DD_EXIT_SLACK_MS;
928
- if (ms > 0) timer = setTimeout(start, ms);
929
- else start();
930
- return cancel;
931
- }
932
-
933
- function ddRevealOnce(dd, panel) {
934
- const trigger = dd?.querySelector?.('[data-dropdown-trigger]');
935
- if (!trigger || typeof trigger.getBoundingClientRect !== 'function' || !panel) return 0;
936
- if (ddLifted(panel)) return ddRevealLifted(dd, panel, trigger);
937
- const fit = ddBodyFit(dd, panel);
938
- if (!fit) {
939
- // A page is held the same way: the shut panel lifts 6px, which would end the page 6px
940
- // sooner under a reader at its end.
941
- if (!dd.__ddPanel && !ddInFilterRow(panel)) ddReserveEnd(dd, panel, ddEdge(panel));
942
- // Focusing End can scroll only far enough to show the row. Finish the page
943
- // scroll so the open panel keeps its edge and the row's outline has room.
944
- if (!dd.__ddPanel && !ddLifted(panel) && !ddInFilterRow(panel)
945
- && panel.contains(dd.ownerDocument.activeElement?.closest?.('[data-dd-item]'))) {
946
- const view = ddViewOf(panel);
947
- const by = Math.ceil(panel.getBoundingClientRect().bottom + ddEdge(panel) - view.innerHeight);
948
- if (by > 0) { view.scrollBy({ top: by, behavior: 'instant' }); return by; }
949
- }
950
- return 0;
951
- }
952
- if (fit.lift) return 0;
953
- const { box, end } = fit;
954
- ddReserveEnd(dd, panel, end);
955
- const t = trigger.getBoundingClientRect();
956
- const edge = ddEdge(panel);
957
- const h = panel.offsetHeight;
958
- const up = ddUp(panel);
959
- const top = up ? t.top - ddGap(panel) - h - edge : ddAnchorTop(dd, t) - edge;
960
- const bottom = (up ? t.bottom : t.bottom + ddGap(panel) + h) + end;
961
- let by = 0;
962
- if (bottom > box.bottom) by = Math.min(bottom - box.bottom, top - box.top);
963
- else if (top < box.top) by = top - box.top;
964
- by = Math.round(by);
965
- if (!by) return 0;
966
- const behavior = prefersReducedMotion() ? 'auto' : 'smooth';
967
- /* The ancestor whose end the reader sees takes the scroll. What it has no room to
968
- * take goes to the others, nearest first, each up to the room it has. */
969
- const move = (el, d) => {
970
- if (typeof el.scrollBy === 'function') el.scrollBy({ top: d, behavior });
971
- else el.scrollTop += d;
972
- };
973
- const room = (el, d) => (d > 0 ? el.scrollHeight - el.clientHeight - el.scrollTop : -el.scrollTop);
974
- const first = room(box.el, by);
975
- move(box.el, by);
976
- let left = by > 0 ? by - Math.max(0, Math.min(by, first)) : by - Math.min(0, Math.max(by, first));
977
- for (const el of box.els) {
978
- if (el === box.el || !left) continue;
979
- const can = left > 0 ? Math.max(0, Math.min(left, room(el, left))) : Math.min(0, Math.max(left, room(el, left)));
980
- if (can) { move(el, can); left -= can; }
981
- }
982
- return by;
983
- }
984
-
985
- /* The scroll ddLiftPlan() asked for. The body may hold too little to scroll that far, so
986
- * the reserved spot is written to where the body's end then has to be. */
987
- function ddRevealLifted(dd, panel, trigger) {
988
- const by = dd.__ddLiftBy || 0;
989
- const box = by && !ddUp(panel) ? ddScrollBox(dd, panel) : null;
990
- if (!box) return 0;
991
- const t = trigger.getBoundingClientRect();
992
- dd.style?.setProperty('--ui-dropdown-reach', `${Math.max(0, box.bottom + by - t.bottom - 1)}px`);
993
- const behavior = prefersReducedMotion() ? 'auto' : 'smooth';
994
- if (typeof box.el.scrollBy === 'function') box.el.scrollBy({ top: by, behavior });
995
- else box.el.scrollTop += by;
996
- return by;
997
- }
998
-
999
- /**
1000
- * Stop an open panel's height where it cuts a row through the middle. A height that
1001
- * falls between two rows, or in a row's padding, shows a complete last label and the
1002
- * list looks whole; a half row says it goes on. The height is the one the panel gets:
1003
- * the smaller of its cap and the room the wiring measured, so a panel the room limits
1004
- * is cut the same way as one the cap limits. The rows are measured as they are drawn,
1005
- * so every row height the kit has, with a description or without and under a search
1006
- * field or not, stops at its own half row. A cap a consumer asked for (`scroll: <n>`)
1007
- * is kept to its number where it is the smaller, and a panel that fits has nothing to
1008
- * cut. Call it with the panel laid out and its room written.
1009
- * why: docs/components.md#the-dropdown-panel
1010
- */
1011
- export function dropdownSnap(dd, panel) {
1012
- if (!panel?.style) return;
1013
- const view = ddViewOf(panel);
1014
- const set = (v) => {
1015
- const next = v == null ? '' : `${v}px`;
1016
- if (panel.style.getPropertyValue('--ui-dropdown-fit') === next) return;
1017
- if (next) panel.style.setProperty('--ui-dropdown-fit', next);
1018
- else panel.style.removeProperty('--ui-dropdown-fit');
1019
- };
1020
- const rows = Array.from(panel.querySelectorAll('[data-dd-item]')).filter((el) => el.getClientRects().length);
1021
- let clip = panel;
1022
- for (let el = rows[0]?.parentElement; el && el !== panel; el = el.parentElement) {
1023
- const overflow = view.getComputedStyle(el).overflowY;
1024
- if (overflow === 'auto' || overflow === 'scroll') { clip = el; break; }
1025
- }
1026
- // The consumer's cap is on the panel, or on the list under a search field, where the
1027
- // panel is that cap and the field over it.
1028
- const own = parseFloat((clip === panel ? panel : clip).style.getPropertyValue('--ui-dropdown-cap'));
1029
- const chrome = clip === panel ? 0 : panel.offsetHeight - clip.offsetHeight;
1030
- const ceiling = ddCeilingOf(panel);
1031
- const room = parseFloat(panel.style.getPropertyValue('--ui-dropdown-avail'));
1032
- /* In a body, the room under the panel may be spent down to the 8px edge to reach the
1033
- * next half row up, rather than stop a whole row short of the room. */
1034
- const fit = room < ceiling && !ddLifted(panel) ? ddBodyFit(dd, panel) : null;
1035
- const spare = fit && !fit.lift ? fit.end - ddEdge(panel) : 0;
1036
- const height = Number.isFinite(room) ? Math.min(ceiling, room) : ceiling;
1037
- if (!rows.length || !Number.isFinite(height)) { set(null); return; }
1038
- // Kept to the consumer's number where it is the one that binds.
1039
- if (Number.isFinite(own) && !(room < ceiling)) { set(chrome ? ceiling : null); return; }
1040
- const box = panel.getBoundingClientRect();
1041
- const clipBox = clip.getBoundingClientRect();
1042
- if (!(box.height > 0)) return;
1043
- let scrolled = 0;
1044
- for (let el = rows[0].parentElement; el; el = el.parentElement) {
1045
- scrolled += el.scrollTop;
1046
- if (el === panel) break;
1047
- }
1048
- const edge = clip === panel ? panel.offsetHeight - panel.clientHeight - panel.clientTop : box.bottom - clipBox.bottom;
1049
- const lead = clip === panel ? panel.clientTop : clipBox.top - box.top;
1050
- const stop = dropdownStop({
1051
- rows: rows.map((el) => {
1052
- const r = el.getBoundingClientRect();
1053
- return { top: r.top - box.top + scrolled, height: r.height };
1054
- }),
1055
- below: edge,
1056
- content: lead + clip.scrollHeight + edge,
1057
- ceiling: height,
1058
- reach: Math.min(ceiling, height + spare),
1059
- });
1060
- set(stop ?? (chrome && Number.isFinite(own) ? ceiling : null));
1061
- if (stop > room) panel.style.setProperty('--ui-dropdown-avail', `${stop}px`);
1062
- }
1063
-
1064
- function ddSizeHeight(dd, panel) {
1065
- if (!panel?.style) return;
1066
- /* Decided when the panel opens and kept while the page or the body scrolls under it,
1067
- * so the panel does not grow or shrink under the reader. A resize, or the next open,
1068
- * decides again. A portalled panel follows its trigger instead, so it is measured
1069
- * again where the trigger now is. A lifted one follows its trigger at the height it
1070
- * opened at. why: docs/components.md#the-dropdown-panel */
1071
- if (dd.__ddSized && !dd.__ddPanel) return;
1072
- const avail = dropdownHeightFit(dd, panel);
1073
- if (avail == null) return;
1074
- // Infinity means the floor could not be met even by spending the whole inset:
1075
- // the property is removed rather than written, so the sheet's own fallback — the
1076
- // viewport less the edge inset, not a trigger-sized sliver — takes over. why:
1077
- // dropdownAvail(), src/logic/dropdown.js
1078
- //
1079
- // `.is-unbounded` marks a panel the room cannot hold. It keeps its cap, and the
1080
- // page, not the panel, is the way to the rows past the fold. why: src/styles/dropdown.css
1081
- panel.classList.toggle('is-unbounded', !Number.isFinite(avail));
1082
- // A number that has not changed is not written again, the way the width fit's
1083
- // own write is guarded: a mutation inside the row that moved nothing vertically
1084
- // would otherwise answer its own write, over and over, through the document
1085
- // observer below. why: dropdownViewportFit()'s own "moved" guard, same file
1086
- const next = Number.isFinite(avail) ? `${avail}px` : '';
1087
- if (panel.style.getPropertyValue('--ui-dropdown-avail') !== next) {
1088
- if (next) panel.style.setProperty('--ui-dropdown-avail', next);
1089
- else panel.style.removeProperty('--ui-dropdown-avail');
1090
- }
1091
- dropdownSnap(dd, panel);
1092
- }
1093
-
1094
- /** Fit a panel again where it now is, whichever placement it uses. */
1095
- function ddPlace(dd) {
1096
- const panel = dd.__ddPanel || ddPanelOf(dd);
1097
- if (dd.__ddPanel) {
1098
- ddResolveDirection(dd, panel);
1099
- positionPortalPanel(dd, panel);
1100
- }
1101
- else if (ddLifted(panel)) { if (dd.classList.contains('open')) dropdownLift(dd, panel); }
1102
- else ddFitViewport(dd, ddPanelOf(dd));
1103
- ddSizeHeight(dd, panel);
1104
- }
1105
-
1106
- /* A few frames past the sheet's own end, so the timer never cuts the fade's last
1107
- * frame. The number the dialogs' exit uses. */
1108
- const DD_EXIT_SLACK_MS = 50;
1109
-
1110
- /* How long the settle fallback waits: past --dur-slow (400ms), the longest motion
1111
- * the kit ships, plus the same slack. A motion longer than this is answered by its
1112
- * own end event; this timer is for the end event that never comes.
1113
- * why: src/tokens/tokens.css */
1114
- const DD_SETTLE_MS = 450;
1115
-
1116
- /**
1117
- * Hold a closing anchored menu's open geometry until its fade has finished.
1118
- *
1119
- * `.open` stops matching in the frame the menu closes; the fade does not — the
1120
- * panel transitions opacity over --dur-med. Dropping the width there left a 240px
1121
- * menu painted as a 48px column of single letters: #549 on the way out. The timer
1122
- * is the way out of a transitionend that never comes.
1123
- * why: src/styles/filter-bar.css
1124
- */
1125
- function ddHoldClose(dd, panel) {
1126
- ddCancelClose(dd, panel);
1127
- panel.classList.add('is-closing');
1128
- let done = false;
1129
- const finish = () => {
1130
- if (done) return;
1131
- done = true;
1132
- dd.__ddClosing = null;
1133
- panel.classList.remove('is-closing');
1134
- panel.style.minWidth = '';
1135
- for (const prop of ['room', 'shift', 'floor']) {
1136
- panel.style.removeProperty(`--ui-filter-panel-${prop}`);
1137
- }
1138
- };
1139
- // Only the panel's own fade: a row's background transition bubbles here too.
1140
- const onEnd = (e) => { if (e.target === panel && e.propertyName === 'opacity') stop(); };
1141
- const timer = setTimeout(() => stop(), transitionMs(panel) + DD_EXIT_SLACK_MS);
1142
- function stop() {
1143
- panel.removeEventListener('transitionend', onEnd);
1144
- clearTimeout(timer);
1145
- finish();
1146
- }
1147
- panel.addEventListener('transitionend', onEnd);
1148
- // Re-opened mid-fade: the wait is abandoned, so it cannot clear a fit the new
1149
- // open has already written.
1150
- dd.__ddClosing = () => {
1151
- done = true;
1152
- dd.__ddClosing = null;
1153
- panel.removeEventListener('transitionend', onEnd);
1154
- clearTimeout(timer);
1155
- panel.classList.remove('is-closing');
1156
- };
1157
- }
1158
-
1159
- function ddCancelClose(dd, panel) {
1160
- if (dd.__ddClosing) dd.__ddClosing();
1161
- else panel?.classList?.remove('is-closing');
1162
- }
1163
-
1164
- // Keep the configured side separate from the side resolved for this opening.
1165
- function ddResolveDirection(dd, panel) {
1166
- const auto = dd.getAttribute('data-dropdown-direction') === 'auto';
1167
- if (!auto && !dd.__ddPanel) return;
1168
- const trigger = dd.querySelector('[data-dropdown-trigger]');
1169
- if (!trigger || typeof trigger.getBoundingClientRect !== 'function') return;
1170
- const t = trigger.getBoundingClientRect();
1171
- const below = ddViewOf(panel).innerHeight - t.bottom;
1172
- if (auto) {
1173
- ddSetUp(panel, below < panel.offsetHeight + ddGap(panel) && t.top > below);
1174
- return;
1175
- }
1176
- const up = dd.__ddPreferredUp;
1177
- const room = (up ? t.top : below) - ddGap(panel);
1178
- const opposite = (up ? below : t.top) - ddGap(panel);
1179
- // Short content or a smaller consumer cap needs less than the usual floor.
1180
- const needed = Math.min(ddMin(panel), panel.offsetHeight);
1181
- ddSetUp(panel, room < needed && opposite > room ? !up : up);
1182
- }
1183
-
1184
- /* Change the side without a transition: the shut panel's transform would otherwise
1185
- * be running when `is-open` arrives, and the open would retarget it from the wrong
1186
- * side. */
1187
- function ddSetUp(panel, up) {
1188
- if (panel.classList.contains('is-up') === up) return;
1189
- const held = panel.style.transition;
1190
- panel.style.transition = 'none';
1191
- panel.classList.toggle('is-up', up);
1192
- ddViewOf(panel).getComputedStyle(panel).transform;
1193
- panel.style.transition = held;
1194
- }
1195
-
1196
- /** The shift a panel is already carrying, the one ddFitViewport() wrote. Taken
1197
- * off before the next measurement, so asking twice answers the same as asking
1198
- * once — the fit is measured from where the sheet puts the panel, not from where
1199
- * the last fit left it. */
1200
- const ddShiftOf = (panel) => parseFloat(panel.style?.translate) || 0;
1201
-
1202
- /** The widest a panel may be: the view it is laid out in, less the keep-out it owes
1203
- * each edge. It is the bound a PORTALLED panel needs, whose room is the whole view
1204
- * because it is `position: fixed`; an in-place one is bounded by its trigger's own
1205
- * block, once `overflow-wrap` has let its long tokens break.
1206
- * why: src/styles/dropdown.css */
1207
- const ddCeiling = (panel) => Math.max(0, ddViewWidth(panel) - 2 * ddEdge(panel));
1208
-
1209
- /** Write the ceiling, BEFORE the panel is measured: capping a panel's width
1210
- * changes the width a shift would be calculated from. The sheet reads the
1211
- * property and keeps its own 240px floor where the two disagree, which is a view
1212
- * narrower than 2 × edge + 240. why: src/styles/dropdown.css */
1213
- function ddWriteCeiling(panel) {
1214
- const max = ddCeiling(panel);
1215
- panel.style?.setProperty('--ui-dropdown-ceiling', max > 0 ? `${max}px` : '');
1216
- }
1217
-
1218
- /** A panel a filter row bounds to the row itself. It is nothing the viewport fit
1219
- * has to measure, and nothing the wiring has to watch for it.
1220
- * why: docs/components.md#a-filter-row-holds-its-panels */
1221
- const ddInFilterRow = (panel) => typeof panel?.closest === 'function' && !!panel.closest('.ui-filter-bar');
1222
-
1223
- /**
1224
- * How wide a panel may be and how far along the inline axis it has to move to stay
1225
- * inside the view it is laid out in: `left` at or after the edge, `right` at or
1226
- * before the far one.
1227
- *
1228
- * `align` decides the edge of the trigger a panel hangs from, and that is all it
1229
- * decides — on a phone it moves the clipping from one side to the other rather
1230
- * than removing it, which is #572. So the preferred edge is measured and kept
1231
- * whenever it fits, and overridden only when it does not: the same shape
1232
- * `direction: 'auto'` gives the block axis.
1233
- *
1234
- * Measured, not derived from the classes: the panel's own box is where the sheet
1235
- * has actually put it, so one answer covers `left: 0`, `.is-end`'s `right: 0` and
1236
- * the topbar's bespoke menus alike, and a rule nobody here has read about cannot
1237
- * send it the wrong way.
1238
- *
1239
- * A panel inside a `.ui-filter-bar` is not this function's subject: a filter row
1240
- * bounds its panels to the row itself, which already holds them inside the view.
1241
- * why: docs/components.md#a-filter-row-holds-its-panels
1242
- *
1243
- * @param {Element} panel a `[data-dropdown-panel]`, as the sheet has placed it
1244
- * @param {{left: number, width: number}} [at] the box the caller is about to
1245
- * write, for a panel it places itself — the portal, whose own box is still the
1246
- * one the last call left it at
1247
- * @returns {{shift: number, left: number, width: number, view: number, edge: number,
1248
- * max: number}|null}
1249
- */
1250
- export function dropdownViewportFit(panel, at) {
1251
- if (!panel || typeof panel.getBoundingClientRect !== 'function') return null;
1252
- if (!at && ddInFilterRow(panel)) return null;
1253
- const view = ddViewWidth(panel);
1254
- const box = panel.getBoundingClientRect();
1255
- const width = at ? at.width : box.width;
1256
- const left = at ? at.left : box.left - ddShiftOf(panel);
1257
- if (!(view > 0) || !(width > 0) || !Number.isFinite(left)) return null;
1258
- const slack = view - width;
1259
- /* The gap is what a panel can afford rather than what it asks for. A panel still
1260
- wider than its view — the floor, inside a view too narrow for it — has no room
1261
- for one and cannot honour both edges at all; it keeps its start, so the reader
1262
- meets the beginning of the rows and not the end. */
1263
- const edge = Math.max(0, Math.min(ddEdge(panel), slack / 2));
1264
- const want = Math.max(edge, Math.min(left, slack - edge));
1265
- return { shift: want - left, left: want, width, view, edge, max: ddCeiling(panel) };
1266
- }
1267
-
1268
- /**
1269
- * Keep a panel in place inside its view, by moving it along the inline axis.
1270
- *
1271
- * `translate` and not `left`, `right` or a margin: an absolutely positioned box is
1272
- * shrink-to-fit, so its width is measured against the room left between its own
1273
- * offsets, and a shift written as one of those offsets changes the width the shift
1274
- * was calculated from. A transform moves no layout, so the number stays true. The
1275
- * entry travel keeps `transform` to itself, and the property is off the panel's
1276
- * transition list, so a panel already open lands at once rather than sliding.
1277
- *
1278
- * A portalled panel is placed by positionPortalPanel(), which writes its edges in
1279
- * viewport coordinates and clamps them there.
1280
- * why: docs/components.md#the-dropdown-panel
1281
- */
1282
- function ddFitViewport(dd, panel) {
1283
- if (!panel?.style || dd?.__ddPanel === panel || ddInFilterRow(panel) || ddLifted(panel)) return;
1284
- ddWriteCeiling(panel);
1285
- const fit = dropdownViewportFit(panel);
1286
- if (!fit) return;
1287
- panel.style.translate = fit.shift ? `${fit.shift}px` : '';
1288
- }
1289
-
1290
- // Nothing lays a portalled panel out any more, so these four inline values are
1291
- // its layout. Inline, so no rule in any sheet can pin the opposite edge.
1292
- function positionPortalPanel(dd, panel) {
1293
- const trigger = dd.querySelector('[data-dropdown-trigger]');
1294
- if (!trigger || typeof trigger.getBoundingClientRect !== 'function') return;
1295
- const view = ddViewOf(panel);
1296
- const t = trigger.getBoundingClientRect();
1297
- const gap = ddGap(panel);
1298
- const s = panel.style;
1299
- if (panel.classList.contains('is-up')) {
1300
- s.top = 'auto';
1301
- s.bottom = `${view.innerHeight - t.top + gap}px`;
1302
- } else {
1303
- s.bottom = 'auto';
1304
- s.top = `${t.bottom + gap}px`;
1305
- }
1306
- /* The inline axis is fitted rather than mirrored. Both of these edges put a
1307
- 240px panel off the screen from a trigger near the one it is anchored to, and
1308
- #572 is that: the fit is asked with the box this function is about to write,
1309
- because the panel's own is still where the last call left it. */
1310
- const end = panel.classList.contains('is-end');
1311
- ddWriteCeiling(panel);
1312
- const width = panel.getBoundingClientRect().width;
1313
- const left = end ? t.right - width : t.left;
1314
- const shift = dropdownViewportFit(panel, { left, width })?.shift || 0;
1315
- if (end) {
1316
- s.left = 'auto';
1317
- s.right = `${ddViewWidth(panel) - t.right - shift}px`;
1318
- } else {
1319
- s.right = 'auto';
1320
- s.left = `${t.left + shift}px`;
1321
- }
1322
- }
1323
-
1324
- // A portalled panel outlives the container that owned it — a re-render replaces
1325
- // the container and the old panel has nothing pointing at it. Swept in the host
1326
- // it was put in, which is the tree the new container is in too.
1327
- function sweepOrphanPanels(host) {
1328
- host.querySelectorAll(':scope > [data-dropdown-panel][data-dropdown-portal]')
1329
- .forEach((p) => { if (!p.__ddOwner || !p.__ddOwner.isConnected) p.remove(); });
1330
- }
1331
-
1332
- function closeDropdown(dd) {
1333
- if (!dd.classList.contains('open')) return;
1334
- dd.classList.remove('open');
1335
- const panel = ddPanelOf(dd);
1336
- panel?.classList.remove('is-open');
1337
- ddUnwatchRow(dd);
1338
- /* A search panel carries the width it was opened at as an inline `min-width`,
1339
- * and inline beats any sheet. Inside a filter row that leaves a SHUT panel wider
1340
- * than its trigger, which is #467. Cleared here, and ddResetSearch() writes it
1341
- * again on the next open — except for an anchored menu, which gives the pin and
1342
- * the fit back at the END of its fade, both being its open geometry. A portalled
1343
- * panel is never fitted, so it has none to hold. why: ddHoldClose() */
1344
- if (panel?.style && !dd.__ddPanel && filterPanelRow(dd)) ddHoldClose(dd, panel);
1345
- else if (panel?.style && dd.closest?.('.ui-filter-bar')) panel.style.minWidth = '';
1346
- dd.querySelector('[data-dropdown-trigger]')?.setAttribute('aria-expanded', 'false');
1347
- /* The anchor may have moved while the panel was open, and a shut panel is laid
1348
- out: its box goes on counting towards the page's scrollable width. One reading
1349
- on the way out, so a panel left behind at 237.6…477.6 does not keep the page
1350
- 478px wide with nothing open. why: ddPlace() */
1351
- if (panel) ddFitViewport(dd, panel);
1352
- if (panel) dropdownRest(dd, panel, false);
1353
- }
1354
-
1355
- /** Every wired dropdown still in a tree, the ones in frames and shadow roots
1356
- * included. Disconnected containers are dropped as they are passed, with a collapse
1357
- * still waiting for a scroll, which would otherwise hold them until the next one. */
1358
- function ddLive() {
1359
- const out = [];
1360
- for (const dd of _ddAll) {
1361
- if (dd.isConnected) out.push(dd);
1362
- else {
1363
- dd.__ddRest?.();
1364
- _ddAll.delete(dd);
1365
- }
1366
- }
1367
- return out;
1368
- }
1369
-
1370
- function closeAllDropdowns(except) {
1371
- for (const dd of ddLive()) if (dd !== except && dd.classList.contains('open')) closeDropdown(dd);
1372
- }
1373
-
1374
- function openDropdown(dd, focusIdx) {
1375
- // Every way in goes through here — the trigger's click, the Enter the browser
1376
- // turns into one, and the arrows — so one refusal covers them all. #580
1377
- if (ddTriggerOff(dd)) return;
1378
- closeAllDropdowns(dd);
1379
- const panel = ddPanelOf(dd);
1380
- const search = ddSearchOf(dd);
1381
- if (panel) {
1382
- // An earlier close may still be holding its geometry; this open owns it now.
1383
- ddCancelClose(dd, panel);
1384
- dropdownRest(dd, panel, true);
1385
- ddResolveDirection(dd, panel);
1386
- if (dd.__ddPanel) { positionPortalPanel(dd, panel); panel.classList.add('is-open'); }
1387
- /* Both fits, because each one answers for the panels the other declines:
1388
- filterPanelFit() is null outside a filter chip, and dropdownViewportFit()
1389
- is null inside a filter row, whose own row already bounds its panels.
1390
- why: docs/components.md#a-filter-row-holds-its-panels */
1391
- else { ddFitFilterPanel(dd, panel); ddWatchRow(dd, panel); ddFitViewport(dd, panel); }
1392
- if (!dd.__ddPanel && !ddInFilterRow(panel)) dropdownLift(dd, panel);
1393
- dd.__ddSized = false;
1394
- ddSizeHeight(dd, panel);
1395
- dd.__ddSized = true;
1396
- }
1397
- // The body was scrolled to show the panel: a row taking focus must not scroll it
1398
- // again to the row alone.
1399
- const keep = panel && dropdownReveal(dd, panel) ? { preventScroll: true } : undefined;
1400
- dd.classList.add('open');
1401
- /* After `open`, and after the fit: ddResetSearch() pins the width it reads off
1402
- * the panel, and the rule that widens a filter menu only applies once the
1403
- * panel is open. Reading first pinned 50px inline, which beats any stylesheet
1404
- * — a searchable chip in a filter row kept the 74px menu #549 reported, while
1405
- * React, whose effects already ran in this order, gave 240px for the same
1406
- * markup. why: src/styles/filter-bar.css */
1407
- if (panel && search) ddResetSearch(dd, panel, search);
1408
- dd.querySelector('[data-dropdown-trigger]')?.setAttribute('aria-expanded', 'true');
1409
- // With search, focus goes to the field however the panel was opened, and
1410
- // the selected row (or the first) is the one Enter would pick.
1411
- if (search) {
1412
- const items = ddItemsOf(dd);
1413
- ddSetActive(dd, items.find((el) => el.getAttribute('aria-selected') === 'true') || items[0] || null);
1414
- search.focus(keep);
1415
- return;
1416
- }
1417
- if (focusIdx != null) {
1418
- const items = ddItemsOf(dd);
1419
- const sel = items.findIndex((el) => el.getAttribute('aria-selected') === 'true');
1420
- (items[focusIdx === 'selected' && sel >= 0 ? sel : (focusIdx === 'selected' ? 0 : focusIdx)] || items[0])?.focus(keep);
1421
- }
1422
- }
1423
-
1424
- // Single-select: reflect the picked option into aria-selected + the trigger value.
1425
- function selectOption(dd, item) {
1426
- if (!dd.hasAttribute('data-dropdown-select')) return;
1427
- // Every enabled row, the ones a search query has hidden included.
1428
- ddPanelOf(dd)?.querySelectorAll('[data-dd-item]:not([aria-disabled="true"])')
1429
- .forEach((el) => el.setAttribute('aria-selected', el === item ? 'true' : 'false'));
1430
- ddPanelOf(dd)?.querySelectorAll('[data-dd-item].is-selected').forEach((el) => el.classList.remove('is-selected'));
1431
- item.classList.add('is-selected');
1432
- const valueEl = dd.querySelector('[data-dropdown-trigger] .ui-dropdown__value');
1433
- const label = item.querySelector('.ui-dropdown__label');
1434
- if (valueEl && label) valueEl.textContent = label.textContent;
1435
- // A picker of people carries the row's mark up into the trigger.
1436
- const mark = item.querySelector(':scope > .ui-avatar');
1437
- const lead = dd.querySelector('[data-dropdown-trigger] > .ui-avatar');
1438
- if (mark && lead) lead.replaceWith(mark.cloneNode(true));
1439
- else if (mark) dd.querySelector('[data-dropdown-trigger]')?.prepend(mark.cloneNode(true));
1440
- else lead?.remove();
1441
- valueEl?.classList.remove('is-placeholder');
1442
- }
1443
-
1444
- // Click-outside, Escape and the repositioning sweep, registered once per document
1445
- // that holds a dropdown — the same shape wireShell()'s listen() has, and for the
1446
- // same reason: a frame is its own document and a listener on the page's never
1447
- // fires there. why: docs/components.md#the-dropdown-panel
1448
- function ddListen(doc) {
1449
- if (!doc || _ddWiredDocs.has(doc)) return;
1450
- _ddWiredDocs.add(doc);
1451
- doc.addEventListener('click', () => closeAllDropdowns());
1452
- doc.addEventListener('keydown', (e) => {
1453
- if (e.key !== 'Escape' || ddComposing(e)) return;
1454
- const open = ddLive().find((dd) => dd.classList.contains('open') && dd.ownerDocument === doc);
1455
- if (open) { closeDropdown(open); open.querySelector('[data-dropdown-trigger]')?.focus(); }
1456
- });
1457
- /* Viewport coordinates go stale the moment anything scrolls, and an in-place
1458
- panel's fit is measured against the view as much as a portalled one's: a
1459
- trigger slid from x=260 to x=10 inside a row that scrolls sideways left its
1460
- panel at −108…132, with the first row's label off the screen. Capture, so a
1461
- scroll inside the rail the panel was lifted out of, or inside that row, counts
1462
- too. why: docs/components.md#the-dropdown-panel */
1463
- const reposition = () => {
1464
- for (const dd of ddLive()) if (dd.classList.contains('open')) ddPlace(dd);
1465
- };
1466
- /* The fallback re-fit, for a view with no ResizeObserver. Not taken as well where
1467
- * ddWatchRow() is watching: a `resize` event is the worse measurement of the two.
1468
- * why: docs/components.md#a-filter-row-holds-its-panels */
1469
- const refit = () => {
1470
- for (const dd of ddLive()) {
1471
- if (dd.classList.contains('open') && !dd.__ddPanel && !dd.__ddRowFit) {
1472
- ddRefitFilterPanel(dd, ddPanelOf(dd));
1473
- }
1474
- }
1475
- };
1476
- /* The shut ones, which the sweep above does not reach and which no reader is
1477
- looking at: a shut panel is laid out, so a panel fitted at 1280 and left shut
1478
- at 375 keeps the page scrolling sideways with nothing open. A shut PORTALLED
1479
- panel is not one of them — `position: fixed` puts it in no page's scrollable
1480
- width. why: docs/components.md#the-dropdown-panel */
1481
- const refitInPlace = () => {
1482
- for (const dd of ddLive()) {
1483
- if (!dd.__ddPanel && !dd.classList.contains('open')) ddFitViewport(dd, ddPanelOf(dd));
1484
- }
1485
- };
1486
- // The two together, which is every panel that owes anybody an answer.
1487
- const follow = () => { reposition(); refitInPlace(); };
1488
- const view = doc.defaultView;
1489
- if (!view) return;
1490
- /* Both states on a scroll, not the open one alone: a shut panel is laid out, so
1491
- an ancestor scrolled back to where it started left one at 258…498 on a 390px
1492
- screen with nothing open — #501's page width, in the state the open sweep
1493
- cannot reach. React's half has always answered both; this is that answer.
1494
- why: docs/components.md#the-dropdown-panel */
1495
- view.addEventListener('scroll', follow, true);
1496
- /* A resize decides the placement again, a panel that was not lifted included: a
1497
- Drawer that held the panel at 844 tall cannot at 320. Lifted first, because the
1498
- height is measured from the placement, and the body is then scrolled to show what
1499
- the new placement needs, as it is on an open. why: openDropdown() */
1500
- const replace = () => {
1501
- for (const dd of ddLive()) {
1502
- dd.__ddSized = false;
1503
- if (!dd.classList.contains('open')) continue;
1504
- const panel = ddPanelOf(dd);
1505
- if (panel && !dd.__ddPanel && !ddInFilterRow(panel)) dropdownLift(dd, panel);
1506
- ddPlace(dd);
1507
- // Held again at the new height while the page scrolls, as after an open.
1508
- dd.__ddSized = true;
1509
- if (panel) dropdownReveal(dd, panel);
1510
- }
1511
- };
1512
- view.addEventListener('resize', replace);
1513
- view.addEventListener('resize', refit);
1514
- view.addEventListener('resize', refitInPlace);
1515
- /* Where motion leaves a trigger, read once it has stopped. The style write that
1516
- starts a transition is a mutation measured in the frame it lands, when the
1517
- trigger has not moved yet: one given `transition: transform 200ms` and then
1518
- translated 220px left its panel 240px outside the view for good, not for 200ms.
1519
- The end events answer that, and one timer per document answers the end event
1520
- that never comes — a cancelled transition's, or one on a box this document
1521
- never hears from. Armed when motion starts and cleared before it is armed
1522
- again, so one is pending at a time, and a fired one walks ddLive(), which has
1523
- already dropped whatever was removed meanwhile. The frames in between are what
1524
- this declines: the reader is owed the final position, not a measurement per
1525
- frame per panel. why: docs/components.md#the-dropdown-panel */
1526
- let settling = null;
1527
- const settle = () => {
1528
- clearTimeout(settling);
1529
- settling = setTimeout(() => { settling = null; follow(); }, DD_SETTLE_MS);
1530
- };
1531
- view.addEventListener('transitionend', follow, true);
1532
- view.addEventListener('animationend', follow, true);
1533
- view.addEventListener('transitionstart', settle, true);
1534
- view.addEventListener('animationstart', settle, true);
1535
- if (typeof view.MutationObserver === 'function' && doc.documentElement) {
1536
- const mo = new view.MutationObserver((records) => {
1537
- if (records.every((m) => ddOurs(m.target))) return;
1538
- follow();
1539
- });
1540
- /* characterData as well as the two structural kinds: growing a sibling TEXT
1541
- NODE moves a trigger along a flex row without changing one observed box, and
1542
- neither a child list nor an attribute changes with it. 39 characters of 10px
1543
- monospace in front of a menu carried both layers' panels from 8…248 to
1544
- 236.8…476.8 and left the page 477px wide. A change inside any panel is still
1545
- skipped, text included: ddOurs() reads a text node's parent.
1546
- why: docs/components.md#the-dropdown-panel */
1547
- mo.observe(doc.documentElement, {
1548
- subtree: true, childList: true, attributes: true, characterData: true,
1549
- });
1550
- }
1551
- }
1552
-
1553
- export function wireDropdown(root = document) {
1554
- const scope = root === document ? document : root;
1555
- scope.querySelectorAll('[data-dropdown]').forEach((dd) => {
1556
- if (dd.__ddWired) return;
1557
- dd.__ddWired = true;
1558
- _ddAll.add(dd);
1559
- ddListen(dd.ownerDocument);
1560
- const trigger = dd.querySelector('[data-dropdown-trigger]');
1561
- const panel = dd.querySelector('[data-dropdown-panel]');
1562
- if (!trigger) return;
1563
-
1564
- // Portal: lift the panel onto <body>. An ancestor whose overflow is not
1565
- // `visible` clips it on both axes, and one that is `position: sticky` opens
1566
- // a stacking context whatever z-index the panel carries — the app rail is
1567
- // both at once. why: docs/components.md#the-dropdown-panel
1568
- if (panel && dd.hasAttribute('data-dropdown-portal')) {
1569
- // The tree the trigger is in, not the page's: a panel lifted out of a
1570
- // frame or a shadow root into the top document leaves its stylesheet and
1571
- // its close handler behind. why: docs/components.md#the-dropdown-panel
1572
- const host = ddHostOf(dd);
1573
- sweepOrphanPanels(host);
1574
- panel.setAttribute('data-dropdown-portal', '');
1575
- panel.__ddOwner = dd;
1576
- dd.__ddPreferredUp = panel.classList.contains('is-up');
1577
- dd.__ddPanel = panel;
1578
- host.appendChild(panel);
1579
- if (dd.classList.contains('open')) {
1580
- ddResolveDirection(dd, panel);
1581
- positionPortalPanel(dd, panel);
1582
- panel.classList.add('is-open');
1583
- }
1584
- }
1585
-
1586
- // A panel rendered already-open never passes through openDropdown(), so its
1587
- // fit has to be taken here too — otherwise a story or a server-rendered bar
1588
- // keeps the fallback width and #549 survives in exactly the place a
1589
- // default-open menu makes most visible.
1590
- if (panel && !dd.__ddPanel && dd.classList.contains('open')) {
1591
- ddFitFilterPanel(dd, panel);
1592
- ddWatchRow(dd, panel);
1593
- }
1594
- if (panel && dd.classList.contains('open')) {
1595
- if (!dd.__ddPanel && !ddInFilterRow(panel)) dropdownLift(dd, panel);
1596
- ddSizeHeight(dd, panel);
1597
- dd.__ddSized = true;
1598
- }
1599
- else if (panel) dropdownRest(dd, panel, false, 0);
1600
-
1601
- trigger.addEventListener('click', (e) => {
1602
- e.stopPropagation();
1603
- if (dd.classList.contains('open')) closeDropdown(dd);
1604
- else openDropdown(dd);
1605
- });
1606
-
1607
- if (panel) {
1608
- // Clicks inside the panel shouldn't reach the document close handler;
1609
- // activating an item selects (single-select) + closes.
1610
- panel.addEventListener('click', (e) => {
1611
- e.stopPropagation();
1612
- const item = e.target.closest('[data-dd-item]');
1613
- if (!item || item.getAttribute('aria-disabled') === 'true') return;
1614
- selectOption(dd, item);
1615
- closeDropdown(dd);
1616
- trigger.focus();
1617
- });
1618
- const field = panel.querySelector('[data-dd-search]');
1619
- if (field) {
1620
- field.addEventListener('input', () => ddFilter(dd));
1621
- // The pointer moves the pick too, so Enter takes the row under it. A
1622
- // move to the same point is the browser's own after a scroll, not the
1623
- // reader's, and would snatch the pick from the arrows.
1624
- let at = '';
1625
- panel.addEventListener('mousemove', (e) => {
1626
- const here = `${e.clientX},${e.clientY}`;
1627
- if (here === at) return;
1628
- at = here;
1629
- const row = e.target.closest('[data-dd-item]');
1630
- if (row && row.getAttribute('aria-disabled') !== 'true' && !row.classList.contains('is-active')) ddSetActive(dd, row);
1631
- });
1632
- }
1633
- }
1634
-
1635
- const onKeydown = (e) => {
1636
- const open = dd.classList.contains('open');
1637
- const onTrigger = e.target === trigger;
1638
- const search = ddSearchOf(dd);
1639
- // While an IME is composing, its keys commit or steer the text, not the
1640
- // list. Safari's committing Enter carries keyCode 229, not isComposing.
1641
- if (e.target === search && ddComposing(e)) return;
1642
- if (search && open) {
1643
- // Arrows walk the rows still showing; focus stays in the field.
1644
- if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
1645
- e.preventDefault();
1646
- const items = ddItemsOf(dd);
1647
- if (!items.length) return;
1648
- const i = items.indexOf(ddActiveOf(dd));
1649
- const next = e.key === 'ArrowDown' ? (i + 1) % items.length : (i <= 0 ? items.length - 1 : i - 1);
1650
- ddSetActive(dd, items[next]);
1651
- return;
1652
- }
1653
- if (e.target === search && e.key === 'Enter') { e.preventDefault(); ddActiveOf(dd)?.click(); return; }
1654
- // Home and End move the caret in a text field; they are not the list's.
1655
- if (e.target === search && (e.key === 'Home' || e.key === 'End')) return;
1656
- }
1657
- if ((e.key === 'ArrowDown' || e.key === 'ArrowUp') && (onTrigger || open)) {
1658
- e.preventDefault();
1659
- if (!open) return openDropdown(dd, e.key === 'ArrowDown' ? 0 : 'selected');
1660
- const items = ddItemsOf(dd);
1661
- const i = items.indexOf(document.activeElement);
1662
- const next = e.key === 'ArrowDown' ? (i + 1) % items.length : (i - 1 + items.length) % items.length;
1663
- items[next < 0 ? 0 : next]?.focus();
1664
- } else if (e.key === 'Home' && open) {
1665
- e.preventDefault(); ddItemsOf(dd)[0]?.focus();
1666
- } else if (e.key === 'End' && open) {
1667
- e.preventDefault(); const it = ddItemsOf(dd); it[it.length - 1]?.focus();
1668
- dropdownReveal(dd, ddPanelOf(dd));
1669
- } else if ((e.key === 'Enter' || e.key === ' ') && open && e.target.matches('[data-dd-item]')) {
1670
- e.preventDefault(); e.target.click();
1671
- } else if (e.key === 'Escape' && open) {
1672
- e.preventDefault(); e.stopPropagation(); closeDropdown(dd); trigger.focus();
1673
- } else if (e.key === 'Tab' && open) {
1674
- closeDropdown(dd);
1675
- }
1676
- };
1677
-
1678
- dd.addEventListener('keydown', onKeydown);
1679
- if (dd.__ddPanel) {
1680
- // A portalled panel is no longer inside the container, so a keystroke on
1681
- // an item never bubbles to it. Bound here only, or it would fire twice.
1682
- dd.__ddPanel.addEventListener('keydown', onKeydown);
1683
- // It is also placed once, on open, and a trigger whose box changes after
1684
- // that — a webfont arriving, a longer label — leaves it adrift. Scroll
1685
- // and resize do not see a reflow; this does.
1686
- if (typeof ResizeObserver === 'function') {
1687
- new ResizeObserver(() => {
1688
- if (dd.classList.contains('open')) positionPortalPanel(dd, dd.__ddPanel);
1689
- }).observe(trigger);
1690
- }
1691
- } else if (panel && !ddInFilterRow(panel)) {
1692
- /* And an in-place panel is fitted here, before anything is clicked, because
1693
- a shut panel is laid out and a laid-out box counts towards the page's
1694
- scrollable width. The two boxes the fit is measured from are both watched:
1695
- the trigger, because the edge an end-aligned panel hangs from is the
1696
- trigger's, and the panel, because its own width is the other half of the
1697
- sum. The view's observer and not the module's: a panel in a frame is laid
1698
- out in that frame. A filter row's panels are skipped outright rather than
1699
- watched for a fit that declines them: that row is their bound, and
1700
- ddWatchRow() is the observer they get instead.
1701
- why: docs/components.md#the-dropdown-panel */
1702
- ddFitViewport(dd, panel);
1703
- const view = dd.ownerDocument?.defaultView;
1704
- if (typeof view?.ResizeObserver === 'function') {
1705
- // Writing a translate moves no layout, so a fit cannot report itself back.
1706
- const ro = new view.ResizeObserver(() => ddFitViewport(dd, panel));
1707
- ro.observe(trigger);
1708
- ro.observe(panel);
1709
- }
1710
- }
1711
- });
1712
-
1713
- }