@luxalgo/vela-ui 0.3.0 → 0.4.0

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 (167) hide show
  1. package/CHANGELOG.md +153 -132
  2. package/LICENSE +201 -201
  3. package/NOTICE +28 -28
  4. package/README.md +86 -86
  5. package/cli/engine.mjs +282 -282
  6. package/cli/index.mjs +154 -154
  7. package/dist/callout-bubble.js +2 -2
  8. package/dist/checkbox.js +2 -2
  9. package/dist/{chunk-KKS6NEGI.js → chunk-BWSOMG3G.js} +1 -1
  10. package/dist/chunk-GUIYFQ27.js +30 -0
  11. package/dist/{chunk-B2EZB5ZG.js → chunk-KUWTI2PE.js} +2 -2
  12. package/dist/{chunk-WWHNUKSZ.js → chunk-QGWAN3EP.js} +2 -2
  13. package/dist/{chunk-TBXUF5YX.js → chunk-RH53NQGE.js} +18 -4
  14. package/dist/{chunk-IOOYDSSK.js → chunk-SKFAYTDK.js} +1 -1
  15. package/dist/{chunk-OQXFQMZM.js → chunk-TGJNHUYV.js} +2 -2
  16. package/dist/{chunk-UEO6W37Z.js → chunk-VC7SVSDK.js} +1 -1
  17. package/dist/{chunk-OJ2SEMN6.js → chunk-YT2BSP7O.js} +1 -1
  18. package/dist/collapsible.js +1 -1
  19. package/dist/color-picker.js +4 -4
  20. package/dist/context-menu.js +3 -3
  21. package/dist/dialog.js +3 -3
  22. package/dist/donut.d.ts +1 -1
  23. package/dist/drawer.js +1 -1
  24. package/dist/dropdown-menu.js +3 -3
  25. package/dist/field.js +8 -8
  26. package/dist/{stat.d.ts → figure.d.ts} +9 -9
  27. package/dist/figure.js +41 -0
  28. package/dist/glyph-select.js +3 -3
  29. package/dist/index.d.ts +2 -2
  30. package/dist/index.js +1 -1
  31. package/dist/manifest.json +74 -74
  32. package/dist/number-input.js +2 -2
  33. package/dist/popover.js +2 -2
  34. package/dist/select.d.ts +1 -1
  35. package/dist/select.js +4 -4
  36. package/dist/slider.js +1 -1
  37. package/dist/sort-button.js +1 -1
  38. package/dist/switch.js +1 -1
  39. package/dist/tabs.js +1 -1
  40. package/dist/{theme-Ct-q58xz.d.ts → theme-TefB8vtl.d.ts} +2 -2
  41. package/dist/theme.d.ts +2 -2
  42. package/dist/theme.js +1 -1
  43. package/dist/theme.schema.json +30 -30
  44. package/dist/toast.d.ts +2 -2
  45. package/dist/toast.js +1 -1
  46. package/dist/toggle-group.js +1 -1
  47. package/dist/tooltip.js +1 -1
  48. package/dist/zag.d.ts +11 -2
  49. package/dist/zag.js +1 -1
  50. package/docs/theming.md +217 -217
  51. package/docs/what-to-change.md +20 -20
  52. package/docs/writing-a-component.md +250 -250
  53. package/llms.txt +3 -3
  54. package/package.json +90 -90
  55. package/registry/badge.ts +119 -119
  56. package/registry/bar-chart.ts +215 -215
  57. package/registry/button.ts +387 -387
  58. package/registry/callout-bubble.ts +347 -347
  59. package/registry/card.ts +379 -379
  60. package/registry/checkbox.ts +234 -234
  61. package/registry/collapsible.ts +271 -271
  62. package/registry/color-picker.ts +582 -582
  63. package/registry/context-menu.ts +208 -208
  64. package/registry/data-table.ts +215 -215
  65. package/registry/date-picker.ts +483 -483
  66. package/registry/dialog.ts +551 -551
  67. package/registry/donut.ts +145 -145
  68. package/registry/drawer.ts +636 -636
  69. package/registry/dropdown-menu.ts +762 -762
  70. package/registry/empty.ts +91 -91
  71. package/registry/field.ts +584 -584
  72. package/registry/{stat.ts → figure.ts} +96 -96
  73. package/registry/glyph-select.ts +268 -268
  74. package/registry/hover-card.ts +222 -222
  75. package/registry/input-group.ts +229 -229
  76. package/registry/input.ts +181 -181
  77. package/registry/item.ts +376 -376
  78. package/registry/kbd.ts +64 -64
  79. package/registry/line-chart.ts +218 -218
  80. package/registry/month-grid.ts +328 -328
  81. package/registry/number-input.ts +443 -443
  82. package/registry/popover.ts +368 -368
  83. package/registry/scatter-chart.ts +221 -221
  84. package/registry/select.ts +620 -620
  85. package/registry/slider.ts +259 -259
  86. package/registry/sort-button.ts +189 -189
  87. package/registry/sparkline.ts +114 -114
  88. package/registry/switch.ts +205 -205
  89. package/registry/tabs.ts +426 -426
  90. package/registry/text-area.ts +186 -186
  91. package/registry/toast.ts +965 -965
  92. package/registry/toggle-group.ts +295 -295
  93. package/registry/tooltip.ts +156 -156
  94. package/registry/treemap.ts +847 -847
  95. package/skills/theming-vela-ui/SKILL.md +137 -137
  96. package/skills/using-vela-ui-components/SKILL.md +139 -139
  97. package/skills/writing-vela-ui-components/SKILL.md +163 -163
  98. package/src/components/badge.ts +119 -119
  99. package/src/components/bar-chart.ts +215 -215
  100. package/src/components/button.ts +387 -387
  101. package/src/components/callout-bubble.ts +347 -347
  102. package/src/components/card.ts +379 -379
  103. package/src/components/checkbox.ts +234 -234
  104. package/src/components/collapsible.ts +271 -271
  105. package/src/components/color-picker.ts +582 -582
  106. package/src/components/context-menu.ts +208 -208
  107. package/src/components/data-table.ts +215 -215
  108. package/src/components/date-picker.ts +483 -483
  109. package/src/components/dialog.ts +551 -551
  110. package/src/components/donut.ts +145 -145
  111. package/src/components/drawer.ts +636 -636
  112. package/src/components/dropdown-menu.ts +762 -762
  113. package/src/components/empty.ts +91 -91
  114. package/src/components/field.ts +584 -584
  115. package/src/components/{stat.ts → figure.ts} +96 -96
  116. package/src/components/glyph-select.ts +268 -268
  117. package/src/components/hover-card.ts +222 -222
  118. package/src/components/input-group.ts +229 -229
  119. package/src/components/input.ts +181 -181
  120. package/src/components/item.ts +376 -376
  121. package/src/components/kbd.ts +64 -64
  122. package/src/components/line-chart.ts +218 -218
  123. package/src/components/month-grid.ts +328 -328
  124. package/src/components/number-input.ts +443 -443
  125. package/src/components/popover.ts +368 -368
  126. package/src/components/scatter-chart.ts +221 -221
  127. package/src/components/select.ts +620 -620
  128. package/src/components/slider.ts +259 -259
  129. package/src/components/sort-button.ts +189 -189
  130. package/src/components/sparkline.ts +114 -114
  131. package/src/components/switch.ts +205 -205
  132. package/src/components/tabs.ts +426 -426
  133. package/src/components/text-area.ts +186 -186
  134. package/src/components/toast.ts +965 -965
  135. package/src/components/toggle-group.ts +295 -295
  136. package/src/components/tooltip.ts +156 -156
  137. package/src/components/treemap.ts +847 -847
  138. package/src/index.ts +24 -24
  139. package/src/lib/calendar.ts +117 -117
  140. package/src/lib/chart.ts +72 -72
  141. package/src/lib/color.ts +89 -89
  142. package/src/lib/component-index.ts +163 -163
  143. package/src/lib/css.ts +48 -48
  144. package/src/lib/define.ts +45 -45
  145. package/src/lib/dispose.ts +36 -36
  146. package/src/lib/h.ts +55 -55
  147. package/src/lib/headless.ts +16 -16
  148. package/src/lib/i18n.ts +30 -30
  149. package/src/lib/icons.ts +244 -244
  150. package/src/lib/kit-text.ts +26 -26
  151. package/src/lib/page.ts +24 -24
  152. package/src/lib/palette.ts +81 -81
  153. package/src/lib/placement.ts +188 -188
  154. package/src/lib/scope.ts +135 -135
  155. package/src/lib/styles.ts +53 -53
  156. package/src/lib/surface-events.ts +31 -31
  157. package/src/lib/surface-exit.ts +87 -87
  158. package/src/lib/t.ts +68 -68
  159. package/src/lib/theme.ts +684 -670
  160. package/src/lib/tokens.ts +110 -110
  161. package/src/lib/variants.ts +32 -32
  162. package/src/lib/zag.ts +61 -46
  163. package/stylelint/index.mjs +60 -60
  164. package/stylelint/lint.mjs +81 -81
  165. package/stylelint/plugin.mjs +115 -115
  166. package/dist/chunk-P4MTEMT7.js +0 -23
  167. package/dist/stat.js +0 -41
