@apliteni/apliteni-ui 0.142.0 → 0.142.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,671 @@
1
+ // Where a floating panel goes and how big it may be: the dropdown's placement, shared
2
+ // by the vanilla wiring and the React <Dropdown> (#429 moved it out of
3
+ // src/components/dropdown.js, so it outlives the vanilla wiring). The functions read
4
+ // and write the panel's DOM; they hold no state of their own.
5
+ // why: docs/components.md#the-dropdown-panel
6
+ import { dropdownAvail, dropdownStop } from './dropdown.js';
7
+ import { transitionMs, prefersReducedMotion } from '../motion.js';
8
+
9
+ /** The window a box is measured in. A panel in a frame is laid out against the
10
+ * frame's viewport, not the top page's. */
11
+ export const ddViewOf = (node) => node.ownerDocument?.defaultView || window;
12
+
13
+ // The trigger-to-panel offset is --ui-dropdown-gap in src/styles/dropdown.css.
14
+ // This is the fallback for a document that has not loaded the sheet;
15
+ // src/components/dropdown.test.js pins the two to each other.
16
+ const DD_GAP = 9;
17
+
18
+ export function ddGap(panel) {
19
+ const declared = parseFloat(ddViewOf(panel).getComputedStyle(panel).getPropertyValue('--ui-dropdown-gap'));
20
+ return Number.isFinite(declared) ? declared : DD_GAP;
21
+ }
22
+
23
+ // The least a panel keeps between itself and the edge of its view. The number is
24
+ // --ui-dropdown-edge in src/styles/dropdown.css, and this is the fallback for a
25
+ // document that has not loaded the sheet, as DD_GAP is for the offset.
26
+ const DD_EDGE = 8;
27
+
28
+ function ddEdge(panel) {
29
+ const declared = parseFloat(ddViewOf(panel).getComputedStyle(panel).getPropertyValue('--ui-dropdown-edge'));
30
+ return Number.isFinite(declared) ? declared : DD_EDGE;
31
+ }
32
+
33
+ // The room a panel that opens down keeps between its end and the end of the Modal
34
+ // or Drawer body that holds it, so its shadow fades before the body clips it. The
35
+ // number is --ui-dropdown-shade in src/styles/dropdown.css.
36
+ const DD_SHADE = 48;
37
+
38
+ function ddShade(panel) {
39
+ const declared = parseFloat(ddViewOf(panel).getComputedStyle(panel).getPropertyValue('--ui-dropdown-shade'));
40
+ return Number.isFinite(declared) ? declared : DD_SHADE;
41
+ }
42
+
43
+ // The least height a capped panel keeps, below which it would rather spend the
44
+ // edge inset than shrink further. The number is --ui-dropdown-min in
45
+ // src/styles/dropdown.css. #489
46
+ const DD_MIN = 120;
47
+
48
+ export function ddMin(panel) {
49
+ const declared = parseFloat(ddViewOf(panel).getComputedStyle(panel).getPropertyValue('--ui-dropdown-min'));
50
+ return Number.isFinite(declared) ? declared : DD_MIN;
51
+ }
52
+
53
+ /** The width a panel has to stay inside: the LAYOUT viewport, which is what both
54
+ * `position: fixed` and a page's scrollable width are measured against. A classic
55
+ * scrollbar is in `innerWidth` and not in the box either of those means, so an
56
+ * end-anchored panel written from `innerWidth` sat a scrollbar's width inside its
57
+ * trigger. The fallback is for a view that lays nothing out, JSDOM among them. */
58
+ export const ddViewWidth = (panel) => {
59
+ const view = ddViewOf(panel);
60
+ return view.document?.documentElement?.clientWidth || view.innerWidth || 0;
61
+ };
62
+
63
+ /* The kit's menu floor, the one `.ui-dropdown__panel` writes. The stylesheets
64
+ * carry the same number; stories/filter-bar-fit.test.js reads all of them and
65
+ * fails when one drifts. why: src/styles/dropdown.css */
66
+ export const DD_MENU_FLOOR = 240;
67
+
68
+ /** The floor a panel asks for in the sheet, or null. A separate name from the
69
+ * floor this fit writes back: one that read its own output would pin a menu at
70
+ * whatever a narrow row once allowed. why: src/styles/filter-bar.css */
71
+ function ddPanelAsk(panel) {
72
+ const view = panel?.ownerDocument?.defaultView;
73
+ if (!panel || typeof view?.getComputedStyle !== 'function') return null;
74
+ const asked = Number.parseFloat(view.getComputedStyle(panel).getPropertyValue('--ui-filter-panel-ask'));
75
+ return Number.isFinite(asked) && asked > 0 ? asked : null;
76
+ }
77
+
78
+ /** The `.ui-dropdown__panel` inside a dropdown, by class rather than by data
79
+ * attribute: the fit's subjects are the panels the stylesheet's rules match, and
80
+ * filter-panel-fit.test.js hands this function hand-made elements. */
81
+ const ddFitPanelOf = (dd) => (typeof dd?.querySelector === 'function'
82
+ ? dd.querySelector('.ui-dropdown__panel') : null);
83
+
84
+ /**
85
+ * The filter row an anchored menu is measured inside, or null outside one.
86
+ *
87
+ * Two panels in a row are anchored at a trigger of their own: a chip's values, and
88
+ * the add control's catalogue, which says so by asking for a width. The slide
89
+ * filterPanelFit() computes is measured from that trigger's offset along the row,
90
+ * which is arithmetic for either. A panel anchored to the row itself is neither,
91
+ * and sizes itself.
92
+ *
93
+ * Published because `<Dropdown>` asks the same question — the same row to observe,
94
+ * the same panels to hold through a close — and a second copy of this rule would
95
+ * drift from the stylesheet. why: src/styles/filter-bar.css
96
+ *
97
+ * @param {Element} dd a `.ui-dropdown` that may be inside a filter row
98
+ * @returns {Element|null} the `.ui-filter-bar` this menu's fit is measured in
99
+ */
100
+ export function filterPanelRow(dd) {
101
+ if (typeof dd?.closest !== 'function') return null;
102
+ const chip = dd.closest('.ui-filter-bar__chip');
103
+ if (chip) return chip.closest('.ui-filter-bar');
104
+ return ddPanelAsk(ddFitPanelOf(dd)) ? dd.closest('.ui-filter-bar') : null;
105
+ }
106
+
107
+ /**
108
+ * Where a filter chip's menu may sit. #484 bounds the panel to its trigger, so a
109
+ * chip printing its value alone (#536) left a 48px menu breaking words
110
+ * mid-letter — #549. An OPEN panel takes the floor instead and slides along the
111
+ * row when the room on the side it opens from is short; shut, it keeps the
112
+ * trigger's width, which is why #467 needs no measuring at all.
113
+ *
114
+ * A panel is anchored at one edge of its dropdown — its inline end when it
115
+ * carries `is-end` — so room is measured from that edge and the slide goes the
116
+ * other way. Measuring an end-anchored panel forwards put one off the page.
117
+ * why: docs/components.md#a-filter-row-holds-its-panels
118
+ *
119
+ * A menu that is not a chip's takes this arithmetic by asking, on its own panel,
120
+ * for a width: `--ui-filter-panel-ask`. why: src/styles/filter-bar.css
121
+ *
122
+ * @param {Element} dd a `.ui-dropdown` that may be inside a filter row
123
+ * @param {number} [floor] the width to reach for; the panel's own ask, else the kit's
124
+ * @returns {{room: number, shift: number, floor: number, end: boolean}|null}
125
+ */
126
+ export function filterPanelFit(dd, floor) {
127
+ const panel = ddFitPanelOf(dd);
128
+ // Which menus are this function's subjects is filterPanelRow()'s question.
129
+ const bar = filterPanelRow(dd);
130
+ if (!bar || typeof bar.getBoundingClientRect !== 'function') return null;
131
+ const row = bar.getBoundingClientRect();
132
+ const box = dd.getBoundingClientRect();
133
+ const end = !!panel?.classList?.contains('is-end');
134
+ // A row narrower than the floor decides the width; nothing may leave the row.
135
+ const want = Math.min(floor ?? ddPanelAsk(panel) ?? DD_MENU_FLOOR, row.width);
136
+ const ahead = end
137
+ ? Math.max(0, box.right - row.left) // an end-anchored panel grows backwards
138
+ : Math.max(0, row.right - box.left);
139
+ const slack = end
140
+ ? Math.max(0, row.right - box.right) // …and slides towards the row's end
141
+ : Math.max(0, box.left - row.left);
142
+ const shift = Math.min(slack, Math.max(0, want - ahead));
143
+ return { room: ahead + shift, shift, floor: want, end };
144
+ }
145
+
146
+ /**
147
+ * How tall a panel may be: the room between its trigger and the viewport edge,
148
+ * from dropdownAvail() in src/logic/dropdown.js — one calculation, so the
149
+ * vanilla wiring and the React `<Dropdown>` cannot disagree about where a panel
150
+ * ends. Measured from the trigger, not the panel, the way dropdownViewportFit()
151
+ * is measured from the panel and not the trigger: each is the box the number it
152
+ * answers actually depends on. `null` when there is nothing to measure.
153
+ * why: docs/components.md#the-dropdown-panel
154
+ *
155
+ * @param {Element} dd the `[data-dropdown]` container the trigger lives in
156
+ * @param {Element} panel a `[data-dropdown-panel]`, for its gap/edge/min and its
157
+ * `is-up` direction
158
+ */
159
+ export function dropdownHeightFit(dd, panel) {
160
+ const trigger = dd?.querySelector?.('[data-dropdown-trigger]');
161
+ if (!trigger || typeof trigger.getBoundingClientRect !== 'function' || !panel) return null;
162
+ const t = trigger.getBoundingClientRect();
163
+ const view = ddViewOf(panel);
164
+ // Inside a scrolling body the panel may take the body less its field: dropdownReveal()
165
+ // scrolls the body to show it, so the room is the body's, not what is left under the
166
+ // trigger now. A lifted panel is measured against the viewport, as a portalled one is.
167
+ const fit = ddLifted(panel) ? null : ddBodyFit(dd, panel);
168
+ if (fit && !fit.lift) return fit.room;
169
+ // A lifted panel is measured from where the body is about to bring its trigger.
170
+ const by = ddLifted(panel) && !ddUp(panel) ? dd.__ddLiftBy || 0 : 0;
171
+ return dropdownAvail({
172
+ anchorTop: t.top - by,
173
+ anchorBottom: t.bottom - by,
174
+ viewport: view.innerHeight,
175
+ gap: ddGap(panel),
176
+ inset: ddEdge(panel),
177
+ min: ddMin(panel),
178
+ up: ddUp(panel),
179
+ });
180
+ }
181
+
182
+ /* A panel the wiring lifted out of a body too short to hold it: `position: fixed`, so
183
+ * it opens over the body the way a portalled panel does. The value is the side it
184
+ * opens on. why: docs/components.md#the-dropdown-panel */
185
+ export const ddLifted = (panel) => typeof panel?.hasAttribute === 'function' && panel.hasAttribute('data-dd-lifted');
186
+ const ddUp = (panel) => (ddLifted(panel)
187
+ ? panel.getAttribute('data-dd-lifted') === 'up'
188
+ : !!panel?.classList?.contains('is-up'));
189
+
190
+ /** Every ancestor that scrolls the block axis, from a wrapper to the Modal or Drawer
191
+ * body round it, with the part of them a reader can see: their padding boxes clipped
192
+ * to each other and to the viewport. `el` is the one whose end is that part's end,
193
+ * which is the one that has to scroll. `height` is the least any of them shows, which
194
+ * is the room a panel has whatever they are scrolled to. `null` for a portalled panel
195
+ * (it is not inside them), a filter row (its row already bounds its panels) and a
196
+ * trigger with none. */
197
+ function ddScrollBox(dd, panel) {
198
+ if (dd.__ddPanel || ddInFilterRow(panel)) return null;
199
+ const view = ddViewOf(panel);
200
+ const els = [];
201
+ let top = 0;
202
+ let bottom = view.innerHeight;
203
+ let height = view.innerHeight;
204
+ let el = null;
205
+ for (let at = dd.parentElement; at && at !== at.ownerDocument.body; at = at.parentElement) {
206
+ const overflow = view.getComputedStyle(at).overflowY;
207
+ if (overflow !== 'auto' && overflow !== 'scroll') continue;
208
+ const start = at.getBoundingClientRect().top + at.clientTop;
209
+ const end = start + at.clientHeight;
210
+ els.push(at);
211
+ top = Math.max(top, start);
212
+ if (end <= bottom) { bottom = end; el = at; }
213
+ height = Math.min(height, at.clientHeight);
214
+ }
215
+ if (!els.length || !(bottom > top)) return null;
216
+ return { el: el || els[0], els, top, bottom, height };
217
+ }
218
+
219
+ /* The top of what has to stay in view over the panel: the field's label when the
220
+ * trigger has one above it, so the reader still sees what the list is for. */
221
+ function ddAnchorTop(dd, t) {
222
+ const label = dd.closest?.('.ui-field')?.querySelector(':scope > .ui-field__label');
223
+ const top = label?.getBoundingClientRect?.().top;
224
+ return Number.isFinite(top) && top < t.top ? top : t.top;
225
+ }
226
+
227
+ /* The height a panel's rows ask for, uncapped: its own box plus whatever it and its
228
+ * list hold past their ends. */
229
+ function ddContentHeight(panel) {
230
+ let h = panel.offsetHeight + panel.scrollHeight - panel.clientHeight;
231
+ const list = panel.querySelector?.('.ui-dropdown__list');
232
+ if (list) h += list.scrollHeight - list.clientHeight;
233
+ return h;
234
+ }
235
+
236
+ /**
237
+ * How a panel fits the body it opens in. The body has to hold the field's label and
238
+ * trigger, the gap, the panel and the room under it. That room is 48px where the body
239
+ * can spare it, so the shadow fades before the body clips it, and it is spent down to
240
+ * the 8px edge where the body cannot. Where even then the body cannot hold the floor
241
+ * (or the whole list, when that is shorter), the panel is lifted out of the body.
242
+ * Measured from the heights alone, so the answer is the same however far the body is
243
+ * scrolled. `null` with no scrolling body.
244
+ */
245
+ function ddBodyFit(dd, panel) {
246
+ const trigger = dd.querySelector('[data-dropdown-trigger]');
247
+ const box = ddScrollBox(dd, panel);
248
+ if (!box || !trigger) return null;
249
+ const t = trigger.getBoundingClientRect();
250
+ const edge = ddEdge(panel);
251
+ const gap = ddGap(panel);
252
+ const need = Math.min(ddMin(panel), ddContentHeight(panel));
253
+ if (ddUp(panel)) {
254
+ const room = box.height - 2 * edge - t.height - gap;
255
+ return room >= need ? { box, end: edge, room, anchor: t.top } : { box, lift: true };
256
+ }
257
+ const anchor = ddAnchorTop(dd, t);
258
+ const spare = box.height - edge - (t.bottom - anchor) - gap - need;
259
+ const end = Math.max(edge, Math.min(ddShade(panel), spare));
260
+ const room = box.height - edge - (t.bottom - anchor) - gap - end;
261
+ return room >= need ? { box, end, room, anchor } : { box, lift: true };
262
+ }
263
+
264
+ /**
265
+ * Lift an open panel out of a body too short to hold it, or put a lifted one back.
266
+ * A lifted panel is `position: fixed` against the viewport and opens over the body,
267
+ * below its trigger or, where the viewport has more room above, over it, the way a
268
+ * portalled panel opens. It follows its trigger while the body scrolls. Call it with
269
+ * the panel open and laid out, before sizing it. Returns whether the panel is lifted.
270
+ * why: docs/components.md#the-dropdown-panel
271
+ */
272
+ export function dropdownLift(dd, panel) {
273
+ if (!dd || !panel?.style || dd.__ddPanel) return false;
274
+ const lift = !!ddBodyFit(dd, panel)?.lift;
275
+ if (!lift) {
276
+ if (ddLifted(panel)) {
277
+ panel.removeAttribute('data-dd-lifted');
278
+ for (const side of ['top', 'bottom', 'left', 'right']) panel.style.removeProperty(side);
279
+ panel.style.removeProperty('inline-size');
280
+ }
281
+ return false;
282
+ }
283
+ dd.__ddLiftBy = ddLiftPlan(dd, panel);
284
+ ddPlaceLifted(dd, panel);
285
+ return true;
286
+ }
287
+
288
+ /* How far the body scrolls to give a lifted panel that opens down the viewport's room
289
+ * under its trigger: no further than the field's label reaching the body's top, and no
290
+ * further than the panel needs. 0 for a panel that opens up. The label stays in view,
291
+ * where a panel lifted over it would cover it. */
292
+ function ddLiftPlan(dd, panel) {
293
+ const trigger = dd.querySelector('[data-dropdown-trigger]');
294
+ const box = ddScrollBox(dd, panel);
295
+ if (!trigger || !box || panel.classList.contains('is-up')) return 0;
296
+ const t = trigger.getBoundingClientRect();
297
+ const edge = ddEdge(panel);
298
+ const rise = Math.max(0, ddAnchorTop(dd, t) - edge - box.top);
299
+ const want = Math.min(ddContentHeight(panel), ddCeilingOf(panel));
300
+ const over = t.bottom + ddGap(panel) + want + edge - ddViewOf(panel).innerHeight;
301
+ return Math.max(0, Math.min(rise, Math.ceil(over)));
302
+ }
303
+
304
+ /* The tallest a panel may be before the room has a say: the cap a consumer asked for,
305
+ * which under a search field is the list's and the field over it, or the standard cap. */
306
+ function ddCeilingOf(panel) {
307
+ const view = ddViewOf(panel);
308
+ const list = panel.querySelector?.('.ui-dropdown__list');
309
+ const own = parseFloat((list || panel).style?.getPropertyValue('--ui-dropdown-cap'));
310
+ if (Number.isFinite(own)) return own + (list ? panel.offsetHeight - list.offsetHeight : 0);
311
+ const max = parseFloat(view.getComputedStyle(panel).getPropertyValue('--ui-dropdown-max'));
312
+ return Number.isFinite(max) ? max : Infinity;
313
+ }
314
+
315
+ function ddPlaceLifted(dd, panel) {
316
+ const trigger = dd.querySelector('[data-dropdown-trigger]');
317
+ if (!trigger) return;
318
+ const view = ddViewOf(panel);
319
+ const t = trigger.getBoundingClientRect();
320
+ const gap = ddGap(panel);
321
+ // Below is counted after the body has scrolled the field up (ddLiftPlan()).
322
+ const below = view.innerHeight - t.bottom - gap + (dd.__ddLiftBy || 0);
323
+ const above = t.top - gap;
324
+ // The configured side, unless it cannot hold the floor and the other side has more.
325
+ const configured = panel.classList.contains('is-up');
326
+ const mine = configured ? above : below;
327
+ const other = configured ? below : above;
328
+ const up = mine < Math.min(ddMin(panel), ddContentHeight(panel)) && other > mine ? !configured : configured;
329
+ const s = panel.style;
330
+ s.translate = '';
331
+ if (panel.getAttribute('data-dd-lifted') !== (up ? 'up' : 'down')) {
332
+ const held = s.transition;
333
+ s.transition = 'none';
334
+ panel.setAttribute('data-dd-lifted', up ? 'up' : 'down');
335
+ view.getComputedStyle(panel).transform;
336
+ s.transition = held;
337
+ }
338
+ ddWriteCeiling(panel);
339
+ if (dd.parentElement?.classList.contains('ui-field')) s.inlineSize = `${t.width}px`;
340
+ const width = panel.getBoundingClientRect().width;
341
+ const end = panel.classList.contains('is-end');
342
+ const shift = dropdownViewportFit(panel, { left: end ? t.right - width : t.left, width })?.shift || 0;
343
+ const left = (end ? t.right - width : t.left) + shift;
344
+ s.right = 'auto';
345
+ s.left = `${left}px`;
346
+ if (up) { s.top = 'auto'; s.bottom = `${view.innerHeight - t.top + gap}px`; }
347
+ else { s.bottom = 'auto'; s.top = `${t.bottom + gap}px`; }
348
+ /* An ancestor with a transform holds a fixed box too, and then the numbers above are
349
+ * read from its corner. Measured and taken back, so the panel lands where they say. */
350
+ const r = panel.getBoundingClientRect();
351
+ if (!(r.width > 0)) return;
352
+ const dx = r.left - left;
353
+ const dy = up ? r.bottom - (t.top - gap) : r.top - (t.bottom + gap);
354
+ if (Math.abs(dx) > 0.5) s.left = `${left - dx}px`;
355
+ if (Math.abs(dy) > 0.5) {
356
+ if (up) s.bottom = `${view.innerHeight - t.top + gap + dy}px`;
357
+ else s.top = `${t.bottom + gap - dy}px`;
358
+ }
359
+ }
360
+
361
+ /**
362
+ * Scroll the body an open panel sits in the least distance that shows the whole
363
+ * panel, the room under it and the field's label over it (dropdownHeightFit() makes
364
+ * the panel no taller than that). A body that already shows them does not move. A
365
+ * wrapper inside the body that does not scroll is passed over: the ancestor whose end
366
+ * is the end of what the reader sees is the one scrolled. Instant under
367
+ * `prefers-reduced-motion`. Returns the distance scrolled.
368
+ * why: docs/components.md#the-dropdown-panel
369
+ */
370
+ export function dropdownReveal(dd, panel) {
371
+ const by = ddRevealOnce(dd, panel);
372
+ /* A shut panel is held 6px off its place and the body cannot scroll past where
373
+ * it ends, so the first scroll falls up to 6px short. One more look once the
374
+ * panel has settled. */
375
+ if (by && panel.style) {
376
+ setTimeout(() => { if (dd.classList.contains('open')) ddRevealOnce(dd, panel); },
377
+ transitionMs(panel) + DD_EXIT_SLACK_MS);
378
+ }
379
+ return by;
380
+ }
381
+
382
+ /* A body cannot scroll past the end of what it holds, and a panel is the last thing
383
+ * in it: the panel's own bottom is the end. Without more below it, the room the
384
+ * reveal keeps cannot be reached at the end of the body. The sheet draws a 1px spot
385
+ * at the distance written here, below the trigger. `end` is that room: the body's,
386
+ * or on a page the 8px edge, which the page's own fit keeps, so opening a panel on a
387
+ * page that does not scroll makes it scroll by nothing. why: src/styles/dropdown.css */
388
+ function ddReserveEnd(dd, panel, end) {
389
+ if (!dd.style || ddUp(panel) || ddLifted(panel)) return;
390
+ const next = `${ddGap(panel) + panel.offsetHeight + end - 1}px`;
391
+ if (dd.style.getPropertyValue('--ui-dropdown-reach') !== next) dd.style.setProperty('--ui-dropdown-reach', next);
392
+ }
393
+
394
+ /* A shut panel is still laid out, and a box that is laid out counts towards the scroll
395
+ * of what holds it: the end of a Modal or Drawer body, or of a page, scrolled to blank
396
+ * space as tall as the panel. So a shut panel is collapsed, once its fade is over, and
397
+ * its room under it goes with it. The body cannot scroll past where it ends, so
398
+ * collapsing under a reader who is looking at that room would slide the field down by
399
+ * the whole of it: the box stays until the reader has scrolled out of the room, and the
400
+ * field never moves. The panel is given its box back before anything measures it.
401
+ * why: docs/components.md#the-dropdown-panel */
402
+ function ddScrollerOf(dd, panel) {
403
+ return ddScrollBox(dd, panel)?.el ?? dd.ownerDocument.scrollingElement;
404
+ }
405
+
406
+ function ddCollapse(dd, panel) {
407
+ const scroller = ddScrollerOf(dd, panel);
408
+ const before = scroller?.scrollTop ?? 0;
409
+ const reach = dd.style?.getPropertyValue('--ui-dropdown-reach') ?? '';
410
+ panel.setAttribute('data-dd-shut', '');
411
+ dd.style?.removeProperty('--ui-dropdown-reach');
412
+ if (!scroller || scroller.scrollTop === before) return true;
413
+ panel.removeAttribute('data-dd-shut');
414
+ if (reach) dd.style.setProperty('--ui-dropdown-reach', reach);
415
+ if (typeof scroller.scrollTo === 'function') scroller.scrollTo({ top: before, behavior: 'instant' });
416
+ else scroller.scrollTop = before;
417
+ return false;
418
+ }
419
+
420
+ /**
421
+ * Give a panel its box while it is open, and take the box away once it has shut and
422
+ * its fade is over. Returns a function that cancels a collapse still waiting.
423
+ * Does nothing for a portalled panel, which is `position: fixed` and adds no scroll,
424
+ * and for a panel in a filter row, which its row already bounds.
425
+ * why: docs/components.md#the-dropdown-panel
426
+ *
427
+ * @param {Element} dd the `[data-dropdown]` container
428
+ * @param {Element} panel its `[data-dropdown-panel]`
429
+ * @param {boolean} open whether the panel is opening (`true`) or has shut (`false`)
430
+ * @param {number} [wait] ms to wait before collapsing; the panel's own fade by default
431
+ */
432
+ export function dropdownRest(dd, panel, open, wait) {
433
+ if (!dd || !panel?.style || dd.__ddPanel || ddInFilterRow(panel)) return () => {};
434
+ dd.__ddRest?.();
435
+ if (open) {
436
+ panel.removeAttribute('data-dd-shut');
437
+ return () => {};
438
+ }
439
+ let timer = null;
440
+ let off = null;
441
+ const cancel = () => {
442
+ clearTimeout(timer);
443
+ off?.();
444
+ dd.__ddRest = null;
445
+ };
446
+ const attempt = () => {
447
+ const done = !dd.isConnected || dd.classList.contains('open') || ddCollapse(dd, panel);
448
+ if (done) cancel();
449
+ return done;
450
+ };
451
+ const start = () => {
452
+ timer = null;
453
+ if (attempt()) return;
454
+ const scroller = ddScrollerOf(dd, panel);
455
+ const target = scroller === dd.ownerDocument.scrollingElement ? ddViewOf(panel) : scroller;
456
+ target.addEventListener('scroll', attempt, { passive: true });
457
+ off = () => target.removeEventListener('scroll', attempt);
458
+ };
459
+ dd.__ddRest = cancel;
460
+ const ms = wait ?? transitionMs(panel) + DD_EXIT_SLACK_MS;
461
+ if (ms > 0) timer = setTimeout(start, ms);
462
+ else start();
463
+ return cancel;
464
+ }
465
+
466
+ function ddRevealOnce(dd, panel) {
467
+ const trigger = dd?.querySelector?.('[data-dropdown-trigger]');
468
+ if (!trigger || typeof trigger.getBoundingClientRect !== 'function' || !panel) return 0;
469
+ if (ddLifted(panel)) return ddRevealLifted(dd, panel, trigger);
470
+ const fit = ddBodyFit(dd, panel);
471
+ if (!fit) {
472
+ // A page is held the same way: the shut panel lifts 6px, which would end the page 6px
473
+ // sooner under a reader at its end.
474
+ if (!dd.__ddPanel && !ddInFilterRow(panel)) ddReserveEnd(dd, panel, ddEdge(panel));
475
+ // Focusing End can scroll only far enough to show the row. Finish the page
476
+ // scroll so the open panel keeps its edge and the row's outline has room.
477
+ if (!dd.__ddPanel && !ddLifted(panel) && !ddInFilterRow(panel)
478
+ && panel.contains(dd.ownerDocument.activeElement?.closest?.('[data-dd-item]'))) {
479
+ const view = ddViewOf(panel);
480
+ const by = Math.ceil(panel.getBoundingClientRect().bottom + ddEdge(panel) - view.innerHeight);
481
+ if (by > 0) { view.scrollBy({ top: by, behavior: 'instant' }); return by; }
482
+ }
483
+ return 0;
484
+ }
485
+ if (fit.lift) return 0;
486
+ const { box, end } = fit;
487
+ ddReserveEnd(dd, panel, end);
488
+ const t = trigger.getBoundingClientRect();
489
+ const edge = ddEdge(panel);
490
+ const h = panel.offsetHeight;
491
+ const up = ddUp(panel);
492
+ const top = up ? t.top - ddGap(panel) - h - edge : ddAnchorTop(dd, t) - edge;
493
+ const bottom = (up ? t.bottom : t.bottom + ddGap(panel) + h) + end;
494
+ let by = 0;
495
+ if (bottom > box.bottom) by = Math.min(bottom - box.bottom, top - box.top);
496
+ else if (top < box.top) by = top - box.top;
497
+ by = Math.round(by);
498
+ if (!by) return 0;
499
+ const behavior = prefersReducedMotion() ? 'auto' : 'smooth';
500
+ /* The ancestor whose end the reader sees takes the scroll. What it has no room to
501
+ * take goes to the others, nearest first, each up to the room it has. */
502
+ const move = (el, d) => {
503
+ if (typeof el.scrollBy === 'function') el.scrollBy({ top: d, behavior });
504
+ else el.scrollTop += d;
505
+ };
506
+ const room = (el, d) => (d > 0 ? el.scrollHeight - el.clientHeight - el.scrollTop : -el.scrollTop);
507
+ const first = room(box.el, by);
508
+ move(box.el, by);
509
+ let left = by > 0 ? by - Math.max(0, Math.min(by, first)) : by - Math.min(0, Math.max(by, first));
510
+ for (const el of box.els) {
511
+ if (el === box.el || !left) continue;
512
+ const can = left > 0 ? Math.max(0, Math.min(left, room(el, left))) : Math.min(0, Math.max(left, room(el, left)));
513
+ if (can) { move(el, can); left -= can; }
514
+ }
515
+ return by;
516
+ }
517
+
518
+ /* The scroll ddLiftPlan() asked for. The body may hold too little to scroll that far, so
519
+ * the reserved spot is written to where the body's end then has to be. */
520
+ function ddRevealLifted(dd, panel, trigger) {
521
+ const by = dd.__ddLiftBy || 0;
522
+ const box = by && !ddUp(panel) ? ddScrollBox(dd, panel) : null;
523
+ if (!box) return 0;
524
+ const t = trigger.getBoundingClientRect();
525
+ dd.style?.setProperty('--ui-dropdown-reach', `${Math.max(0, box.bottom + by - t.bottom - 1)}px`);
526
+ const behavior = prefersReducedMotion() ? 'auto' : 'smooth';
527
+ if (typeof box.el.scrollBy === 'function') box.el.scrollBy({ top: by, behavior });
528
+ else box.el.scrollTop += by;
529
+ return by;
530
+ }
531
+
532
+ /**
533
+ * Stop an open panel's height where it cuts a row through the middle. A height that
534
+ * falls between two rows, or in a row's padding, shows a complete last label and the
535
+ * list looks whole; a half row says it goes on. The height is the one the panel gets:
536
+ * the smaller of its cap and the room the wiring measured, so a panel the room limits
537
+ * is cut the same way as one the cap limits. The rows are measured as they are drawn,
538
+ * so every row height the kit has, with a description or without and under a search
539
+ * field or not, stops at its own half row. A cap a consumer asked for (`scroll: <n>`)
540
+ * is kept to its number where it is the smaller, and a panel that fits has nothing to
541
+ * cut. Call it with the panel laid out and its room written.
542
+ * why: docs/components.md#the-dropdown-panel
543
+ */
544
+ export function dropdownSnap(dd, panel) {
545
+ if (!panel?.style) return;
546
+ const view = ddViewOf(panel);
547
+ const set = (v) => {
548
+ const next = v == null ? '' : `${v}px`;
549
+ if (panel.style.getPropertyValue('--ui-dropdown-fit') === next) return;
550
+ if (next) panel.style.setProperty('--ui-dropdown-fit', next);
551
+ else panel.style.removeProperty('--ui-dropdown-fit');
552
+ };
553
+ const rows = Array.from(panel.querySelectorAll('[data-dd-item]')).filter((el) => el.getClientRects().length);
554
+ let clip = panel;
555
+ for (let el = rows[0]?.parentElement; el && el !== panel; el = el.parentElement) {
556
+ const overflow = view.getComputedStyle(el).overflowY;
557
+ if (overflow === 'auto' || overflow === 'scroll') { clip = el; break; }
558
+ }
559
+ // The consumer's cap is on the panel, or on the list under a search field, where the
560
+ // panel is that cap and the field over it.
561
+ const own = parseFloat((clip === panel ? panel : clip).style.getPropertyValue('--ui-dropdown-cap'));
562
+ const chrome = clip === panel ? 0 : panel.offsetHeight - clip.offsetHeight;
563
+ const ceiling = ddCeilingOf(panel);
564
+ const room = parseFloat(panel.style.getPropertyValue('--ui-dropdown-avail'));
565
+ /* In a body, the room under the panel may be spent down to the 8px edge to reach the
566
+ * next half row up, rather than stop a whole row short of the room. */
567
+ const fit = room < ceiling && !ddLifted(panel) ? ddBodyFit(dd, panel) : null;
568
+ const spare = fit && !fit.lift ? fit.end - ddEdge(panel) : 0;
569
+ const height = Number.isFinite(room) ? Math.min(ceiling, room) : ceiling;
570
+ if (!rows.length || !Number.isFinite(height)) { set(null); return; }
571
+ // Kept to the consumer's number where it is the one that binds.
572
+ if (Number.isFinite(own) && !(room < ceiling)) { set(chrome ? ceiling : null); return; }
573
+ const box = panel.getBoundingClientRect();
574
+ const clipBox = clip.getBoundingClientRect();
575
+ if (!(box.height > 0)) return;
576
+ let scrolled = 0;
577
+ for (let el = rows[0].parentElement; el; el = el.parentElement) {
578
+ scrolled += el.scrollTop;
579
+ if (el === panel) break;
580
+ }
581
+ const edge = clip === panel ? panel.offsetHeight - panel.clientHeight - panel.clientTop : box.bottom - clipBox.bottom;
582
+ const lead = clip === panel ? panel.clientTop : clipBox.top - box.top;
583
+ const stop = dropdownStop({
584
+ rows: rows.map((el) => {
585
+ const r = el.getBoundingClientRect();
586
+ return { top: r.top - box.top + scrolled, height: r.height };
587
+ }),
588
+ below: edge,
589
+ content: lead + clip.scrollHeight + edge,
590
+ ceiling: height,
591
+ reach: Math.min(ceiling, height + spare),
592
+ });
593
+ set(stop ?? (chrome && Number.isFinite(own) ? ceiling : null));
594
+ if (stop > room) panel.style.setProperty('--ui-dropdown-avail', `${stop}px`);
595
+ }
596
+
597
+ /* A few frames past the sheet's own end, so the timer never cuts the fade's last
598
+ * frame. The number the dialogs' exit uses. */
599
+ export const DD_EXIT_SLACK_MS = 50;
600
+
601
+ /** The shift a panel is already carrying, the one ddFitViewport() wrote. Taken
602
+ * off before the next measurement, so asking twice answers the same as asking
603
+ * once — the fit is measured from where the sheet puts the panel, not from where
604
+ * the last fit left it. */
605
+ const ddShiftOf = (panel) => parseFloat(panel.style?.translate) || 0;
606
+
607
+ /** The widest a panel may be: the view it is laid out in, less the keep-out it owes
608
+ * each edge. It is the bound a PORTALLED panel needs, whose room is the whole view
609
+ * because it is `position: fixed`; an in-place one is bounded by its trigger's own
610
+ * block, once `overflow-wrap` has let its long tokens break.
611
+ * why: src/styles/dropdown.css */
612
+ const ddCeiling = (panel) => Math.max(0, ddViewWidth(panel) - 2 * ddEdge(panel));
613
+
614
+ /** Write the ceiling, BEFORE the panel is measured: capping a panel's width
615
+ * changes the width a shift would be calculated from. The sheet reads the
616
+ * property and keeps its own 240px floor where the two disagree, which is a view
617
+ * narrower than 2 × edge + 240. why: src/styles/dropdown.css */
618
+ export function ddWriteCeiling(panel) {
619
+ const max = ddCeiling(panel);
620
+ panel.style?.setProperty('--ui-dropdown-ceiling', max > 0 ? `${max}px` : '');
621
+ }
622
+
623
+ /** A panel a filter row bounds to the row itself. It is nothing the viewport fit
624
+ * has to measure, and nothing the wiring has to watch for it.
625
+ * why: docs/components.md#a-filter-row-holds-its-panels */
626
+ export const ddInFilterRow = (panel) => typeof panel?.closest === 'function' && !!panel.closest('.ui-filter-bar');
627
+
628
+ /**
629
+ * How wide a panel may be and how far along the inline axis it has to move to stay
630
+ * inside the view it is laid out in: `left` at or after the edge, `right` at or
631
+ * before the far one.
632
+ *
633
+ * `align` decides the edge of the trigger a panel hangs from, and that is all it
634
+ * decides — on a phone it moves the clipping from one side to the other rather
635
+ * than removing it, which is #572. So the preferred edge is measured and kept
636
+ * whenever it fits, and overridden only when it does not: the same shape
637
+ * `direction: 'auto'` gives the block axis.
638
+ *
639
+ * Measured, not derived from the classes: the panel's own box is where the sheet
640
+ * has actually put it, so one answer covers `left: 0`, `.is-end`'s `right: 0` and
641
+ * the topbar's bespoke menus alike, and a rule nobody here has read about cannot
642
+ * send it the wrong way.
643
+ *
644
+ * A panel inside a `.ui-filter-bar` is not this function's subject: a filter row
645
+ * bounds its panels to the row itself, which already holds them inside the view.
646
+ * why: docs/components.md#a-filter-row-holds-its-panels
647
+ *
648
+ * @param {Element} panel a `[data-dropdown-panel]`, as the sheet has placed it
649
+ * @param {{left: number, width: number}} [at] the box the caller is about to
650
+ * write, for a panel it places itself — the portal, whose own box is still the
651
+ * one the last call left it at
652
+ * @returns {{shift: number, left: number, width: number, view: number, edge: number,
653
+ * max: number}|null}
654
+ */
655
+ export function dropdownViewportFit(panel, at) {
656
+ if (!panel || typeof panel.getBoundingClientRect !== 'function') return null;
657
+ if (!at && ddInFilterRow(panel)) return null;
658
+ const view = ddViewWidth(panel);
659
+ const box = panel.getBoundingClientRect();
660
+ const width = at ? at.width : box.width;
661
+ const left = at ? at.left : box.left - ddShiftOf(panel);
662
+ if (!(view > 0) || !(width > 0) || !Number.isFinite(left)) return null;
663
+ const slack = view - width;
664
+ /* The gap is what a panel can afford rather than what it asks for. A panel still
665
+ wider than its view — the floor, inside a view too narrow for it — has no room
666
+ for one and cannot honour both edges at all; it keeps its start, so the reader
667
+ meets the beginning of the rows and not the end. */
668
+ const edge = Math.max(0, Math.min(ddEdge(panel), slack / 2));
669
+ const want = Math.max(edge, Math.min(left, slack - edge));
670
+ return { shift: want - left, left: want, width, view, edge, max: ddCeiling(panel) };
671
+ }