glasslikeui 1.6.1 → 1.8.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 (46) hide show
  1. package/LICENSE +373 -674
  2. package/README.md +299 -4
  3. package/dist/actions/dragSnap.d.ts +16 -39
  4. package/dist/actions/dragSnap.js +6 -224
  5. package/dist/actions/dragSnapMath.d.ts +68 -0
  6. package/dist/actions/dragSnapMath.js +166 -0
  7. package/dist/actions/dragSurface.d.ts +26 -0
  8. package/dist/actions/dragSurface.js +187 -0
  9. package/dist/actions/focusRingFit.d.ts +22 -0
  10. package/dist/actions/focusRingFit.js +115 -0
  11. package/dist/actions/focusTrap.d.ts +22 -0
  12. package/dist/actions/focusTrap.js +103 -0
  13. package/dist/actions/index.d.ts +3 -0
  14. package/dist/actions/index.js +3 -0
  15. package/dist/actions/inertSiblings.d.ts +10 -0
  16. package/dist/actions/inertSiblings.js +35 -0
  17. package/dist/actions/reducedMotion.d.ts +25 -0
  18. package/dist/actions/reducedMotion.js +26 -0
  19. package/dist/actions/sheetBodyDrag.d.ts +14 -0
  20. package/dist/actions/sheetBodyDrag.js +26 -0
  21. package/dist/actions/sheetExit.d.ts +36 -0
  22. package/dist/actions/sheetExit.js +65 -0
  23. package/dist/actions/swipeActions.d.ts +14 -5
  24. package/dist/actions/swipeActions.js +89 -16
  25. package/dist/actions/viewTransition.d.ts +2 -1
  26. package/dist/actions/viewTransition.js +4 -2
  27. package/dist/components/glass/Glass.svelte +97 -6
  28. package/dist/components/glass/GlassMorph.svelte +21 -0
  29. package/dist/components/glass/Sheet.svelte +243 -61
  30. package/dist/components/glass/Sheet.svelte.d.ts +7 -1
  31. package/dist/components/interactive/Badge.svelte +2 -1
  32. package/dist/components/interactive/Button.svelte +164 -18
  33. package/dist/components/interactive/IconButton.svelte +23 -1
  34. package/dist/components/interactive/TabView.svelte +24 -1
  35. package/dist/components/interactive/Toggle.svelte +22 -4
  36. package/dist/components/layout/ScrollView.svelte +6 -0
  37. package/dist/components/list/ListRow.svelte +43 -9
  38. package/dist/components/menu/Menu.svelte +23 -0
  39. package/dist/components/menu/MenuItem.svelte +15 -2
  40. package/dist/components/navigation/NavigationLink.svelte +38 -2
  41. package/dist/components/typography/Text.svelte +2 -2
  42. package/dist/constants/shapes.d.ts +7 -0
  43. package/dist/constants/shapes.js +16 -0
  44. package/dist/styles/glasslikeui.css +143 -15
  45. package/dist/styles/lens.css +77 -0
  46. package/package.json +2 -2
package/README.md CHANGED
@@ -4,7 +4,7 @@ Svelte component library with frosted glass materials. Pseudo-element
4
4
  lensing, two-axis variant API, drag-snap sheets, View Transitions morph,
5
5
  accessibility-aware out of the box, cross-platform typography.
6
6
 
7
- Svelte 5 only. GPLv3 licensed.
7
+ Svelte 5 only. MPL-2.0 licensed.
8
8
 
9
9
  ## Install
10
10
 
@@ -107,6 +107,12 @@ attributes on non-Safari browsers:
107
107
  - `capsule` -- fully rounded ends.
108
108
  - `circle` -- 50% radius, locked to a 1:1 box.
109
109
 
110
+ `capsule` and `circle` always centre their content on both axes. A `rect`
111
+ centres its content the same way only when it holds a single text-level
112
+ child (`span`, `label`, `strong`, `b`, `em`, `small`, `svg` or `img`), so
113
+ panels and cards built from stacks, paragraphs and grids keep their layout.
114
+ Bare text directly inside a `rect` is not centred, wrap it in a `span`.
115
+
110
116
  Buttons get the same treatment through the `glass` and
111
117
  `glassProminent` variants, which read their blur and saturation from
112
118
  the shared intensity tokens rather than duplicating them.
@@ -135,16 +141,64 @@ settles -- including when it rejects:
135
141
  </ScrollView>
