@barqjs/aria 0.0.0-stage → 0.2.0-next.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 (103) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +304 -2
  3. package/package.json +437 -4
  4. package/src/autocomplete.tsx +581 -0
  5. package/src/breadcrumbs.tsx +297 -0
  6. package/src/button.tsx +468 -0
  7. package/src/calendar.tsx +2316 -0
  8. package/src/checkbox.tsx +732 -0
  9. package/src/collections.ts +1059 -0
  10. package/src/color.ts +2119 -0
  11. package/src/colorpicker.tsx +2023 -0
  12. package/src/colorswatchpicker.tsx +240 -0
  13. package/src/combobox.tsx +3003 -0
  14. package/src/command.tsx +1203 -0
  15. package/src/date.ts +674 -0
  16. package/src/datefield.tsx +2066 -0
  17. package/src/datepicker.tsx +907 -0
  18. package/src/dialog.tsx +1077 -0
  19. package/src/disclosure.tsx +711 -0
  20. package/src/dnd/clipboard.ts +125 -0
  21. package/src/dnd/collection.ts +1265 -0
  22. package/src/dnd/data.ts +409 -0
  23. package/src/dnd/drag-drop.ts +801 -0
  24. package/src/dnd/index.ts +133 -0
  25. package/src/dnd/manager.ts +639 -0
  26. package/src/dnd/strings.ts +1279 -0
  27. package/src/dnd/targets.ts +726 -0
  28. package/src/dnd/types.ts +212 -0
  29. package/src/dom.ts +703 -0
  30. package/src/drag-and-drop.tsx +669 -0
  31. package/src/drawer.ts +674 -0
  32. package/src/dropzone.tsx +208 -0
  33. package/src/file-trigger.tsx +103 -0
  34. package/src/focus.ts +1370 -0
  35. package/src/form.tsx +94 -0
  36. package/src/gridlist.tsx +1354 -0
  37. package/src/group.tsx +146 -0
  38. package/src/i18n.ts +823 -0
  39. package/src/index.ts +1672 -0
  40. package/src/interactions/description.ts +73 -0
  41. package/src/interactions/flags.ts +35 -0
  42. package/src/interactions/focus-events.ts +226 -0
  43. package/src/interactions/focusable.ts +86 -0
  44. package/src/interactions/hover.ts +213 -0
  45. package/src/interactions/interact-outside.ts +123 -0
  46. package/src/interactions/keyboard.ts +298 -0
  47. package/src/interactions/listeners.ts +78 -0
  48. package/src/interactions/long-press.ts +160 -0
  49. package/src/interactions/modality.ts +428 -0
  50. package/src/interactions/move.ts +257 -0
  51. package/src/interactions/open-link.ts +226 -0
  52. package/src/interactions/press.ts +915 -0
  53. package/src/interactions/prevent-focus.ts +102 -0
  54. package/src/interactions/scroll-wheel.ts +43 -0
  55. package/src/interactions/text-selection.ts +77 -0
  56. package/src/interactions.ts +81 -0
  57. package/src/label.ts +140 -0
  58. package/src/link.tsx +477 -0
  59. package/src/listbox.tsx +1247 -0
  60. package/src/live.ts +208 -0
  61. package/src/menu.tsx +2383 -0
  62. package/src/menubar.tsx +579 -0
  63. package/src/navigation-tree.tsx +357 -0
  64. package/src/navigation.ts +735 -0
  65. package/src/numberfield.tsx +942 -0
  66. package/src/otp.ts +430 -0
  67. package/src/overlay-arrow.tsx +157 -0
  68. package/src/overlays.ts +1549 -0
  69. package/src/platform.ts +75 -0
  70. package/src/presence.ts +164 -0
  71. package/src/preview-trigger.tsx +582 -0
  72. package/src/progress-bar-context.ts +15 -0
  73. package/src/questionnaire.tsx +1717 -0
  74. package/src/radio.tsx +641 -0
  75. package/src/register-dom.ts +12 -0
  76. package/src/scroller.ts +1165 -0
  77. package/src/select.tsx +1745 -0
  78. package/src/selection-indicator.tsx +74 -0
  79. package/src/selection.ts +1472 -0
  80. package/src/shared-element-transition.tsx +316 -0
  81. package/src/sheet.tsx +1461 -0
  82. package/src/slider.tsx +1137 -0
  83. package/src/splitter.ts +1152 -0
  84. package/src/static-collection.ts +211 -0
  85. package/src/switch.tsx +212 -0
  86. package/src/table.tsx +2218 -0
  87. package/src/tabs.tsx +1127 -0
  88. package/src/tag.tsx +637 -0
  89. package/src/textarea.tsx +186 -0
  90. package/src/textfield.tsx +483 -0
  91. package/src/toast-components.tsx +589 -0
  92. package/src/toast.ts +658 -0
  93. package/src/toggle-button-group.tsx +175 -0
  94. package/src/toggle-input.tsx +86 -0
  95. package/src/toggle.ts +384 -0
  96. package/src/togglegroup.ts +365 -0
  97. package/src/tokenfield.tsx +1673 -0
  98. package/src/toolbar.tsx +184 -0
  99. package/src/tooltip.tsx +674 -0
  100. package/src/tree.tsx +2075 -0
  101. package/src/utils.ts +787 -0
  102. package/src/validation.ts +504 -0
  103. package/src/virtualizer.tsx +837 -0
