@zazz-ui/core 0.13.1 → 0.14.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.
Files changed (88) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/README.md +5 -9
  3. package/dist/sri.json +35 -31
  4. package/dist/zazz.css +1 -1
  5. package/dist/zazz.js +1 -1
  6. package/editor/zazz.css-data.json +173 -3
  7. package/editor/zazz.html-data.json +138 -0
  8. package/editor/zazz.language-data.json +313 -125
  9. package/editor/zazz.lint-data.json +1501 -1383
  10. package/package.json +1 -5
  11. package/src/base/_defaults.css +1 -1
  12. package/src/base/_reset.css +16 -2
  13. package/src/base/_variables.css +43 -31
  14. package/src/base/carousel-scroll.d.ts +161 -0
  15. package/src/base/carousel-scroll.d.ts.map +1 -0
  16. package/src/base/carousel-scroll.js +1035 -0
  17. package/src/base/carousel-scroll.ts +1227 -0
  18. package/src/base/carousel.d.ts +34 -0
  19. package/src/base/carousel.d.ts.map +1 -0
  20. package/src/base/carousel.js +279 -0
  21. package/src/base/carousel.ts +292 -0
  22. package/src/base/dialog-lifecycle.js +1 -1
  23. package/src/base/dialog-lifecycle.ts +1 -1
  24. package/src/base/gesture.d.ts +201 -0
  25. package/src/base/gesture.d.ts.map +1 -0
  26. package/src/base/gesture.js +317 -0
  27. package/src/base/gesture.ts +494 -0
  28. package/src/base/kit-styling.d.ts.map +1 -1
  29. package/src/base/kit-styling.js +182 -162
  30. package/src/base/kit-styling.ts +182 -162
  31. package/src/base/navigation.d.ts +12 -1
  32. package/src/base/navigation.d.ts.map +1 -1
  33. package/src/base/navigation.js +65 -1
  34. package/src/base/navigation.ts +66 -1
  35. package/src/base/utils.d.ts +1 -1
  36. package/src/base/utils.js +2 -2
  37. package/src/base/utils.ts +2 -2
  38. package/src/globals.d.ts +7 -30
  39. package/src/head.d.ts.map +1 -1
  40. package/src/head.js +1 -25
  41. package/src/head.ts +1 -25
  42. package/src/index.css +1 -0
  43. package/src/index.d.ts +6 -5
  44. package/src/index.d.ts.map +1 -1
  45. package/src/index.js +6 -5
  46. package/src/index.ts +6 -5
  47. package/src/manifest.d.ts +1 -1
  48. package/src/manifest.d.ts.map +1 -1
  49. package/src/manifest.js +25 -13
  50. package/src/manifest.ts +26 -14
  51. package/src/primitives/button/button.css +1 -1
  52. package/src/primitives/carousel/carousel.css +103 -20
  53. package/src/primitives/carousel/carousel.d.ts +4 -32
  54. package/src/primitives/carousel/carousel.d.ts.map +1 -1
  55. package/src/primitives/carousel/carousel.js +39 -14
  56. package/src/primitives/carousel/carousel.ts +21 -25
  57. package/src/primitives/dialog/dialog.css +14 -8
  58. package/src/primitives/drawer/drawer-indent.html +27 -0
  59. package/src/primitives/drawer/drawer-nested.html +72 -0
  60. package/src/primitives/drawer/drawer-responsive-dialog.html +44 -0
  61. package/src/primitives/drawer/drawer-snap.html +26 -0
  62. package/src/primitives/drawer/drawer.css +528 -0
  63. package/src/primitives/drawer/drawer.d.ts +24 -0
  64. package/src/primitives/drawer/drawer.d.ts.map +1 -0
  65. package/src/primitives/drawer/drawer.html +42 -0
  66. package/src/primitives/drawer/drawer.js +765 -0
  67. package/src/primitives/drawer/drawer.ts +823 -0
  68. package/src/primitives/fields/fields.css +4 -2
  69. package/src/primitives/input/input.css +1 -1
  70. package/src/primitives/input-group/input-group.css +5 -5
  71. package/src/primitives/lightbox/lightbox.css +2 -2
  72. package/src/primitives/lightbox/lightbox.d.ts.map +1 -1
  73. package/src/primitives/lightbox/lightbox.js +9 -8
  74. package/src/primitives/lightbox/lightbox.ts +9 -8
  75. package/src/primitives/password-group/password-group.css +5 -5
  76. package/src/primitives/radio/radio.css +15 -10
  77. package/src/primitives/slider/slider.css +2 -2
  78. package/src/primitives/switch/switch.css +6 -6
  79. package/src/primitives/tabs/tabs.css +10 -10
  80. package/src/primitives/toaster/toaster.css +29 -1
  81. package/src/primitives/toaster/toaster.d.ts.map +1 -1
  82. package/src/primitives/toaster/toaster.js +117 -9
  83. package/src/primitives/toaster/toaster.ts +136 -9
  84. package/src/primitives/tooltip/tooltip.css +93 -10
  85. package/src/base/embla.d.ts +0 -90
  86. package/src/base/embla.d.ts.map +0 -1
  87. package/src/base/embla.js +0 -878
  88. package/src/base/embla.ts +0 -1066