136
142
  ```
137
143
 
144
+ Dragging past the width of the action strip is damped by a rubber band
145
+ and never travels further than the row is wide. The strip grows to fill
146
+ exactly the space the row has uncovered, so it stays attached to the row
147
+ and the edge-most action (the last for trailing, the first for leading)
148
+ keeps its label centred as it stretches. Both rules use `:where()`, so
149
+ your own styles on the buttons still win.
150
+
138
151
  Both are also available as standalone actions for your own markup.
139
152
  They drive `--swipe-x` / `--refresh-pull` and `data-swipe-state` /
140
- `data-refresh-phase`; style off those.
153
+ `data-refresh-phase`. Style off those. `swipeActions` also writes the
154
+ unsigned distance travelled to `--swipe-reveal` and sets
155
+ `data-swipe-dragging` while a drag is in progress. Pass `stateElement`
156
+ to mirror all of these onto an ancestor that your strip can read.
157
+
158
+ ## Sheet
159
+
160
+ ```svelte
161
+ <Sheet bind:isOpen title="Options" onClose={() => (selected = null)}>
162
+ {#snippet children()}...{/snippet}
163
+ </Sheet>
164
+ ```
165
+
166
+ A sheet with a `title` shows a header with the title centred and an icon-only
167
+ close button (`aria-label="Close"`) at the trailing side. The sheet is a modal
168
+ `dialog`, labelled by its title (or by an `aria-label` when there is none).
169
+
170
+ - Dragging the handle or the header moves the sheet between its detents.
171
+ Presses on the close button or on interactive content never start a drag.
172
+ - The body drags too. A press in the content starts a drag once it pulls down
173
+ with the content scrolled to the top. Taps, scrolling and controls in the
174
+ content keep working, and a press on a button or field never drags. Under
175
+ reduced motion the snap back and the exit are instant. On engines without
176
+ directional `touch-action` (for example Safari on iOS), a touch pull on
177
+ content that scrolls is a scroll, so touch users dismiss from the handle or
178
+ the header there. Mouse and pen are not affected.
179
+ - Dragging down below the smallest detent follows the finger. Releasing past
180
+ 30% of that detent's height below it, or flicking down quickly, dismisses
181
+ the sheet. Anything shorter snaps back. Set `interactiveDismissDisabled`
182
+ to turn this off, mirroring SwiftUI. The close button, Escape and the
183
+ backdrop still close the sheet.
184
+ - The sheet is a viewport tall and slides down to its detent. The content area
185
+ ends at the bottom of the screen at every detent, so the end of long content
186
+ can be scrolled into view. It resizes when a drag snaps. Remove any
187
+ `margin-bottom` you added to `.sheet-content` to work around this.
188
+ - Every close path (button, Escape, backdrop, drag, or the parent setting
189
+ `isOpen` to `false`) slides the sheet down and fades the backdrop before
190
+ it unmounts. `isOpen` turns false and `onClose` fires when the close
191
+ starts, and reopening during the slide cancels it. With
192
+ `prefers-reduced-motion` or `data-reduced-motion="true"` the sheet
193
+ unmounts immediately.
141
194
 
142
195
  ## Actions
143
196
 
144
197
  | Export | Purpose |
145
198
  | -------------------------------- | ------------------------------------------------------ |
146
199
  | `scrollEdge` | Fade a scroll container at edges meeting glass chrome. |
147
- | `dragSnap` | Detent-based drag gesture (used by `Sheet`). |
200
+ | `dragSnap` | Detent-based drag gesture (used by `Sheet`). Pass `onDismiss` to let a long pull or flick below the smallest detent dismiss. |
201
+ | `startSheetExit` | Slide a sheet down and out, then report completion. |
148
202
  | `swipeActions` | Swipe a row aside to reveal actions. |
149
203
  | `refreshable` | Pull-to-refresh gesture. |
150
204
  | `deviceMotion` | Ties the glass highlight angle to device tilt. |
@@ -224,6 +278,119 @@ Cross-browser fallback attributes (flip at `:root`):
224
278
 
225
279
  Call `syncAccessibilityPreferences()` to manage these automatically.
226
280
 
281
+ `Sheet` is a modal dialog. While it is open or sliding out, the siblings of the
282
+ sheet and of each ancestor up to `body` get the `inert` attribute, and are
283
+ restored exactly when it closes. Ancestors are never made inert, and anything
284
+ you had already made inert stays inert. Tab and Shift+Tab wrap inside the
285
+ sheet, and focus returns to the element that opened it.
286
+
287
+ Under reduced transparency (the media query, or
288
+ `data-reduced-transparency="true"` on `:root` or on any element around the
289
+ parts, in both themes):
290
+
291
+ - `Glass`, and everything built on it, loses its blur, lens filter and blended
292
+ highlight. `--glass-opacity` becomes 1, so the default background is solid
293
+ `--glass-surface-color`, and a `tint` is painted over a solid base of that
294
+ colour. A background of your own that works normally works here too, and so
295
+ does your own `--glass-surface-bg`: both are left as you set them, see-through
296
+ ones included, so keep them opaque enough for their text.
297
+ - To recolour surfaces, set `--glass-surface-color` on `:root`. To recolour one
298
+ surface, set `--glass-surface-bg` or `tint` on it. `--glass-surface-color` set
299
+ on a single surface does not change its default background, with or without
300
+ reduced transparency, because `--glass-surface-bg` is resolved on `:root`.
301
+ - Glass `Button`s lose their blur and get a solid fill. `glassProminent`
302
+ becomes solid accent with its `--color-on-accent` label.
303
+ - `Sheet` turns its blur off, including the backdrop blur
304
+ (`--glass-backdrop-blur`), and its background becomes near opaque
305
+ (`--glass-sheet-bg` at 0.98 alpha). `Menu` goes opaque with it.
306
+ - `NavigationBar` becomes near opaque too (`--glass-nav-bg` at 0.98 alpha).
307
+
308
+ The empty `::before` layer is removed from `Glass` and glass `Button`s, so a
309
+ `::before` rule of your own for the fill cannot cover the solid one, and
310
+ contrast checkers can read the background. A tinted `Glass` keeps the layer to
311
+ paint its tint, so a checker may report its text as incomplete.
312
+
313
+ On an element inside the page, the attribute also makes `--glass-surface-bg`
314
+ solid `--glass-surface-color` there, in place of a value you set on `:root`, and
315
+ the light theme is still read from `:root`. To switch the preference for the
316
+ whole page, put the attribute on `:root`.
317
+
318
+ With the media query, the library's values (`--glass-opacity`, the blurs,
319
+ `--glass-sheet-bg` and `--glass-nav-bg`) are declared on `:root:root`, so your
320
+ plain `:root` values for them do not keep sheets and bars see-through before any
321
+ script has run. A selector of the same weight loaded later, such as
322
+ `:root[data-theme='dark']`, or a heavier one, still wins, so give such rules
323
+ solid values under the media query. To use your own solid colours there,
324
+ outrank the library:
325
+
326
+ ```css
327
+ @media (prefers-reduced-transparency: reduce) {
328
+ :root:root:root {
329
+ --glass-sheet-bg: #101820;
330
+ --glass-nav-bg: #101820;
331
+ }
332
+ }
333
+ ```
334
+
335
+ No `!important` is needed. `Glass` still sets `--glass-blur` and the other
336
+ effect values inline; the rules replace the properties that read them. Asking
337
+ for more contrast at the same time leaves surfaces solid.
338
+
339
+ Under reduced motion, `withGlassTransition` runs the update with no view
340
+ transition and returns `{ supported: false }`, and `GlassMorph` elements do not
341
+ animate even in a view transition you start yourself.
342
+
343
+ A `Button` with `href` and `disabled` renders a link with no `href`, marked
344
+ `aria-disabled="true"`. It cannot be focused or followed and does not call
345
+ `onclick`.
346
+
347
+ ### Focus ring
348
+
349
+ The library's buttons, links, rows, tabs, menu items and switch draw one shared
350
+ ring for keyboard users. Restyle the rings with these tokens, set on `:root` or
351
+ on any ancestor:
352
+
353
+ | Token | Default |
354
+ | ------------------------------- | ------------------------------------ |
355
+ | `--glass-focus-ring-color` | `#9ecbff` dark, `#00408a` light |
356
+ | `--glass-focus-ring-halo-color` | `#000000` dark, `#ffffff` light |
357
+ | `--glass-focus-ring-width` | `2px` |
358
+ | `--glass-focus-ring-offset` | `2px` |
359
+
360
+ The ring has two tones, because no single colour holds 3:1 against every
361
+ backdrop: the outline, and a halo that fills the gap inside it (inside the
362
+ outline on `ListRow` and `MenuItem`). With the defaults, one tone or the other
363
+ holds 3:1 against any backdrop. If you change either colour, keep the two at
364
+ least 9:1 apart, or set the halo to `transparent` and check the single ring
365
+ against your backgrounds. The four tokens are unset by default (the per theme
366
+ colours live in the `-default` tokens), so a value you set wins in both themes.
367
+ The halo is a `box-shadow`. On `Button` it has to outrank the variant shadows, so
368
+ a `box-shadow` of yours needs more than two classes to replace it there. `ListRow` and `MenuItem` sit in clipping containers, so their ring
369
+ is always drawn inside, offset by minus the width. The colour, width and style
370
+ rules have zero specificity, so any focus rule of your own beats them. The
371
+ inward offsets are the exception, so that an ordinary
372
+ `:focus-visible { outline-offset: 2px }` of yours cannot push a ring out where
373
+ it is cut off. Their selectors weigh two classes on `ListRow` and `MenuItem`,
374
+ three on a part marked `data-focus-ring="inset"` and four on a `Toggle` track
375
+ marked that way. To change one on purpose, use a heavier selector.
376
+
377
+ A container that clips can also cut off the ring of a part flush against its
378
+ edge: a full width `Button` in `<Glass padding="none">`, in a `ScrollView` or at
379
+ the top of `Sheet` content. When `Button`, `IconButton`, a `TabView` item,
380
+ `NavigationLink`, the `Menu` trigger or `Toggle` takes focus with no room for
381
+ its ring, it sets `data-focus-ring="inset"` and draws the ring inside, in its
382
+ label colour unless `--glass-focus-ring-color` is set. A colour you set should
383
+ then stand out on the part's own fill as well as on the page. This is measured
384
+ when the part takes focus.
385
+
386
+ The `Sheet` close button focus ring is two tones, so it holds 3:1 on both the
387
+ dark and the light sheet. It follows the shared width and offset, and
388
+ `--glass-focus-ring-color`, when set on any ancestor, replaces its outer tone.
389
+ Without that, `--sheet-focus-ring-outer` colours the outline, and
390
+ `--sheet-focus-ring-inner` the ring against the button. To give this button its
391
+ own colour while a shared one is set, set `--glass-focus-ring-color` on
392
+ `.sheet-close-btn`.
393
+
227
394
  ## Theming
228
395
 
229
396
  All design tokens are CSS custom properties. Toggle dark / light with
@@ -242,6 +409,134 @@ Override any token via your own stylesheet, e.g.:
242
409
  }