@@ -1,636 +1,636 @@
1
- // Drawer: a bottom sheet. A dimmed backdrop, a panel that slides up from the host's bottom
2
- // edge, and a grab handle with drag-to-dismiss; the body is the caller's. It rides Zag's
3
- // dialog machine (focus trap, dismissal, ARIA) with drawer defaults: a backdrop tap
4
- // dismisses. Built for the mobile chrome, but host-agnostic like every kit component.
5
- import * as dialog from '@zag-js/dialog';
6
- import { css, defineStyles } from '../lib/css';
7
- import { defineComponent } from '../lib/define';
8
- import { disposeWithin } from '../lib/dispose';
9
- import { t } from '../lib/t';
10
- import { announceSurface } from '../lib/surface-events';
11
- import { holdForExit, type SurfaceExit } from '../lib/surface-exit';
12
- import { nextUid, normalizeProps, runMachine, spreadProps, type HandleOf } from '../lib/zag';
13
-
14
- export interface DrawerControllerOptions {
15
- closeOnEscape?: boolean;
16
- /** Tap outside (on the backdrop) dismisses — default true. */
17
- closeOnInteractOutside?: boolean;
18
- /** Element to focus on open (default: the machine's first-tabbable pick). The view
19
- * points this at the sheet itself so opening never focuses an input — on touch
20
- * devices that would pop the on-screen keyboard over the sheet. */
21
- initialFocusEl?: () => HTMLElement | null;
22
- onOpenChange?: (open: boolean) => void;
23
- }
24
-
25
- export type DrawerService = dialog.Service;
26
- export type DrawerApi = dialog.Api;
27
-
28
- export interface DrawerController {
29
- machine: typeof dialog.machine;
30
- props: Partial<dialog.Props>;
31
- connect(service: DrawerService): DrawerApi;
32
- }
33
-
34
- /** Zag's dialog machine with the drawer's defaults, for any view layer. */
35
- export function drawerController(opts: DrawerControllerOptions = {}): DrawerController {
36
- return {
37
- machine: dialog.machine,
38
- props: {
39
- id: nextUid('vela-drawer'),
40
- modal: true,
41
- closeOnEscape: opts.closeOnEscape ?? true,
42
- closeOnInteractOutside: opts.closeOnInteractOutside ?? true,
43
- initialFocusEl: opts.initialFocusEl,
44
- onOpenChange: (d: dialog.OpenChangeDetails) => opts.onOpenChange?.(d.open),
45
- } satisfies Partial<dialog.Props>,
46
- connect: (service: DrawerService): DrawerApi => dialog.connect(service, normalizeProps),
47
- };
48
- }
49
-
50
- export const drawerDef = defineComponent({
51
- name: 'drawer',
52
- parts: ['backdrop', 'positioner', 'content', 'grab', 'title', 'body'],
53
- settings: { radius: '14px 14px 0 0', 'edge-radius': '14px', 'side-width': 'min(75%, 360px)', 'grab-radius': '2px' },
54
- });
55
-
56
- const injectStyles = defineStyles(
57
- 'vela-ui-drawer',
58
- css`
59
- @layer vela.ui {
60
- [data-slot='drawer-backdrop'] {
61
- position: fixed;
62
- inset: 0;
63
- background: ${t.backdrop};
64
- z-index: ${t.z.dialog};
65
-
66
- /* Inside a shell that declares a size class, the sheet scopes to the SHELL's
67
- bounds (the widget root is position:relative) instead of the whole viewport:
68
- an embedded chart must not curtain the host page. */
69
- &:is([data-layout] *) {
70
- position: absolute;
71
- }
72
- }
73
- [data-slot='drawer-positioner'] {
74
- position: fixed;
75
- inset: 0;
76
- display: flex;
77
- align-items: flex-end;
78
- justify-content: center;
79
- z-index: ${t.z.dialog};
80
-
81
- &:is([data-layout] *) {
82
- position: absolute;
83
- }
84
- }
85
- [data-slot='drawer-content'] {
86
- background: ${t.surface};
87
- color: ${t.fg};
88
- border: 1px solid ${t.border.strong};
89
- border-bottom: none;
90
- border-radius: ${drawerDef.vars.radius};
91
- box-shadow: ${t.shadow.dialog};
92
- font-size: 13px;
93
- width: 100%;
94
- max-height: 85%;
95
- display: flex;
96
- flex-direction: column;
97
- overflow: hidden;
98
- outline: 2px solid transparent;
99
-
100
- &[data-state='open'] {
101
- animation: vela-drawer-in ${t.dur.med} ${t.ease};
102
- }
103
- &[data-direction='top'] {
104
- border: 1px solid ${t.border.strong};
105
- border-top: none;
106
- border-radius: 0;
107
- border-end-start-radius: ${drawerDef.vars['edge-radius']};
108
- border-end-end-radius: ${drawerDef.vars['edge-radius']};
109
- }
110
- &[data-direction='left'],
111
- &[data-direction='right'] {
112
- border: 1px solid ${t.border.strong};
113
- border-radius: 0;
114
- width: ${drawerDef.vars['side-width']};
115
- max-height: none;
116
- height: 100%;
117
- }
118
- &[data-direction='right'] {
119
- border-inline-end: none;
120
- border-start-start-radius: ${drawerDef.vars['edge-radius']};
121
- border-end-start-radius: ${drawerDef.vars['edge-radius']};
122
- }
123
- &[data-direction='left'] {
124
- border-inline-start: none;
125
- border-start-end-radius: ${drawerDef.vars['edge-radius']};
126
- border-end-end-radius: ${drawerDef.vars['edge-radius']};
127
- }
128
- &[data-direction='top'][data-state='open'] {
129
- animation-name: vela-drawer-in-top;
130
- }
131
- &[data-direction='right'][data-state='open'] {
132
- animation-name: vela-drawer-in-right;
133
- }
134
- &[data-direction='left'][data-state='open'] {
135
- animation-name: vela-drawer-in-left;
136
- }
137
- /* A side drawer's right is the inline end: it mirrors in right-to-left layouts. */
138
- &[data-direction='right'][data-state='open']:dir(rtl) {
139
- animation-name: vela-drawer-in-left;
140
- }
141
- &[data-direction='left'][data-state='open']:dir(rtl) {
142
- animation-name: vela-drawer-in-right;
143
- }
144
- }
145
- [data-slot='drawer-positioner'][data-direction='top'] {
146
- align-items: flex-start;
147
- }
148
- [data-slot='drawer-positioner'][data-direction='right'] {
149
- align-items: stretch;
150
- justify-content: flex-end;
151
- }
152
- [data-slot='drawer-positioner'][data-direction='left'] {
153
- align-items: stretch;
154
- justify-content: flex-start;
155
- }
156
- @keyframes vela-drawer-in {
157
- from {
158
- transform: translateY(100%);
159
- }
160
- to {
161
- transform: translateY(0);
162
- }
163
- }
164
- @keyframes vela-drawer-in-top {
165
- from {
166
- transform: translateY(-100%);
167
- }
168
- to {
169
- transform: translateY(0);
170
- }
171
- }
172
- @keyframes vela-drawer-in-right {
173
- from {
174
- transform: translateX(100%);
175
- }
176
- to {
177
- transform: translateX(0);
178
- }
179
- }
180
- @keyframes vela-drawer-in-left {
181
- from {
182
- transform: translateX(-100%);
183
- }
184
- to {
185
- transform: translateX(0);
186
- }
187
- }
188
- /* The grab zone owns its touches (drag-to-dismiss), so the browser must not scroll it. */
189
- [data-slot='drawer-grab'] {
190
- flex: none;
191
- display: flex;
192
- align-items: center;
193
- justify-content: center;
194
- padding: 10px 0 6px;
195
- cursor: grab;
196
- touch-action: none;
197
- user-select: none;
198
-
199
- &::before {
200
- content: '';
201
- width: 36px;
202
- height: 4px;
203
- border-radius: ${drawerDef.vars['grab-radius']};
204
- background: ${t.border.strong};
205
- }
206
- }
207
- /* A top sheet's handle sits on its inner (lower) edge; a side drawer drags anywhere. */
208
- [data-slot='drawer-content'][data-direction='top'] [data-slot='drawer-grab'] {
209
- order: 1;
210
- padding: 6px 0 10px;
211
- }
212
- [data-slot='drawer-content']:is([data-direction='left'], [data-direction='right']) [data-slot='drawer-grab'] {
213
- display: none;
214
- }
215
- [data-slot='drawer-title'] {
216
- flex: none;
217
- padding: 0 16px 10px;
218
- font-size: 15px;
219
- font-weight: 600;
220
- letter-spacing: 0.2px;
221
- color: ${t.fg.bright};
222
- user-select: none;
223
-
224
- &:empty {
225
- display: none;
226
- }
227
- }
228
- [data-slot='drawer-body'] {
229
- flex: 1 1 auto;
230
- min-height: 0;
231
- overflow-y: auto;
232
- overscroll-behavior: contain;
233
- -webkit-overflow-scrolling: touch;
234
- /* Vertical pans stay native scrolling; horizontal moves reach the sheet's
235
- gesture recognizer as pointer events (tab swipes). Without this the browser
236
- claims a sideways touch as a scroll attempt and CANCELS the pointer stream,
237
- so swipes never registered on real touch devices. Sideways-scrolling strips
238
- inside the body opt back in with their own touch-action: pan-x. */
239
- touch-action: pan-y;
240
- padding: 0 ${t.space[3]} calc(${t.space[3]} + env(safe-area-inset-bottom, 0px));
241
- }
242
- }
243
- `,
244
- );
245
- /** Drag past this fraction of the sheet's height (or this many px, whichever is
246
- * smaller) and the release dismisses; anything less springs back. */
247
- const DISMISS_FRACTION = 0.33;
248
- const DISMISS_PX = 96;
249
- /** Movement below this is a tap; past it the gesture commits to a direction. */
250
- const SLOP_PX = 8;
251
- /** A horizontal swipe must travel at least this far to fire `onSwipe`. */
252
- const HSWIPE_MIN_PX = 48;
253
-
254
- export type DrawerProps = DrawerOptions;
255
-
256
- export type DrawerDirection = 'top' | 'right' | 'bottom' | 'left';
257
-
258
- export interface DrawerOptions extends DrawerControllerOptions {
259
- /** The edge it slides in from (default `'bottom'`, a bottom sheet). A drag toward that
260
- * edge dismisses it. */
261
- direction?: DrawerDirection;
262
- title?: string;
263
- content?: Node | ((body: HTMLElement) => void);
264
- host?: HTMLElement;
265
- /** Horizontal swipe across the sheet (fires on release; `'left'` = the finger moved
266
- * left). Gestures that start inside a horizontally scrollable strip (tabs, chip
267
- * rows) keep their native scroll instead. */
268
- onSwipe?: (dir: 'left' | 'right') => void;
269
- }
270
-
271
- /** What the active pointer gesture has committed to (decided once past the slop). */
272
- type GestureMode = 'idle' | 'pending' | 'drag' | 'hswipe' | 'scroll';
273
-
274
- /** How far a move goes toward the drawer's edge (its dismiss direction), and across it. A
275
- * side drawer's `right` is the inline end, so `mirrored` (right to left) flips it. */
276
- export function dismissAxis(dx: number, dy: number, direction: DrawerDirection, mirrored = false): { toward: number; across: number } {
277
- if (direction === 'bottom') return { toward: dy, across: dx };
278
- if (direction === 'top') return { toward: -dy, across: dx };
279
- const x = mirrored ? -dx : dx;
280
- return { toward: direction === 'right' ? x : -x, across: dy };
281
- }
282
-
283
- /**
284
- * Classify a pointer gesture over the sheet — PURE. `'pending'` until the movement
285
- * clears the slop; then a decided pull toward the drawer's edge (down for a bottom sheet)
286
- * becomes the dismiss `'drag'` (only while every scroller under the finger is at rest — a
287
- * scrolled list keeps native scrolling), a decidedly horizontal move on a top or bottom
288
- * sheet becomes an `'hswipe'` (when the sheet has a swipe handler and the finger is not on a
289
- * strip that scrolls sideways itself), and everything else stays native `'scroll'`.
290
- */
291
- export function classifyGesture(
292
- dx: number,
293
- dy: number,
294
- ctx: { canSwipe: boolean; scrolled: boolean; hScrollable: boolean },
295
- direction: DrawerDirection = 'bottom',
296
- mirrored = false,
297
- ): 'pending' | 'drag' | 'hswipe' | 'scroll' {
298
- if (Math.max(Math.abs(dx), Math.abs(dy)) < SLOP_PX) return 'pending';
299
- const { toward, across } = dismissAxis(dx, dy, direction, mirrored);
300
- if (Math.abs(toward) > Math.abs(across)) return toward > 0 && !ctx.scrolled ? 'drag' : 'scroll';
301
- const vertical = direction === 'top' || direction === 'bottom';
302
- return vertical && ctx.canSwipe && !ctx.hScrollable ? 'hswipe' : 'scroll';
303
- }
304
-
305
- /** Whether releasing a dismiss drag `d` px toward the edge closes the sheet, given the
306
- * sheet's size along that axis — PURE. */
307
- export function dragDismisses(d: number, panelSizePx: number): boolean {
308
- return d >= Math.min(DISMISS_PX, panelSizePx * DISMISS_FRACTION);
309
- }
310
-
311
- /** The direction a released horizontal swipe fires, or null when it was too short
312
- * (or more vertical than horizontal after all) — PURE. */
313
- export function swipeDirection(dx: number, dy: number): 'left' | 'right' | null {
314
- if (Math.abs(dx) < HSWIPE_MIN_PX || Math.abs(dx) <= Math.abs(dy)) return null;
315
- return dx < 0 ? 'left' : 'right';
316
- }
317
-
318
- export class Drawer {
319
- /** Caller-owned content area — append your rows/lists here. */
320
- readonly body: HTMLElement;
321
- private readonly backdrop: HTMLElement;
322
- private readonly positioner: HTMLElement;
323
- private readonly panel: HTMLElement;
324
- private readonly titleEl: HTMLElement;
325
- private readonly handle: HandleOf<typeof dialog.machine>;
326
- private readonly ctrl: DrawerController;
327
- private readonly direction: DrawerDirection;
328
-
329
- constructor(opts: DrawerOptions = {}) {
330
- const doc = (opts.host ?? document.body).ownerDocument;
331
- injectStyles(doc);
332
- const host = opts.host ?? doc.body;
333
-
334
- this.backdrop = doc.createElement('div');
335
- this.backdrop.className = 'vela-drawer-backdrop vela-ui-layer';
336
- this.backdrop.dataset.slot = drawerDef.slot('backdrop');
337
- this.positioner = doc.createElement('div');
338
- this.positioner.className = 'vela-drawer-positioner vela-ui-layer';
339
- this.positioner.dataset.slot = drawerDef.slot('positioner');
340
- this.panel = doc.createElement('div');
341
- this.panel.className = 'vela-drawer';
342
- this.panel.dataset.slot = drawerDef.slot('content');
343
- // Programmatically focusable: the sheet itself takes the dialog machine's initial
344
- // focus — focusing the first tabbable (often a search input) would pop the
345
- // on-screen keyboard over a surface that just slid in.
346
- this.panel.tabIndex = -1;
347
-
348
- const grab = doc.createElement('div');
349
- grab.className = 'vela-drawer-grab';
350
- grab.dataset.slot = drawerDef.slot('grab');
351
- this.titleEl = doc.createElement('div');
352
- this.titleEl.className = 'vela-drawer-title';
353
- this.titleEl.dataset.slot = drawerDef.slot('title');
354
- this.titleEl.textContent = opts.title ?? '';
355
-
356
- this.body = doc.createElement('div');
357
- this.body.className = 'vela-drawer-body';
358
- this.body.dataset.slot = drawerDef.slot('body');
359
- if (opts.content instanceof Node) this.body.appendChild(opts.content);
360
- else if (typeof opts.content === 'function') opts.content(this.body);
361
-
362
- this.direction = opts.direction ?? 'bottom';
363
- if (this.direction !== 'bottom') {
364
- this.positioner.dataset.direction = this.direction;
365
- this.panel.dataset.direction = this.direction;
366
- }
367
- this.panel.append(grab, this.titleEl, this.body);
368
- this.positioner.appendChild(this.panel);
369
- host.append(this.backdrop, this.positioner);
370
- this.wireGestures(grab, opts.onSwipe);
371
-
372
- this.ctrl = drawerController({ ...opts, initialFocusEl: () => this.panel });
373
- const mid = String(this.ctrl.props.id);
374
- this.handle = runMachine(this.ctrl.machine, this.ctrl.props, (service) => {
375
- const api = this.ctrl.connect(service);
376
- // Close announces while the panel still shows (before the close props land), open once it does.
377
- const closing = this.wasOpen && !api.open;
378
- if (closing) this.announce(false);
379
- spreadProps(this.backdrop, api.getBackdropProps(), mid);
380
- spreadProps(this.positioner, api.getPositionerProps(), mid);
381
- spreadProps(this.panel, api.getContentProps(), mid);
382
- spreadProps(this.titleEl, api.getTitleProps(), mid);
383
- // Dialog-family machines expect conditional rendering (their `hidden` reaches the
384
- // panel and backdrop only, and the sheet's authored display beats it) — the view
385
- // toggles visibility from `api.open` itself, once the exit animation of a close has run.
386
- if (api.open) {
387
- this.exit?.cancel();
388
- this.exit = null;
389
- this.setShown(true);
390
- } else if (closing) {
391
- this.holdExit();
392
- } else if (!this.exit) {
393
- this.setShown(false);
394
- }
395
- if (api.open && !this.wasOpen) this.announce(true);
396
- if (this.wasOpen && !api.open) this.restoreOpener();
397
- this.wasOpen = api.open;
398
- });
399
- }
400
-
401
- /** Any element between `from` and the panel that has already been scrolled down —
402
- * a downward pull there must scroll it back up, never drag the sheet. */
403
- private scrolledAncestor(from: EventTarget | null): boolean {
404
- let el = from instanceof Element ? from : null;
405
- while (el && el !== this.panel) {
406
- if (el.scrollTop > 0) return true;
407
- el = el.parentElement;
408
- }
409
- return false;
410
- }
411
-
412
- /** Any element between `from` and the panel that a pull toward this drawer's edge would
413
- * scroll instead: scrolled down (bottom sheet), not at its end (top sheet), or scrolling
414
- * sideways (side drawers). */
415
- private scrollsTowardEdge(from: EventTarget | null): boolean {
416
- if (this.direction === 'bottom') return this.scrolledAncestor(from);
417
- if (this.direction !== 'top') return this.hScrollableAncestor(from);
418
- let el = from instanceof Element ? from : null;
419
- while (el && el !== this.panel) {
420
- if (el.scrollTop + el.clientHeight < el.scrollHeight - 1) return true;
421
- el = el.parentElement;
422
- }
423
- return false;
424
- }
425
-
426
- /** Any element between `from` and the panel that scrolls horizontally on its own
427
- * (the tab strip, chip rows) — a sideways move there is ITS scroll, not a swipe. */
428
- private hScrollableAncestor(from: EventTarget | null): boolean {
429
- let el = from instanceof Element ? from : null;
430
- while (el && el !== this.panel) {
431
- if (el.scrollWidth > el.clientWidth + 1) return true;
432
- el = el.parentElement;
433
- }
434
- return false;
435
- }
436
-
437
- /**
438
- * One gesture recognizer for the whole sheet. A downward pull dismisses from
439
- * anywhere — the grab handle immediately, the content once it is decidedly vertical
440
- * and its scroller is at rest (a scrolled list keeps native scrolling). A decidedly
441
- * horizontal move becomes an `onSwipe` (tabbed drawers flip pages with it). The
442
- * non-passive touchmove hook is what keeps the browser from claiming the pull as a
443
- * scroll once the sheet is (or may become) the drag target.
444
- */
445
- private wireGestures(grab: HTMLElement, onSwipe?: (dir: 'left' | 'right') => void): void {
446
- let startX = 0;
447
- let startY = 0;
448
- let dx = 0;
449
- let dy = 0;
450
- let d = 0;
451
- let mirrored = false;
452
- let mode: GestureMode = 'idle';
453
- const dir = this.direction;
454
- const vertical = dir === 'top' || dir === 'bottom';
455
-
456
- const beginDrag = (e: PointerEvent): void => {
457
- mode = 'drag';
458
- // Rebase so the sheet tracks from the commit point instead of jumping by the slop.
459
- startX = e.clientX;
460
- startY = e.clientY;
461
- this.panel.style.transition = 'none';
462
- try {
463
- this.panel.setPointerCapture(e.pointerId);
464
- } catch {
465
- /* detached target or a test double without capture support */
466
- }
467
- };
468
-
469
- this.panel.addEventListener('pointerdown', (e) => {
470
- if (e.isPrimary === false) return;
471
- startX = e.clientX;
472
- startY = e.clientY;
473
- dx = 0;
474
- dy = 0;
475
- d = 0;
476
- mirrored = !vertical && getComputedStyle(this.panel).direction === 'rtl';
477
- // The handle is a dedicated dismiss affordance (touch-action:none) — no slop.
478
- if (grab.contains(e.target as Node)) beginDrag(e);
479
- else mode = 'pending';
480
- });
481
-
482
- this.panel.addEventListener('pointermove', (e) => {
483
- if (mode === 'idle' || mode === 'scroll') return;
484
- dx = e.clientX - startX;
485
- dy = e.clientY - startY;
486
- if (mode === 'pending') {
487
- const intent = classifyGesture(
488
- dx,
489
- dy,
490
- {
491
- canSwipe: !!onSwipe,
492
- scrolled: this.scrollsTowardEdge(e.target),
493
- hScrollable: this.hScrollableAncestor(e.target),
494
- },
495
- dir,
496
- mirrored,
497
- );
498
- if (intent === 'pending') return;
499
- if (intent === 'drag') beginDrag(e);
500
- else mode = intent;
501
- }
502
- if (mode === 'drag') {
503
- d = Math.max(0, dismissAxis(e.clientX - startX, e.clientY - startY, dir, mirrored).toward);
504
- const shift = dir === 'bottom' ? d : dir === 'top' ? -d : (dir === 'right') !== mirrored ? d : -d;
505
- this.panel.style.transform = d > 0 ? (vertical ? `translateY(${shift}px)` : `translateX(${shift}px)`) : '';
506
- }
507
- });
508
-
509
- // Keep the browser's scroll logic off a pull the sheet owns (or may still claim):
510
- // without preventDefault here, the scroller grabs the touch and cancels the
511
- // pointer stream before the drag can commit. Only downward pulls on an at-rest
512
- // scroller are blocked — everything else keeps native behavior.
513
- this.panel.addEventListener(
514
- 'touchmove',
515
- (e) => {
516
- if (mode === 'drag' || mode === 'hswipe') {
517
- e.preventDefault();
518
- return;
519
- }
520
- if (mode !== 'pending') return;
521
- const t = e.touches[0];
522
- if (!t) return;
523
- const { toward, across } = dismissAxis(t.clientX - startX, t.clientY - startY, dir, mirrored);
524
- if (toward > Math.abs(across) && !this.scrollsTowardEdge(e.target)) e.preventDefault();
525
- },
526
- { passive: false },
527
- );
528
-
529
- const settle = (): void => {
530
- if (mode === 'idle') return;
531
- const finished = mode;
532
- mode = 'idle';
533
- if (finished === 'drag') {
534
- this.panel.style.transition = '';
535
- this.panel.style.transform = '';
536
- const box = this.panel.getBoundingClientRect();
537
- if (dragDismisses(d, vertical ? box.height : box.width)) this.hide();
538
- } else if (finished === 'hswipe') {
539
- const dir = swipeDirection(dx, dy);
540
- if (dir) onSwipe?.(dir);
541
- }
542
- };
543
- this.panel.addEventListener('pointerup', settle);
544
- this.panel.addEventListener('pointercancel', settle);
545
- }
546
-
547
- setTitle(title: string): void {
548
- this.titleEl.textContent = title;
549
- }
550
-
551
- private opener: HTMLElement | null = null;
552
- private wasOpen = false;
553
- /** The sheet and scrim's exit animation after a close; a reopen cancels it. */
554
- private exit: SurfaceExit | null = null;
555
- private destroyed = false;
556
-
557
- private setShown(shown: boolean): void {
558
- this.backdrop.style.display = shown ? '' : 'none';
559
- this.positioner.style.display = shown ? '' : 'none';
560
- }
561
-
562
- /** Keep the just-closed sheet up through its exit animation, then hide it — or
563
- * remove it, when it was destroyed meanwhile. `spreadProps` re-applies the close
564
- * props' `hidden` only when its value changes, so lifting it keeps the sheet and
565
- * scrim up until the exit ends. The positioner spans the host: inert, it lets
566
- * clicks through to the page while the sheet animates out. */
567
- private holdExit(): void {
568
- const held = [this.panel, this.backdrop];
569
- for (const el of held) el.hidden = false;
570
- this.exit = holdForExit(
571
- held,
572
- () => {
573
- this.exit = null;
574
- if (this.destroyed) {
575
- this.detach();
576
- } else if (!this.open) {
577
- for (const el of held) el.hidden = true;
578
- this.setShown(false);
579
- }
580
- },
581
- { inert: [this.positioner] },
582
- );
583
- }
584
-
585
- private detach(): void {
586
- this.backdrop.remove();
587
- this.positioner.remove();
588
- }
589
-
590
- /** Closing hands focus back to whatever opened it (Escape, the ✕, hide(), or a
591
- * teardown that outruns the machine's close notification). */
592
- private restoreOpener(): void {
593
- const opener = this.opener;
594
- this.opener = null;
595
- if (opener?.isConnected) opener.focus({ preventScroll: true });
596
- }
597
-
598
- private announce(open: boolean): void {
599
- const opener = this.opener === this.panel.ownerDocument.body ? null : this.opener;
600
- announceSurface(this.panel, open, 'drawer', opener);
601
- }
602
-
603
- get open(): boolean {
604
- return this.ctrl.connect(this.handle.service).open;
605
- }
606
-
607
- show(): void {
608
- this.opener = this.panel.ownerDocument.activeElement as HTMLElement | null;
609
- this.ctrl.connect(this.handle.service).setOpen(true);
610
- }
611
-
612
- hide(): void {
613
- this.ctrl.connect(this.handle.service).setOpen(false);
614
- }
615
-
616
- destroy(): void {
617
- // Closed but not projected yet — an owner disposing of the sheet as it reports
618
- // closing: project the close now, so it animates out like any other close and
619
- // leaves the DOM when its exit ends. A teardown while open leaves at once.
620
- if (this.wasOpen && !this.open) this.handle.flush();
621
- this.handle.stop();
622
- this.destroyed = true;
623
- // Torn down while open: the stopped machine never projects the close.
624
- if (this.wasOpen) {
625
- this.wasOpen = false;
626
- this.announce(false);
627
- }
628
- this.restoreOpener();
629
- disposeWithin(this.panel);
630
- if (!this.exit) this.detach();
631
- }
632
- }
633
-
634
- export function createDrawer(props: DrawerProps = {}): Drawer {
635
- return new Drawer(props);
636
- }
1
+ // Drawer: a bottom sheet. A dimmed backdrop, a panel that slides up from the host's bottom
2
+ // edge, and a grab handle with drag-to-dismiss; the body is the caller's. It rides Zag's
3
+ // dialog machine (focus trap, dismissal, ARIA) with drawer defaults: a backdrop tap
4
+ // dismisses. Built for the mobile chrome, but host-agnostic like every kit component.
5
+ import * as dialog from '@zag-js/dialog';
6
+ import { css, defineStyles } from '../lib/css';
7
+ import { defineComponent } from '../lib/define';
8
+ import { disposeWithin } from '../lib/dispose';
9
+ import { t } from '../lib/t';
10
+ import { announceSurface } from '../lib/surface-events';
11
+ import { holdForExit, type SurfaceExit } from '../lib/surface-exit';
12
+ import { nextUid, normalizeProps, runMachine, spreadProps, type HandleOf } from '../lib/zag';
13
+
14
+ export interface DrawerControllerOptions {
15
+ closeOnEscape?: boolean;
16
+ /** Tap outside (on the backdrop) dismisses — default true. */
17
+ closeOnInteractOutside?: boolean;
18
+ /** Element to focus on open (default: the machine's first-tabbable pick). The view
19
+ * points this at the sheet itself so opening never focuses an input — on touch
20
+ * devices that would pop the on-screen keyboard over the sheet. */
21
+ initialFocusEl?: () => HTMLElement | null;
22
+ onOpenChange?: (open: boolean) => void;
23
+ }
24
+
25
+ export type DrawerService = dialog.Service;
26
+ export type DrawerApi = dialog.Api;
27
+
28
+ export interface DrawerController {
29
+ machine: typeof dialog.machine;
30
+ props: Partial<dialog.Props>;
31
+ connect(service: DrawerService): DrawerApi;
32
+ }
33
+
34
+ /** Zag's dialog machine with the drawer's defaults, for any view layer. */
35
+ export function drawerController(opts: DrawerControllerOptions = {}): DrawerController {
36
+ return {
37
+ machine: dialog.machine,
38
+ props: {
39
+ id: nextUid('vela-drawer'),
40
+ modal: true,
41
+ closeOnEscape: opts.closeOnEscape ?? true,
42
+ closeOnInteractOutside: opts.closeOnInteractOutside ?? true,
43
+ initialFocusEl: opts.initialFocusEl,
44
+ onOpenChange: (d: dialog.OpenChangeDetails) => opts.onOpenChange?.(d.open),
45
+ } satisfies Partial<dialog.Props>,
46
+ connect: (service: DrawerService): DrawerApi => dialog.connect(service, normalizeProps),
47
+ };
48
+ }
49
+
50
+ export const drawerDef = defineComponent({
51
+ name: 'drawer',
52
+ parts: ['backdrop', 'positioner', 'content', 'grab', 'title', 'body'],
53
+ settings: { radius: '14px 14px 0 0', 'edge-radius': '14px', 'side-width': 'min(75%, 360px)', 'grab-radius': '2px' },
54
+ });
55
+
56
+ const injectStyles = defineStyles(
57
+ 'vela-ui-drawer',
58
+ css`
59
+ @layer vela.ui {
60
+ [data-slot='drawer-backdrop'] {
61
+ position: fixed;
62
+ inset: 0;
63
+ background: ${t.backdrop};
64
+ z-index: ${t.z.dialog};
65
+
66
+ /* Inside a shell that declares a size class, the sheet scopes to the SHELL's
67
+ bounds (the widget root is position:relative) instead of the whole viewport:
68
+ an embedded chart must not curtain the host page. */
69
+ &:is([data-layout] *) {
70
+ position: absolute;
71
+ }
72
+ }
73
+ [data-slot='drawer-positioner'] {
74
+ position: fixed;
75
+ inset: 0;
76
+ display: flex;
77
+ align-items: flex-end;
78
+ justify-content: center;
79
+ z-index: ${t.z.dialog};
80
+
81
+ &:is([data-layout] *) {
82
+ position: absolute;
83
+ }
84
+ }
85
+ [data-slot='drawer-content'] {
86
+ background: ${t.surface};
87
+ color: ${t.fg};
88
+ border: 1px solid ${t.border.strong};
89
+ border-bottom: none;
90
+ border-radius: ${drawerDef.vars.radius};
91
+ box-shadow: ${t.shadow.dialog};
92
+ font-size: 13px;
93
+ width: 100%;
94
+ max-height: 85%;
95
+ display: flex;
96
+ flex-direction: column;
97
+ overflow: hidden;
98
+ outline: 2px solid transparent;
99
+
100
+ &[data-state='open'] {
101
+ animation: vela-drawer-in ${t.dur.med} ${t.ease};
102
+ }
103
+ &[data-direction='top'] {
104
+ border: 1px solid ${t.border.strong};
105
+ border-top: none;
106
+ border-radius: 0;
107
+ border-end-start-radius: ${drawerDef.vars['edge-radius']};
108
+ border-end-end-radius: ${drawerDef.vars['edge-radius']};
109
+ }
110
+ &[data-direction='left'],
111
+ &[data-direction='right'] {
112
+ border: 1px solid ${t.border.strong};
113
+ border-radius: 0;
114
+ width: ${drawerDef.vars['side-width']};
115
+ max-height: none;
116
+ height: 100%;
117
+ }
118
+ &[data-direction='right'] {
119
+ border-inline-end: none;
120
+ border-start-start-radius: ${drawerDef.vars['edge-radius']};
121
+ border-end-start-radius: ${drawerDef.vars['edge-radius']};
122
+ }
123
+ &[data-direction='left'] {
124
+ border-inline-start: none;
125
+ border-start-end-radius: ${drawerDef.vars['edge-radius']};
126
+ border-end-end-radius: ${drawerDef.vars['edge-radius']};
127
+ }
128
+ &[data-direction='top'][data-state='open'] {
129
+ animation-name: vela-drawer-in-top;
130
+ }
131
+ &[data-direction='right'][data-state='open'] {
132
+ animation-name: vela-drawer-in-right;
133
+ }
134
+ &[data-direction='left'][data-state='open'] {
135
+ animation-name: vela-drawer-in-left;
136
+ }
137
+ /* A side drawer's right is the inline end: it mirrors in right-to-left layouts. */
138
+ &[data-direction='right'][data-state='open']:dir(rtl) {
139
+ animation-name: vela-drawer-in-left;
140
+ }
141
+ &[data-direction='left'][data-state='open']:dir(rtl) {
142
+ animation-name: vela-drawer-in-right;
143
+ }
144
+ }
145
+ [data-slot='drawer-positioner'][data-direction='top'] {
146
+ align-items: flex-start;
147
+ }
148
+ [data-slot='drawer-positioner'][data-direction='right'] {
149
+ align-items: stretch;
150
+ justify-content: flex-end;
151
+ }
152
+ [data-slot='drawer-positioner'][data-direction='left'] {
153
+ align-items: stretch;
154
+ justify-content: flex-start;
155
+ }
156
+ @keyframes vela-drawer-in {
157
+ from {
158
+ transform: translateY(100%);
159
+ }
160
+ to {
161
+ transform: translateY(0);
162
+ }
163
+ }
164
+ @keyframes vela-drawer-in-top {
165
+ from {
166
+ transform: translateY(-100%);
167
+ }
168
+ to {
169
+ transform: translateY(0);
170
+ }
171
+ }
172
+ @keyframes vela-drawer-in-right {
173
+ from {
174
+ transform: translateX(100%);
175
+ }
176
+ to {
177
+ transform: translateX(0);
178
+ }
179
+ }
180
+ @keyframes vela-drawer-in-left {
181
+ from {
182
+ transform: translateX(-100%);
183
+ }
184
+ to {
185
+ transform: translateX(0);
186
+ }
187
+ }
188
+ /* The grab zone owns its touches (drag-to-dismiss), so the browser must not scroll it. */
189
+ [data-slot='drawer-grab'] {
190
+ flex: none;
191
+ display: flex;
192
+ align-items: center;
193
+ justify-content: center;
194
+ padding: 10px 0 6px;
195
+ cursor: grab;
196
+ touch-action: none;
197
+ user-select: none;
198
+
199
+ &::before {
200
+ content: '';
201
+ width: 36px;
202
+ height: 4px;
203
+ border-radius: ${drawerDef.vars['grab-radius']};
204
+ background: ${t.border.strong};
205
+ }
206
+ }
207
+ /* A top sheet's handle sits on its inner (lower) edge; a side drawer drags anywhere. */
208
+ [data-slot='drawer-content'][data-direction='top'] [data-slot='drawer-grab'] {
209
+ order: 1;
210
+ padding: 6px 0 10px;
211
+ }
212
+ [data-slot='drawer-content']:is([data-direction='left'], [data-direction='right']) [data-slot='drawer-grab'] {
213
+ display: none;
214
+ }
215
+ [data-slot='drawer-title'] {
216
+ flex: none;
217
+ padding: 0 16px 10px;
218
+ font-size: 15px;
219
+ font-weight: 600;
220
+ letter-spacing: 0.2px;
221
+ color: ${t.fg.bright};
222
+ user-select: none;
223
+
224
+ &:empty {
225
+ display: none;
226
+ }
227
+ }
228
+ [data-slot='drawer-body'] {
229
+ flex: 1 1 auto;
230
+ min-height: 0;
231
+ overflow-y: auto;
232
+ overscroll-behavior: contain;
233
+ -webkit-overflow-scrolling: touch;
234
+ /* Vertical pans stay native scrolling; horizontal moves reach the sheet's
235
+ gesture recognizer as pointer events (tab swipes). Without this the browser
236
+ claims a sideways touch as a scroll attempt and CANCELS the pointer stream,
237
+ so swipes never registered on real touch devices. Sideways-scrolling strips
238
+ inside the body opt back in with their own touch-action: pan-x. */
239
+ touch-action: pan-y;
240
+ padding: 0 ${t.space[3]} calc(${t.space[3]} + env(safe-area-inset-bottom, 0px));
241
+ }
242
+ }
243
+ `,
244
+ );
245
+ /** Drag past this fraction of the sheet's height (or this many px, whichever is
246
+ * smaller) and the release dismisses; anything less springs back. */
247
+ const DISMISS_FRACTION = 0.33;
248
+ const DISMISS_PX = 96;
249
+ /** Movement below this is a tap; past it the gesture commits to a direction. */
250
+ const SLOP_PX = 8;
251
+ /** A horizontal swipe must travel at least this far to fire `onSwipe`. */
252
+ const HSWIPE_MIN_PX = 48;
253
+
254
+ export type DrawerProps = DrawerOptions;
255
+
256
+ export type DrawerDirection = 'top' | 'right' | 'bottom' | 'left';
257
+
258
+ export interface DrawerOptions extends DrawerControllerOptions {
259
+ /** The edge it slides in from (default `'bottom'`, a bottom sheet). A drag toward that
260
+ * edge dismisses it. */
261
+ direction?: DrawerDirection;
262
+ title?: string;
263
+ content?: Node | ((body: HTMLElement) => void);
264
+ host?: HTMLElement;
265
+ /** Horizontal swipe across the sheet (fires on release; `'left'` = the finger moved
266
+ * left). Gestures that start inside a horizontally scrollable strip (tabs, chip
267
+ * rows) keep their native scroll instead. */
268
+ onSwipe?: (dir: 'left' | 'right') => void;
269
+ }
270
+
271
+ /** What the active pointer gesture has committed to (decided once past the slop). */
272
+ type GestureMode = 'idle' | 'pending' | 'drag' | 'hswipe' | 'scroll';
273
+
274
+ /** How far a move goes toward the drawer's edge (its dismiss direction), and across it. A
275
+ * side drawer's `right` is the inline end, so `mirrored` (right to left) flips it. */
276
+ export function dismissAxis(dx: number, dy: number, direction: DrawerDirection, mirrored = false): { toward: number; across: number } {
277
+ if (direction === 'bottom') return { toward: dy, across: dx };
278
+ if (direction === 'top') return { toward: -dy, across: dx };
279
+ const x = mirrored ? -dx : dx;
280
+ return { toward: direction === 'right' ? x : -x, across: dy };
281
+ }
282
+
283
+ /**
284
+ * Classify a pointer gesture over the sheet — PURE. `'pending'` until the movement
285
+ * clears the slop; then a decided pull toward the drawer's edge (down for a bottom sheet)
286
+ * becomes the dismiss `'drag'` (only while every scroller under the finger is at rest — a
287
+ * scrolled list keeps native scrolling), a decidedly horizontal move on a top or bottom
288
+ * sheet becomes an `'hswipe'` (when the sheet has a swipe handler and the finger is not on a
289
+ * strip that scrolls sideways itself), and everything else stays native `'scroll'`.
290
+ */
291
+ export function classifyGesture(
292
+ dx: number,
293
+ dy: number,
294
+ ctx: { canSwipe: boolean; scrolled: boolean; hScrollable: boolean },
295
+ direction: DrawerDirection = 'bottom',
296
+ mirrored = false,
297
+ ): 'pending' | 'drag' | 'hswipe' | 'scroll' {
298
+ if (Math.max(Math.abs(dx), Math.abs(dy)) < SLOP_PX) return 'pending';
299
+ const { toward, across } = dismissAxis(dx, dy, direction, mirrored);
300
+ if (Math.abs(toward) > Math.abs(across)) return toward > 0 && !ctx.scrolled ? 'drag' : 'scroll';
301
+ const vertical = direction === 'top' || direction === 'bottom';
302
+ return vertical && ctx.canSwipe && !ctx.hScrollable ? 'hswipe' : 'scroll';
303
+ }
304
+
305
+ /** Whether releasing a dismiss drag `d` px toward the edge closes the sheet, given the
306
+ * sheet's size along that axis — PURE. */
307
+ export function dragDismisses(d: number, panelSizePx: number): boolean {
308
+ return d >= Math.min(DISMISS_PX, panelSizePx * DISMISS_FRACTION);
309
+ }
310
+
311
+ /** The direction a released horizontal swipe fires, or null when it was too short
312
+ * (or more vertical than horizontal after all) — PURE. */
313
+ export function swipeDirection(dx: number, dy: number): 'left' | 'right' | null {
314
+ if (Math.abs(dx) < HSWIPE_MIN_PX || Math.abs(dx) <= Math.abs(dy)) return null;
315
+ return dx < 0 ? 'left' : 'right';
316
+ }
317
+
318
+ export class Drawer {
319
+ /** Caller-owned content area — append your rows/lists here. */
320
+ readonly body: HTMLElement;
321
+ private readonly backdrop: HTMLElement;
322
+ private readonly positioner: HTMLElement;
323
+ private readonly panel: HTMLElement;
324
+ private readonly titleEl: HTMLElement;
325
+ private readonly handle: HandleOf<typeof dialog.machine>;
326
+ private readonly ctrl: DrawerController;
327
+ private readonly direction: DrawerDirection;
328
+
329
+ constructor(opts: DrawerOptions = {}) {
330
+ const doc = (opts.host ?? document.body).ownerDocument;
331
+ injectStyles(doc);
332
+ const host = opts.host ?? doc.body;
333
+
334
+ this.backdrop = doc.createElement('div');
335
+ this.backdrop.className = 'vela-drawer-backdrop vela-ui-layer';
336
+ this.backdrop.dataset.slot = drawerDef.slot('backdrop');
337
+ this.positioner = doc.createElement('div');
338
+ this.positioner.className = 'vela-drawer-positioner vela-ui-layer';
339
+ this.positioner.dataset.slot = drawerDef.slot('positioner');
340
+ this.panel = doc.createElement('div');
341
+ this.panel.className = 'vela-drawer';
342
+ this.panel.dataset.slot = drawerDef.slot('content');
343
+ // Programmatically focusable: the sheet itself takes the dialog machine's initial
344
+ // focus — focusing the first tabbable (often a search input) would pop the
345
+ // on-screen keyboard over a surface that just slid in.
346
+ this.panel.tabIndex = -1;
347
+
348
+ const grab = doc.createElement('div');
349
+ grab.className = 'vela-drawer-grab';
350
+ grab.dataset.slot = drawerDef.slot('grab');
351
+ this.titleEl = doc.createElement('div');
352
+ this.titleEl.className = 'vela-drawer-title';
353
+ this.titleEl.dataset.slot = drawerDef.slot('title');
354
+ this.titleEl.textContent = opts.title ?? '';
355
+
356
+ this.body = doc.createElement('div');
357
+ this.body.className = 'vela-drawer-body';
358
+ this.body.dataset.slot = drawerDef.slot('body');
359
+ if (opts.content instanceof Node) this.body.appendChild(opts.content);
360
+ else if (typeof opts.content === 'function') opts.content(this.body);
361
+
362
+ this.direction = opts.direction ?? 'bottom';
363
+ if (this.direction !== 'bottom') {
364
+ this.positioner.dataset.direction = this.direction;
365
+ this.panel.dataset.direction = this.direction;
366
+ }
367
+ this.panel.append(grab, this.titleEl, this.body);
368
+ this.positioner.appendChild(this.panel);
369
+ host.append(this.backdrop, this.positioner);
370
+ this.wireGestures(grab, opts.onSwipe);
371
+
372
+ this.ctrl = drawerController({ ...opts, initialFocusEl: () => this.panel });
373
+ const mid = String(this.ctrl.props.id);
374
+ this.handle = runMachine(this.ctrl.machine, this.ctrl.props, (service) => {
375
+ const api = this.ctrl.connect(service);
376
+ // Close announces while the panel still shows (before the close props land), open once it does.
377
+ const closing = this.wasOpen && !api.open;
378
+ if (closing) this.announce(false);
379
+ spreadProps(this.backdrop, api.getBackdropProps(), mid);
380
+ spreadProps(this.positioner, api.getPositionerProps(), mid);
381
+ spreadProps(this.panel, api.getContentProps(), mid);
382
+ spreadProps(this.titleEl, api.getTitleProps(), mid);
383
+ // Dialog-family machines expect conditional rendering (their `hidden` reaches the
384
+ // panel and backdrop only, and the sheet's authored display beats it) — the view
385
+ // toggles visibility from `api.open` itself, once the exit animation of a close has run.
386
+ if (api.open) {
387
+ this.exit?.cancel();
388
+ this.exit = null;
389
+ this.setShown(true);
390
+ } else if (closing) {
391
+ this.holdExit();
392
+ } else if (!this.exit) {
393
+ this.setShown(false);
394
+ }
395
+ if (api.open && !this.wasOpen) this.announce(true);
396
+ if (this.wasOpen && !api.open) this.restoreOpener();
397
+ this.wasOpen = api.open;
398
+ });
399
+ }
400
+
401
+ /** Any element between `from` and the panel that has already been scrolled down —
402
+ * a downward pull there must scroll it back up, never drag the sheet. */
403
+ private scrolledAncestor(from: EventTarget | null): boolean {
404
+ let el = from instanceof Element ? from : null;
405
+ while (el && el !== this.panel) {
406
+ if (el.scrollTop > 0) return true;
407
+ el = el.parentElement;
408
+ }
409
+ return false;
410
+ }
411
+
412
+ /** Any element between `from` and the panel that a pull toward this drawer's edge would
413
+ * scroll instead: scrolled down (bottom sheet), not at its end (top sheet), or scrolling
414
+ * sideways (side drawers). */
415
+ private scrollsTowardEdge(from: EventTarget | null): boolean {
416
+ if (this.direction === 'bottom') return this.scrolledAncestor(from);
417
+ if (this.direction !== 'top') return this.hScrollableAncestor(from);
418
+ let el = from instanceof Element ? from : null;
419
+ while (el && el !== this.panel) {
420
+ if (el.scrollTop + el.clientHeight < el.scrollHeight - 1) return true;
421
+ el = el.parentElement;
422
+ }
423
+ return false;
424
+ }
425
+
426
+ /** Any element between `from` and the panel that scrolls horizontally on its own
427
+ * (the tab strip, chip rows) — a sideways move there is ITS scroll, not a swipe. */
428
+ private hScrollableAncestor(from: EventTarget | null): boolean {
429
+ let el = from instanceof Element ? from : null;
430
+ while (el && el !== this.panel) {
431
+ if (el.scrollWidth > el.clientWidth + 1) return true;
432
+ el = el.parentElement;
433
+ }
434
+ return false;
435
+ }
436
+
437
+ /**
438
+ * One gesture recognizer for the whole sheet. A downward pull dismisses from
439
+ * anywhere — the grab handle immediately, the content once it is decidedly vertical
440
+ * and its scroller is at rest (a scrolled list keeps native scrolling). A decidedly
441
+ * horizontal move becomes an `onSwipe` (tabbed drawers flip pages with it). The
442
+ * non-passive touchmove hook is what keeps the browser from claiming the pull as a
443
+ * scroll once the sheet is (or may become) the drag target.
444
+ */
445
+ private wireGestures(grab: HTMLElement, onSwipe?: (dir: 'left' | 'right') => void): void {
446
+ let startX = 0;
447
+ let startY = 0;
448
+ let dx = 0;
449
+ let dy = 0;
450
+ let d = 0;
451
+ let mirrored = false;
452
+ let mode: GestureMode = 'idle';
453
+ const dir = this.direction;
454
+ const vertical = dir === 'top' || dir === 'bottom';
455
+
456
+ const beginDrag = (e: PointerEvent): void => {
457
+ mode = 'drag';
458
+ // Rebase so the sheet tracks from the commit point instead of jumping by the slop.
459
+ startX = e.clientX;
460
+ startY = e.clientY;
461
+ this.panel.style.transition = 'none';
462
+ try {
463
+ this.panel.setPointerCapture(e.pointerId);
464
+ } catch {
465
+ /* detached target or a test double without capture support */
466
+ }
467
+ };
468
+
469
+ this.panel.addEventListener('pointerdown', (e) => {
470
+ if (e.isPrimary === false) return;
471
+ startX = e.clientX;
472
+ startY = e.clientY;
473
+ dx = 0;
474
+ dy = 0;
475
+ d = 0;
476
+ mirrored = !vertical && getComputedStyle(this.panel).direction === 'rtl';
477
+ // The handle is a dedicated dismiss affordance (touch-action:none) — no slop.
478
+ if (grab.contains(e.target as Node)) beginDrag(e);
479
+ else mode = 'pending';
480
+ });
481
+
482
+ this.panel.addEventListener('pointermove', (e) => {
483
+ if (mode === 'idle' || mode === 'scroll') return;
484
+ dx = e.clientX - startX;
485
+ dy = e.clientY - startY;
486
+ if (mode === 'pending') {
487
+ const intent = classifyGesture(
488
+ dx,
489
+ dy,
490
+ {
491
+ canSwipe: !!onSwipe,
492
+ scrolled: this.scrollsTowardEdge(e.target),
493
+ hScrollable: this.hScrollableAncestor(e.target),
494
+ },
495
+ dir,
496
+ mirrored,
497
+ );
498
+ if (intent === 'pending') return;
499
+ if (intent === 'drag') beginDrag(e);
500
+ else mode = intent;
501
+ }
502
+ if (mode === 'drag') {
503
+ d = Math.max(0, dismissAxis(e.clientX - startX, e.clientY - startY, dir, mirrored).toward);
504
+ const shift = dir === 'bottom' ? d : dir === 'top' ? -d : (dir === 'right') !== mirrored ? d : -d;
505
+ this.panel.style.transform = d > 0 ? (vertical ? `translateY(${shift}px)` : `translateX(${shift}px)`) : '';
506
+ }
507
+ });
508
+
509
+ // Keep the browser's scroll logic off a pull the sheet owns (or may still claim):
510
+ // without preventDefault here, the scroller grabs the touch and cancels the
511
+ // pointer stream before the drag can commit. Only downward pulls on an at-rest
512
+ // scroller are blocked — everything else keeps native behavior.
513
+ this.panel.addEventListener(
514
+ 'touchmove',
515
+ (e) => {
516
+ if (mode === 'drag' || mode === 'hswipe') {
517
+ e.preventDefault();
518
+ return;
519
+ }
520
+ if (mode !== 'pending') return;
521
+ const t = e.touches[0];
522
+ if (!t) return;
523
+ const { toward, across } = dismissAxis(t.clientX - startX, t.clientY - startY, dir, mirrored);
524
+ if (toward > Math.abs(across) && !this.scrollsTowardEdge(e.target)) e.preventDefault();
525
+ },
526
+ { passive: false },
527
+ );
528
+
529
+ const settle = (): void => {
530
+ if (mode === 'idle') return;
531
+ const finished = mode;
532
+ mode = 'idle';
533
+ if (finished === 'drag') {
534
+ this.panel.style.transition = '';
535
+ this.panel.style.transform = '';
536
+ const box = this.panel.getBoundingClientRect();
537
+ if (dragDismisses(d, vertical ? box.height : box.width)) this.hide();
538
+ } else if (finished === 'hswipe') {
539
+ const dir = swipeDirection(dx, dy);
540
+ if (dir) onSwipe?.(dir);
541
+ }
542
+ };
543
+ this.panel.addEventListener('pointerup', settle);
544
+ this.panel.addEventListener('pointercancel', settle);
545
+ }
546
+
547
+ setTitle(title: string): void {
548
+ this.titleEl.textContent = title;
549
+ }
550
+
551
+ private opener: HTMLElement | null = null;
552
+ private wasOpen = false;
553
+ /** The sheet and scrim's exit animation after a close; a reopen cancels it. */
554
+ private exit: SurfaceExit | null = null;
555
+ private destroyed = false;
556
+
557
+ private setShown(shown: boolean): void {
558
+ this.backdrop.style.display = shown ? '' : 'none';
559
+ this.positioner.style.display = shown ? '' : 'none';
560
+ }
561
+
562
+ /** Keep the just-closed sheet up through its exit animation, then hide it — or
563
+ * remove it, when it was destroyed meanwhile. `spreadProps` re-applies the close
564
+ * props' `hidden` only when its value changes, so lifting it keeps the sheet and
565
+ * scrim up until the exit ends. The positioner spans the host: inert, it lets
566
+ * clicks through to the page while the sheet animates out. */
567
+ private holdExit(): void {
568
+ const held = [this.panel, this.backdrop];
569
+ for (const el of held) el.hidden = false;
570
+ this.exit = holdForExit(
571
+ held,
572
+ () => {
573
+ this.exit = null;
574
+ if (this.destroyed) {
575
+ this.detach();
576
+ } else if (!this.open) {
577
+ for (const el of held) el.hidden = true;
578
+ this.setShown(false);
579
+ }
580
+ },
581
+ { inert: [this.positioner] },
582
+ );
583
+ }
584
+
585
+ private detach(): void {
586
+ this.backdrop.remove();
587
+ this.positioner.remove();
588
+ }
589
+
590
+ /** Closing hands focus back to whatever opened it (Escape, the ✕, hide(), or a
591
+ * teardown that outruns the machine's close notification). */
592
+ private restoreOpener(): void {
593
+ const opener = this.opener;
594
+ this.opener = null;
595
+ if (opener?.isConnected) opener.focus({ preventScroll: true });
596
+ }
597
+
598
+ private announce(open: boolean): void {
599
+ const opener = this.opener === this.panel.ownerDocument.body ? null : this.opener;
600
+ announceSurface(this.panel, open, 'drawer', opener);
601
+ }
602
+
603
+ get open(): boolean {
604
+ return this.ctrl.connect(this.handle.service).open;
605
+ }
606
+
607
+ show(): void {
608
+ this.opener = this.panel.ownerDocument.activeElement as HTMLElement | null;
609
+ this.ctrl.connect(this.handle.service).setOpen(true);
610
+ }
611
+
612
+ hide(): void {
613
+ this.ctrl.connect(this.handle.service).setOpen(false);
614
+ }
615
+
616
+ destroy(): void {
617
+ // Closed but not projected yet — an owner disposing of the sheet as it reports
618
+ // closing: project the close now, so it animates out like any other close and
619
+ // leaves the DOM when its exit ends. A teardown while open leaves at once.
620
+ if (this.wasOpen && !this.open) this.handle.flush();
621
+ this.handle.stop();
622
+ this.destroyed = true;
623
+ // Torn down while open: the stopped machine never projects the close.
624
+ if (this.wasOpen) {
625
+ this.wasOpen = false;
626
+ this.announce(false);
627
+ }
628
+ this.restoreOpener();
629
+ disposeWithin(this.panel);
630
+ if (!this.exit) this.detach();
631
+ }
632
+ }
633
+
634
+ export function createDrawer(props: DrawerProps = {}): Drawer {
635
+ return new Drawer(props);
636
+ }