@@ -0,0 +1,823 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * @fileoverview Drawer: drag-to-dismiss for `<dialog data-ui="drawer">` bottom sheets.
5
+ * @description A drawer is a native modal `<dialog>`, opened and closed like
6
+ * any other (`command="show-modal"`, `command="close"`, Esc, the backdrop with
7
+ * `closedby="any"`). This script adds the gesture: drag the drawer down and
8
+ * let go to dismiss it.
9
+ *
10
+ * - `data-ui="drawer"` is a drawer on every device.
11
+ * - `data-ui="dialog drawer"` is a drawer below the `sm` band on a touch
12
+ * screen, and a plain dialog (no dragging) everywhere else.
13
+ *
14
+ * While the pointer is down the drawer follows it 1:1 and the backdrop fades
15
+ * with it. Letting go past a quarter of the drawer's height, or with a quick
16
+ * downward flick, slides it off the bottom edge and then closes it through
17
+ * `requestClose()`, so `cancel` and `close` fire as they do for Esc; anything
18
+ * less returns it to rest. Until it has slid out it can be caught again. Pulling it up
19
+ * past its resting place meets resistance.
20
+ *
21
+ * A drag starts anywhere on the drawer except on form fields, selected text,
22
+ * and anything inside `[data-ui-no-drag]`. Inside scrolling content it starts
23
+ * only once that content is scrolled to the top and the pointer moves down,
24
+ * so the body scrolls first and the drawer follows; the handle
25
+ * (`data-drawer-slot="handle"`) always drags. There is no custom element and
26
+ * nothing to initialize: the script binds a drawer when it opens.
27
+ *
28
+ * **Snap points.** `data-drawer-snap="148px 0.5 1"` gives the drawer resting
29
+ * heights, smallest first: a number up to 1 is a share of the drawer's full
30
+ * height, a `px` or `rem` length is a visible height. It opens at the first.
31
+ * Letting go settles on the nearest; a flick moves one stop in its direction,
32
+ * a very fast one goes all the way (or one stop, with
33
+ * `data-drawer-snap-sequential`), and from the lowest stop a flick or enough
34
+ * travel downward closes the drawer. Below the largest stop the drawer takes
35
+ * every vertical drag and its content does not scroll. A click on the handle
36
+ * steps to the next stop; make the handle a `<button>` to give the keyboard
37
+ * the same. Each change fires `zazz:drawer-snap` (`detail.index`,
38
+ * `detail.value` in px), `data-drawer-state` carries `expanded` at the largest
39
+ * stop, and `snapDrawer(dialog, index)` moves it from script.
40
+ *
41
+ * **The software keyboard.** A phone lays a drawer out against the full
42
+ * screen, which the keyboard does not shrink. While a field in the front
43
+ * drawer has the keyboard up, the drawer's content ends at the keyboard's top
44
+ * edge (its surface runs on underneath), the focused field scrolls into what
45
+ * is still visible, and the page behind stays where it was. Nothing to author.
46
+ *
47
+ * **Stacked drawers.** A drawer opened over another scales the one behind back
48
+ * and lifts it, and that one follows as the front drawer is dragged. Nothing
49
+ * to author: the script counts the open drawers.
50
+ *
51
+ * **Indent.** Wrap the page in `<ui-drawer-indent>` (or put
52
+ * `data-ui="drawer-indent"` on its wrapper) and it scales back behind any open
53
+ * drawer, with rounded top corners, and follows the drag of the last one. Only
54
+ * transforms animate. While indented the wrapper is transformed, so a
55
+ * `position: fixed` element inside it moves with the page; `position: sticky`
56
+ * is unaffected.
57
+ *
58
+ * @example
59
+ * <button data-ui="button" command="show-modal" commandfor="filters">Filters</button>
60
+ * <dialog id="filters" data-ui="drawer" closedby="any">
61
+ * <div data-drawer-slot="handle"></div>
62
+ * <div data-drawer-slot="content">
63
+ * <header data-drawer-slot="header">…</header>
64
+ * <div data-drawer-slot="body">…</div>
65
+ * </div>
66
+ * </dialog>
67
+ */
68
+
69
+ import {
70
+ currentTranslate,
71
+ maxTransitionMs,
72
+ pickSnap,
73
+ rubberBand,
74
+ trackDrag,
75
+ } from "../../base/gesture.ts";
76
+ import type { DragState } from "../../base/gesture.ts";
77
+
78
+ // --- Tuning ---
79
+
80
+ /** Share of the drawer's visible height, at its lowest stop, that dismisses on its own. */
81
+ const CLOSE_RATIO = 0.25;
82
+
83
+ /** Speed that moves the drawer one stop, or dismisses it from the lowest, in px/ms. */
84
+ const FLICK_VELOCITY = 0.4;
85
+
86
+ /** Speed that skips every stop: all the way open, or closed, in px/ms. */
87
+ const FLING_VELOCITY = 2;
88
+
89
+ /**
90
+ * After inner content scrolls, how long before the drawer may be dragged, in
91
+ * ms. A fast scroll that reaches the top would otherwise carry straight on
92
+ * into dragging the drawer away.
93
+ */
94
+ const SCROLL_GUARD_MS = 100;
95
+
96
+ /** Length of the backdrop's scrub animation: its timeline is drag progress, not time. */
97
+ const SCRUB_MS = 1000;
98
+
99
+ const DRAWER = 'dialog[data-ui~="drawer"]';
100
+ const HANDLE = '[data-drawer-slot~="handle"]';
101
+ const INDENT = 'ui-drawer-indent, [data-ui~="drawer-indent"]';
102
+ const INDENT_STATE = "data-drawer-indent-state";
103
+
104
+ // --- Helpers ---
105
+
106
+ /** Adds or removes one token of a space-separated state attribute; an empty attribute is removed. */
107
+ function setToken(element: Element, attribute: string, token: string, on: boolean): void {
108
+ const tokens = new Set((element.getAttribute(attribute) ?? "").split(/\s+/).filter(Boolean));
109
+ if (tokens.has(token) === on) return;
110
+ if (on) tokens.add(token);
111
+ else tokens.delete(token);
112
+ if (tokens.size) element.setAttribute(attribute, [...tokens].join(" "));
113
+ else element.removeAttribute(attribute);
114
+ }
115
+
116
+ /** Adds or removes a token of a drawer's `data-drawer-state`. */
117
+ function setState(dialog: HTMLDialogElement, token: string, on: boolean): void {
118
+ setToken(dialog, "data-drawer-state", token, on);
119
+ }
120
+
121
+ /** Adds or removes the `dragging` token of a drawer's `data-drawer-state`. */
122
+ function setDragging(dialog: HTMLDialogElement, on: boolean): void {
123
+ setState(dialog, "dragging", on);
124
+ }
125
+
126
+ /** Clears everything a drag wrote on the drawer. */
127
+ function reset(dialog: HTMLDialogElement): void {
128
+ setDragging(dialog, false);
129
+ dialog.style.removeProperty("translate");
130
+ dialog.style.removeProperty("--_drawer-backdrop");
131
+ }
132
+
133
+ /**
134
+ * @description Reads a drawer's snap points as resting positions: px the
135
+ * drawer is pushed down at each, the smallest visible height first.
136
+ *
137
+ * @param dialog - The drawer.
138
+ * @param height - The drawer's full visible height in px.
139
+ * @returns The positions, descending; `[0]` without usable snap points.
140
+ * @private
141
+ */
142
+ function readStops(dialog: HTMLDialogElement, height: number): number[] {
143
+ const raw = dialog.getAttribute("data-drawer-snap")?.trim();
144
+ if (!raw) return [0];
145
+ const rem = Number.parseFloat(getComputedStyle(document.documentElement).fontSize) || 16;
146
+ const positions = new Set<number>();
147
+ for (const token of raw.split(/\s+/)) {
148
+ const value = Number.parseFloat(token);
149
+ if (!Number.isFinite(value) || value <= 0) continue;
150
+ let visible = value * height;
151
+ if (token.endsWith("rem")) visible = value * rem;
152
+ else if (token.endsWith("px") || value > 1) visible = value;
153
+ positions.add(Math.round(height - Math.min(height, Math.max(1, visible))));
154
+ }
155
+ return positions.size ? [...positions].sort((a, b) => b - a) : [0];
156
+ }
157
+
158
+ /**
159
+ * @description Starts a paused opacity animation on the drawer's backdrop, to
160
+ * be scrubbed with the drag. An animation, not a style write: it reaches the
161
+ * pseudo-element without restyling the drawer's content, in engines that do
162
+ * not re-resolve `::backdrop` when a non-inherited property changes on its
163
+ * dialog (WebKit).
164
+ *
165
+ * @param dialog - The drawer.
166
+ * @returns The animation, or null where `::backdrop` cannot be animated; the
167
+ * caller then writes `--_drawer-backdrop`, which drawer.css reads.
168
+ * @private
169
+ */
170
+ function scrubBackdrop(dialog: HTMLDialogElement): Animation | null {
171
+ try {
172
+ const animation = dialog.animate([{ opacity: 1 }, { opacity: 0 }], {
173
+ pseudoElement: "::backdrop",
174
+ duration: SCRUB_MS,
175
+ fill: "both",
176
+ });
177
+ animation.pause();
178
+ return animation;
179
+ } catch {
180
+ return null;
181
+ }
182
+ }
183
+
184
+ /** Whether drawer.css has the dialog in drawer mode right now. */
185
+ function inDrawerMode(dialog: HTMLDialogElement): boolean {
186
+ return getComputedStyle(dialog).getPropertyValue("--_drawer-mode").trim() === "1";
187
+ }
188
+
189
+ /** Whether an element scrolls its content on the block axis. */
190
+ function scrolls(element: Element): boolean {
191
+ if (element.scrollHeight <= element.clientHeight) return false;
192
+ const overflow = getComputedStyle(element).overflowY;
193
+ return overflow === "auto" || overflow === "scroll";
194
+ }
195
+
196
+ /**
197
+ * @description Whether a press may drag the drawer, given what it landed on
198
+ * and which way it is moving.
199
+ *
200
+ * @param dialog - The drawer.
201
+ * @param drag - The drag about to start; `offset` carries its direction.
202
+ * @param lastScroll - When content inside the drawer last scrolled.
203
+ * @param partial - Whether the drawer rests below its largest snap point.
204
+ * @returns Whether the drawer takes the gesture.
205
+ * @private
206
+ */
207
+ function claims(
208
+ dialog: HTMLDialogElement,
209
+ drag: DragState,
210
+ lastScroll: number,
211
+ partial: boolean,
212
+ ): boolean {
213
+ if (!inDrawerMode(dialog)) return false;
214
+
215
+ // a press on the backdrop targets the dialog, outside its box
216
+ const box = dialog.getBoundingClientRect();
217
+ if (drag.startY < box.top || drag.startX < box.left || drag.startX > box.right) return false;
218
+
219
+ if (drag.target.closest(HANDLE)) return true;
220
+ // below its largest stop the drawer moves before anything inside it scrolls
221
+ if (partial) return true;
222
+
223
+ // scrolling content goes first: it must be at the top, and the pull downward
224
+ const down = drag.offset > 0;
225
+ for (
226
+ let node: Element | null = drag.target;
227
+ node && dialog.contains(node);
228
+ node = node.parentElement
229
+ ) {
230
+ if (scrolls(node) && (node.scrollTop > 0 || !down)) return false;
231
+ }
232
+ return performance.now() - lastScroll >= SCROLL_GUARD_MS;
233
+ }
234
+
235
+ // --- Stack ---
236
+
237
+ /** The open drawers in drawer mode, the front one last. */
238
+ const stack: HTMLDialogElement[] = [];
239
+
240
+ /**
241
+ * @description Writes each open drawer's place in the stack: how many drawers
242
+ * sit in front of it (`--_drawer-depth`, `stacked`) and whether it opened over
243
+ * another (`nested`). Runs when a drawer opens or closes, never per frame.
244
+ * @private
245
+ */
246
+ function restack(): void {
247
+ // a drawer removed from the page while open never reports its close
248
+ for (let index = stack.length - 1; index >= 0; index--) {
249
+ const dialog = stack[index]!;
250
+ if (!dialog.isConnected || !dialog.open) stack.splice(index, 1);
251
+ }
252
+ stack.forEach((dialog, index) => {
253
+ const depth = stack.length - 1 - index;
254
+ setState(dialog, "following", false);
255
+ setState(dialog, "stacked", depth > 0);
256
+ setState(dialog, "nested", index > 0);
257
+ if (depth > 0) dialog.style.setProperty("--_drawer-depth", String(depth));
258
+ else dialog.style.removeProperty("--_drawer-depth");
259
+ });
260
+ indentPose(stack.length > 0);
261
+ }
262
+
263
+ /**
264
+ * @description Moves the drawers behind `front` with its drag: at progress 1
265
+ * each sits where it will once `front` is gone. The depth is a non-inheriting
266
+ * property, so the write restyles those drawers and not their content.
267
+ *
268
+ * @param front - The drawer being dragged or released.
269
+ * @param progress - How far `front` is toward closed, 0 to 1.
270
+ * @param live - Whether a pointer is driving it (transitions off).
271
+ * @private
272
+ */
273
+ function follow(front: HTMLDialogElement, progress: number, live: boolean): void {
274
+ const index = stack.indexOf(front);
275
+ for (let behind = 0; behind < index; behind++) {
276
+ const dialog = stack[behind]!;
277
+ dialog.style.setProperty("--_drawer-depth", String(index - behind - progress));
278
+ setState(dialog, "following", live);
279
+ }
280
+ }
281
+
282
+ // --- Indent ---
283
+
284
+ /** The page wrapper that is indented right now, and what ends its return to rest. */
285
+ let indented: HTMLElement | null = null;
286
+ let cancelOutdent: (() => void) | null = null;
287
+
288
+ /**
289
+ * @description Measures what the indent needs, once per activation and on
290
+ * resize: the scale that pulls each side in by the inset hook, and where the
291
+ * viewport sits inside the wrapper (the transform's origin, the clip, and the
292
+ * corner pieces all hang off its top edge).
293
+ * @private
294
+ */
295
+ function measureIndent(wrapper: HTMLElement): void {
296
+ const box = wrapper.getBoundingClientRect();
297
+ const width = wrapper.offsetWidth || 1;
298
+ const inset =
299
+ Number.parseFloat(getComputedStyle(wrapper).getPropertyValue("--_drawer-indent-inset")) || 0;
300
+ const top = Math.max(0, -box.top);
301
+ const bottom = Math.max(0, wrapper.offsetHeight - top - window.innerHeight);
302
+ wrapper.style.setProperty("--_drawer-indent-scale", String(Math.max(0, 1 - (inset * 2) / width)));
303
+ wrapper.style.setProperty("--_drawer-indent-top", `${top}px`);
304
+ wrapper.style.setProperty("--_drawer-indent-bottom", `${bottom}px`);
305
+ }
306
+
307
+ /**
308
+ * @description Indents the page wrapper or sends it back to rest. The pose is
309
+ * a state token and the motion a CSS transition; the `on` token (clip,
310
+ * corners, backing) outlasts the pose until the return has finished.
311
+ *
312
+ * @param active - Whether a drawer is open.
313
+ * @private
314
+ */
315
+ function indentPose(active: boolean): void {
316
+ // a wrapper that left the page takes its state with it
317
+ if (indented && !indented.isConnected) {
318
+ cancelOutdent?.();
319
+ indented = null;
320
+ }
321
+ const wrapper = indented ?? document.querySelector<HTMLElement>(INDENT);
322
+ if (!wrapper) return;
323
+ if (active) {
324
+ cancelOutdent?.();
325
+ if (indented !== wrapper) {
326
+ measureIndent(wrapper);
327
+ indented = wrapper;
328
+ }
329
+ setToken(wrapper, INDENT_STATE, "on", true);
330
+ setToken(wrapper, INDENT_STATE, "active", true);
331
+ return;
332
+ }
333
+ if (!indented || cancelOutdent) return;
334
+ setToken(wrapper, INDENT_STATE, "dragging", false);
335
+ wrapper.style.removeProperty("--_drawer-indent-amount");
336
+ setToken(wrapper, INDENT_STATE, "active", false);
337
+
338
+ const off = () => {
339
+ cancelOutdent?.();
340
+ wrapper.removeAttribute(INDENT_STATE);
341
+ for (const name of ["scale", "top", "bottom"]) {
342
+ wrapper.style.removeProperty(`--_drawer-indent-${name}`);
343
+ }
344
+ indented = null;
345
+ };
346
+ const ms = maxTransitionMs(wrapper);
347
+ if (ms <= 0) {
348
+ off();
349
+ return;
350
+ }
351
+ const onReturned = (event: TransitionEvent) => {
352
+ if (event.target === wrapper && event.propertyName === "scale") off();
353
+ };
354
+ const timer = window.setTimeout(off, ms + 100);
355
+ wrapper.addEventListener("transitionend", onReturned);
356
+ cancelOutdent = () => {
357
+ window.clearTimeout(timer);
358
+ wrapper.removeEventListener("transitionend", onReturned);
359
+ cancelOutdent = null;
360
+ };
361
+ }
362
+
363
+ /**
364
+ * @description Links the indent to the last open drawer's drag.
365
+ *
366
+ * @param progress - How far the drawer is toward closed, 0 to 1.
367
+ * @param live - Whether a pointer is driving it (transitions off).
368
+ * @private
369
+ */
370
+ function indentProgress(progress: number, live: boolean): void {
371
+ if (!indented) return;
372
+ setToken(indented, INDENT_STATE, "dragging", live);
373
+ if (live) indented.style.setProperty("--_drawer-indent-amount", String(1 - progress));
374
+ else indented.style.removeProperty("--_drawer-indent-amount");
375
+ }
376
+
377
+ // --- Keyboard ---
378
+
379
+ /** The keyboard's height on the front drawer, which drawer.css adds to its bottom padding. */
380
+ const KEYBOARD_INSET = "--_drawer-keyboard";
381
+
382
+ /** Space kept between a revealed field and the keyboard's top edge, in px. */
383
+ const REVEAL_GAP = 16;
384
+
385
+ /** Inputs that open a picker or nothing rather than the software keyboard. */
386
+ const NO_KEYBOARD =
387
+ /^(?:button|checkbox|color|file|hidden|image|radio|range|reset|submit|date|datetime-local|month|time|week)$/;
388
+
389
+ /** Whether focus on this element opens the software keyboard. */
390
+ function typesText(element: Element): boolean {
391
+ if (element instanceof HTMLTextAreaElement) return !element.readOnly;
392
+ if (element instanceof HTMLInputElement)
393
+ return !element.readOnly && !NO_KEYBOARD.test(element.type);
394
+ return element instanceof HTMLElement && element.isContentEditable;
395
+ }
396
+
397
+ /**
398
+ * @description How much of the layout viewport the software keyboard covers,
399
+ * from the bottom: the part below the visual viewport. 0 while the page is
400
+ * pinch-zoomed, when the visual viewport is smaller for another reason.
401
+ * @private
402
+ */
403
+ function keyboardInset(): number {
404
+ const viewport = window.visualViewport;
405
+ if (!viewport || Math.abs(viewport.scale - 1) > 0.01) return 0;
406
+ const bottom = Math.max(0, viewport.offsetTop) + viewport.height;
407
+ return Math.max(0, Math.round(window.innerHeight - Math.min(window.innerHeight, bottom)));
408
+ }
409
+
410
+ /**
411
+ * @description Keeps an open drawer usable with the software keyboard up.
412
+ * iOS lays out the top layer against the layout viewport, which the keyboard
413
+ * does not shrink, and scrolls the page behind a modal to reveal a focused
414
+ * field. While the drawer is the front one this writes the keyboard's height
415
+ * to `--_drawer-keyboard` (drawer.css pads the sheet by it, so its
416
+ * content ends at the keyboard's top edge), holds the page at its scroll
417
+ * position, and scrolls a focused field into the part of its scrolling slot
418
+ * that is still visible.
419
+ *
420
+ * @param dialog - The drawer.
421
+ * @param signal - Aborts when the drawer closes.
422
+ * @param onChange - Runs after the inset changes, once the new padding is in place.
423
+ * @private
424
+ */
425
+ function trackKeyboard(dialog: HTMLDialogElement, signal: AbortSignal, onChange: () => void): void {
426
+ const viewport = window.visualViewport;
427
+ if (!viewport) return;
428
+ const front = () => stack[stack.length - 1] === dialog;
429
+ const pageX = window.scrollX;
430
+ const pageY = window.scrollY;
431
+ let frame = 0;
432
+ let current = 0;
433
+
434
+ const update = () => {
435
+ frame = 0;
436
+ const inset = front() ? keyboardInset() : 0;
437
+ if (inset === current) return;
438
+ current = inset;
439
+ if (inset > 0) dialog.style.setProperty(KEYBOARD_INSET, `${inset}px`);
440
+ else dialog.style.removeProperty(KEYBOARD_INSET);
441
+ onChange();
442
+ };
443
+ const schedule = () => {
444
+ if (!frame) frame = requestAnimationFrame(update);
445
+ };
446
+
447
+ /** Scrolls the field's scrolling slot so the field sits above the keyboard and below the slot's top. */
448
+ const reveal = (field: Element) => {
449
+ if (!dialog.contains(field) || document.activeElement !== field) return;
450
+ let container: Element | null = field.parentElement;
451
+ while (container && dialog.contains(container) && !scrolls(container)) {
452
+ container = container.parentElement;
453
+ }
454
+ if (!container || !dialog.contains(container)) return;
455
+ const box = container.getBoundingClientRect();
456
+ const target = field.getBoundingClientRect();
457
+ const visibleBottom = Math.min(box.bottom, viewport.offsetTop + viewport.height) - REVEAL_GAP;
458
+ const visibleTop = Math.max(box.top, viewport.offsetTop) + REVEAL_GAP;
459
+ let by = 0;
460
+ if (target.bottom > visibleBottom) by = target.bottom - visibleBottom;
461
+ if (target.top - by < visibleTop) by = target.top - visibleTop;
462
+ if (Math.abs(by) < 1) return;
463
+ const still = matchMedia("(prefers-reduced-motion: reduce)").matches;
464
+ container.scrollBy({ top: by, behavior: still ? "instant" : "smooth" });
465
+ };
466
+
467
+ viewport.addEventListener("resize", schedule, { signal });
468
+ viewport.addEventListener("scroll", schedule, { signal });
469
+
470
+ // the page behind a modal stays where it was, whatever iOS scrolls to show the field
471
+ window.addEventListener(
472
+ "scroll",
473
+ () => {
474
+ if (!front() || (window.scrollX === pageX && window.scrollY === pageY)) return;
475
+ window.scrollTo({ left: pageX, top: pageY, behavior: "instant" });
476
+ },
477
+ { passive: true, signal },
478
+ );
479
+
480
+ // the keyboard settles over a few frames: reveal after it has, and again once it is up
481
+ dialog.addEventListener(
482
+ "focusin",
483
+ (event) => {
484
+ const field = event.target;
485
+ if (!(field instanceof Element) || !typesText(field) || !front()) return;
486
+ for (const ms of [100, 350]) {
487
+ const timer = window.setTimeout(() => {
488
+ update();
489
+ reveal(field);
490
+ }, ms);
491
+ signal.addEventListener("abort", () => window.clearTimeout(timer), { once: true });
492
+ }
493
+ },
494
+ { signal },
495
+ );
496
+
497
+ signal.addEventListener("abort", () => {
498
+ cancelAnimationFrame(frame);
499
+ dialog.style.removeProperty(KEYBOARD_INSET);
500
+ });
501
+ update();
502
+ }
503
+
504
+ // --- Binding ---
505
+
506
+ /** What an open drawer exposes to the rest of the module. */
507
+ interface BoundDrawer {
508
+ controller: AbortController;
509
+ snapTo(index: number): void;
510
+ }
511
+
512
+ /** Open drawers and what unbinds or moves each. */
513
+ const bound = new WeakMap<HTMLDialogElement, BoundDrawer>();
514
+
515
+ /** Each drawer's backdrop animation, kept past its close so the next open can drop it. */
516
+ const fades = new WeakMap<HTMLDialogElement, Animation>();
517
+
518
+ /**
519
+ * @description Binds drag-to-dismiss to an open drawer until it closes.
520
+ *
521
+ * @param dialog - The drawer.
522
+ */
523
+ function bindDrawer(dialog: HTMLDialogElement): void {
524
+ if (bound.has(dialog)) return;
525
+ const controller = new AbortController();
526
+ const { signal } = controller;
527
+ // what the last dismissal left in place: the slid-out translate, the cleared backdrop
528
+ fades.get(dialog)?.cancel();
529
+ fades.delete(dialog);
530
+ reset(dialog);
531
+
532
+ const snaps = dialog.hasAttribute("data-drawer-snap");
533
+ let lastScroll = 0;
534
+ // where the drawer was when the drag caught it (mid snap-back, usually its stop)
535
+ let base = 0;
536
+ let height = 1;
537
+ // the sheet's bleed past the bottom edge: the most it may be pulled up
538
+ let lift = 0;
539
+ // resting positions, px pushed down, the lowest snap point first; and the one it rests at
540
+ let stops = [0];
541
+ let active = 0;
542
+ let fade: Animation | null = null;
543
+ // undoes a dismissal still sliding out, so a new drag can catch the drawer
544
+ let cancelClose: (() => void) | null = null;
545
+
546
+ const measure = () => {
547
+ lift = Math.max(0, -Number.parseFloat(getComputedStyle(dialog).marginBlockEnd) || 0);
548
+ // the layout height: a stacked drawer's scale must not shrink it
549
+ height = Math.max(1, dialog.offsetHeight - lift);
550
+ stops = snaps ? readStops(dialog, height) : [0];
551
+ active = Math.min(active, stops.length - 1);
552
+ };
553
+
554
+ /** Writes where the drawer rests: drawer.css turns `--_drawer-snap` into its `translate`. */
555
+ const place = () => {
556
+ if (!snaps) return;
557
+ const largest = active === stops.length - 1;
558
+ dialog.style.setProperty("--_drawer-snap", `${stops[active] ?? 0}px`);
559
+ setState(dialog, "expanded", largest);
560
+ setState(dialog, "partial", !largest);
561
+ };
562
+
563
+ /** Everything that moves with the drawer's progress toward closed, besides its backdrop. */
564
+ const link = (progress: number, live: boolean) => {
565
+ follow(dialog, progress, live);
566
+ if (stack.length === 1 && stack[0] === dialog) indentProgress(progress, live);
567
+ };
568
+
569
+ /**
570
+ * Runs the backdrop from where the drag left it to clear or back to full,
571
+ * in `ms`. Back at full the animation is dropped; clear, it holds until the
572
+ * drawer next opens, over whatever the closed dialog's own backdrop does.
573
+ */
574
+ const settle = (closing: boolean, ms: number) => {
575
+ dialog.style.removeProperty("--_drawer-backdrop");
576
+ const animation = fade;
577
+ if (!animation) return;
578
+ const done = () => {
579
+ if (closing || fade !== animation || animation.playState !== "finished") return;
580
+ animation.cancel();
581
+ fades.delete(dialog);
582
+ fade = null;
583
+ };
584
+ const at = Number(animation.currentTime) || 0;
585
+ const left = closing ? SCRUB_MS - at : at;
586
+ if (ms <= 0 || left <= 0) {
587
+ animation.playbackRate = closing ? 1 : -1;
588
+ animation.finish();
589
+ done();
590
+ return;
591
+ }
592
+ animation.playbackRate = ((closing ? 1 : -1) * left) / ms;
593
+ animation.play();
594
+ animation.finished.then(done, () => {});
595
+ };
596
+
597
+ /** Settles the drawer on a stop; the dialog's `translate` transition carries it there. */
598
+ const snapTo = (index: number) => {
599
+ const next = Math.min(Math.max(index, 0), stops.length - 1);
600
+ const changed = next !== active;
601
+ active = next;
602
+ place();
603
+ setDragging(dialog, false);
604
+ settle(false, maxTransitionMs(dialog));
605
+ dialog.style.removeProperty("translate");
606
+ link(0, false);
607
+ if (!changed) return;
608
+ dialog.dispatchEvent(
609
+ new CustomEvent("zazz:drawer-snap", {
610
+ bubbles: true,
611
+ detail: { index: active, value: height - (stops[active] ?? 0) },
612
+ }),
613
+ );
614
+ };
615
+
616
+ const rest = () => snapTo(active);
617
+
618
+ /** Closes the dialog; a `cancel` listener that keeps it open sends it back to rest. */
619
+ const close = () => {
620
+ if (!dialog.open) return;
621
+ if (typeof dialog.requestClose === "function") dialog.requestClose();
622
+ else dialog.close();
623
+ if (!dialog.open) return;
624
+ if (stack.length === 1) indentPose(true);
625
+ rest();
626
+ };
627
+
628
+ /**
629
+ * Slides the drawer off the bottom edge while it is still open, then closes
630
+ * it. The slide is the drawer's own `translate` transition, so it does not
631
+ * depend on the engine animating a dialog's exit (WebKit removes a closed
632
+ * dialog at once), and until it ends the drawer can be caught again.
633
+ * Whatever is linked to the drawer leaves with it.
634
+ */
635
+ const slideOutAndClose = (ms: number) => {
636
+ dialog.style.translate = `0 ${height + lift}px`;
637
+ settle(true, ms);
638
+ follow(dialog, 1, false);
639
+ if (stack.length === 1 && stack[0] === dialog) indentPose(false);
640
+ if (ms <= 0) {
641
+ close();
642
+ return;
643
+ }
644
+ const onSlid = (event: TransitionEvent) => {
645
+ if (event.target === dialog && event.propertyName === "translate") finish();
646
+ };
647
+ const finish = () => {
648
+ cancelClose?.();
649
+ close();
650
+ };
651
+ // the timer covers a transition that never reports its end
652
+ const timer = window.setTimeout(finish, ms + 100);
653
+ dialog.addEventListener("transitionend", onSlid);
654
+ cancelClose = () => {
655
+ window.clearTimeout(timer);
656
+ dialog.removeEventListener("transitionend", onSlid);
657
+ cancelClose = null;
658
+ };
659
+ };
660
+
661
+ bound.set(dialog, { controller, snapTo });
662
+ if (inDrawerMode(dialog)) {
663
+ measure();
664
+ place();
665
+ stack.push(dialog);
666
+ restack();
667
+ trackKeyboard(dialog, signal, () => {
668
+ measure();
669
+ place();
670
+ });
671
+ }
672
+
673
+ signal.addEventListener("abort", () => {
674
+ cancelClose?.();
675
+ // a drawer closed some other way mid-drag: nothing may hold the backdrop
676
+ if (fade?.playState === "paused") {
677
+ fade.cancel();
678
+ fades.delete(dialog);
679
+ }
680
+ });
681
+
682
+ dialog.addEventListener(
683
+ "scroll",
684
+ () => {
685
+ lastScroll = performance.now();
686
+ },
687
+ { capture: true, passive: true, signal },
688
+ );
689
+
690
+ // the handle steps through the snap points: a click, so a button handle works from the keyboard
691
+ dialog.addEventListener(
692
+ "click",
693
+ (event) => {
694
+ if (stops.length < 2 || !(event.target instanceof Element)) return;
695
+ if (event.target.closest(HANDLE)) snapTo((active + 1) % stops.length);
696
+ },
697
+ { signal },
698
+ );
699
+
700
+ window.addEventListener(
701
+ "resize",
702
+ () => {
703
+ if (!stack.includes(dialog)) return;
704
+ measure();
705
+ place();
706
+ },
707
+ { signal },
708
+ );
709
+
710
+ trackDrag(dialog, {
711
+ axis: "y",
712
+ signal,
713
+ canStart: (drag) => claims(dialog, drag, lastScroll, active < stops.length - 1),
714
+ onStart: () => {
715
+ // a drawer caught on its way out: what left with it comes back
716
+ if (cancelClose && stack.length === 1) indentPose(true);
717
+ cancelClose?.();
718
+ base = currentTranslate(dialog).y;
719
+ measure();
720
+ if (!fade) {
721
+ fade = scrubBackdrop(dialog);
722
+ if (fade) fades.set(dialog, fade);
723
+ }
724
+ fade?.pause();
725
+ setDragging(dialog, true);
726
+ },
727
+ onMove: ({ offset }) => {
728
+ const travel = base + offset;
729
+ const top = stops[stops.length - 1] ?? 0;
730
+ const y = travel >= top ? travel : top + rubberBand(travel - top, lift + top);
731
+ dialog.style.translate = `0 ${y}px`;
732
+ // progress runs from the lowest stop to gone: above it nothing fades
733
+ const lowest = stops[0] ?? 0;
734
+ const progress = Math.min(1, Math.max(0, (y - lowest) / Math.max(1, height - lowest)));
735
+ if (fade) fade.currentTime = progress * SCRUB_MS;
736
+ else dialog.style.setProperty("--_drawer-backdrop", String(1 - progress));
737
+ link(progress, true);
738
+ },
739
+ onEnd: ({ offset, velocity }) => {
740
+ const target = pickSnap({
741
+ stops,
742
+ position: base + offset,
743
+ velocity,
744
+ active,
745
+ size: height,
746
+ closeRatio: CLOSE_RATIO,
747
+ flick: FLICK_VELOCITY,
748
+ fling: FLING_VELOCITY,
749
+ sequential: dialog.hasAttribute("data-drawer-snap-sequential"),
750
+ });
751
+ // transitions back on: the inline translate now eases to wherever it is set
752
+ setDragging(dialog, false);
753
+ if (target < 0) slideOutAndClose(maxTransitionMs(dialog));
754
+ else snapTo(target);
755
+ },
756
+ onCancel: rest,
757
+ });
758
+ }
759
+
760
+ /** Unbinds a drawer that closed. */
761
+ function unbindDrawer(dialog: HTMLDialogElement): void {
762
+ bound.get(dialog)?.controller.abort();
763
+ bound.delete(dialog);
764
+ dialog.removeAttribute("data-drawer-state");
765
+ dialog.style.removeProperty("--_drawer-depth");
766
+ const index = stack.indexOf(dialog);
767
+ if (index < 0) return;
768
+ stack.splice(index, 1);
769
+ restack();
770
+ }
771
+
772
+ /**
773
+ * @description Moves an open drawer to one of its snap points.
774
+ *
775
+ * @param dialog - The drawer.
776
+ * @param index - The snap point, counted from the smallest; clamped to the ones it has.
777
+ */
778
+ function snapDrawer(dialog: HTMLDialogElement, index: number): void {
779
+ bound.get(dialog)?.snapTo(index);
780
+ }
781
+
782
+ interface InitDrawersFn {
783
+ (): void;
784
+ _bound?: boolean;
785
+ }
786
+
787
+ /**
788
+ * @description Starts drawer binding for the page: every drawer is bound when
789
+ * the dialog lifecycle reports it open and unbound when it closes. Idempotent.
790
+ */
791
+ const initDrawers: InitDrawersFn = function () {
792
+ if (initDrawers._bound) return;
793
+ initDrawers._bound = true;
794
+
795
+ document.addEventListener("zazz:dialog-open", (event) => {
796
+ if (event.target instanceof HTMLDialogElement && event.target.matches(DRAWER)) {
797
+ bindDrawer(event.target);
798
+ }
799
+ });
800
+ document.addEventListener("zazz:dialog-close", (event) => {
801
+ if (event.target instanceof HTMLDialogElement) unbindDrawer(event.target);
802
+ });
803
+
804
+ window.addEventListener("resize", () => {
805
+ if (indented) measureIndent(indented);
806
+ });
807
+
808
+ // drawers that were already open when the script loaded
809
+ for (const dialog of document.querySelectorAll<HTMLDialogElement>(`${DRAWER}[open]`)) {
810
+ bindDrawer(dialog);
811
+ }
812
+ };
813
+
814
+ // Auto-initialize when DOM is ready (only in browser environment)
815
+ if (typeof window !== "undefined" && typeof document !== "undefined") {
816
+ if (document.readyState === "loading") {
817
+ document.addEventListener("DOMContentLoaded", initDrawers);
818
+ } else {
819
+ initDrawers();
820
+ }
821
+ }
822
+
823
+ export { bindDrawer, initDrawers, snapDrawer };