package/src/sheet.tsx ADDED
@@ -0,0 +1,1461 @@
1
+ /**
2
+ * Sheets: an overlay that slides in from an edge of the viewport and is swiped
3
+ * away.
4
+ *
5
+ * The gesture is the browser's own scrolling, which is upstream's design and
6
+ * the reason this shares no engine with `drawer.ts`. The sheet sits in a stage
7
+ * one viewport into a scroll container two viewports long. Opening scrolls the
8
+ * stage on screen, a swipe scrolls it off, scroll snapping decides where a
9
+ * release comes to rest, and the moment the content has left the viewport an
10
+ * `IntersectionObserver` closes the sheet. Momentum, rubber-banding and the
11
+ * hand-off between a list inside the sheet and the sheet itself are the
12
+ * platform's, run off the main thread. `drawer.ts` measures a pointer and
13
+ * decides in script, with Vaul's thresholds and a snap point that is a share of
14
+ * the viewport; a snap point here is a CSS length the browser resolves against
15
+ * the sheet. The two agree on nothing that could be shared without making one
16
+ * of them wrong.
17
+ *
18
+ * Swipe and stack animations are CSS keyframes bound to the content's view
19
+ * timeline, so they track the finger exactly. Where view timelines are missing
20
+ * (Firefox) they play over a fixed time while the sheet enters and leaves.
21
+ */
22
+
23
+ import {
24
+ cells,
25
+ createContext,
26
+ createEffect,
27
+ createMemo,
28
+ createSignal,
29
+ createUniqueId,
30
+ For,
31
+ getContext,
32
+ isBlock,
33
+ omit,
34
+ onCleanup,
35
+ onSettled,
36
+ provide,
37
+ Show,
38
+ untrack,
39
+ type Accessor,
40
+ type Child,
41
+ type Incoming,
42
+ } from "@barqjs/core";
43
+ import { Portal } from "@barqjs/web";
44
+ import { ref as makeRef, mergeRefs, type RefTarget } from "@barqjs/primitives/refs";
45
+
46
+ import { Dialog, type DialogComponentProps } from "./dialog.tsx";
47
+ import {
48
+ activeElement,
49
+ contains,
50
+ focusWithoutScrolling,
51
+ isScrollable,
52
+ ownerDocument,
53
+ ownerWindow,
54
+ } from "./dom.ts";
55
+ import { focusScope } from "./focus.ts";
56
+ import { useLocale } from "./i18n.ts";
57
+ import {
58
+ dismissButtonProps,
59
+ followOpen,
60
+ modalOverlay,
61
+ overlayTrigger,
62
+ overlayTriggerState,
63
+ portalContainer,
64
+ usePortalTarget,
65
+ type OverlayTriggerState,
66
+ } from "./overlays.ts";
67
+ import { isIOS, isSafari } from "./platform.ts";
68
+ import { exitDuration } from "./presence.ts";
69
+ import {
70
+ callback,
71
+ filterDOMProps,
72
+ fromProps,
73
+ clearTriggerSlot,
74
+ mergeProps,
75
+ provideTriggerSlot,
76
+ type DOMProps,
77
+ type StyleProps,
78
+ } from "./utils.ts";
79
+
80
+ export type SheetPosition = "bottom" | "top" | "left" | "right" | "center";
81
+ export type SheetSwipeDirection = "bottom" | "top" | "vertical" | "left" | "right" | "horizontal";
82
+ /** Pixels as a number, or any CSS length. A percentage is of the sheet's own size. */
83
+ export type SheetSnapPoint = number | string;
84
+
85
+ type Axis = "x" | "y";
86
+ type Style = Record<string, string | number | undefined>;
87
+
88
+ /** What every part of a sheet can read, each field live. */
89
+ export interface SheetRenderState {
90
+ /** `start` and `end` already resolved for the reading direction. */
91
+ position: Accessor<SheetPosition>;
92
+ swipeDirection: Accessor<SheetSwipeDirection>;
93
+ /** Its place among the open sheets, 0 for the one at the back. */
94
+ stackIndex: Accessor<number>;
95
+ /** Whether another sheet is open in front of it. */
96
+ hasDescendants: Accessor<boolean>;
97
+ /** Resting at its last snap point, wholly on screen. */
98
+ isExpanded: Accessor<boolean>;
99
+ isEntering: Accessor<boolean>;
100
+ isExiting: Accessor<boolean>;
101
+ close: () => void;
102
+ }
103
+
104
+ // ---------------------------------------------------------------------------
105
+ // Geometry
106
+ // ---------------------------------------------------------------------------
107
+
108
+ interface SwipeConfig {
109
+ axis: Axis;
110
+ /** Can be swiped off the top or left edge. */
111
+ before: boolean;
112
+ /** Can be swiped off the bottom or right edge. */
113
+ after: boolean;
114
+ /** Distance between the two extreme scroll positions, in viewport percent. */
115
+ maxScroll: number;
116
+ /** The scroll position at which it is fully entered, in viewport percent. */
117
+ enteredScroll: number;
118
+ /** Offset of the scroll container along the axis, in viewport percent. */
119
+ containerOffset: number;
120
+ viewRange: "cover" | "exit" | "entry";
121
+ viewDirection: "normal" | "reverse" | "alternate";
122
+ viewIterations: number;
123
+ }
124
+
125
+ function swipeConfig(direction: SheetSwipeDirection): SwipeConfig {
126
+ const axis: Axis =
127
+ direction === "top" || direction === "bottom" || direction === "vertical" ? "y" : "x";
128
+ const before =
129
+ direction === "top" ||
130
+ direction === "left" ||
131
+ direction === "vertical" ||
132
+ direction === "horizontal";
133
+ const after =
134
+ direction === "bottom" ||
135
+ direction === "right" ||
136
+ direction === "vertical" ||
137
+ direction === "horizontal";
138
+ // A sheet that leaves only toward the start edge rests at scroll 0 and is
139
+ // dismissed toward the far end; every other one rests a viewport in.
140
+ const startOnly = before && !after;
141
+ // In view-timeline terms `entry` is the scrollport's end edge and `exit` its
142
+ // start edge. Each direction is chosen so progress 0 is gone and 1 is
143
+ // entered, matching keyframes written from exited to entered. A sheet that
144
+ // crosses both edges runs the same keyframes twice over `cover`, alternating,
145
+ // so an author never writes a symmetric 0/50/100 variant.
146
+ return {
147
+ axis,
148
+ before,
149
+ after,
150
+ maxScroll: (Number(before) + Number(after)) * 100,
151
+ enteredScroll: startOnly ? 0 : 100,
152
+ containerOffset: startOnly ? -100 : 0,
153
+ viewRange: before && after ? "cover" : before ? "exit" : "entry",
154
+ viewDirection: before && after ? "alternate" : before ? "reverse" : "normal",
155
+ viewIterations: before && after ? 2 : 1,
156
+ };
157
+ }
158
+
159
+ function resolveDirection<T extends string>(
160
+ value: T | "start" | "end",
161
+ direction: "ltr" | "rtl",
162
+ ): T | "left" | "right" {
163
+ if (value === "start") return direction === "rtl" ? "right" : "left";
164
+ if (value === "end") return direction === "rtl" ? "left" : "right";
165
+ return value;
166
+ }
167
+
168
+ /** The resting `[x, y]` flex alignment for each position, whatever the swipe. */
169
+ const POSITION_ALIGNMENT: Record<SheetPosition, [string, string]> = {
170
+ top: ["center", "flex-start"],
171
+ bottom: ["center", "flex-end"],
172
+ left: ["flex-start", "center"],
173
+ right: ["flex-end", "center"],
174
+ center: ["center", "center"],
175
+ };
176
+
177
+ /**
178
+ * iOS Safari draws past the viewport it reports, behind its toolbar, even with
179
+ * the toolbar collapsed. A bottom sheet is pushed that much further out so it
180
+ * is wholly gone before it counts as gone. The 58px is upstream's measurement
181
+ * of the toolbar.
182
+ */
183
+ function viewportPadding(after: boolean, axis: Axis): string {
184
+ return after && axis === "y" && isIOS() && isSafari() ? "calc(100lvh - 100svh + 58px)" : "0px";
185
+ }
186
+
187
+ function toLength(point: SheetSnapPoint): string {
188
+ return typeof point === "number" ? `${point}px` : point;
189
+ }
190
+
191
+ /** A `calc()` resolved to pixels by laying it out, since nothing else can. */
192
+ function calcToPx(value: string, doc: Document): string {
193
+ if (!value.startsWith("calc(")) return value;
194
+ const probe = doc.createElement("div");
195
+ probe.inert = true;
196
+ probe.style.position = "absolute";
197
+ probe.style.top = "0px";
198
+ probe.style.left = "0px";
199
+ probe.style.contain = "strict";
200
+ probe.style.height = value;
201
+ doc.body.append(probe);
202
+ const height = ownerWindow(probe).getComputedStyle(probe).height;
203
+ probe.remove();
204
+ return height;
205
+ }
206
+
207
+ function reduceMotion(view: Window): boolean {
208
+ return (
209
+ typeof view.matchMedia === "function" &&
210
+ view.matchMedia("(prefers-reduced-motion: reduce)").matches
211
+ );
212
+ }
213
+
214
+ function supportsViewTimeline(): boolean {
215
+ return (
216
+ typeof CSS !== "undefined" &&
217
+ typeof CSS.supports === "function" &&
218
+ CSS.supports("animation-timeline: view()")
219
+ );
220
+ }
221
+
222
+ function scrollAlongAxis(element: HTMLElement, axis: Axis, value: number, smooth = false): void {
223
+ const behavior: ScrollBehavior | undefined =
224
+ smooth && !reduceMotion(ownerWindow(element)) ? "smooth" : undefined;
225
+ element.scrollTo(axis === "y" ? { top: value, behavior } : { left: value, behavior });
226
+ }
227
+
228
+ /**
229
+ * Move the scroller so the sheet's leading edge sits at the viewport edge,
230
+ * with snapping off so the browser does not pull it back. Returns whether it
231
+ * moved: an enter animation that starts a viewport away spends its first part
232
+ * moving nothing anyone can see.
233
+ */
234
+ function skipOffscreenTravel(
235
+ scroller: HTMLElement,
236
+ content: HTMLElement,
237
+ axis: Axis,
238
+ viewport: number,
239
+ ): boolean {
240
+ const rect = content.getBoundingClientRect();
241
+ const start = axis === "y" ? rect.top : rect.left;
242
+ const end = axis === "y" ? rect.bottom : rect.right;
243
+ const delta = start > viewport ? start - viewport : end < 0 ? end : 0;
244
+ if (delta === 0) return false;
245
+
246
+ scroller.style.scrollSnapType = "none";
247
+ if (axis === "y") scroller.scrollTop += delta;
248
+ else scroller.scrollLeft += delta;
249
+ return true;
250
+ }
251
+
252
+ /** Rest a snap marker where scroll snapping would, less or plus its scroll margin. */
253
+ function scrollDetentIntoView(
254
+ scroller: HTMLElement,
255
+ marker: HTMLElement,
256
+ axis: Axis,
257
+ align: "start" | "end",
258
+ smooth: boolean,
259
+ ): void {
260
+ const behavior: ScrollBehavior =
261
+ smooth && !reduceMotion(ownerWindow(scroller)) ? "smooth" : "auto";
262
+ const markerRect = marker.getBoundingClientRect();
263
+ const scrollerRect = scroller.getBoundingClientRect();
264
+ const style = ownerWindow(marker).getComputedStyle(marker);
265
+ if (axis === "y") {
266
+ const top =
267
+ align === "start"
268
+ ? markerRect.top -
269
+ scrollerRect.top +
270
+ scroller.scrollTop -
271
+ (Number.parseFloat(style.scrollMarginTop) || 0)
272
+ : markerRect.bottom -
273
+ scrollerRect.top +
274
+ scroller.scrollTop +
275
+ (Number.parseFloat(style.scrollMarginBottom) || 0) -
276
+ scroller.clientHeight;
277
+ scroller.scrollTo({ top, behavior });
278
+ return;
279
+ }
280
+ const left =
281
+ align === "start"
282
+ ? markerRect.left -
283
+ scrollerRect.left +
284
+ scroller.scrollLeft -
285
+ (Number.parseFloat(style.scrollMarginLeft) || 0)
286
+ : markerRect.right -
287
+ scrollerRect.left +
288
+ scroller.scrollLeft +
289
+ (Number.parseFloat(style.scrollMarginRight) || 0) -
290
+ scroller.clientWidth;
291
+ scroller.scrollTo({ left, behavior });
292
+ }
293
+
294
+ function waitFor(target: EventTarget, type: string): Promise<void> {
295
+ return new Promise((resolve) => {
296
+ target.addEventListener(type, () => resolve(), { once: true });
297
+ });
298
+ }
299
+
300
+ function delay(ms: number): Promise<void> {
301
+ return new Promise((resolve) => setTimeout(resolve, ms));
302
+ }
303
+
304
+ // ---------------------------------------------------------------------------
305
+ // The stack of open sheets
306
+ // ---------------------------------------------------------------------------
307
+
308
+ interface StackEntry {
309
+ id: string;
310
+ timelineName: string;
311
+ range: string;
312
+ direction: string;
313
+ iterations: number;
314
+ }
315
+
316
+ let sheetStack: readonly StackEntry[] = [];
317
+ const [stackVersion, publishStack] = createSignal(0, { equals: false, ownedWrite: true });
318
+
319
+ function readStack(): readonly StackEntry[] {
320
+ stackVersion();
321
+ return sheetStack;
322
+ }
323
+
324
+ /**
325
+ * A parent sheet's stack animation runs on its CHILD's view timeline, which is
326
+ * declared inside the child and is out of the parent's reach. `timeline-scope`
327
+ * on the root hoists every open sheet's timeline to where any element can name
328
+ * it.
329
+ */
330
+ function writeStack(doc: Document): void {
331
+ doc.documentElement.style.setProperty(
332
+ "timeline-scope",
333
+ sheetStack.map((entry) => entry.timelineName).join(", "),
334
+ );
335
+ publishStack(0);
336
+ }
337
+
338
+ function registerSheet(entry: StackEntry, doc: Document): () => void {
339
+ sheetStack = [...sheetStack, entry];
340
+ writeStack(doc);
341
+ return () => {
342
+ sheetStack = sheetStack.filter((other) => other.id !== entry.id);
343
+ writeStack(doc);
344
+ };
345
+ }
346
+
347
+ // ---------------------------------------------------------------------------
348
+ // Contexts
349
+ // ---------------------------------------------------------------------------
350
+
351
+ interface SheetTriggerValue {
352
+ state: OverlayTriggerState;
353
+ }
354
+
355
+ const SheetTriggerContext = createContext<SheetTriggerValue | null>(null);
356
+
357
+ /** The triggers whose sheets enclose this point, outermost first. */
358
+ const EnclosingTriggersContext = createContext<readonly SheetTriggerValue[]>([]);
359
+
360
+ interface SheetContextValue {
361
+ config: Accessor<SwipeConfig>;
362
+ position: Accessor<SheetPosition>;
363
+ swipeDirection: Accessor<SheetSwipeDirection>;
364
+ snapPoints: Accessor<readonly SheetSnapPoint[] | undefined>;
365
+ preventDismissal: Accessor<boolean>;
366
+ isNonModal: Accessor<boolean>;
367
+ isEntering: Accessor<boolean>;
368
+ isExiting: Accessor<boolean>;
369
+ timelineName: string;
370
+ descendants: Accessor<readonly StackEntry[]>;
371
+ /** The `data-*` every part writes. */
372
+ dataProps: DOMProps;
373
+ /** Escape and focus-within, for the sheet's own element. */
374
+ modalProps: DOMProps;
375
+ setModal: (element: HTMLDivElement | null) => void;
376
+ modal: Accessor<HTMLDivElement | null>;
377
+ state: SheetRenderState;
378
+ /** The triggers whose sheets enclose this one, its own last. */
379
+ triggers: readonly SheetTriggerValue[];
380
+ }
381
+
382
+ const SheetContext = createContext<SheetContextValue | null>(null);
383
+
384
+ function useSheetContext(part: string): SheetContextValue {
385
+ const value = getContext(SheetContext);
386
+ if (value === null || value === undefined) {
387
+ throw new Error(`A ${part} must be rendered inside a SheetOverlay.`);
388
+ }
389
+ return value;
390
+ }
391
+
392
+ /** The enclosing sheet's state, or `null` outside one. */
393
+ export function useSheet(): SheetRenderState | null {
394
+ return getContext(SheetContext)?.state ?? null;
395
+ }
396
+
397
+ function SheetProvider(props: { value: SheetContextValue; children?: Child }) {
398
+ return provide(
399
+ SheetContext,
400
+ () => props.value,
401
+ () =>
402
+ provide(
403
+ EnclosingTriggersContext,
404
+ () => props.value.triggers,
405
+ () => props.children as unknown,
406
+ ),
407
+ );
408
+ }
409
+
410
+ type RenderChildren = (state: SheetRenderState) => Child;
411
+
412
+ /** A children callback, told from content by declaring its parameter. */
413
+ function renderFunction(children: unknown): RenderChildren | null {
414
+ if (typeof children !== "function") return null;
415
+ if (children.length > 0) return children as RenderChildren;
416
+ if (isBlock(children)) return null;
417
+ const inner: unknown = (children as () => unknown)();
418
+ return typeof inner === "function" && inner.length > 0 ? (inner as RenderChildren) : null;
419
+ }
420
+
421
+ /**
422
+ * The callback runs once. Its fields are accessors that its JSX follows; a
423
+ * read in its body must not rebuild everything it returned.
424
+ */
425
+ function renderChildren(children: unknown, state: SheetRenderState): Child {
426
+ const render = renderFunction(children);
427
+ return render === null ? (children as Child) : untrack(() => render(state));
428
+ }
429
+
430
+ // ---------------------------------------------------------------------------
431
+ // SheetTrigger
432
+ // ---------------------------------------------------------------------------
433
+
434
+ export interface SheetTriggerProps {
435
+ children?: Child;
436
+ isOpen?: boolean;
437
+ defaultOpen?: boolean;
438
+ onOpenChange?: (isOpen: boolean) => void;
439
+ }
440
+
441
+ /**
442
+ * A button and the sheet it opens, sharing one piece of state.
443
+ *
444
+ * ```tsx
445
+ * <SheetTrigger>
446
+ * <Button>Open</Button>
447
+ * <SheetOverlay>
448
+ * <SheetBackdrop />
449
+ * <Sheet>
450
+ * <SheetContent>
451
+ * <Heading slot="title">Order</Heading>
452
+ * </SheetContent>
453
+ * </Sheet>
454
+ * </SheetOverlay>
455
+ * </SheetTrigger>
456
+ * ```
457
+ */
458
+ export function SheetTrigger(props: Incoming<SheetTriggerProps>) {
459
+ const options = fromProps(props);
460
+ const state = overlayTriggerState(options);
461
+ const { triggerProps } = overlayTrigger({ type: "dialog" }, state);
462
+ const value: SheetTriggerValue = { state };
463
+
464
+ return provide(
465
+ SheetTriggerContext,
466
+ () => value,
467
+ () => {
468
+ provideTriggerSlot({ props: triggerProps });
469
+ return props.children;
470
+ },
471
+ );
472
+ }
473
+
474
+ // ---------------------------------------------------------------------------
475
+ // SheetOverlay
476
+ // ---------------------------------------------------------------------------
477
+
478
+ export interface SheetOverlayProps extends StyleProps {
479
+ children?: Child | ((state: SheetRenderState) => Child);
480
+ /**
481
+ * The edge it is anchored to. `start` and `end` follow the reading direction.
482
+ * @default "bottom"
483
+ */
484
+ position?: "bottom" | "top" | "left" | "right" | "start" | "end" | "center";
485
+ /**
486
+ * Which way it can be swiped. `start` and `end` follow the reading direction.
487
+ * @default the position, or `"vertical"` for a centred sheet
488
+ */
489
+ swipeDirection?:
490
+ | "bottom"
491
+ | "top"
492
+ | "vertical"
493
+ | "left"
494
+ | "right"
495
+ | "start"
496
+ | "end"
497
+ | "horizontal";
498
+ /**
499
+ * Where it stops, as how much of it is visible. It opens at the first and
500
+ * can always be swiped to fully open.
501
+ */
502
+ snapPoints?: readonly SheetSnapPoint[];
503
+ /**
504
+ * No swipe, Escape or outside press closes it. It still moves between its
505
+ * snap points, and closes when told to. @default false
506
+ */
507
+ preventDismissal?: boolean;
508
+ /**
509
+ * Leave the page behind usable: nothing behind is hidden or inert, the page
510
+ * scrolls, focus may leave and a press outside does not close it. Escape
511
+ * still does. @default false
512
+ */
513
+ isNonModal?: boolean;
514
+ isOpen?: boolean;
515
+ defaultOpen?: boolean;
516
+ onOpenChange?: (isOpen: boolean) => void;
517
+ /** Veto an outside press for a particular element. */
518
+ shouldCloseOnInteractOutside?: (element: Element) => boolean;
519
+ ref?: RefTarget<HTMLDivElement>;
520
+ }
521
+
522
+ interface OverlayShared {
523
+ state: OverlayTriggerState;
524
+ triggers: readonly SheetTriggerValue[];
525
+ id: string;
526
+ timelineName: string;
527
+ position: Accessor<SheetPosition>;
528
+ swipeDirection: Accessor<SheetSwipeDirection>;
529
+ config: Accessor<SwipeConfig>;
530
+ snapPoints: Accessor<readonly SheetSnapPoint[] | undefined>;
531
+ preventDismissal: Accessor<boolean>;
532
+ isNonModal: Accessor<boolean>;
533
+ isExiting: Accessor<boolean>;
534
+ shouldCloseOnInteractOutside: (element: Element) => boolean;
535
+ domProps: DOMProps;
536
+ className: Accessor<string | undefined>;
537
+ style: Accessor<Style | undefined>;
538
+ ref: RefTarget<HTMLDivElement> | undefined;
539
+ attach: (body: OverlayBody | null) => void;
540
+ }
541
+
542
+ interface OverlayBody {
543
+ enter(): void;
544
+ exit(): Promise<void>;
545
+ }
546
+
547
+ /**
548
+ * The layer a sheet and its backdrop live in, portalled over the page.
549
+ *
550
+ * Inside a {@link SheetTrigger} it uses the trigger's state, unless it is given
551
+ * `isOpen` or `defaultOpen` of its own, which a sheet without a trigger needs.
552
+ */
553
+ export function SheetOverlay(props: SheetOverlayProps) {
554
+ clearTriggerSlot();
555
+ const options = fromProps(cells(props));
556
+ const trigger = getContext(SheetTriggerContext) ?? null;
557
+ const enclosing = getContext(EnclosingTriggersContext) ?? [];
558
+ const local = overlayTriggerState(options);
559
+ const target = usePortalTarget();
560
+ const locale = useLocale();
561
+
562
+ const own = (): boolean =>
563
+ props.isOpen !== undefined || props.defaultOpen !== undefined || trigger === null;
564
+ const current = (): OverlayTriggerState => (own() || trigger === null ? local : trigger.state);
565
+ const state: OverlayTriggerState = {
566
+ isOpen: () => current().isOpen(),
567
+ setOpen: (open) => current().setOpen(open),
568
+ open: () => current().open(),
569
+ close: () => current().close(),
570
+ toggle: () => current().toggle(),
571
+ };
572
+
573
+ const position = createMemo((): SheetPosition =>
574
+ resolveDirection(props.position ?? "bottom", locale().direction),
575
+ );
576
+ const swipeDirection = createMemo((): SheetSwipeDirection => {
577
+ const given = props.swipeDirection;
578
+ if (given !== undefined) return resolveDirection(given, locale().direction);
579
+ const at = position();
580
+ return at === "center" ? "vertical" : at;
581
+ });
582
+ const config = createMemo(() => swipeConfig(swipeDirection()));
583
+
584
+ const id = createUniqueId();
585
+ const [isPresent, setPresent] = createSignal(state.isOpen());
586
+ const [isExiting, setExiting] = createSignal(false);
587
+ let body: OverlayBody | null = null;
588
+ let exits = 0;
589
+
590
+ followOpen(state.isOpen, (open) => {
591
+ if (open) {
592
+ exits++;
593
+ if (isExiting()) {
594
+ setExiting(false);
595
+ body?.enter();
596
+ }
597
+ setPresent(true);
598
+ return undefined;
599
+ }
600
+ if (!isPresent()) return undefined;
601
+ if (body === null) {
602
+ setPresent(false);
603
+ return undefined;
604
+ }
605
+ const exit = ++exits;
606
+ setExiting(true);
607
+ void body.exit().then(() => {
608
+ if (exit !== exits) return;
609
+ setExiting(false);
610
+ setPresent(false);
611
+ });
612
+ return undefined;
613
+ });
614
+
615
+ const shared: OverlayShared = {
616
+ state,
617
+ triggers: trigger === null ? enclosing : [...enclosing, trigger],
618
+ id,
619
+ timelineName: `--sheet-timeline-${id.replace(/[^\w-]/g, "")}`,
620
+ position,
621
+ swipeDirection,
622
+ config,
623
+ snapPoints: () => props.snapPoints,
624
+ preventDismissal: () => props.preventDismissal === true,
625
+ isNonModal: () => props.isNonModal === true,
626
+ isExiting,
627
+ shouldCloseOnInteractOutside: (element) =>
628
+ callback(options.shouldCloseOnInteractOutside)?.(element) ?? true,
629
+ domProps: filterDOMProps(options, { global: true }),
630
+ className: () => props.class ?? props.className,
631
+ style: () => props.style,
632
+ ref: props.ref,
633
+ attach: (next) => {
634
+ body = next;
635
+ },
636
+ };
637
+
638
+ return (
639
+ <Show when={isPresent()}>
640
+ <Portal mount={portalContainer(target)}>
641
+ <SheetOverlayBody shared={shared}>{props.children}</SheetOverlayBody>
642
+ </Portal>
643
+ </Show>
644
+ );
645
+ }
646
+
647
+ interface ViewportBox {
648
+ width: number;
649
+ height: number;
650
+ pageWidth: number;
651
+ pageHeight: number;
652
+ }
653
+
654
+ function measureViewport(doc: Document): ViewportBox {
655
+ const view = ownerWindow(doc.documentElement);
656
+ const root = doc.documentElement;
657
+ const visual = view.visualViewport;
658
+ const scrolling = isScrollable(doc.body) ? doc.body : (doc.scrollingElement ?? root);
659
+ const box = scrolling.getBoundingClientRect();
660
+ return {
661
+ // The visual viewport's width can include the scrollbar gutter.
662
+ width: visual ? Math.min(visual.width * visual.scale, root.clientWidth) : root.clientWidth,
663
+ height: visual ? visual.height * visual.scale : root.clientHeight,
664
+ // A fractional page size makes Firefox add scrollbars.
665
+ pageWidth: scrolling.scrollWidth - (box.width % 1),
666
+ pageHeight: scrolling.scrollHeight - (box.height % 1),
667
+ };
668
+ }
669
+
670
+ /**
671
+ * Everything that exists only while the sheet is on screen.
672
+ *
673
+ * A component of its own because the focus scope has to be created with the
674
+ * content it contains: disposing this subtree is what puts focus back.
675
+ */
676
+ function SheetOverlayBody(props: { shared: OverlayShared; children?: Child | RenderChildren }) {
677
+ const shared = props.shared;
678
+ const overlayRef = makeRef<HTMLDivElement>();
679
+ const modalRef = makeRef<HTMLDivElement>();
680
+ const [isEntering, setEntering] = createSignal(true);
681
+ const [isExpanded, setExpanded] = createSignal(false);
682
+ const [viewport, setViewport] = createSignal<ViewportBox | null>(
683
+ typeof document === "undefined" ? null : measureViewport(document),
684
+ );
685
+
686
+ let visible = false;
687
+ let seen = false;
688
+ let disposed = false;
689
+ let enters = 0;
690
+ let hidden: (() => void)[] = [];
691
+
692
+ const scope = focusScope({
693
+ contain: () => !shared.isNonModal() && !shared.isExiting(),
694
+ restoreFocus: true,
695
+ autoFocus: false,
696
+ });
697
+
698
+ // While the sheet slides in, nothing behind it is hidden and focus stays
699
+ // where it was: moving the VoiceOver cursor into the sheet scrolls, and on
700
+ // iOS that interrupts the scroll that is bringing it on screen.
701
+ const { overlayProps, modalProps } = modalOverlay(
702
+ {
703
+ isDismissable: () => !shared.preventDismissal() && !shared.isNonModal(),
704
+ isKeyboardDismissDisabled: shared.preventDismissal,
705
+ isScrollDisabled: shared.isNonModal,
706
+ isNonModal: shared.isNonModal,
707
+ isEntering,
708
+ shouldCloseOnEscapeAnywhere: shared.isNonModal,
709
+ shouldCloseOnInteractOutside: shared.shouldCloseOnInteractOutside,
710
+ },
711
+ shared.state,
712
+ modalRef,
713
+ );
714
+
715
+ const stackIndex = createMemo(() =>
716
+ Math.max(
717
+ 0,
718
+ readStack().findIndex((entry) => entry.id === shared.id),
719
+ ),
720
+ );
721
+ const descendants = createMemo((): readonly StackEntry[] => {
722
+ const all = readStack();
723
+ const at = all.findIndex((entry) => entry.id === shared.id);
724
+ return at < 0 ? [] : all.slice(at + 1);
725
+ });
726
+
727
+ const renderState: SheetRenderState = {
728
+ position: shared.position,
729
+ swipeDirection: shared.swipeDirection,
730
+ stackIndex,
731
+ hasDescendants: () => descendants().length > 0,
732
+ isExpanded,
733
+ isEntering,
734
+ isExiting: shared.isExiting,
735
+ close: () => shared.state.close(),
736
+ };
737
+
738
+ const dataProps: DOMProps = {
739
+ "data-position": shared.position,
740
+ "data-swipe-direction": shared.swipeDirection,
741
+ "data-expanded": () => (isExpanded() ? "" : undefined),
742
+ "data-stack-index": () => String(stackIndex()),
743
+ "data-has-descendants": () => (descendants().length > 0 ? "" : undefined),
744
+ };
745
+
746
+ const viewportExtent = (element: Element, config: SwipeConfig): number => {
747
+ const view = ownerWindow(element);
748
+ return config.axis === "y"
749
+ ? view.innerHeight +
750
+ Number.parseFloat(
751
+ calcToPx(viewportPadding(config.after, config.axis), ownerDocument(element)),
752
+ )
753
+ : view.innerWidth;
754
+ };
755
+
756
+ const enter = (): void => {
757
+ const overlay = overlayRef();
758
+ if (overlay === null) return;
759
+ const scroller = overlay.querySelector<HTMLElement>("[data-sheet-scroll]");
760
+ if (scroller === null) return;
761
+ setEntering(true);
762
+ const attempt = ++enters;
763
+ const config = shared.config();
764
+ const content = overlay.querySelector<HTMLElement>("[data-sheet-content]");
765
+ const initial = overlay.querySelector<HTMLElement>("[data-sheet-initial]");
766
+ const extent = viewportExtent(overlay, config);
767
+ const view = ownerWindow(overlay);
768
+
769
+ const scrollToRest = (smooth: boolean): void => {
770
+ if (initial === null) {
771
+ scrollAlongAxis(scroller, config.axis, (config.enteredScroll / 100) * extent, smooth);
772
+ } else {
773
+ scrollDetentIntoView(
774
+ scroller,
775
+ initial,
776
+ config.axis,
777
+ config.after ? "start" : "end",
778
+ smooth,
779
+ );
780
+ }
781
+ };
782
+
783
+ // Resting at scroll 0 means mounting already entered: jump to the exit.
784
+ if (config.enteredScroll === 0) {
785
+ scrollAlongAxis(scroller, config.axis, (config.maxScroll / 100) * extent);
786
+ }
787
+ const snapType = scroller.style.scrollSnapType;
788
+ const skipped =
789
+ content !== null &&
790
+ !reduceMotion(view) &&
791
+ skipOffscreenTravel(scroller, content, config.axis, extent);
792
+
793
+ const start = (): void => {
794
+ if (disposed || attempt !== enters) return;
795
+ scrollToRest(true);
796
+ // Listened for only once the smooth scroll has begun, so the jump's own
797
+ // `scrollend` does not end the entrance.
798
+ void waitFor(scroller, "scrollend").then(() => {
799
+ if (skipped) scroller.style.scrollSnapType = snapType;
800
+ if (disposed || attempt !== enters) return;
801
+ entered();
802
+ });
803
+ };
804
+
805
+ // A jump and a smooth scroll in the same task can leave the browser stuck
806
+ // at the jumped-to position.
807
+ if (config.enteredScroll === 0 || skipped) view.requestAnimationFrame(start);
808
+ else start();
809
+ };
810
+
811
+ const entered = (): void => {
812
+ setEntering(false);
813
+ const content = overlayRef()?.querySelector<HTMLElement>("[data-sheet-content]") ?? null;
814
+ if (content !== null && !contains(content, activeElement(ownerDocument(content)))) {
815
+ focusWithoutScrolling(content);
816
+ }
817
+ };
818
+
819
+ const exit = (): Promise<void> => {
820
+ enters++;
821
+ const overlay = overlayRef();
822
+ if (overlay === null) return Promise.resolve();
823
+ const scroller = overlay.querySelector<HTMLElement>("[data-sheet-scroll]");
824
+ const config = shared.config();
825
+
826
+ // An exit rule is selected by `data-exiting`, which the binding writes a
827
+ // flush from now. Measured a task later so the rule is in the cascade.
828
+ const animations = delay(0).then(() => {
829
+ const modal = modalRef();
830
+ const longest = Math.max(exitDuration(overlay), modal === null ? 0 : exitDuration(modal));
831
+ return longest > 0 ? delay(longest) : undefined;
832
+ });
833
+
834
+ let motion: Promise<void>;
835
+ if (!visible || scroller === null) {
836
+ // Swiped away already. Desktop Safari keeps the momentum going, and a
837
+ // scroll that outlives the sheet lands on the one behind it. A sheet
838
+ // never seen on screen was not swiped, and no `scrollend` is coming.
839
+ motion =
840
+ scroller !== null && seen && isSafari() && !isIOS()
841
+ ? waitFor(scroller, "scrollend").then(() => delay(50))
842
+ : Promise.resolve();
843
+ } else {
844
+ const extent = viewportExtent(overlay, config);
845
+ const furthest = (config.maxScroll / 100) * extent;
846
+ const at = config.axis === "y" ? scroller.scrollTop : scroller.scrollLeft;
847
+ const to =
848
+ config.after && !config.before
849
+ ? 0
850
+ : config.before && !config.after
851
+ ? furthest
852
+ : at > (config.enteredScroll / 100) * extent
853
+ ? furthest
854
+ : 0;
855
+ scrollAlongAxis(scroller, config.axis, to, true);
856
+ motion = new Promise((resolve) => hidden.push(resolve));
857
+ }
858
+
859
+ return Promise.all([motion, animations]).then(() => undefined);
860
+ };
861
+
862
+ shared.attach({ enter, exit });
863
+ onCleanup(() => {
864
+ disposed = true;
865
+ shared.attach(null);
866
+ });
867
+
868
+ onSettled(() => {
869
+ const overlay = overlayRef();
870
+ if (overlay === null) return undefined;
871
+ const doc = ownerDocument(overlay);
872
+ const view = ownerWindow(overlay);
873
+ const config = shared.config();
874
+ const scroller = overlay.querySelector<HTMLElement>("[data-sheet-scroll]");
875
+
876
+ // A sheet resting at scroll 0 mounts already entered. It is moved out
877
+ // before the observer looks, or the observer would see it entered and
878
+ // then close it when the entrance jumps it out.
879
+ if (config.enteredScroll === 0 && scroller !== null) {
880
+ scrollAlongAxis(
881
+ scroller,
882
+ config.axis,
883
+ (config.maxScroll / 100) * (config.axis === "y" ? view.innerHeight : view.innerWidth),
884
+ );
885
+ }
886
+
887
+ const observer =
888
+ typeof view.IntersectionObserver === "function"
889
+ ? new view.IntersectionObserver(
890
+ (entries) => {
891
+ const entry = entries[0];
892
+ if (entry === undefined) return;
893
+ // `data-expanded` lets a stylesheet make the content scroll only
894
+ // once the sheet is fully open; until then a swipe on the
895
+ // content grows the sheet, as on iOS.
896
+ setExpanded(entry.intersectionRatio >= 1);
897
+ visible = entry.intersectionRatio > 0;
898
+ seen ||= visible;
899
+ if (seen && entry.intersectionRatio <= 0) {
900
+ shared.state.close();
901
+ const waiting = hidden;
902
+ hidden = [];
903
+ for (const resolve of waiting) resolve();
904
+ }
905
+ },
906
+ {
907
+ threshold: [0, 1],
908
+ rootMargin: `0px 0px ${calcToPx(viewportPadding(config.after, config.axis), doc)} 0px`,
909
+ },
910
+ )
911
+ : null;
912
+ const content = overlay.querySelector("[data-sheet-content]");
913
+ if (observer !== null && content !== null) observer.observe(content);
914
+
915
+ const unregister = registerSheet(
916
+ {
917
+ id: shared.id,
918
+ timelineName: shared.timelineName,
919
+ range: config.viewRange,
920
+ direction: config.viewDirection,
921
+ iterations: config.viewIterations,
922
+ },
923
+ doc,
924
+ );
925
+
926
+ const resize = (): void => {
927
+ const visual = view.visualViewport;
928
+ if (visual !== null && visual.scale > 1) return;
929
+ setViewport(measureViewport(doc));
930
+ };
931
+ const resizes: EventTarget = view.visualViewport ?? view;
932
+ resizes.addEventListener("resize", resize);
933
+ setViewport(measureViewport(doc));
934
+
935
+ enter();
936
+
937
+ return () => {
938
+ observer?.disconnect();
939
+ unregister();
940
+ resizes.removeEventListener("resize", resize);
941
+ };
942
+ });
943
+
944
+ const setModal = (element: HTMLDivElement | null): void => {
945
+ modalRef.set(element);
946
+ };
947
+
948
+ const value: SheetContextValue = {
949
+ config: shared.config,
950
+ position: shared.position,
951
+ swipeDirection: shared.swipeDirection,
952
+ snapPoints: shared.snapPoints,
953
+ preventDismissal: shared.preventDismissal,
954
+ isNonModal: shared.isNonModal,
955
+ isEntering,
956
+ isExiting: shared.isExiting,
957
+ timelineName: shared.timelineName,
958
+ descendants,
959
+ dataProps,
960
+ modalProps: mergeProps(overlayProps, modalProps),
961
+ setModal,
962
+ modal: modalRef,
963
+ state: renderState,
964
+ triggers: shared.triggers,
965
+ };
966
+
967
+ const style = (): Style => {
968
+ const box = viewport();
969
+ return {
970
+ // Absolute rather than fixed, or iOS Safari clips it.
971
+ position: "absolute",
972
+ top: 0,
973
+ left: 0,
974
+ width: "max(var(--page-width), 100vw)",
975
+ height: "max(var(--page-height), 100dvh)",
976
+ overflow: "clip",
977
+ pointerEvents: shared.isNonModal() ? "none" : undefined,
978
+ ...shared.style(),
979
+ "--sheet-scroll-padding-x": "calc(100vw - var(--visual-viewport-width))",
980
+ "--sheet-scroll-padding-y": "calc(100dvh - var(--visual-viewport-height))",
981
+ "--visual-viewport-width": box === null ? undefined : `${box.width}px`,
982
+ "--visual-viewport-height": box === null ? undefined : `${box.height}px`,
983
+ "--page-width": box === null ? undefined : `${box.pageWidth}px`,
984
+ "--page-height": box === null ? undefined : `${box.pageHeight}px`,
985
+ };
986
+ };
987
+
988
+ const elementProps = mergeProps(shared.domProps, dataProps, {
989
+ class: shared.className,
990
+ style,
991
+ "data-entering": () => (isEntering() ? "" : undefined),
992
+ "data-exiting": () => (shared.isExiting() ? "" : undefined),
993
+ });
994
+
995
+ return (
996
+ <div {...elementProps} ref={mergeRefs(overlayRef.set, shared.ref)}>
997
+ <span hidden ref={scope.startRef} />
998
+ <SheetProvider value={value}>{renderChildren(props.children, renderState)}</SheetProvider>
999
+ <span hidden ref={scope.endRef} />
1000
+ </div>
1001
+ );
1002
+ }
1003
+
1004
+ // ---------------------------------------------------------------------------
1005
+ // Swipe animations
1006
+ // ---------------------------------------------------------------------------
1007
+
1008
+ interface SwipeAnimationProps {
1009
+ /** A CSS `@keyframes` name, played from exited to entered as the sheet moves. */
1010
+ swipeAnimation?: string;
1011
+ /**
1012
+ * The snap points, by index, between which it plays.
1013
+ * @default the whole of the sheet's travel
1014
+ */
1015
+ swipeAnimationRange?: { start?: number; end?: number };
1016
+ }
1017
+
1018
+ function swipeAnimationStyle(
1019
+ sheet: SheetContextValue,
1020
+ animation: string | undefined,
1021
+ range: { start?: number; end?: number } | undefined,
1022
+ ): Style {
1023
+ if (animation === undefined || animation === "") return {};
1024
+ const direction = sheet.swipeDirection();
1025
+ const config = sheet.config();
1026
+ const points = sheet.snapPoints();
1027
+
1028
+ let start = range?.start === undefined ? "0%" : toLength(points?.[range.start] ?? "0%");
1029
+ let end = range?.end === undefined ? "100%" : toLength(points?.[range.end] ?? "100%");
1030
+ if (direction === "top" || direction === "left") {
1031
+ [start, end] = [`calc(100% - ${end})`, `calc(100% - ${start})`];
1032
+ }
1033
+
1034
+ if (supportsViewTimeline()) {
1035
+ return {
1036
+ animationName: animation,
1037
+ animationTimeline: sheet.timelineName,
1038
+ animationDirection: config.viewDirection,
1039
+ animationIterationCount: String(config.viewIterations),
1040
+ animationFillMode: "both",
1041
+ animationRange: `${config.viewRange} ${start} ${config.viewRange} ${end}`,
1042
+ animationTimingFunction: "linear",
1043
+ animationComposition: "replace",
1044
+ };
1045
+ }
1046
+ const exiting = sheet.isExiting();
1047
+ if (!sheet.isEntering() && !exiting) return {};
1048
+ return {
1049
+ animationName: animation,
1050
+ animationDirection: exiting ? "reverse" : "normal",
1051
+ animationDuration: "300ms",
1052
+ animationIterationCount: "1",
1053
+ animationFillMode: "both",
1054
+ animationTimingFunction: "linear",
1055
+ animationComposition: "replace",
1056
+ };
1057
+ }
1058
+
1059
+ // ---------------------------------------------------------------------------
1060
+ // Sheet
1061
+ // ---------------------------------------------------------------------------
1062
+
1063
+ export interface SheetProps extends StyleProps, SwipeAnimationProps {
1064
+ children?: Child | ((state: SheetRenderState) => Child);
1065
+ /**
1066
+ * A CSS `@keyframes` name played once for every sheet open in front of this
1067
+ * one, on that sheet's swipe, so a stack recedes as it grows.
1068
+ */
1069
+ stackAnimation?: string;
1070
+ /** Pad the sheet past the viewport edge, so a rubber-band pull shows more sheet. */
1071
+ overscrollPadding?: boolean;
1072
+ ref?: RefTarget<HTMLDivElement>;
1073
+ }
1074
+
1075
+ /**
1076
+ * The surface that slides, inside the scroll container that moves it.
1077
+ *
1078
+ * Its element is the modal: what Escape is heard on, what a press outside is
1079
+ * measured against, and what stays visible while the page behind is hidden.
1080
+ */
1081
+ export function Sheet(props: SheetProps) {
1082
+ const sheet = useSheetContext("Sheet");
1083
+ const options = fromProps(cells(props));
1084
+ const locale = useLocale();
1085
+ const scrollRef = makeRef<HTMLDivElement>();
1086
+ const stageRef = makeRef<HTMLDivElement>();
1087
+ const config = sheet.config;
1088
+
1089
+ const viewport = (): string => (config().axis === "y" ? "100dvh" : "100dvw");
1090
+ const isTransitioning = (): boolean => sheet.isEntering() || sheet.isExiting();
1091
+ const hasSnapPoints = (): boolean =>
1092
+ (sheet.snapPoints()?.length ?? 0) > 0 && config().before !== config().after;
1093
+ // Enter and exit still need the room to leave, so the clamp holds only while
1094
+ // the sheet is at rest.
1095
+ const isClamped = (): boolean => sheet.preventDismissal() && !isTransitioning();
1096
+
1097
+ const travel = snapPointTravel(stageRef, sheet.modal, config, () =>
1098
+ sheet.preventDismissal() && hasSnapPoints() ? (sheet.snapPoints() ?? []).join(" ") : null,
1099
+ );
1100
+ // At least 1px, so there is still somewhere to scroll and the browser still
1101
+ // bounces when there is nowhere to snap to.
1102
+ const clampedTravel = (): string => `${hasSnapPoints() ? Math.max(1, travel()) : 1}px`;
1103
+
1104
+ const stageStart = (): string => {
1105
+ const { after, axis } = config();
1106
+ return isClamped() && after
1107
+ ? clampedTravel()
1108
+ : `calc(${viewport()} + ${viewportPadding(after, axis)})`;
1109
+ };
1110
+ const endMarker = (): string => {
1111
+ const { before, after } = config();
1112
+ if (isClamped() && before && after) return `calc(${stageStart()} + ${viewport()} + 1px)`;
1113
+ if (isClamped() && before) return `calc(${clampedTravel()} + ${viewport()})`;
1114
+ return `calc(${stageStart()} + ${viewport()}${before && after ? ` + ${viewport()}` : ""})`;
1115
+ };
1116
+
1117
+ // The clamped geometry moves the stage. The scroll position moves with it,
1118
+ // so the sheet stays where it was on screen.
1119
+ let stageOffset: number | null = null;
1120
+ let wasClamped = untrack(isClamped);
1121
+ createEffect(
1122
+ () => [isClamped(), stageStart(), stageRef(), scrollRef(), config().axis] as const,
1123
+ ([clamped, , stage, scroller, axis]) => {
1124
+ if (stage === null || scroller === null) return;
1125
+ const vertical = axis === "y";
1126
+ const offset = vertical ? stage.offsetTop : stage.offsetLeft;
1127
+ if (clamped !== wasClamped && stageOffset !== null && offset !== stageOffset) {
1128
+ if (vertical) scroller.scrollTop += offset - stageOffset;
1129
+ else scroller.scrollLeft += offset - stageOffset;
1130
+ }
1131
+ wasClamped = clamped;
1132
+ stageOffset = offset;
1133
+ },
1134
+ );
1135
+
1136
+ const overscrollInset = (): string | undefined =>
1137
+ props.overscrollPadding === true && sheet.position() === sheet.swipeDirection()
1138
+ ? config().axis === "y"
1139
+ ? "100vh"
1140
+ : "100vw"
1141
+ : undefined;
1142
+
1143
+ const ownStyle = (): Style => {
1144
+ const style: Style = {
1145
+ position: "relative",
1146
+ pointerEvents: sheet.isNonModal() ? "auto" : undefined,
1147
+ ...swipeAnimationStyle(sheet, props.swipeAnimation, props.swipeAnimationRange),
1148
+ };
1149
+
1150
+ const inset = overscrollInset();
1151
+ if (inset !== undefined) {
1152
+ const side = sheet.position();
1153
+ const edge = side.charAt(0).toUpperCase() + side.slice(1);
1154
+ style[`padding${edge}`] = inset;
1155
+ style[`margin${edge}`] = `-${inset}`;
1156
+ }
1157
+
1158
+ const stacked = sheet.descendants();
1159
+ if (props.stackAnimation && stacked.length > 0 && supportsViewTimeline()) {
1160
+ const name = props.stackAnimation;
1161
+ const perSheet: Record<string, (entry: StackEntry) => string> = {
1162
+ animationName: () => name,
1163
+ animationTimeline: (entry) => entry.timelineName,
1164
+ animationDirection: (entry) => entry.direction,
1165
+ animationIterationCount: (entry) => String(entry.iterations),
1166
+ animationFillMode: () => "both",
1167
+ animationRange: (entry) => entry.range,
1168
+ animationComposition: () => "accumulate",
1169
+ animationTimingFunction: () => "linear",
1170
+ };
1171
+ for (const [key, value] of Object.entries(perSheet)) {
1172
+ style[key] = [style[key], ...stacked.map(value)].filter(Boolean).join(", ");
1173
+ }
1174
+ }
1175
+ return style;
1176
+ };
1177
+
1178
+ const scrollerStyle = (): Style => {
1179
+ const { axis, containerOffset } = config();
1180
+ const view = typeof window === "undefined" ? null : window;
1181
+ const scrollX = view === null ? 0 : untrack(() => view.scrollX);
1182
+ const scrollY = view === null ? 0 : untrack(() => view.scrollY);
1183
+ return {
1184
+ position: "absolute",
1185
+ top: axis === "y" ? `calc(${scrollY}px + ${containerOffset}dvh)` : `${scrollY}px`,
1186
+ left: axis === "x" ? `calc(${scrollX}px + ${containerOffset}dvw)` : `${scrollX}px`,
1187
+ height: axis === "y" ? "200dvh" : "100dvh",
1188
+ width: axis === "x" ? "200dvw" : "100dvw",
1189
+ overflowX: axis === "x" ? "auto" : "hidden",
1190
+ overflowY: axis === "y" ? "auto" : "hidden",
1191
+ // Only off while a sheet that cannot be dismissed changes geometry.
1192
+ // Changing it during a swipe away cancels Safari's momentum scroll
1193
+ // without the `scrollend` the exit waits for.
1194
+ scrollSnapType: sheet.preventDismissal() && isTransitioning() ? "none" : `${axis} mandatory`,
1195
+ overscrollBehaviorY: axis === "y" ? "contain" : "none",
1196
+ overscrollBehaviorX: axis === "x" ? "contain" : "none",
1197
+ scrollbarWidth: "none",
1198
+ // The scroll geometry is physical whatever the reading direction.
1199
+ direction: "ltr",
1200
+ };
1201
+ };
1202
+
1203
+ const stageStyle = (): Style => {
1204
+ const { axis } = config();
1205
+ const [x, y] = POSITION_ALIGNMENT[sheet.position()];
1206
+ return {
1207
+ position: "absolute",
1208
+ top: axis === "y" ? stageStart() : 0,
1209
+ left: axis === "x" ? stageStart() : 0,
1210
+ height: "100dvh",
1211
+ width: "100dvw",
1212
+ display: "flex",
1213
+ flexDirection: axis === "y" ? "column" : "row",
1214
+ alignItems: axis === "y" ? x : y,
1215
+ justifyContent: axis === "y" ? y : x,
1216
+ };
1217
+ };
1218
+
1219
+ const markersStyle = (): Style => {
1220
+ const inset = overscrollInset();
1221
+ return {
1222
+ position: "absolute",
1223
+ inset: 0,
1224
+ ...(inset === undefined ? null : { [sheet.position()]: inset }),
1225
+ pointerEvents: "none",
1226
+ };
1227
+ };
1228
+
1229
+ const elementProps = mergeProps(
1230
+ sheet.modalProps,
1231
+ filterDOMProps(options, { global: true }),
1232
+ sheet.dataProps,
1233
+ {
1234
+ class: () => props.class ?? props.className,
1235
+ style: () => ({ direction: locale().direction, ...props.style, ...ownStyle() }),
1236
+ "data-entering": () => (sheet.isEntering() ? "" : undefined),
1237
+ "data-exiting": () => (sheet.isExiting() ? "" : undefined),
1238
+ },
1239
+ );
1240
+
1241
+ const scrollerProps: DOMProps = { "data-sheet-scroll": "", style: scrollerStyle };
1242
+ const dismissProps = dismissButtonProps(() => sheet.state.close());
1243
+ const stageProps: DOMProps = { style: stageStyle };
1244
+ const markersProps: DOMProps = { style: markersStyle };
1245
+
1246
+ return (
1247
+ <div {...scrollerProps} ref={scrollRef.set}>
1248
+ <SnapPoint
1249
+ point={0}
1250
+ align={isClamped() && config().after ? "none" : "start"}
1251
+ axis={config().axis}
1252
+ />
1253
+ <Show when={config().before && config().after}>
1254
+ <SnapPoint point={stageStart()} align="start" axis={config().axis} />
1255
+ </Show>
1256
+ <div {...stageProps} ref={stageRef.set}>
1257
+ <div {...elementProps} ref={mergeRefs(sheet.setModal, props.ref)}>
1258
+ <Show when={!sheet.preventDismissal() && !sheet.isNonModal()}>
1259
+ <button type="button" {...dismissProps} />
1260
+ </Show>
1261
+ <Show when={sheet.snapPoints()}>
1262
+ <div {...markersProps}>
1263
+ <For each={sheet.snapPoints() ?? []} keyed={false}>
1264
+ {(point, index) => (
1265
+ <DetentPoint
1266
+ point={point()}
1267
+ axis={config().axis}
1268
+ after={config().after}
1269
+ isInitial={index === 0}
1270
+ />
1271
+ )}
1272
+ </For>
1273
+ </div>
1274
+ </Show>
1275
+ {renderChildren(props.children, sheet.state)}
1276
+ </div>
1277
+ </div>
1278
+ <SnapPoint
1279
+ point={endMarker()}
1280
+ align={isClamped() && config().before ? "none" : "end"}
1281
+ axis={config().axis}
1282
+ />
1283
+ </div>
1284
+ );
1285
+ }
1286
+
1287
+ /** A full viewport long, so its start or end edge lands on the snap position. */
1288
+ function SnapPoint(props: { point: SheetSnapPoint; align: "start" | "end" | "none"; axis: Axis }) {
1289
+ const style = (): Style => {
1290
+ const offset = toLength(props.point);
1291
+ const main = props.axis === "y" ? "dvh" : "dvw";
1292
+ return {
1293
+ position: "absolute",
1294
+ top: props.axis === "y" ? offset : 0,
1295
+ left: props.axis === "x" ? offset : 0,
1296
+ scrollSnapAlign: props.align,
1297
+ width: props.axis === "x" ? `100${main}` : "1px",
1298
+ height: props.axis === "y" ? `100${main}` : "1px",
1299
+ };
1300
+ };
1301
+ const elementProps: DOMProps = { style };
1302
+ return <div {...elementProps} />;
1303
+ }
1304
+
1305
+ /**
1306
+ * A snap marker inside the sheet, `point` in from its leading edge.
1307
+ *
1308
+ * It moves with the sheet, so snapping it with a scroll margin of one viewport
1309
+ * rests it at the viewport's edge with exactly `point` of the sheet on screen.
1310
+ * The point is an inset rather than part of the margin, which is what makes a
1311
+ * percentage one of the sheet's size.
1312
+ */
1313
+ function DetentPoint(props: {
1314
+ point: SheetSnapPoint;
1315
+ axis: Axis;
1316
+ after: boolean;
1317
+ isInitial: boolean;
1318
+ }) {
1319
+ const style = (): Style => {
1320
+ const viewport = props.axis === "y" ? "100dvh" : "100dvw";
1321
+ const offset = toLength(props.point);
1322
+ const edge: Style =
1323
+ props.axis === "y"
1324
+ ? props.after
1325
+ ? { top: offset, left: 0, scrollMarginTop: viewport }
1326
+ : { bottom: offset, left: 0, scrollMarginBottom: viewport }
1327
+ : props.after
1328
+ ? { top: 0, left: offset, scrollMarginLeft: viewport }
1329
+ : { top: 0, right: offset, scrollMarginRight: viewport };
1330
+ return {
1331
+ position: "absolute",
1332
+ width: "1px",
1333
+ height: "1px",
1334
+ scrollSnapAlign: props.after ? "start" : "end",
1335
+ ...edge,
1336
+ };
1337
+ };
1338
+ const elementProps: DOMProps = {
1339
+ "data-sheet-detent": "",
1340
+ "data-sheet-initial": () => (props.isInitial ? "" : undefined),
1341
+ style,
1342
+ };
1343
+ return <div {...elementProps} />;
1344
+ }
1345
+
1346
+ /**
1347
+ * How far a sheet that cannot be dismissed travels from its smallest snap
1348
+ * point to fully open: from that point's marker to the stage's exit edge.
1349
+ *
1350
+ * Measured from the rendered markers, so a snap point may be any CSS length,
1351
+ * and from layout offsets rather than boxes, so a swipe or stack transform
1352
+ * does not move the answer.
1353
+ */
1354
+ function snapPointTravel(
1355
+ stage: Accessor<HTMLElement | null>,
1356
+ sheet: Accessor<HTMLElement | null>,
1357
+ config: Accessor<SwipeConfig>,
1358
+ key: Accessor<string | null>,
1359
+ ): Accessor<number> {
1360
+ const [travel, setTravel] = createSignal(0);
1361
+
1362
+ followOpen(
1363
+ () => [key(), stage(), sheet(), config().axis, config().after] as const,
1364
+ ([points, stageElement, sheetElement, axis, after]) => {
1365
+ if (points === null || stageElement === null || sheetElement === null) return undefined;
1366
+
1367
+ const measure = (): void => {
1368
+ const stageSize = axis === "y" ? stageElement.clientHeight : stageElement.clientWidth;
1369
+ let max = 0;
1370
+ for (const marker of sheetElement.querySelectorAll<HTMLElement>("[data-sheet-detent]")) {
1371
+ let offset = 0;
1372
+ let at: HTMLElement | null = marker;
1373
+ while (at !== null && at !== stageElement) {
1374
+ offset += axis === "y" ? at.offsetTop : at.offsetLeft;
1375
+ at = (at.offsetParent as HTMLElement | null) ?? null;
1376
+ }
1377
+ const size = axis === "y" ? marker.offsetHeight : marker.offsetWidth;
1378
+ max = Math.max(max, after ? stageSize - offset : offset + size);
1379
+ }
1380
+ setTravel(max);
1381
+ };
1382
+
1383
+ measure();
1384
+ const view = ownerWindow(stageElement);
1385
+ if (typeof view.ResizeObserver !== "function") return undefined;
1386
+ const observer = new view.ResizeObserver(measure);
1387
+ observer.observe(stageElement);
1388
+ observer.observe(sheetElement);
1389
+ return () => observer.disconnect();
1390
+ },
1391
+ );
1392
+
1393
+ return travel;
1394
+ }
1395
+
1396
+ // ---------------------------------------------------------------------------
1397
+ // SheetBackdrop
1398
+ // ---------------------------------------------------------------------------
1399
+
1400
+ export interface SheetBackdropProps extends StyleProps, SwipeAnimationProps {
1401
+ ref?: RefTarget<HTMLDivElement>;
1402
+ }
1403
+
1404
+ /** What covers the page behind the sheet. A press on it is a press outside. */
1405
+ export function SheetBackdrop(props: SheetBackdropProps) {
1406
+ const sheet = useSheetContext("SheetBackdrop");
1407
+ const options = fromProps(cells(props));
1408
+
1409
+ const elementProps = mergeProps(filterDOMProps(options, { global: true }), sheet.dataProps, {
1410
+ class: () => props.class ?? props.className,
1411
+ style: () => ({
1412
+ ...swipeAnimationStyle(sheet, props.swipeAnimation, props.swipeAnimationRange),
1413
+ position: "absolute",
1414
+ inset: 0,
1415
+ ...props.style,
1416
+ }),
1417
+ "data-entering": () => (sheet.isEntering() ? "" : undefined),
1418
+ "data-exiting": () => (sheet.isExiting() ? "" : undefined),
1419
+ });
1420
+
1421
+ return <div {...elementProps} ref={mergeRefs(props.ref)} />;
1422
+ }
1423
+
1424
+ // ---------------------------------------------------------------------------
1425
+ // SheetContent
1426
+ // ---------------------------------------------------------------------------
1427
+
1428
+ export interface SheetContentProps extends Omit<DialogComponentProps, "children"> {
1429
+ children?: Child | ((state: SheetRenderState) => Child);
1430
+ }
1431
+
1432
+ /**
1433
+ * The dialog inside the sheet, and the subject of the view timeline every
1434
+ * swipe and stack animation runs on.
1435
+ *
1436
+ * The timeline is the content's rather than the sheet's because overscroll
1437
+ * padding leaves the sheet never wholly on screen. The inset crops the scroll
1438
+ * container down to the viewport that is actually visible.
1439
+ */
1440
+ export function SheetContent(props: SheetContentProps) {
1441
+ const sheet = useSheetContext("SheetContent");
1442
+
1443
+ const style = (): Style => {
1444
+ const { axis, before, after } = sheet.config();
1445
+ const viewport = axis === "y" ? "100dvh" : "100dvw";
1446
+ return {
1447
+ ...props.style,
1448
+ width: "100%",
1449
+ height: "100%",
1450
+ viewTimelineName: sheet.timelineName,
1451
+ viewTimelineAxis: axis,
1452
+ viewTimelineInset: before && !after ? `${viewport} 0` : `0 ${viewport}`,
1453
+ };
1454
+ };
1455
+
1456
+ return (
1457
+ <Dialog {...omit(props, "children", "style")} style={style()} data-sheet-content="">
1458
+ {renderChildren(props.children, sheet.state)}
1459
+ </Dialog>
1460
+ );
1461
+ }