243
410
  ```
244
411
 
412
+ ### Component tokens
413
+
414
+ These are unset by default, so you can set them on `:root` or on any ancestor.
415
+
416
+ | Token | Used by | Default |
417
+ | ------------------------- | ------------------------------------------------- | --------------------- |
418
+ | `--glass-track-checked` | The checked `Toggle` track. | `--color-accent` |
419
+ | `--color-on-accent` | Labels on accent fills: filled `Button`, filled `IconButton` and `glassProminent`. | `white` |
420
+ | `--color-on-danger` | The `destructive` `Button` label. | `white` |
421
+ | `--glass-sheet-max-width` | `Sheet` width cap on viewports from 769px. | `900px` |
422
+ | `--glass-button-fill` | The resting fill of the plain `glass` `Button`. You own its contrast. | see below |
423
+ | `--glass-button-fill-hover` | Its hover fill. | `--glass-button-fill`, else the library hover fill |
424
+ | `--glass-button-fill-active` | Its pressed fill. | `--glass-button-fill`, else the library pressed fill |
425
+
426
+ ```css
427
+ .my-sheet {
428
+ --glass-sheet-max-width: 1100px;
429
+ }
430
+ ```
431
+
432
+ If you change `--color-accent` or `--color-danger` to a light colour, set the
433
+ matching label token and check for 4.5:1.
434
+
435
+ `glassProminent` fills with `--color-accent`, shaded toward black and slightly
436
+ see-through (84% opaque, a little darker on hover and again when pressed), with
437
+ a `--color-on-accent` label. With the default colours the label holds at least
438
+ 4.5:1 over any backdrop. Your own pair needs more room than on a solid fill:
439
+ the shade darkens the accent and the backdrop shows through, so check it over
440
+ both black and white.
441
+
442
+ The plain `glass` `Button` is see-through, and its default label holds 4.5:1
443
+ (WCAG 2.2 AA) at rest, on hover and when pressed, over any backdrop, in both
444
+ themes: smoked glass under a light label in the dark theme, and white glass,
445
+ 55% opaque or more, under a dark label in the light one. This takes your
446
+ `--color-text` to be light in the dark theme (about `#f5f5f7`) and dark in the
447
+ light theme (about `#1d1d1f`); the library does not set it. The button's edge
448
+ can be faint against a backdrop of a similar grey.
449
+
450
+ Change the fill with `--glass-button-fill` and, if you want hover and press
451
+ feedback with it, the `-hover` and `-active` tokens. A fill of your own owns its
452
+ contrast: check the label against it over your lightest and darkest backdrops.
453
+ Reduced transparency ignores all three. Use them instead of styling the
454
+ button's `::before`.
455
+
456
+ ### Text and fill colours (WCAG 2.2 AA)
457
+
458
+ With the default colours, the labels of these hold 4.5:1 (WCAG 2.2 AA 1.4.3) at
459
+ rest, on hover and when pressed, measured from painted pixels in Chromium and
460
+ WebKit.
461
+
462
+ Solid fills, over any backdrop: `filled` `Button` and `IconButton` (4.70 rest,
463
+ 5.38 hover and press at the lowest), `destructive` `Button` (4.72, 5.43, 6.11),
464
+ `glassProminent` and the plain `glass` `Button` (see above).
465
+
466
+ See-through variants, over the surfaces of their theme: `outlined`, `plain` and
467
+ `tinted` `Button`s, accent `Badge`, the active `TabView` item, `Text` with
468
+ `color="accent"` or `"danger"`, and a destructive `MenuItem`. The lowest measured
469
+ over the dark theme's black, `rgb(28, 28, 30)`, `rgb(53, 53, 55)` and
470
+ `rgb(64, 64, 66)`, and the light theme's white, `rgb(242, 242, 247)` and
471
+ `rgb(224, 224, 224)`, is 4.87:1. They do not hold over every backdrop, and no
472
+ colour can: text that contrasts with both black and white fails against a grey
473
+ or saturated colour in between. Over white in the dark theme, black in the light
474
+ theme or a saturated colour they measure from 1.0 to 1.3:1. Use `filled`,
475
+ `glassProminent` or `glass` over busy backdrops.
476
+
477
+ Text in the accent or danger colour is the colour mixed toward white in the dark
478
+ theme and toward black in the light one, worked out from `--color-accent` or
479
+ `--color-danger` where the part is, so it follows a wrapper's own colour with
480
+ nothing to mark:
481
+
482
+ | Token | Default |
483
+ | ------------------------------------ | ---------------------------------------- |
484
+ | `--color-accent-text` | the accent, 33% (dark) or 72% (light) toward white or black |
485
+ | `--color-accent-text-hover` | the same at 26% (dark) or 62% (light) |
486
+ | `--color-danger-text` | the danger colour, 30% (dark) or 78% (light) |
487
+
488
+ They are unset by default. The strengths and direction are
489
+ `--glass-accent-text-strength`, `--glass-accent-text-strength-hover`,
490
+ `--glass-danger-text-strength` and `--glass-text-toward`. If you set an accent
491
+ that suits the other theme, such as a pale accent in the light theme, set
492
+ `--color-accent-text` yourself.
493
+
494
+ **What an override owns.** The numbers above are for the library's default
495
+ colours. A `--color-accent`, `--color-danger`, `--color-on-accent`,
496
+ `--color-on-danger`, `--color-accent-text`, `--color-danger-text` or glass fill
497
+ token of your own makes its contrast yours to check. Your values on `:root` for
498
+ `--color-accent-hover`, `--color-danger-hover` and the other shades still apply.
499
+ `--color-accent-hover` and `--color-danger-hover` default to the colour mixed 92%
500
+ with black, because a white label on a lighter shade falls below 4.5:1. The
501
+ default `--color-danger` is `#d23c3c`, the lightest red a white label holds 4.5:1
502
+ on.
503
+
504
+ The active `NavigationLink` has an accent fill of its own and a `--color-on-accent`
505
+ label, like a filled `Button`, so it holds over any page or bar: 4.70 at rest,
506
+ 5.38 on hover and 6.10 when pressed, in both themes and in the reduced-transparency
507
+ and increased-contrast modes. It was white with no fill, 1.00:1 on a light page.
508
+
509
+ Not met: `SymbolImage` icons in the accent colour are non-text and need 3:1: the default blue is 2.2:1
510
+ on `rgb(64, 64, 66)`.
511
+
512
+ ### A wrapper with its own accent
513
+
514
+ `--color-accent-hover`, `-active`, `-10`, `-15`, `-25`, `-50` and
515
+ `--color-danger-hover` and `-active` are worked out on `:root`, where you can
516
+ still override them. Text in the accent or danger colour is worked out in the
517
+ part itself, so a wrapper's colour reaches it without a mark. A wrapper that sets `--color-accent` or `--color-danger`
518
+ inline works them out again from its own colour. A wrapper that sets either
519
+ from a stylesheet cannot be detected, so mark it:
520
+
521
+ ```svelte
522
+ <div class="my-theme glass-accent-scope">...</div>
523
+ ```
524
+
525
+ ```css
526
+ .my-theme {
527
+ --color-accent: #dcdff0;
528
+ --color-on-accent: #0f1014;
529
+ }
530
+ ```
531
+
532
+ Without the mark, the fills for hover and press of a filled or destructive
533
+ button keep the root's colour: with a pale accent and a dark label they measure
534
+ 3.1 to 3.6:1, against 5.2 and above with the mark or an inline colour. Inside
535
+ such a scope the shades follow the wrapper, in place of overrides on
536
+ `:root`. A shade you set on the wrapper itself wins. Without the mark, hover,
537
+ press and wash colours keep the root's colour, which can put your label below
538
+ 4.5:1. `glassProminent` follows the wrapper without a mark.
539
+
245
540
  ## Browser support
246
541
 
247
542
  | Browser | Support |
@@ -263,4 +558,4 @@ npm run test:coverage # with v8 coverage
263
558
 
264
559
  ## License
265
560
 
266
- GNU General Public License v3.0 or later (GPL-3.0-or-later). Copyright (c) 2026 Beau Ayres. See `LICENSE`.
561
+ Mozilla Public License 2.0 (MPL-2.0). Copyright (c) 2026 Beau Ayres. See `LICENSE`.
@@ -3,7 +3,9 @@
3
3
  *
4
4
  * Attaches pointer handlers to a handle element and drags a target surface
5
5
  * between a set of named detent positions. Velocity-based snap on release,
6
- * rubber-band feel when dragged past bounds.
6
+ * rubber-band feel when dragged past bounds. When `onDismiss` is given, pulling
7
+ * the surface below its smallest detent tracks the finger one to one, and a long
8
+ * enough pull (or a downward flick) dismisses it instead of snapping back.
7
9
  *
8
10
  * Usage:
9
11
  * <div use:dragSnap={{
@@ -32,46 +34,21 @@ export interface DragSnapOptions {
32
34
  respectScroll?: boolean;
33
35
  /** Disable the gesture. */
34
36
  disabled?: boolean;
35
- }
36
- export interface PointerSample {
37
- y: number;
38
- t: number;
37
+ /**
38
+ * Called when a release dismisses the surface (see `shouldDismiss`). The
39
+ * surface has already been sent down and out by then. When absent, dragging
40
+ * below the smallest detent rubber-bands and snaps back, exactly as before.
41
+ */
42
+ onDismiss?: () => void;
43
+ /**
44
+ * Decides whether a pointer press may start a drag. Receives the pointerdown
45
+ * event. Omit to allow every press on the node.
46
+ */
47
+ canStart?: (event: PointerEvent) => boolean;
39
48
  }
40
49
  export declare function dragSnap(node: HTMLElement, initialOptions: DragSnapOptions): {
41
50
  update(newOptions: DragSnapOptions): void;
42
51
  destroy(): void;
43
52
  };
44
- /** Clamp a detent index into range; 0 when there are no detents. */
45
- export declare function clampIndex(i: number, len: number): number;
46
- /** The fraction at an index, falling back to the first detent then 0. */
47
- export declare function detentAt(detents: number[], index: number): number;
48
- /**
49
- * Rubber-band a fraction dragged beyond the detent range, so overshoot moves
50
- * at a reduced rate instead of tracking the pointer one-to-one.
51
- */
52
- export declare function applyRubberBand(fraction: number, minDetent: number, maxDetent: number, rubber: number): number;
53
- /**
54
- * Pick the detent to settle on: a flick faster than the threshold moves one
55
- * step in its direction, otherwise snap to whichever detent is nearest.
56
- */
57
- export declare function chooseNextIndex(currentIndex: number, velocity: number, threshold: number, finalFraction: number, detents: number[]): number;
58
- /** Index of the detent closest to `fraction`; ties resolve to the lower index. */
59
- export declare function nearestDetentIndex(fraction: number, detents: number[]): number;
60
- /** How many pointer samples the velocity window keeps. */
61
- export declare const SAMPLE_WINDOW = 5;
62
- /**
63
- * Append a sample, keeping at most SAMPLE_WINDOW of them. Velocity is measured
64
- * across this window so a release reflects the recent flick rather than the
65
- * whole gesture. Returns a new array; the input is not mutated.
66
- */
67
- export declare function pushSample(samples: PointerSample[], sample: PointerSample, max?: number): PointerSample[];
68
- /** Average pointer velocity in px/s across the sample window; 0 if unknowable. */
69
- export declare function computeVelocity(samples: PointerSample[]): number;
70
- export declare const DEFAULT_DETENT_FRACTIONS: {
71
- readonly small: 0.25;
72
- readonly medium: 0.5;
73
- readonly large: 0.9;
74
- readonly fullscreen: 1;
75
- };
76
- export type SheetDetentName = keyof typeof DEFAULT_DETENT_FRACTIONS;
77
- export declare function detentFractions(names: readonly SheetDetentName[]): number[];
53
+ export { DEFAULT_DETENT_FRACTIONS, DRAG_BLOCKER_SELECTOR, SAMPLE_WINDOW, SHEET_DISMISS_FRACTION, SHEET_TRANSITION, applyRubberBand, chooseNextIndex, clampIndex, computeVelocity, detentAt, detentFractions, isDragStartAllowed, nearestDetentIndex, pushSample, resolveDragFraction, shouldDismiss, sheetYForFraction } from './dragSnapMath';
54
+ export type { PointerSample, SheetDetentName } from './dragSnapMath';
@@ -3,7 +3,9 @@
3
3
  *
4
4
  * Attaches pointer handlers to a handle element and drags a target surface
5
5
  * between a set of named detent positions. Velocity-based snap on release,
6
- * rubber-band feel when dragged past bounds.
6
+ * rubber-band feel when dragged past bounds. When `onDismiss` is given, pulling
7
+ * the surface below its smallest detent tracks the finger one to one, and a long
8
+ * enough pull (or a downward flick) dismisses it instead of snapping back.
7
9
  *
8
10
  * Usage:
9
11
  * <div use:dragSnap={{
@@ -13,228 +15,8 @@
13
15
  * onSnap: (i) => currentDetent = i
14
16
  * }}>...</div>
15
17
  */
16
- var __assign = (this && this.__assign) || function () {
17
- __assign = Object.assign || function(t) {
18
- for (var s, i = 1, n = arguments.length; i < n; i++) {
19
- s = arguments[i];
20
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
21
- t[p] = s[p];
22
- }
23
- return t;
24
- };
25
- return __assign.apply(this, arguments);
26
- };
27
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
28
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
29
- if (ar || !(i in from)) {
30
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
31
- ar[i] = from[i];
32
- }
33
- }
34
- return to.concat(ar || Array.prototype.slice.call(from));
35
- };
18
+ import { dragSurface } from './dragSurface';
36
19
  export function dragSnap(node, initialOptions) {
37
- var _a;
38
- var options = __assign({}, initialOptions);
39
- var currentIndex = clampIndex((_a = options.initial) !== null && _a !== void 0 ? _a : 0, options.detents.length);
40
- var dragging = false;
41
- var pointerId = null;
42
- var startY = 0;
43
- var startFraction = detentAt(options.detents, currentIndex);
44
- var samples = [];
45
- var target = function () { var _a; return (_a = options.target) !== null && _a !== void 0 ? _a : node; };
46
- function applyFraction(fraction, animate) {
47
- // target() falls back to `node`, so there is always an element.
48
- var el = target();
49
- el.style.transition = animate
50
- ? 'transform 0.4s cubic-bezier(0.32, 0.72, 0, 1)'
51
- : 'none';
52
- var offset = (1 - fraction) * 100;
53
- el.style.setProperty('--sheet-y', "".concat(offset, "vh"));
54
- }
55
- function onPointerDown(event) {
56
- if (options.disabled)
57
- return;
58
- if (event.button !== undefined && event.button !== 0)
59
- return;
60
- if (options.respectScroll !== false) {
61
- var scrollable = findScrollableAncestor(event.target, node);
62
- if (scrollable && scrollable.scrollTop > 0)
63
- return;
64
- }
65
- dragging = true;
66
- pointerId = event.pointerId;
67
- startY = event.clientY;
68
- startFraction = detentAt(options.detents, currentIndex);
69
- samples = [{ y: event.clientY, t: performance.now() }];
70
- try {
71
- node.setPointerCapture(event.pointerId);
72
- }
73
- catch (_a) {
74
- /* jsdom / test env may not support */
75
- }
76
- }
77
- function onPointerMove(event) {
78
- var _a, _b;
79
- if (!dragging || event.pointerId !== pointerId)
80
- return;
81
- var viewportH = window.innerHeight || 1;
82
- var deltaY = event.clientY - startY;
83
- var fractionDelta = -deltaY / viewportH;
84
- var newFraction = applyRubberBand(startFraction + fractionDelta, Math.min.apply(Math, options.detents), Math.max.apply(Math, options.detents), (_a = options.rubberBand) !== null && _a !== void 0 ? _a : 0.3);
85
- applyFraction(newFraction, false);
86
- samples = pushSample(samples, { y: event.clientY, t: performance.now() });
87
- (_b = options.onDrag) === null || _b === void 0 ? void 0 : _b.call(options, deltaY, newFraction);
88
- }
89
- function onPointerUp(event) {
90
- var _a, _b;
91
- if (!dragging || event.pointerId !== pointerId)
92
- return;
93
- dragging = false;
94
- pointerId = null;
95
- var viewportH = window.innerHeight || 1;
96
- var finalFraction = startFraction + -(event.clientY - startY) / viewportH;
97
- currentIndex = chooseNextIndex(currentIndex, computeVelocity(samples), (_a = options.velocityThreshold) !== null && _a !== void 0 ? _a : 500, finalFraction, options.detents);
98
- var snappedFraction = detentAt(options.detents, currentIndex);
99
- applyFraction(snappedFraction, true);
100
- (_b = options.onSnap) === null || _b === void 0 ? void 0 : _b.call(options, currentIndex, snappedFraction);
101
- try {
102
- node.releasePointerCapture(event.pointerId);
103
- }
104
- catch (_c) {
105
- /* noop */
106
- }
107
- }
108
- function onPointerCancel(event) {
109
- if (!dragging || event.pointerId !== pointerId)
110
- return;
111
- dragging = false;
112
- pointerId = null;
113
- applyFraction(detentAt(options.detents, currentIndex), true);
114
- }
115
- node.addEventListener('pointerdown', onPointerDown);
116
- node.addEventListener('pointermove', onPointerMove);
117
- node.addEventListener('pointerup', onPointerUp);
118
- node.addEventListener('pointercancel', onPointerCancel);
119
- // Start at closed (100vh offset) then animate into the initial detent
120
- // on the next frame so the sheet's entry reads as a spring.
121
- var el = target();
122
- el.style.transition = 'none';
123
- el.style.setProperty('--sheet-y', '100vh');
124
- var raf = typeof requestAnimationFrame === 'function' ? requestAnimationFrame : function (cb) { return cb(); };
125
- raf(function () { return applyFraction(detentAt(options.detents, currentIndex), true); });
126
- return {
127
- update: function (newOptions) {
128
- var _a;
129
- options = __assign({}, newOptions);
130
- currentIndex = clampIndex((_a = options.initial) !== null && _a !== void 0 ? _a : currentIndex, options.detents.length);
131
- applyFraction(detentAt(options.detents, currentIndex), true);
132
- },
133
- destroy: function () {
134
- node.removeEventListener('pointerdown', onPointerDown);
135
- node.removeEventListener('pointermove', onPointerMove);
136
- node.removeEventListener('pointerup', onPointerUp);
137
- node.removeEventListener('pointercancel', onPointerCancel);
138
- }
139
- };
140
- }
141
- /** Clamp a detent index into range; 0 when there are no detents. */
142
- export function clampIndex(i, len) {
143
- // An empty list yields 0: Math.min(i, -1) then Math.max(0, ...) collapses there.
144
- return Math.max(0, Math.min(i, len - 1));
145
- }
146
- /** The fraction at an index, falling back to the first detent then 0. */
147
- export function detentAt(detents, index) {
148
- var _a, _b;
149
- return (_b = (_a = detents[index]) !== null && _a !== void 0 ? _a : detents[0]) !== null && _b !== void 0 ? _b : 0;
150
- }
151
- /**
152
- * Rubber-band a fraction dragged beyond the detent range, so overshoot moves
153
- * at a reduced rate instead of tracking the pointer one-to-one.
154
- */
155
- export function applyRubberBand(fraction, minDetent, maxDetent, rubber) {
156
- if (fraction > maxDetent)
157
- return maxDetent + (fraction - maxDetent) * rubber;
158
- if (fraction < minDetent)
159
- return minDetent - (minDetent - fraction) * rubber;
160
- return fraction;
161
- }
162
- /**
163
- * Pick the detent to settle on: a flick faster than the threshold moves one
164
- * step in its direction, otherwise snap to whichever detent is nearest.
165
- */
166
- export function chooseNextIndex(currentIndex, velocity, threshold, finalFraction, detents) {
167
- if (Math.abs(velocity) > threshold) {
168
- // Clamp the step: a currentIndex outside the list would otherwise step to
169
- // an unindexable position (e.g. -1) rather than a real detent.
170
- var stepped = velocity < 0 ? currentIndex + 1 : currentIndex - 1;
171
- return clampIndex(stepped, detents.length);
172
- }
173
- return nearestDetentIndex(finalFraction, detents);
174
- }
175
- /** Index of the detent closest to `fraction`; ties resolve to the lower index. */
176
- export function nearestDetentIndex(fraction, detents) {
177
- var bestIndex = 0;
178
- var bestDistance = Infinity;
179
- for (var i = 0; i < detents.length; i++) {
180
- var value = detents[i];
181
- if (value === undefined)
182
- continue;
183
- var d = Math.abs(value - fraction);
184
- if (d < bestDistance) {
185
- bestDistance = d;
186
- bestIndex = i;
187
- }
188
- }
189
- return bestIndex;
190
- }
191
- /** How many pointer samples the velocity window keeps. */
192
- export var SAMPLE_WINDOW = 5;
193
- /**
194
- * Append a sample, keeping at most SAMPLE_WINDOW of them. Velocity is measured
195
- * across this window so a release reflects the recent flick rather than the
196
- * whole gesture. Returns a new array; the input is not mutated.
197
- */
198
- export function pushSample(samples, sample, max) {
199
- if (max === void 0) { max = SAMPLE_WINDOW; }
200
- var next = __spreadArray(__spreadArray([], samples, true), [sample], false);
201
- return next.length > max ? next.slice(next.length - max) : next;
202
- }
203
- /** Average pointer velocity in px/s across the sample window; 0 if unknowable. */
204
- export function computeVelocity(samples) {
205
- if (samples.length < 2)
206
- return 0;
207
- var first = samples[0];
208
- var last = samples[samples.length - 1];
209
- if (!first || !last)
210
- return 0;
211
- var dt = (last.t - first.t) / 1000;
212
- if (dt <= 0)
213
- return 0;
214
- var velocity = (last.y - first.y) / dt;
215
- // A vanishingly small dt overflows the division to Infinity, which would
216
- // then clear every velocity threshold and force a flick snap.
217
- return Number.isFinite(velocity) ? velocity : 0;
218
- }
219
- function findScrollableAncestor(el, stopAt) {
220
- var node = el;
221
- while (node && node !== stopAt) {
222
- if (node instanceof HTMLElement) {
223
- var overflowY = getComputedStyle(node).overflowY;
224
- if ((overflowY === 'auto' || overflowY === 'scroll') && node.scrollHeight > node.clientHeight) {
225
- return node;
226
- }
227
- }
228
- node = node.parentElement;
229
- }
230
- return null;
231
- }
232
- export var DEFAULT_DETENT_FRACTIONS = {
233
- small: 0.25,
234
- medium: 0.5,
235
- large: 0.9,
236
- fullscreen: 1
237
- };
238
- export function detentFractions(names) {
239
- return names.map(function (n) { return DEFAULT_DETENT_FRACTIONS[n]; });
20
+ return dragSurface(node, initialOptions);
240
21
  }
22
+ export { DEFAULT_DETENT_FRACTIONS, DRAG_BLOCKER_SELECTOR, SAMPLE_WINDOW, SHEET_DISMISS_FRACTION, SHEET_TRANSITION, applyRubberBand, chooseNextIndex, clampIndex, computeVelocity, detentAt, detentFractions, isDragStartAllowed, nearestDetentIndex, pushSample, resolveDragFraction, shouldDismiss, sheetYForFraction } from './dragSnapMath';