@surdeddd/bottom-sheet 0.1.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 (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +377 -0
  3. package/dist/BottomSheetEngine-CvSVbo6c.d.cts +704 -0
  4. package/dist/BottomSheetEngine-DbO8rW_3.d.ts +704 -0
  5. package/dist/element.cjs +3442 -0
  6. package/dist/element.d.cts +88 -0
  7. package/dist/element.d.ts +88 -0
  8. package/dist/element.iife.global.js +3 -0
  9. package/dist/element.js +3442 -0
  10. package/dist/index.cjs +3693 -0
  11. package/dist/index.d.cts +184 -0
  12. package/dist/index.d.ts +184 -0
  13. package/dist/index.js +3669 -0
  14. package/dist/integrations/formik.cjs +27 -0
  15. package/dist/integrations/formik.d.cts +27 -0
  16. package/dist/integrations/formik.d.ts +27 -0
  17. package/dist/integrations/formik.js +25 -0
  18. package/dist/integrations/react-hook-form.cjs +28 -0
  19. package/dist/integrations/react-hook-form.d.cts +30 -0
  20. package/dist/integrations/react-hook-form.d.ts +30 -0
  21. package/dist/integrations/react-hook-form.js +26 -0
  22. package/dist/overlay.cjs +1058 -0
  23. package/dist/overlay.d.cts +282 -0
  24. package/dist/overlay.d.ts +282 -0
  25. package/dist/overlay.js +1053 -0
  26. package/dist/preact.cjs +2 -0
  27. package/dist/preact.d.cts +5 -0
  28. package/dist/preact.d.ts +5 -0
  29. package/dist/preact.js +2 -0
  30. package/dist/qwik.cjs +3046 -0
  31. package/dist/qwik.d.cts +55 -0
  32. package/dist/qwik.d.ts +55 -0
  33. package/dist/qwik.js +3044 -0
  34. package/dist/react.cjs +4162 -0
  35. package/dist/react.d.cts +301 -0
  36. package/dist/react.d.ts +301 -0
  37. package/dist/react.js +4156 -0
  38. package/dist/solid.cjs +3063 -0
  39. package/dist/solid.d.cts +66 -0
  40. package/dist/solid.d.ts +66 -0
  41. package/dist/solid.js +3061 -0
  42. package/dist/styles.css +508 -0
  43. package/dist/svelte.cjs +3200 -0
  44. package/dist/svelte.d.ts +89 -0
  45. package/dist/svelte.js +3177 -0
  46. package/dist/themes/ios.css +24 -0
  47. package/dist/themes/material.css +24 -0
  48. package/dist/themes/vercel.css +24 -0
  49. package/dist/transform-Brkf-wzo.d.cts +4 -0
  50. package/dist/transform-Brkf-wzo.d.ts +4 -0
  51. package/dist/vue.cjs +3361 -0
  52. package/dist/vue.d.ts +68 -0
  53. package/dist/vue.js +3358 -0
  54. package/package.json +288 -0
package/dist/vue.js ADDED
@@ -0,0 +1,3358 @@
1
+ import { ref, reactive, onMounted, onBeforeUnmount, openBlock, createElementBlock, createCommentVNode, renderSlot, createElementVNode, normalizeClass, toDisplayString, defineComponent, watch, computed, readonly } from 'vue';
2
+
3
+ var __defProp = Object.defineProperty;
4
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
5
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
6
+
7
+ // src/core/lifecycle/sheetStack.ts
8
+ var BASE_Z = 100;
9
+ var STEP = 10;
10
+ var SheetStack = class {
11
+ constructor() {
12
+ __publicField(this, "entries", []);
13
+ }
14
+ push(entry) {
15
+ this.entries.push(entry);
16
+ this.recompute();
17
+ return () => this.remove(entry.id);
18
+ }
19
+ remove(id) {
20
+ const idx = this.entries.findIndex((e) => e.id === id);
21
+ if (idx === -1) return;
22
+ this.entries.splice(idx, 1);
23
+ this.recompute();
24
+ }
25
+ size() {
26
+ return this.entries.length;
27
+ }
28
+ clear() {
29
+ this.entries = [];
30
+ }
31
+ recompute() {
32
+ this.entries.forEach((entry, i) => {
33
+ entry.setZIndex(BASE_Z + i * STEP);
34
+ entry.setIsTop(i === this.entries.length - 1);
35
+ });
36
+ }
37
+ };
38
+ var sheetStack = new SheetStack();
39
+
40
+ // src/core/primitives/transform.ts
41
+ function buildTransformTemplate(axis) {
42
+ switch (axis) {
43
+ case "bottom":
44
+ return (offset) => `translate3d(0, ${offset}px, 0)`;
45
+ case "top":
46
+ return (offset) => `translate3d(0, ${-offset}px, 0)`;
47
+ case "left":
48
+ return (offset) => `translate3d(${-offset}px, 0, 0)`;
49
+ case "right":
50
+ return (offset) => `translate3d(${offset}px, 0, 0)`;
51
+ }
52
+ }
53
+ var layoutAxis = (axis) => axis === "left" || axis === "right" ? "width" : "height";
54
+
55
+ // src/core/primitives/instance-id.ts
56
+ var counters = {};
57
+ function nextInstanceId(prefix) {
58
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
59
+ return `${prefix}-${crypto.randomUUID()}`;
60
+ }
61
+ counters[prefix] = (counters[prefix] ?? 0) + 1;
62
+ return `${prefix}-${counters[prefix]}`;
63
+ }
64
+
65
+ // src/core/primitives/event-bus.ts
66
+ function createEventBus() {
67
+ const listeners = /* @__PURE__ */ new Map();
68
+ return {
69
+ on(event, fn) {
70
+ let set = listeners.get(event);
71
+ if (!set) {
72
+ set = /* @__PURE__ */ new Set();
73
+ listeners.set(event, set);
74
+ }
75
+ set.add(fn);
76
+ return () => {
77
+ set.delete(fn);
78
+ };
79
+ },
80
+ emit(event, payload) {
81
+ const set = listeners.get(event);
82
+ if (!set) return;
83
+ for (const fn of [...set]) {
84
+ fn(payload);
85
+ }
86
+ },
87
+ listenerCount(event) {
88
+ return listeners.get(event)?.size ?? 0;
89
+ },
90
+ clear() {
91
+ listeners.clear();
92
+ }
93
+ };
94
+ }
95
+
96
+ // src/core/primitives/cssLength.ts
97
+ var probe = null;
98
+ var PROBE_ATTR = "data-bs-probe";
99
+ var ensureProbe = (axis) => {
100
+ if (typeof document === "undefined") return null;
101
+ if (!probe || !probe.isConnected) {
102
+ const existing = document.querySelector(`[${PROBE_ATTR}]`);
103
+ if (existing) {
104
+ probe = existing;
105
+ } else {
106
+ probe = document.createElement("div");
107
+ probe.setAttribute("aria-hidden", "true");
108
+ probe.setAttribute(PROBE_ATTR, "");
109
+ probe.style.cssText = "position:absolute;visibility:hidden;pointer-events:none;contain:strict;left:0;top:0;width:0;height:0;";
110
+ document.body.appendChild(probe);
111
+ }
112
+ }
113
+ if (axis === "vertical") {
114
+ probe.style.width = "0";
115
+ probe.style.height = "";
116
+ } else {
117
+ probe.style.height = "0";
118
+ probe.style.width = "";
119
+ }
120
+ return probe;
121
+ };
122
+ var isViewportAxisVertical = (mode) => mode === "bottom" || mode === "top";
123
+ var viewportSize = (mode) => {
124
+ if (typeof window === "undefined") return 0;
125
+ return isViewportAxisVertical(mode) ? window.innerHeight : window.innerWidth;
126
+ };
127
+ var PERCENT = /^(-?\d+(?:\.\d+)?)%$/;
128
+ var resolveSnap = (point, mode, measureFit) => {
129
+ if (typeof point === "number") return Math.max(0, point);
130
+ if (point === "full") return viewportSize(mode);
131
+ if (point === "fit") return Math.max(0, measureFit?.() ?? 0);
132
+ const pctMatch = point.match(PERCENT);
133
+ if (pctMatch) {
134
+ const pct = parseFloat(pctMatch[1]) / 100;
135
+ return Math.max(0, viewportSize(mode) * pct);
136
+ }
137
+ const axis = isViewportAxisVertical(mode) ? "vertical" : "horizontal";
138
+ const el = ensureProbe(axis);
139
+ if (!el) return 0;
140
+ if (axis === "vertical") {
141
+ el.style.height = point;
142
+ return Math.max(0, el.getBoundingClientRect().height);
143
+ }
144
+ el.style.width = point;
145
+ return Math.max(0, el.getBoundingClientRect().width);
146
+ };
147
+
148
+ // src/core/primitives/snap-points.ts
149
+ var resolveSnapList = (points, mode, measureFit) => points.map((p) => {
150
+ const raw = resolveSnap(p.size, mode, measureFit);
151
+ if (!Number.isFinite(raw) || raw < 0) {
152
+ console.warn(
153
+ `[BottomSheet] snap "${p.id}" resolved to invalid size (${String(p.size)} \u2192 ${raw}); clamped to 0.`
154
+ );
155
+ return { id: p.id, size: 0 };
156
+ }
157
+ return { id: p.id, size: raw };
158
+ }).sort((a, b) => a.size - b.size);
159
+ var VH_NOT_DVH = /(^|[^a-z])vh\b/i;
160
+ var auditVhUsage = (points) => {
161
+ for (const p of points) {
162
+ if (typeof p.size !== "string") continue;
163
+ if (!VH_NOT_DVH.test(p.size)) continue;
164
+ console.warn(
165
+ `[BottomSheet] snap "${p.id}" uses "vh" \u2014 prefer "dvh" on mobile (iOS Safari URL bar makes vh unstable). See https://web.dev/blog/viewport-units`
166
+ );
167
+ }
168
+ };
169
+ var findNearest = (size, resolved, allowed, direction = 0, bias = 0) => {
170
+ const pool = resolved.filter((p) => allowed.includes(p.id));
171
+ if (pool.length === 0) return null;
172
+ const target = size + direction * bias;
173
+ let best = pool[0];
174
+ let bestDist = Math.abs(target - best.size);
175
+ for (let i = 1; i < pool.length; i++) {
176
+ const cand = pool[i];
177
+ const dist = Math.abs(target - cand.size);
178
+ if (dist < bestDist) {
179
+ best = cand;
180
+ bestDist = dist;
181
+ }
182
+ }
183
+ return best;
184
+ };
185
+ var allowedRange = (resolved, allowed) => {
186
+ const pool = resolved.filter((p) => allowed.includes(p.id));
187
+ if (pool.length === 0) return { min: 0, max: 0 };
188
+ return {
189
+ min: pool[0].size,
190
+ max: pool[pool.length - 1].size
191
+ };
192
+ };
193
+ var findById = (id, resolved) => resolved.find((p) => p.id === id) ?? null;
194
+ var MOUSE_FLICK_VELOCITY = 0.4;
195
+ var MOUSE_DRAG_THRESHOLD = 12;
196
+ var DIRECTIONAL_INTENT_VELOCITY = 0.15;
197
+ var findDragSettleTarget = (input) => {
198
+ const speed = Math.abs(input.velocity);
199
+ const flickThreshold = input.pointerKind === "mouse" ? MOUSE_FLICK_VELOCITY : input.flickVelocity;
200
+ const dragThresh = input.pointerKind === "mouse" ? MOUSE_DRAG_THRESHOLD : input.dragThreshold;
201
+ let direction = 0;
202
+ if (speed > flickThreshold || speed > DIRECTIONAL_INTENT_VELOCITY) {
203
+ direction = input.velocity > 0 ? 1 : -1;
204
+ }
205
+ if (Math.abs(input.delta) < dragThresh && direction === 0) {
206
+ return findById(input.activeId, input.resolved);
207
+ }
208
+ const speedBias = speed > flickThreshold ? Math.min(speed * 180, input.maxAxisSize) : 0;
209
+ return findNearest(
210
+ input.size,
211
+ input.resolved,
212
+ input.allowed,
213
+ direction,
214
+ speedBias
215
+ );
216
+ };
217
+
218
+ // src/core/primitives/snap-resolver.ts
219
+ var SnapResolver = class {
220
+ constructor(raw, allowed, mode, measureFit, onMaxAxisSizeChange) {
221
+ __publicField(this, "mode", mode);
222
+ __publicField(this, "measureFit", measureFit);
223
+ __publicField(this, "onMaxAxisSizeChange", onMaxAxisSizeChange);
224
+ __publicField(this, "raw");
225
+ __publicField(this, "allowedIds");
226
+ __publicField(this, "resolved", []);
227
+ __publicField(this, "maxAxisSize", 0);
228
+ __publicField(this, "rangeCache", null);
229
+ this.raw = raw;
230
+ this.allowedIds = allowed ?? raw.map((p) => p.id);
231
+ this.recompute();
232
+ }
233
+ /**
234
+ * Re-resolve raw → resolved against the current viewport / fit-measure,
235
+ * recompute maxAxisSize, invalidate range cache, notify engine. Called on
236
+ * resize, orientationchange, visualViewport changes, and snap-list swaps.
237
+ */
238
+ recompute() {
239
+ this.resolved = resolveSnapList(this.raw, this.mode, this.measureFit);
240
+ this.maxAxisSize = this.resolved.reduce(
241
+ (m, s) => s.size > m ? s.size : m,
242
+ 0
243
+ );
244
+ this.rangeCache = null;
245
+ this.onMaxAxisSizeChange?.(this.maxAxisSize);
246
+ }
247
+ /** Replace the raw snap list and recompute. Engine calls on `setSnapPoints`. */
248
+ setRaw(raw) {
249
+ this.raw = raw;
250
+ this.recompute();
251
+ }
252
+ /**
253
+ * Replace the allow-list. Range cache depends on `(resolvedSnaps ×
254
+ * allowedIds)` so flipping ids alone invalidates without a full recompute.
255
+ */
256
+ setAllowedIds(ids) {
257
+ this.allowedIds = ids;
258
+ this.rangeCache = null;
259
+ }
260
+ findById(id) {
261
+ return findById(id, this.resolved);
262
+ }
263
+ /**
264
+ * Pure drag-settle target resolution. Engine passes the gesture-specific
265
+ * fields (delta, velocity, pointerKind, flickVelocity, dragThreshold) plus
266
+ * `size`/`activeId` since those are still engine-owned.
267
+ */
268
+ findDragSettleTarget(args) {
269
+ return findDragSettleTarget({
270
+ ...args,
271
+ resolved: this.resolved,
272
+ allowed: this.allowedIds,
273
+ maxAxisSize: this.maxAxisSize
274
+ });
275
+ }
276
+ /**
277
+ * Memoised allowed-range query. Twice-per-drag-frame (gesture onMove +
278
+ * applySize→computeProgress); cache collapses 2× iteration of resolvedSnaps
279
+ * to one recompute per geometry/allow-list change.
280
+ */
281
+ getAllowedRange() {
282
+ return this.rangeCache ?? (this.rangeCache = allowedRange(this.resolved, this.allowedIds));
283
+ }
284
+ /**
285
+ * Read-only view of resolved snaps. Returned as `readonly` to discourage
286
+ * accidental mutation by feature install sites that close over this list.
287
+ */
288
+ getResolvedSnaps() {
289
+ return this.resolved;
290
+ }
291
+ getAllowedIds() {
292
+ return this.allowedIds;
293
+ }
294
+ getMaxAxisSize() {
295
+ return this.maxAxisSize;
296
+ }
297
+ /**
298
+ * External clamp override. The resize-observer feature compares
299
+ * `getMaxAxisSize()` against the live viewport and shrinks if the largest
300
+ * resolved snap exceeds it (mobile address-bar collapse / soft-keyboard
301
+ * window resize). The next `recompute()` overwrites this clamp from the
302
+ * resolved-snap reduction.
303
+ *
304
+ * Does NOT invalidate the range cache — viewport clamping doesn't change
305
+ * `(resolvedSnaps × allowedIds) → range`. DOES fire `onMaxAxisSizeChange`
306
+ * so the resolver owns the layout-axis style write end-to-end (symmetric
307
+ * with `recompute()` — feature call sites no longer duplicate the write).
308
+ */
309
+ setMaxAxisSize(n) {
310
+ this.maxAxisSize = n;
311
+ this.onMaxAxisSizeChange?.(n);
312
+ }
313
+ };
314
+
315
+ // src/core/features/persist.ts
316
+ function readPersistedId(key) {
317
+ if (!key) return null;
318
+ if (typeof window === "undefined") return null;
319
+ if (typeof localStorage === "undefined") return null;
320
+ try {
321
+ return localStorage.getItem(key);
322
+ } catch {
323
+ return null;
324
+ }
325
+ }
326
+ function installPersist(engine, key) {
327
+ const unsubscribe = engine.on("snap", ({ id }) => {
328
+ if (typeof window === "undefined") return;
329
+ if (typeof localStorage === "undefined") return;
330
+ try {
331
+ localStorage.setItem(key, id);
332
+ } catch {
333
+ }
334
+ });
335
+ return unsubscribe;
336
+ }
337
+
338
+ // src/core/features/auto-collapse.ts
339
+ function installAutoCollapse(deps) {
340
+ const { ms } = deps;
341
+ if (ms === void 0 || ms <= 0) {
342
+ return () => {
343
+ };
344
+ }
345
+ let timer = null;
346
+ const clearTimer = () => {
347
+ if (timer !== null) {
348
+ clearTimeout(timer);
349
+ timer = null;
350
+ }
351
+ };
352
+ const fire = () => {
353
+ if (deps.isDestroyed()) return;
354
+ if (deps.isDragging()) return;
355
+ const allowed = deps.getAllowedIds();
356
+ const target = allowed.find((id) => {
357
+ const snap = deps.resolveSnap(id);
358
+ return snap !== null && snap.size > 0;
359
+ });
360
+ if (!target) return;
361
+ if (target === deps.getActiveId()) return;
362
+ deps.snapTo(target);
363
+ };
364
+ const reset = () => {
365
+ clearTimer();
366
+ if (deps.isDestroyed()) return;
367
+ timer = setTimeout(() => {
368
+ timer = null;
369
+ fire();
370
+ }, ms);
371
+ };
372
+ const unsubscribe = deps.on("snap", () => reset());
373
+ return () => {
374
+ clearTimer();
375
+ unsubscribe();
376
+ };
377
+ }
378
+
379
+ // src/core/features/linked-sheets.ts
380
+ function notifyLinkedSheets(sheets, self) {
381
+ if (sheets.length === 0) return;
382
+ for (const linked of sheets) {
383
+ if (linked === self) continue;
384
+ try {
385
+ const ids = linked.getAllowedIds();
386
+ const target = ids.find((id) => id !== "closed");
387
+ if (target && target !== linked.state.activeId) {
388
+ void linked.snapTo(target);
389
+ }
390
+ } catch (err) {
391
+ queueMicrotask(() => {
392
+ throw err;
393
+ });
394
+ }
395
+ }
396
+ }
397
+
398
+ // src/core/features/route.ts
399
+ function installRoute(deps) {
400
+ if (typeof window === "undefined") {
401
+ return () => {
402
+ };
403
+ }
404
+ if (!deps.routedTo && !deps.closeOnBack) {
405
+ return () => {
406
+ };
407
+ }
408
+ let routePushed = false;
409
+ let closeOnBackPushed = false;
410
+ let detachPopstate = null;
411
+ const popOurMarker = (key, expected) => {
412
+ const state = history.state;
413
+ if (state && state[key] === expected) {
414
+ try {
415
+ history.back();
416
+ } catch {
417
+ }
418
+ }
419
+ };
420
+ const onOpen = () => {
421
+ if (deps.routedTo && !detachPopstate) {
422
+ const target = deps.routedTo;
423
+ try {
424
+ history.pushState({ __bsRouted: target }, "", target);
425
+ routePushed = true;
426
+ } catch {
427
+ }
428
+ const onPop = (event) => {
429
+ if (deps.isDestroyed()) return;
430
+ const state = event.state;
431
+ if (state && state.__bsRouted === target && deps.getSize() > 0) {
432
+ routePushed = false;
433
+ void deps.close();
434
+ }
435
+ };
436
+ window.addEventListener("popstate", onPop);
437
+ detachPopstate = () => window.removeEventListener("popstate", onPop);
438
+ } else if (deps.closeOnBack && !detachPopstate) {
439
+ try {
440
+ history.pushState({ __bsSheet: deps.sheetId }, "");
441
+ closeOnBackPushed = true;
442
+ } catch {
443
+ }
444
+ const onPop = () => {
445
+ if (deps.isDestroyed()) return;
446
+ if (deps.getSize() > 0 && deps.isTopSheet()) {
447
+ const state = history.state;
448
+ if (state?.__bsSheet !== deps.sheetId) closeOnBackPushed = false;
449
+ void deps.close();
450
+ }
451
+ };
452
+ window.addEventListener("popstate", onPop);
453
+ detachPopstate = () => window.removeEventListener("popstate", onPop);
454
+ }
455
+ };
456
+ const onClose = () => {
457
+ detachPopstate?.();
458
+ detachPopstate = null;
459
+ if (routePushed) {
460
+ routePushed = false;
461
+ if (deps.routedTo !== void 0) popOurMarker("__bsRouted", deps.routedTo);
462
+ }
463
+ if (closeOnBackPushed) {
464
+ closeOnBackPushed = false;
465
+ popOurMarker("__bsSheet", deps.sheetId);
466
+ }
467
+ };
468
+ const unsubscribeOpen = deps.on("open", onOpen);
469
+ const unsubscribeClose = deps.on("close", onClose);
470
+ if (deps.getSize() > 0) onOpen();
471
+ return () => {
472
+ unsubscribeOpen();
473
+ unsubscribeClose();
474
+ detachPopstate?.();
475
+ detachPopstate = null;
476
+ if (routePushed) {
477
+ routePushed = false;
478
+ if (deps.routedTo !== void 0) popOurMarker("__bsRouted", deps.routedTo);
479
+ }
480
+ if (closeOnBackPushed) {
481
+ closeOnBackPushed = false;
482
+ popOurMarker("__bsSheet", deps.sheetId);
483
+ }
484
+ };
485
+ }
486
+
487
+ // src/core/features/content-swipe.ts
488
+ var CONTENT_PULL_THRESHOLD = 60;
489
+ function installContentSwipe(deps) {
490
+ const { container } = deps;
491
+ let startY = 0;
492
+ let moved = false;
493
+ const onTouchStart = (e) => {
494
+ const t = e.touches[0];
495
+ if (!t) return;
496
+ startY = t.clientY;
497
+ moved = false;
498
+ };
499
+ const onTouchMove = (e) => {
500
+ const t = e.touches[0];
501
+ if (!t) return;
502
+ if (Math.abs(t.clientY - startY) > CONTENT_PULL_THRESHOLD) moved = true;
503
+ };
504
+ const onTouchEnd = (e) => {
505
+ if (!moved) return;
506
+ if (deps.isDragging() || deps.isAnimating()) return;
507
+ const t = e.changedTouches[0];
508
+ if (!t) return;
509
+ const deltaY = t.clientY - startY;
510
+ const atTop = container.scrollTop <= 0;
511
+ const allowed = deps.getAllowedIds();
512
+ const idx = allowed.indexOf(deps.getActiveId());
513
+ if (idx === -1) return;
514
+ if (atTop && deltaY > CONTENT_PULL_THRESHOLD && idx > 0) {
515
+ deps.snapTo(allowed[idx - 1]);
516
+ } else if (deltaY < -CONTENT_PULL_THRESHOLD && idx < allowed.length - 1) {
517
+ deps.snapTo(allowed[idx + 1]);
518
+ }
519
+ };
520
+ container.addEventListener("touchstart", onTouchStart, { passive: true });
521
+ container.addEventListener("touchmove", onTouchMove, { passive: true });
522
+ container.addEventListener("touchend", onTouchEnd, { passive: true });
523
+ return () => {
524
+ container.removeEventListener("touchstart", onTouchStart);
525
+ container.removeEventListener("touchmove", onTouchMove);
526
+ container.removeEventListener("touchend", onTouchEnd);
527
+ };
528
+ }
529
+
530
+ // src/core/features/visual-viewport.ts
531
+ var SAFETY_PAD = 8;
532
+ function installVisualViewport(deps) {
533
+ if (typeof window === "undefined" || !window.visualViewport) {
534
+ return () => {
535
+ };
536
+ }
537
+ const vv = window.visualViewport;
538
+ let rafId = null;
539
+ const onResize = () => {
540
+ if (rafId !== null) return;
541
+ rafId = requestAnimationFrame(() => {
542
+ rafId = null;
543
+ if (deps.isDestroyed()) return;
544
+ deps.recomputeSnaps();
545
+ const isVertical = deps.isVerticalAxis();
546
+ const visible = isVertical ? vv.height : vv.width;
547
+ const windowSize = isVertical ? window.innerHeight : window.innerWidth;
548
+ const clamp = Math.max(0, Math.min(windowSize, visible) - SAFETY_PAD);
549
+ if (clamp < deps.getMaxAxisSize()) {
550
+ deps.setMaxAxisSize(clamp);
551
+ }
552
+ const max = deps.getMaxAxisSize();
553
+ deps.setSize(Math.min(deps.getSize(), max));
554
+ const current = deps.resolveActiveSnap();
555
+ if (current && !deps.isDragging()) {
556
+ deps.applySize(Math.min(current.size, max));
557
+ } else {
558
+ deps.applySize(deps.getSize());
559
+ }
560
+ });
561
+ };
562
+ vv.addEventListener("resize", onResize);
563
+ return () => {
564
+ vv.removeEventListener("resize", onResize);
565
+ if (rafId !== null) cancelAnimationFrame(rafId);
566
+ };
567
+ }
568
+
569
+ // src/core/features/resize-observer.ts
570
+ function installResizeObserver(deps) {
571
+ if (typeof window === "undefined") {
572
+ return () => {
573
+ };
574
+ }
575
+ const onResize = () => {
576
+ if (deps.isDestroyed()) return;
577
+ deps.recomputeSnaps();
578
+ const mode = deps.getMode();
579
+ const isVerticalAxis = mode === "bottom" || mode === "top";
580
+ const viewportSize2 = isVerticalAxis ? window.innerHeight : window.innerWidth;
581
+ const max = deps.getMaxAxisSize();
582
+ if (viewportSize2 > 0 && viewportSize2 < max) {
583
+ deps.setMaxAxisSize(viewportSize2);
584
+ }
585
+ deps.cancelInFlight();
586
+ deps.newCycle();
587
+ const current = deps.resolveActiveSnap();
588
+ const newMax = deps.getMaxAxisSize();
589
+ const targetSize = current ? Math.min(current.size, newMax) : Math.min(deps.getSize(), newMax);
590
+ deps.setSize(targetSize);
591
+ if (current && !deps.isDragging()) deps.applySize(targetSize);
592
+ };
593
+ let resizeObserver = null;
594
+ if (typeof ResizeObserver !== "undefined") {
595
+ resizeObserver = new ResizeObserver(onResize);
596
+ resizeObserver.observe(document.documentElement);
597
+ } else {
598
+ window.addEventListener("resize", onResize);
599
+ }
600
+ window.addEventListener("orientationchange", onResize);
601
+ const onVisibility = () => {
602
+ if (deps.isDestroyed()) return;
603
+ if (document.hidden) deps.cancelInFlight();
604
+ };
605
+ document.addEventListener("visibilitychange", onVisibility);
606
+ return () => {
607
+ resizeObserver?.disconnect();
608
+ window.removeEventListener("resize", onResize);
609
+ window.removeEventListener("orientationchange", onResize);
610
+ document.removeEventListener("visibilitychange", onVisibility);
611
+ };
612
+ }
613
+
614
+ // src/core/features/slider-keyboard.ts
615
+ function installSliderKeyboard(deps) {
616
+ const isVerticalAxis = deps.mode === "bottom" || deps.mode === "top";
617
+ const stepUp = isVerticalAxis ? "ArrowUp" : "ArrowRight";
618
+ const stepDown = isVerticalAxis ? "ArrowDown" : "ArrowLeft";
619
+ const sheetExpandsKey = deps.mode === "top" ? stepDown : stepUp;
620
+ const sheetCollapsesKey = deps.mode === "top" ? stepUp : stepDown;
621
+ const onHandleKey = (e) => {
622
+ if (deps.isDestroyed()) return;
623
+ const allowed = deps.getAllowedIds();
624
+ const idx = allowed.indexOf(deps.getActiveId());
625
+ if (idx === -1) return;
626
+ if (e.key === sheetExpandsKey && idx < allowed.length - 1) {
627
+ e.preventDefault();
628
+ deps.snapTo(allowed[idx + 1]);
629
+ } else if (e.key === sheetCollapsesKey && idx > 0) {
630
+ e.preventDefault();
631
+ deps.snapTo(allowed[idx - 1]);
632
+ } else if (e.key === "Home") {
633
+ e.preventDefault();
634
+ deps.snapTo(allowed[0]);
635
+ } else if (e.key === "End") {
636
+ e.preventDefault();
637
+ deps.snapTo(allowed[allowed.length - 1]);
638
+ }
639
+ };
640
+ deps.handle.addEventListener("keydown", onHandleKey);
641
+ return () => deps.handle.removeEventListener("keydown", onHandleKey);
642
+ }
643
+
644
+ // src/core/types.ts
645
+ var SCRIM_PRESETS = Object.freeze({
646
+ subtle: {
647
+ color: "rgba(0,0,0,0.2)",
648
+ blur: void 0,
649
+ range: [0.3, 1],
650
+ interactive: false
651
+ },
652
+ standard: {
653
+ color: "rgba(0,0,0,0.4)",
654
+ blur: void 0,
655
+ range: [0, 1],
656
+ interactive: false
657
+ },
658
+ monitoring: {
659
+ color: "rgba(15,15,20,0.55)",
660
+ blur: "4px",
661
+ range: [0, 1],
662
+ interactive: false
663
+ },
664
+ cinematic: {
665
+ color: "rgba(0,0,0,0.7)",
666
+ blur: "12px",
667
+ range: [0, 1],
668
+ interactive: false
669
+ }
670
+ });
671
+
672
+ // src/core/primitives/hot-path-thresholds.ts
673
+ var SIZE_WRITE_EPSILON = 0.5;
674
+ var OPACITY_WRITE_EPSILON = 5e-3;
675
+ var POINTER_EVENTS_OPACITY_THRESHOLD = 0.05;
676
+ var RANGE_DIVISION_EPSILON = 1e-4;
677
+
678
+ // src/core/primitives/opacity-dedup.ts
679
+ var WriteSentinel = class {
680
+ constructor() {
681
+ __publicField(this, "last", -1);
682
+ }
683
+ /**
684
+ * Returns `true` (and updates the cached value) if `next` differs from the
685
+ * cached `last` by more than `epsilon`. Returns `false` (and leaves the
686
+ * cache untouched) when the delta is within epsilon — caller skips the
687
+ * CSSOM write.
688
+ */
689
+ shouldWrite(next, epsilon) {
690
+ if (Math.abs(next - this.last) <= epsilon) return false;
691
+ this.last = next;
692
+ return true;
693
+ }
694
+ /**
695
+ * Force the next `shouldWrite` to pass. Resets the cache to `-1` so any
696
+ * non-negative `next` exceeds the epsilon comparison. Called from setters
697
+ * that mutate state under the cache (range/mode/enabled flips that change
698
+ * the progress→opacity mapping but don't move `progress` itself).
699
+ */
700
+ invalidate() {
701
+ this.last = -1;
702
+ }
703
+ /**
704
+ * Record `value` as the last-written without performing a write. Used
705
+ * when a setter writes a literal value through a different path (e.g.
706
+ * `setScrimMode("off")` writes `opacity: "0"` inline) and wants future
707
+ * `shouldWrite` calls to short-circuit against that known cached state.
708
+ */
709
+ setLastWritten(value) {
710
+ this.last = value;
711
+ }
712
+ /** Read-only accessor for diagnostic / dedup-aware peek. */
713
+ get value() {
714
+ return this.last;
715
+ }
716
+ };
717
+
718
+ // src/core/controllers/scrim-controller.ts
719
+ var ScrimController = class {
720
+ constructor(deps, opts) {
721
+ // ── DOM refs (mirror engine's; cached for hot path) ─────────────────
722
+ __publicField(this, "screenComponent");
723
+ __publicField(this, "backdrop");
724
+ __publicField(this, "mode");
725
+ // ── Engine callbacks ────────────────────────────────────────────────
726
+ __publicField(this, "isDestroyed");
727
+ __publicField(this, "isTopSheet");
728
+ __publicField(this, "getAllowedIds");
729
+ __publicField(this, "getResolvedSnaps");
730
+ __publicField(this, "snapToFn");
731
+ // ── Mode + state ────────────────────────────────────────────────────
732
+ __publicField(this, "scrimMode");
733
+ __publicField(this, "backdropRange");
734
+ __publicField(this, "screenRange");
735
+ // setScrimEnabled toggle — gated through `scrimEnabled` rather than nuking
736
+ // ranges so re-enable can restore prior values without a remount. Public
737
+ // so tests / introspection can read it without an `as any` cast.
738
+ __publicField(this, "scrimEnabled", true);
739
+ __publicField(this, "savedScrimRanges", null);
740
+ // ── Tap-to-close ────────────────────────────────────────────────────
741
+ __publicField(this, "scrimTapToCloseEnabled", false);
742
+ __publicField(this, "detachScrimTap", null);
743
+ // ── Scrim overlay slot (positioned floating element) ────────────────
744
+ __publicField(this, "scrimOverlayTeardown", null);
745
+ // ── Hot-path opacity dedup caches (per-frame writes) ────────────────
746
+ // Numeric sentinels migrated to WriteSentinel primitive — single
747
+ // invalidation surface, shared with the engine's size/progress sentinels.
748
+ // The two string-typed sentinels (`Pointer`, `Display`) keep their inline
749
+ // pattern: equality on string union, no epsilon, different reset semantics.
750
+ __publicField(this, "backdropOpacitySentinel", new WriteSentinel());
751
+ __publicField(this, "screenOpacitySentinel", new WriteSentinel());
752
+ __publicField(this, "lastBackdropPointer", "");
753
+ __publicField(this, "lastScreenDisplay", "");
754
+ this.screenComponent = deps.screenComponent;
755
+ this.backdrop = deps.backdrop;
756
+ this.mode = deps.mode;
757
+ this.isDestroyed = deps.isDestroyed;
758
+ this.isTopSheet = deps.isTopSheet;
759
+ this.getAllowedIds = deps.getAllowedIds;
760
+ this.getResolvedSnaps = deps.getResolvedSnaps;
761
+ this.snapToFn = deps.snapTo;
762
+ this.scrimMode = opts.scrimMode ?? "full";
763
+ const preset = opts.scrimPreset ? SCRIM_PRESETS[opts.scrimPreset] : null;
764
+ this.backdropRange = opts.backdropRange ?? preset?.range ?? [0, 1];
765
+ this.screenRange = opts.screenRange ?? preset?.range ?? [0, 1];
766
+ this.scrimTapToCloseEnabled = opts.scrimTapToClose ?? false;
767
+ if (this.screenComponent) {
768
+ this.applyScrimStyles({
769
+ color: opts.scrimColor ?? preset?.color,
770
+ blur: opts.scrimBlur ?? preset?.blur,
771
+ interactive: opts.scrimInteractive ?? preset?.interactive ?? false
772
+ });
773
+ if (this.scrimMode === "above-sheet") {
774
+ this.applyAboveSheetInset();
775
+ } else if (this.scrimMode === "off") {
776
+ const s = this.screenComponent.style;
777
+ s.opacity = "0";
778
+ s.display = "none";
779
+ this.screenOpacitySentinel.setLastWritten(0);
780
+ this.lastScreenDisplay = "none";
781
+ }
782
+ }
783
+ }
784
+ /**
785
+ * Invalidate the opacity dedup caches. Called from any setter that mutates
786
+ * range/mode/enabled — opacity is a pure function of (progress, range,
787
+ * enabled), so a config change makes the cached values stale even if
788
+ * `progress` itself didn't move. Next `applyOpacity(progress, false)` call
789
+ * sees the -1 sentinel and re-runs the math instead of short-circuiting.
790
+ *
791
+ * Public for the engine: `setSnapPoints` mutates resolved geometry which
792
+ * shifts `progress→opacity` mapping under the cache; engine calls this to
793
+ * keep the next render frame correct on a static sheet.
794
+ * @internal
795
+ */
796
+ invalidateOpacityCache() {
797
+ this.backdropOpacitySentinel.invalidate();
798
+ this.screenOpacitySentinel.invalidate();
799
+ }
800
+ /** Engine calls this when its `attach()` runs — installs scrim-tap-click if requested. */
801
+ attach() {
802
+ if (this.scrimTapToCloseEnabled) {
803
+ this.setScrimTapToClose(true);
804
+ }
805
+ }
806
+ // ── Hot-path: opacity computation called per-frame from engine.applySize ──
807
+ /**
808
+ * Per-frame opacity writer. Computes backdrop + screen opacity from the
809
+ * sheet's progress (0..1 within allowed range), gated by sub-pixel dedup
810
+ * caches so steady-state frames don't trigger style recalc.
811
+ *
812
+ * `progressChanged` is the engine's already-computed dedup gate — when
813
+ * `false`, opacity is by construction a pure function of `progress` so
814
+ * cached values are still valid; we short-circuit the Math.min/max +
815
+ * division work entirely. Setters that mutate ranges/mode/enabled
816
+ * invalidate the cache by writing -1 sentinels so the next call re-runs
817
+ * the math.
818
+ */
819
+ applyOpacity(progress, progressChanged) {
820
+ if (!progressChanged && this.backdropOpacitySentinel.value !== -1 && this.screenOpacitySentinel.value !== -1) {
821
+ return;
822
+ }
823
+ if (this.backdrop && this.isTopSheet()) {
824
+ const [s, e] = this.backdropRange;
825
+ const range = Math.max(e - s, RANGE_DIVISION_EPSILON);
826
+ const backdropOpacity = Math.min(
827
+ Math.max((progress - s) / range, 0),
828
+ 1
829
+ );
830
+ if (this.backdropOpacitySentinel.shouldWrite(
831
+ backdropOpacity,
832
+ OPACITY_WRITE_EPSILON
833
+ )) {
834
+ this.backdrop.style.opacity = String(backdropOpacity);
835
+ }
836
+ const nextPointer = backdropOpacity > POINTER_EVENTS_OPACITY_THRESHOLD ? "auto" : "none";
837
+ if (nextPointer !== this.lastBackdropPointer) {
838
+ this.backdrop.style.pointerEvents = nextPointer;
839
+ this.lastBackdropPointer = nextPointer;
840
+ }
841
+ }
842
+ if (this.screenComponent && this.scrimMode !== "off") {
843
+ const [ss, se] = this.screenRange;
844
+ const screenOpacity = Math.min(
845
+ 1,
846
+ Math.max(
847
+ 0,
848
+ (progress - ss) / Math.max(RANGE_DIVISION_EPSILON, se - ss)
849
+ )
850
+ );
851
+ if (this.screenOpacitySentinel.shouldWrite(
852
+ screenOpacity,
853
+ OPACITY_WRITE_EPSILON
854
+ )) {
855
+ this.screenComponent.style.opacity = String(screenOpacity);
856
+ }
857
+ const nextDisplay = screenOpacity > 0 ? "" : "none";
858
+ if (nextDisplay !== this.lastScreenDisplay) {
859
+ this.screenComponent.style.display = nextDisplay;
860
+ this.lastScreenDisplay = nextDisplay;
861
+ }
862
+ }
863
+ }
864
+ // ── Public setters (engine forwards these 1:1) ─────────────────────
865
+ /**
866
+ * Replace the [start, end] progress window in which the backdrop fades 0→1.
867
+ * @param range - Tuple of two progress values in 0..1 (start <= end).
868
+ * @param applySize - Engine-supplied recompute hook; runs one applyOpacity pass.
869
+ * @example
870
+ * // Backdrop only starts darkening after the sheet crosses 30% open.
871
+ * engine.setBackdropRange([0.3, 1]);
872
+ */
873
+ setBackdropRange(range, applySize) {
874
+ if (this.isDestroyed()) return;
875
+ this.backdropRange = range;
876
+ this.invalidateOpacityCache();
877
+ applySize();
878
+ }
879
+ /**
880
+ * Replace the [start, end] progress window in which the screen scrim fades 0→1.
881
+ * @param range - Tuple of two progress values in 0..1 (start <= end).
882
+ * @param applySize - Engine-supplied recompute hook; runs one applyOpacity pass.
883
+ * @example
884
+ * // Scrim is fully opaque only when the sheet is past 50% — softer feel.
885
+ * engine.setScreenRange([0, 0.5]);
886
+ */
887
+ setScreenRange(range, applySize) {
888
+ if (this.isDestroyed()) return;
889
+ this.screenRange = range;
890
+ this.invalidateOpacityCache();
891
+ applySize();
892
+ }
893
+ /**
894
+ * Set the scrim background color. Pass `null`/`undefined` to clear the
895
+ * inline write and let consumer CSS take over.
896
+ * @param color - Any valid CSS color string, or `null`/`undefined` to clear.
897
+ * @example
898
+ * engine.setScrimColor("rgba(0, 0, 0, 0.6)");
899
+ * engine.setScrimColor(null); // hand back to consumer CSS
900
+ */
901
+ setScrimColor(color) {
902
+ if (this.isDestroyed()) return;
903
+ this.applyScrimStyles({ color: color === void 0 ? null : color });
904
+ }
905
+ /**
906
+ * Set the scrim backdrop-filter blur radius. Pass `null`/`undefined` to clear.
907
+ * @param blur - CSS length (e.g. `"8px"`) consumed as `blur(<value>)`, or
908
+ * `null`/`undefined` to remove the filter.
909
+ * @example
910
+ * engine.setScrimBlur("12px"); // frosted-glass effect
911
+ * engine.setScrimBlur(null); // disable blur
912
+ */
913
+ setScrimBlur(blur) {
914
+ if (this.isDestroyed()) return;
915
+ this.applyScrimStyles({ blur: blur === void 0 ? null : blur });
916
+ }
917
+ /**
918
+ * Toggle whether the scrim layer captures pointer events.
919
+ * @param interactive - `true` → `pointer-events: auto`; `false` → `none`.
920
+ * @example
921
+ * engine.setScrimInteractive(true); // scrim swallows clicks
922
+ * engine.setScrimInteractive(false); // clicks pass through to content below
923
+ */
924
+ setScrimInteractive(interactive) {
925
+ if (this.isDestroyed()) return;
926
+ this.applyScrimStyles({ interactive });
927
+ }
928
+ /**
929
+ * Switch scrim positioning at runtime.
930
+ * @param mode - `"full"` (consumer CSS), `"above-sheet"` (engine-pinned inset
931
+ * so only the area NOT covered by the sheet is dimmed), or
932
+ * `"off"` (display:none + opacity:0 — no remount needed).
933
+ * @param applySize - Engine-supplied recompute hook; runs one applyOpacity pass.
934
+ * @example
935
+ * engine.setScrimMode("above-sheet"); // dim only the area above the sheet
936
+ * engine.setScrimMode("off"); // disable scrim layer
937
+ */
938
+ setScrimMode(mode, applySize) {
939
+ if (this.isDestroyed()) return;
940
+ if (mode === this.scrimMode) return;
941
+ this.invalidateOpacityCache();
942
+ const previous = this.scrimMode;
943
+ this.scrimMode = mode;
944
+ if (this.screenComponent) {
945
+ const s = this.screenComponent.style;
946
+ if (previous === "above-sheet" && mode !== "above-sheet") {
947
+ s.position = "";
948
+ s.inset = "";
949
+ s.pointerEvents = "";
950
+ }
951
+ if (mode === "above-sheet") {
952
+ this.applyAboveSheetInset();
953
+ } else if (mode === "off") {
954
+ s.opacity = "0";
955
+ s.display = "none";
956
+ this.screenOpacitySentinel.setLastWritten(0);
957
+ this.lastScreenDisplay = "none";
958
+ } else {
959
+ if (this.lastScreenDisplay === "none") {
960
+ s.display = "";
961
+ this.lastScreenDisplay = "";
962
+ }
963
+ }
964
+ }
965
+ applySize();
966
+ }
967
+ /**
968
+ * Enable or disable click-on-scrim → snap to first non-zero allowed snap.
969
+ * Auto-promotes `pointer-events: auto` when scrim is non-interactive so the
970
+ * click listener actually fires.
971
+ * @param enabled - `true` installs the click listener; `false` removes it.
972
+ * @example
973
+ * engine.setScrimTapToClose(true); // tap outside sheet collapses it
974
+ * engine.setScrimTapToClose(false); // require explicit close button
975
+ */
976
+ setScrimTapToClose(enabled) {
977
+ if (this.isDestroyed()) return;
978
+ if (!this.screenComponent) return;
979
+ const installed = this.detachScrimTap !== null;
980
+ if (enabled === installed) return;
981
+ if (enabled) {
982
+ const target = this.screenComponent;
983
+ if (target.style.pointerEvents === "none") {
984
+ target.style.pointerEvents = "auto";
985
+ }
986
+ const onClick = () => {
987
+ if (this.isDestroyed()) return;
988
+ const allowed = this.getAllowedIds();
989
+ const snaps = this.getResolvedSnaps();
990
+ const fallback = allowed.find((id) => {
991
+ const snap = findById(id, snaps);
992
+ return snap !== null && snap.size > 0;
993
+ });
994
+ if (fallback) this.snapToFn(fallback);
995
+ };
996
+ target.addEventListener("click", onClick);
997
+ this.detachScrimTap = () => target.removeEventListener("click", onClick);
998
+ this.scrimTapToCloseEnabled = true;
999
+ } else {
1000
+ this.detachScrimTap?.();
1001
+ this.detachScrimTap = null;
1002
+ this.scrimTapToCloseEnabled = false;
1003
+ }
1004
+ }
1005
+ /**
1006
+ * Toggle the scrim layer without remounting. Disabling stashes current
1007
+ * `screenRange`/`backdropRange` and degenerates them to `[1, 1]` (opacity
1008
+ * formula → 0 across the whole range); re-enabling restores the saved values.
1009
+ * @param enabled - `false` hides scrim, `true` restores prior ranges.
1010
+ * @param applySize - Engine-supplied recompute hook; runs one applyOpacity pass.
1011
+ * @example
1012
+ * engine.setScrimEnabled(false); // hide scrim, ranges remembered
1013
+ * engine.setScrimEnabled(true); // restore prior ranges (no remount)
1014
+ */
1015
+ setScrimEnabled(enabled, applySize) {
1016
+ if (this.isDestroyed()) return;
1017
+ if (enabled === this.scrimEnabled) return;
1018
+ this.scrimEnabled = enabled;
1019
+ if (!enabled) {
1020
+ this.savedScrimRanges = {
1021
+ screen: this.screenRange,
1022
+ backdrop: this.backdropRange
1023
+ };
1024
+ this.screenRange = [1, 1];
1025
+ this.backdropRange = [1, 1];
1026
+ } else {
1027
+ this.screenRange = this.savedScrimRanges?.screen ?? [0, 1];
1028
+ this.backdropRange = this.savedScrimRanges?.backdrop ?? [0, 1];
1029
+ this.savedScrimRanges = null;
1030
+ }
1031
+ applySize();
1032
+ }
1033
+ /**
1034
+ * Batch-update multiple scrim fields with a single applySize() at the end.
1035
+ * If `preset` is set, it seeds color/blur/interactive/range first; explicit
1036
+ * fields override.
1037
+ * @param opts - Partial scrim config: preset, mode, enabled, tapToClose,
1038
+ * color, blur, interactive, range.
1039
+ * @param applySize - Engine-supplied recompute hook; runs ONCE per call.
1040
+ * @example
1041
+ * engine.setScrim({
1042
+ * preset: "frosted",
1043
+ * mode: "above-sheet",
1044
+ * tapToClose: true,
1045
+ * });
1046
+ */
1047
+ setScrim(opts, applySize) {
1048
+ if (this.isDestroyed()) return;
1049
+ if (opts.preset) {
1050
+ const cfg = SCRIM_PRESETS[opts.preset];
1051
+ this.applyScrimStyles({
1052
+ color: cfg.color,
1053
+ blur: cfg.blur ?? null,
1054
+ interactive: cfg.interactive
1055
+ });
1056
+ this.screenRange = cfg.range;
1057
+ }
1058
+ const noop = () => {
1059
+ };
1060
+ if (opts.mode !== void 0) this.setScrimMode(opts.mode, noop);
1061
+ if (opts.enabled !== void 0) this.setScrimEnabled(opts.enabled, noop);
1062
+ if (opts.tapToClose !== void 0) this.setScrimTapToClose(opts.tapToClose);
1063
+ this.applyScrimStyles({
1064
+ color: opts.color,
1065
+ blur: opts.blur,
1066
+ interactive: opts.interactive
1067
+ });
1068
+ if (opts.range !== void 0) {
1069
+ this.screenRange = opts.range;
1070
+ }
1071
+ this.invalidateOpacityCache();
1072
+ applySize();
1073
+ }
1074
+ /**
1075
+ * Inject a positioned floating element into the scrim layer (e.g. a close
1076
+ * button anchored top-right). Replaces any prior overlay so repeated calls
1077
+ * (reactive effects re-running) don't accumulate wrappers.
1078
+ * @param opts - Children element, optional `inset` (default `"16px"`),
1079
+ * `position` (9-way grid, default `"top-right"`), and
1080
+ * `interactive` flag (default `true`).
1081
+ * @returns Teardown function that removes the wrapper from the DOM.
1082
+ * @example
1083
+ * const teardown = engine.setScrimOverlay({
1084
+ * children: closeBtn,
1085
+ * position: "top-right",
1086
+ * inset: "20px",
1087
+ * });
1088
+ * // later: teardown(); // remove the floating button
1089
+ */
1090
+ setScrimOverlay(opts) {
1091
+ if (this.isDestroyed()) return () => {
1092
+ };
1093
+ if (!this.screenComponent) return () => {
1094
+ };
1095
+ this.scrimOverlayTeardown?.();
1096
+ const screen = this.screenComponent;
1097
+ const inset = opts.inset ?? "16px";
1098
+ const position = opts.position ?? "top-right";
1099
+ const interactive = opts.interactive ?? true;
1100
+ const wrapper = screen.ownerDocument.createElement("div");
1101
+ wrapper.className = "bs-scrim-overlay";
1102
+ const ws = wrapper.style;
1103
+ ws.position = "absolute";
1104
+ switch (position) {
1105
+ case "top-left":
1106
+ ws.top = inset;
1107
+ ws.left = inset;
1108
+ break;
1109
+ case "top-center":
1110
+ ws.top = inset;
1111
+ ws.left = "50%";
1112
+ ws.transform = "translateX(-50%)";
1113
+ break;
1114
+ case "top-right":
1115
+ ws.top = inset;
1116
+ ws.right = inset;
1117
+ break;
1118
+ case "center-left":
1119
+ ws.top = "50%";
1120
+ ws.left = inset;
1121
+ ws.transform = "translateY(-50%)";
1122
+ break;
1123
+ case "center":
1124
+ ws.top = "50%";
1125
+ ws.left = "50%";
1126
+ ws.transform = "translate(-50%, -50%)";
1127
+ break;
1128
+ case "center-right":
1129
+ ws.top = "50%";
1130
+ ws.right = inset;
1131
+ ws.transform = "translateY(-50%)";
1132
+ break;
1133
+ case "bottom-left":
1134
+ ws.bottom = inset;
1135
+ ws.left = inset;
1136
+ break;
1137
+ case "bottom-center":
1138
+ ws.bottom = inset;
1139
+ ws.left = "50%";
1140
+ ws.transform = "translateX(-50%)";
1141
+ break;
1142
+ case "bottom-right":
1143
+ ws.bottom = inset;
1144
+ ws.right = inset;
1145
+ break;
1146
+ }
1147
+ if (interactive) {
1148
+ ws.pointerEvents = "auto";
1149
+ }
1150
+ wrapper.appendChild(opts.children);
1151
+ screen.appendChild(wrapper);
1152
+ const teardown = () => {
1153
+ if (wrapper.parentNode) wrapper.parentNode.removeChild(wrapper);
1154
+ if (this.scrimOverlayTeardown === teardown) {
1155
+ this.scrimOverlayTeardown = null;
1156
+ }
1157
+ };
1158
+ this.scrimOverlayTeardown = teardown;
1159
+ return teardown;
1160
+ }
1161
+ /** Tear down toggle-state listeners + remove any injected overlay wrapper. */
1162
+ destroy() {
1163
+ this.detachScrimTap?.();
1164
+ this.detachScrimTap = null;
1165
+ this.scrimOverlayTeardown?.();
1166
+ this.scrimOverlayTeardown = null;
1167
+ if (this.screenComponent) {
1168
+ const s = this.screenComponent.style;
1169
+ s.opacity = "";
1170
+ s.display = "";
1171
+ }
1172
+ if (this.backdrop) {
1173
+ this.backdrop.style.opacity = "";
1174
+ this.backdrop.style.pointerEvents = "";
1175
+ }
1176
+ this.invalidateOpacityCache();
1177
+ this.lastBackdropPointer = "";
1178
+ this.lastScreenDisplay = "";
1179
+ }
1180
+ // ── Private helpers ────────────────────────────────────────────────
1181
+ /** Centralized scrim style writer — atomic 3-property write across all setters. */
1182
+ applyScrimStyles(opts) {
1183
+ if (!this.screenComponent) return;
1184
+ const s = this.screenComponent.style;
1185
+ if (opts.color !== void 0) {
1186
+ s.background = opts.color === null ? "" : opts.color;
1187
+ }
1188
+ if (opts.blur !== void 0) {
1189
+ const w = s;
1190
+ if (opts.blur === null) {
1191
+ s.backdropFilter = "";
1192
+ w.webkitBackdropFilter = "";
1193
+ } else {
1194
+ const filter = `blur(${opts.blur})`;
1195
+ s.backdropFilter = filter;
1196
+ w.webkitBackdropFilter = filter;
1197
+ }
1198
+ }
1199
+ if (opts.interactive !== void 0) {
1200
+ s.pointerEvents = opts.interactive ? "auto" : "none";
1201
+ }
1202
+ }
1203
+ /** Pin the screen overlay to the area NOT occupied by the sheet. */
1204
+ applyAboveSheetInset() {
1205
+ if (!this.screenComponent) return;
1206
+ const insetByMode = {
1207
+ bottom: "0 0 var(--bs-size) 0",
1208
+ top: "var(--bs-size) 0 0 0",
1209
+ left: "0 0 0 var(--bs-size)",
1210
+ right: "0 var(--bs-size) 0 0"
1211
+ };
1212
+ const s = this.screenComponent.style;
1213
+ s.position = "fixed";
1214
+ s.inset = insetByMode[this.mode];
1215
+ s.pointerEvents = "none";
1216
+ }
1217
+ };
1218
+
1219
+ // src/core/animation/animation.ts
1220
+ var easeOutBack = (t) => {
1221
+ const c1 = 1.40158;
1222
+ const c3 = c1 + 1;
1223
+ return 1 + c3 * Math.pow(t - 1, 3) + c1 * Math.pow(t - 1, 2);
1224
+ };
1225
+ var easeOutCubic = (t) => 1 - Math.pow(1 - t, 3);
1226
+ var easeLinear = (t) => t;
1227
+ var easeOutQuint = (t) => 1 - Math.pow(1 - t, 5);
1228
+ var tween = ({
1229
+ from,
1230
+ to,
1231
+ duration,
1232
+ easing = easeOutCubic,
1233
+ onUpdate
1234
+ }) => {
1235
+ let cancelled = false;
1236
+ let rafId = 0;
1237
+ let resolveFn = null;
1238
+ const start = performance.now();
1239
+ const promise = new Promise((resolve) => {
1240
+ resolveFn = resolve;
1241
+ if (duration <= 0) {
1242
+ onUpdate(to);
1243
+ resolve();
1244
+ return;
1245
+ }
1246
+ const step = (now) => {
1247
+ if (cancelled) return;
1248
+ const elapsed = now - start;
1249
+ const t = Math.min(elapsed / duration, 1);
1250
+ const value = from + (to - from) * easing(t);
1251
+ onUpdate(value);
1252
+ if (t < 1) {
1253
+ rafId = requestAnimationFrame(step);
1254
+ } else {
1255
+ resolve();
1256
+ }
1257
+ };
1258
+ rafId = requestAnimationFrame(step);
1259
+ });
1260
+ return {
1261
+ cancel: () => {
1262
+ cancelled = true;
1263
+ cancelAnimationFrame(rafId);
1264
+ resolveFn?.();
1265
+ },
1266
+ promise
1267
+ };
1268
+ };
1269
+
1270
+ // src/core/animation/spring.ts
1271
+ var DEFAULT_SPRING = {
1272
+ stiffness: 220,
1273
+ damping: 26,
1274
+ mass: 1,
1275
+ restDelta: 0.5,
1276
+ restSpeed: 0.5
1277
+ };
1278
+ var MAX_DT = 1 / 30;
1279
+ var runSpring = ({
1280
+ from,
1281
+ to,
1282
+ velocity = 0,
1283
+ config,
1284
+ onUpdate
1285
+ }) => {
1286
+ const cfg = { ...DEFAULT_SPRING, ...config };
1287
+ let cancelled = false;
1288
+ let rafId = 0;
1289
+ let resolveFn = null;
1290
+ let x = from;
1291
+ let v = velocity;
1292
+ let lastTime = performance.now();
1293
+ const promise = new Promise((resolve) => {
1294
+ resolveFn = resolve;
1295
+ const step = (now) => {
1296
+ if (cancelled) return;
1297
+ const dt = Math.min((now - lastTime) / 1e3, MAX_DT);
1298
+ lastTime = now;
1299
+ const subDt = Math.min(dt, 1 / 240);
1300
+ let stepsLeft = Math.max(1, Math.ceil(dt / subDt));
1301
+ while (stepsLeft-- > 0) {
1302
+ const force = -cfg.stiffness * (x - to) - cfg.damping * v;
1303
+ const accel = force / cfg.mass;
1304
+ v += accel * subDt;
1305
+ x += v * subDt;
1306
+ }
1307
+ onUpdate(x, v);
1308
+ const isAtRest = Math.abs(to - x) < (cfg.restDelta ?? 0.5) && Math.abs(v) < (cfg.restSpeed ?? 0.5);
1309
+ if (isAtRest) {
1310
+ onUpdate(to, 0);
1311
+ resolve();
1312
+ } else {
1313
+ rafId = requestAnimationFrame(step);
1314
+ }
1315
+ };
1316
+ rafId = requestAnimationFrame(step);
1317
+ });
1318
+ return {
1319
+ cancel: () => {
1320
+ cancelled = true;
1321
+ cancelAnimationFrame(rafId);
1322
+ resolveFn?.();
1323
+ },
1324
+ promise
1325
+ };
1326
+ };
1327
+
1328
+ // src/core/animation/animation-presets.ts
1329
+ var DEFAULT_DURATION = 220;
1330
+ function resolveAnimationPreset(animation) {
1331
+ switch (animation) {
1332
+ case "ios-spring":
1333
+ return {
1334
+ kind: "spring",
1335
+ spring: { stiffness: 300, damping: 30, mass: 1 }
1336
+ };
1337
+ case "material-bounce":
1338
+ return {
1339
+ kind: "spring",
1340
+ spring: { stiffness: 200, damping: 22, mass: 1 }
1341
+ };
1342
+ case "linear":
1343
+ return { kind: "tween", duration: DEFAULT_DURATION, easing: easeLinear };
1344
+ case "snappy":
1345
+ return { kind: "tween", duration: 180, easing: easeOutQuint };
1346
+ case "tween":
1347
+ return { kind: "tween" };
1348
+ case "spring":
1349
+ case void 0:
1350
+ default:
1351
+ return { kind: "spring" };
1352
+ }
1353
+ }
1354
+
1355
+ // src/core/controllers/animation-runner.ts
1356
+ var DEFAULT_DURATION2 = 220;
1357
+ var VELOCITY_PX_PER_S = 1e3;
1358
+ var AnimationRunner = class {
1359
+ constructor(deps, opts) {
1360
+ __publicField(this, "element");
1361
+ __publicField(this, "getRootEl");
1362
+ __publicField(this, "applySizeFn");
1363
+ __publicField(this, "getSize");
1364
+ __publicField(this, "isDragging");
1365
+ __publicField(this, "animationKind");
1366
+ __publicField(this, "springConfig");
1367
+ __publicField(this, "duration");
1368
+ __publicField(this, "easing");
1369
+ __publicField(this, "respectReducedMotion");
1370
+ /** Live-tracked via mq listener so animateTo skips matchMedia per snap. */
1371
+ __publicField(this, "reducedMotion", false);
1372
+ /** Disposes the matchMedia change listener — drained from destroy(). */
1373
+ __publicField(this, "detachReducedMotion", null);
1374
+ /** Computed once — both inputs (option + API presence) stable for life. */
1375
+ __publicField(this, "viewTransitionsAvailable");
1376
+ /** In-flight handles. Public for tests / debugging only — engine drives via cancel(). */
1377
+ __publicField(this, "currentTween", null);
1378
+ __publicField(this, "currentSpring", null);
1379
+ this.element = deps.element;
1380
+ this.getRootEl = deps.getRootEl;
1381
+ this.applySizeFn = deps.applySize;
1382
+ this.getSize = deps.getSize;
1383
+ this.isDragging = deps.isDragging;
1384
+ const preset = resolveAnimationPreset(opts.animation);
1385
+ this.animationKind = preset.kind;
1386
+ this.duration = opts.duration ?? preset.duration ?? DEFAULT_DURATION2;
1387
+ this.easing = opts.easing ?? preset.easing ?? easeOutBack;
1388
+ this.springConfig = { ...preset.spring ?? {}, ...opts.spring ?? {} };
1389
+ this.respectReducedMotion = opts.respectReducedMotion ?? true;
1390
+ const viewTransitionsEnabled = opts.viewTransitions ?? false;
1391
+ this.viewTransitionsAvailable = viewTransitionsEnabled && typeof document !== "undefined" && typeof document.startViewTransition === "function";
1392
+ if (this.respectReducedMotion && typeof window !== "undefined" && typeof window.matchMedia === "function") {
1393
+ const mq = window.matchMedia("(prefers-reduced-motion: reduce)");
1394
+ this.reducedMotion = mq.matches;
1395
+ const onMqChange = (e) => {
1396
+ this.reducedMotion = e.matches;
1397
+ };
1398
+ if (typeof mq.addEventListener === "function") {
1399
+ mq.addEventListener("change", onMqChange);
1400
+ this.detachReducedMotion = () => mq.removeEventListener("change", onMqChange);
1401
+ } else if (typeof mq.addListener === "function") {
1402
+ mq.addListener(onMqChange);
1403
+ this.detachReducedMotion = () => mq.removeListener(onMqChange);
1404
+ }
1405
+ }
1406
+ }
1407
+ /**
1408
+ * Live derived flag — `true` whenever a spring/tween handle is in flight.
1409
+ * Reading the canonical handles (instead of mirroring into a separate
1410
+ * boolean) eliminates the reduced-motion early-return latent bug where
1411
+ * the flag stayed true forever, and removes the cross-controller
1412
+ * setIsAnimating callback.
1413
+ */
1414
+ get isAnimating() {
1415
+ return this.currentTween !== null || this.currentSpring !== null;
1416
+ }
1417
+ /** Cancel any in-flight tween/spring without touching engine state. */
1418
+ cancel() {
1419
+ this.currentTween?.cancel();
1420
+ this.currentSpring?.cancel();
1421
+ }
1422
+ /**
1423
+ * Animate from current size to `target`. Resolves when the animation
1424
+ * completes; resolves early if cancelled mid-flight (caller checks an
1425
+ * abort signal post-await for cycle-invariant correctness).
1426
+ */
1427
+ async animateTo(target, velocityPxPerMs) {
1428
+ if (target === this.getSize()) return;
1429
+ this.currentTween?.cancel();
1430
+ this.currentSpring?.cancel();
1431
+ this.getRootEl()?.setAttribute("data-animating", "true");
1432
+ this.element.style.willChange = "transform";
1433
+ if (this.reducedMotion) {
1434
+ this.applySizeFn(target);
1435
+ this.getRootEl()?.removeAttribute("data-animating");
1436
+ if (!this.isDragging()) this.element.style.willChange = "auto";
1437
+ return;
1438
+ }
1439
+ if (this.animationKind === "spring") {
1440
+ const spring = runSpring({
1441
+ from: this.getSize(),
1442
+ to: target,
1443
+ velocity: velocityPxPerMs * VELOCITY_PX_PER_S,
1444
+ config: this.springConfig,
1445
+ onUpdate: (v) => this.applySizeFn(v)
1446
+ });
1447
+ this.currentSpring = spring;
1448
+ await spring.promise;
1449
+ if (this.currentSpring === spring) this.currentSpring = null;
1450
+ } else {
1451
+ const tw = tween({
1452
+ from: this.getSize(),
1453
+ to: target,
1454
+ duration: this.duration,
1455
+ easing: this.easing,
1456
+ onUpdate: (v) => this.applySizeFn(v)
1457
+ });
1458
+ this.currentTween = tw;
1459
+ await tw.promise;
1460
+ if (this.currentTween === tw) this.currentTween = null;
1461
+ }
1462
+ if (!this.isAnimating) {
1463
+ this.getRootEl()?.removeAttribute("data-animating");
1464
+ if (!this.isDragging()) this.element.style.willChange = "auto";
1465
+ }
1466
+ }
1467
+ /** Tear down the matchMedia listener. Engine calls from destroy(). */
1468
+ destroy() {
1469
+ this.detachReducedMotion?.();
1470
+ this.detachReducedMotion = null;
1471
+ this.currentTween = null;
1472
+ this.currentSpring = null;
1473
+ }
1474
+ };
1475
+
1476
+ // src/core/lifecycle/focusTrap.ts
1477
+ var FOCUSABLE = [
1478
+ "a[href]",
1479
+ "area[href]",
1480
+ "button:not([disabled])",
1481
+ "input:not([disabled]):not([type='hidden'])",
1482
+ "select:not([disabled])",
1483
+ "textarea:not([disabled])",
1484
+ "iframe",
1485
+ "object",
1486
+ "embed",
1487
+ "[contenteditable='true']",
1488
+ "[tabindex]:not([tabindex='-1'])"
1489
+ ].join(",");
1490
+ var isVisible = (el) => {
1491
+ if (typeof el.checkVisibility === "function") {
1492
+ return el.checkVisibility({ checkOpacity: false, checkVisibilityCSS: true });
1493
+ }
1494
+ return el.offsetParent !== null;
1495
+ };
1496
+ var focusables = (root) => Array.from(root.querySelectorAll(FOCUSABLE)).filter(
1497
+ (el) => !el.hasAttribute("inert") && isVisible(el) && !el.matches("[aria-hidden='true']")
1498
+ );
1499
+ var installFocusTrap = (container, options = {}) => {
1500
+ if (typeof document === "undefined") return () => {
1501
+ };
1502
+ const previouslyFocused = document.activeElement;
1503
+ const focusInitial = () => {
1504
+ const initial = typeof options.initialFocus === "string" ? container.querySelector(options.initialFocus) : options.initialFocus ?? focusables(container)[0] ?? container;
1505
+ initial?.focus({ preventScroll: true });
1506
+ };
1507
+ focusInitial();
1508
+ const handleKey = (e) => {
1509
+ if (e.key === "Escape" && options.onEscape) {
1510
+ options.onEscape();
1511
+ return;
1512
+ }
1513
+ if (e.key !== "Tab") return;
1514
+ const list = focusables(container);
1515
+ if (list.length === 0) {
1516
+ e.preventDefault();
1517
+ return;
1518
+ }
1519
+ const first = list[0];
1520
+ const last = list[list.length - 1];
1521
+ const active = document.activeElement;
1522
+ if (e.shiftKey && active === first) {
1523
+ e.preventDefault();
1524
+ last.focus();
1525
+ } else if (!e.shiftKey && active === last) {
1526
+ e.preventDefault();
1527
+ first.focus();
1528
+ }
1529
+ };
1530
+ const handleFocusIn = (e) => {
1531
+ const target = e.target;
1532
+ if (target && !container.contains(target)) {
1533
+ const list = focusables(container);
1534
+ list[0]?.focus({ preventScroll: true });
1535
+ }
1536
+ };
1537
+ document.addEventListener("keydown", handleKey, true);
1538
+ document.addEventListener("focusin", handleFocusIn, true);
1539
+ let released = false;
1540
+ return () => {
1541
+ if (released) return;
1542
+ released = true;
1543
+ document.removeEventListener("keydown", handleKey, true);
1544
+ document.removeEventListener("focusin", handleFocusIn, true);
1545
+ if (previouslyFocused && document.contains(previouslyFocused)) {
1546
+ previouslyFocused.focus({ preventScroll: true });
1547
+ } else {
1548
+ const fallback = document.querySelector("[data-bs-restore-fallback]");
1549
+ fallback?.focus({ preventScroll: true });
1550
+ }
1551
+ };
1552
+ };
1553
+
1554
+ // src/core/lifecycle/scrollLock.ts
1555
+ var lockCount = 0;
1556
+ var savedStyles = null;
1557
+ var lockBodyScroll = () => {
1558
+ if (typeof document === "undefined") return () => {
1559
+ };
1560
+ if (lockCount === 0) {
1561
+ const body = document.body;
1562
+ savedStyles = {
1563
+ overflow: body.style.overflow,
1564
+ position: body.style.position,
1565
+ top: body.style.top,
1566
+ width: body.style.width,
1567
+ scrollY: window.scrollY
1568
+ };
1569
+ body.style.overflow = "hidden";
1570
+ body.style.position = "fixed";
1571
+ body.style.top = `-${savedStyles.scrollY}px`;
1572
+ body.style.width = "100%";
1573
+ }
1574
+ lockCount++;
1575
+ let released = false;
1576
+ return () => {
1577
+ if (released) return;
1578
+ released = true;
1579
+ lockCount = Math.max(0, lockCount - 1);
1580
+ if (lockCount === 0 && savedStyles) {
1581
+ const body = document.body;
1582
+ body.style.overflow = savedStyles.overflow;
1583
+ body.style.position = savedStyles.position;
1584
+ body.style.top = savedStyles.top;
1585
+ body.style.width = savedStyles.width;
1586
+ window.scrollTo(0, savedStyles.scrollY);
1587
+ savedStyles = null;
1588
+ }
1589
+ };
1590
+ };
1591
+
1592
+ // src/core/features/inert-siblings.ts
1593
+ function createInertSiblings(rootProvider) {
1594
+ const tracked = [];
1595
+ return {
1596
+ apply() {
1597
+ if (typeof document === "undefined") return;
1598
+ const root = rootProvider();
1599
+ const parent = root.parentElement ?? document.body;
1600
+ for (const child of Array.from(parent.children)) {
1601
+ if (child === root) continue;
1602
+ if (child.hasAttribute("inert")) continue;
1603
+ child.setAttribute("inert", "");
1604
+ tracked.push(child);
1605
+ }
1606
+ },
1607
+ remove() {
1608
+ for (const el of tracked) el.removeAttribute("inert");
1609
+ tracked.length = 0;
1610
+ }
1611
+ };
1612
+ }
1613
+
1614
+ // src/core/controllers/lifecycle-controller.ts
1615
+ var LifecycleController = class {
1616
+ constructor(deps, opts) {
1617
+ __publicField(this, "element");
1618
+ __publicField(this, "closeFn");
1619
+ __publicField(this, "focusTrapEnabled");
1620
+ __publicField(this, "initialFocus");
1621
+ __publicField(this, "closeOnEscape");
1622
+ __publicField(this, "bodyScrollLockEnabled");
1623
+ __publicField(this, "inertSiblingsEnabled");
1624
+ __publicField(this, "inertSiblings");
1625
+ __publicField(this, "shouldApplyInertSiblings");
1626
+ __publicField(this, "returnFocus");
1627
+ /** Toggle-state teardowns — fire on close, NOT in destroy-only stack. */
1628
+ __publicField(this, "releaseFocusTrap", null);
1629
+ __publicField(this, "releaseScrollLock", null);
1630
+ /** True between install() and release(). Guards release()/destroy() from
1631
+ * re-running side effects (notably `returnFocus.focus()`) on already-
1632
+ * released or never-installed instances. */
1633
+ __publicField(this, "installed", false);
1634
+ __publicField(this, "destroyed", false);
1635
+ this.element = deps.element;
1636
+ this.closeFn = deps.close;
1637
+ this.focusTrapEnabled = opts.focusTrap ?? false;
1638
+ this.initialFocus = opts.initialFocus;
1639
+ this.closeOnEscape = opts.closeOnEscape ?? true;
1640
+ this.bodyScrollLockEnabled = opts.lockBodyScroll ?? true;
1641
+ this.inertSiblingsEnabled = opts.inertSiblings ?? false;
1642
+ this.shouldApplyInertSiblings = opts.shouldApplyInertSiblings ?? (() => true);
1643
+ this.returnFocus = opts.returnFocus;
1644
+ this.inertSiblings = createInertSiblings(() => this.element);
1645
+ }
1646
+ /**
1647
+ * Run the open-time install steps. Idempotent: each step checks its
1648
+ * existing teardown ref so a re-open during a half-cancelled close
1649
+ * doesn't double-install. Sets `installed=true` BEFORE the first side
1650
+ * effect so a partial throw (detached / shadow-DOM target) leaves the
1651
+ * caller's `release()` rollback path armed to undo whatever did succeed.
1652
+ * No-op when destroyed.
1653
+ */
1654
+ install() {
1655
+ if (this.destroyed) return;
1656
+ this.installed = true;
1657
+ if (this.bodyScrollLockEnabled && !this.releaseScrollLock) {
1658
+ this.releaseScrollLock = lockBodyScroll();
1659
+ }
1660
+ if (this.focusTrapEnabled && !this.releaseFocusTrap) {
1661
+ this.releaseFocusTrap = installFocusTrap(this.element, {
1662
+ initialFocus: this.initialFocus,
1663
+ onEscape: this.closeOnEscape ? () => void this.closeFn() : void 0
1664
+ });
1665
+ }
1666
+ if (this.inertSiblingsEnabled && this.shouldApplyInertSiblings()) {
1667
+ this.inertSiblings.apply();
1668
+ }
1669
+ }
1670
+ /**
1671
+ * Update the post-release focus target. Overlay re-binds this when the
1672
+ * consumer changes `returnFocus` after construction; the new value applies
1673
+ * on the next `release()`. No-op when destroyed.
1674
+ */
1675
+ setReturnFocus(target) {
1676
+ if (this.destroyed) return;
1677
+ this.returnFocus = target;
1678
+ }
1679
+ /**
1680
+ * Release all install-time teardowns. Short-circuits when not installed,
1681
+ * so `close() → destroy()` (each routing through here) only restores
1682
+ * focus once. The `installed` guard lets `inertSiblings.remove()` and
1683
+ * the focus-trap/scroll-lock teardown nullings stay simple — they were
1684
+ * already idempotent, but `returnFocus.focus()` was firing on every call.
1685
+ */
1686
+ release() {
1687
+ if (!this.installed) return;
1688
+ this.installed = false;
1689
+ this.releaseFocusTrap?.();
1690
+ this.releaseFocusTrap = null;
1691
+ this.releaseScrollLock?.();
1692
+ this.releaseScrollLock = null;
1693
+ this.inertSiblings.remove();
1694
+ if (this.returnFocus) {
1695
+ const target = typeof this.returnFocus === "function" ? this.returnFocus() : this.returnFocus;
1696
+ target?.focus?.();
1697
+ }
1698
+ }
1699
+ /**
1700
+ * Final teardown — releases any still-installed listeners and seals the
1701
+ * controller. After destroy(), install() is a no-op and setReturnFocus()
1702
+ * is rejected, so post-destroy mutations can't queue up a stale focus
1703
+ * restore.
1704
+ */
1705
+ destroy() {
1706
+ this.release();
1707
+ this.destroyed = true;
1708
+ }
1709
+ };
1710
+
1711
+ // src/core/gestures.ts
1712
+ var isAxisVertical = (mode) => mode === "bottom" || mode === "top";
1713
+ var SampleRing = class {
1714
+ // current count, ≤ capacity
1715
+ constructor(capacity) {
1716
+ __publicField(this, "slots");
1717
+ __publicField(this, "capacity");
1718
+ __publicField(this, "head", 0);
1719
+ // next write index
1720
+ __publicField(this, "size", 0);
1721
+ this.capacity = capacity;
1722
+ this.slots = new Array(capacity);
1723
+ for (let i = 0; i < capacity; i++) this.slots[i] = { t: 0, v: 0 };
1724
+ }
1725
+ push(t, v) {
1726
+ const slot = this.slots[this.head];
1727
+ slot.t = t;
1728
+ slot.v = v;
1729
+ this.head = (this.head + 1) % this.capacity;
1730
+ if (this.size < this.capacity) this.size++;
1731
+ }
1732
+ /**
1733
+ * Drop oldest entries whose timestamp is below `cutoff`, but never shrink
1734
+ * below `minKeep`. Mirrors the original
1735
+ * `while (samples.length > minKeep && samples[0].t < cutoff) samples.shift()`
1736
+ * but without copying — just advances the logical tail.
1737
+ */
1738
+ pruneBefore(cutoff, minKeep) {
1739
+ while (this.size > minKeep) {
1740
+ const oldestIdx = (this.head - this.size + this.capacity) % this.capacity;
1741
+ if (this.slots[oldestIdx].t < cutoff) this.size--;
1742
+ else break;
1743
+ }
1744
+ }
1745
+ get length() {
1746
+ return this.size;
1747
+ }
1748
+ oldest() {
1749
+ if (this.size === 0) return void 0;
1750
+ return this.slots[(this.head - this.size + this.capacity) % this.capacity];
1751
+ }
1752
+ newest() {
1753
+ if (this.size === 0) return void 0;
1754
+ return this.slots[(this.head - 1 + this.capacity) % this.capacity];
1755
+ }
1756
+ reset() {
1757
+ this.head = 0;
1758
+ this.size = 0;
1759
+ }
1760
+ };
1761
+ var installGestures = (handle, mode, callbacks) => {
1762
+ let activePointerId = null;
1763
+ let activePointerType = "touch";
1764
+ let startCoord = 0;
1765
+ let lastCoord = 0;
1766
+ const VELOCITY_WINDOW_MS = (kind) => kind === "mouse" ? 160 : 120;
1767
+ const MAX_SAMPLES = 32;
1768
+ const samples = new SampleRing(MAX_SAMPLES);
1769
+ const axis = isAxisVertical(mode) ? "Y" : "X";
1770
+ const sign = mode === "bottom" || mode === "right" ? -1 : 1;
1771
+ const coordOf = (e) => axis === "Y" ? e.clientY : e.clientX;
1772
+ const onPointerDown = (e) => {
1773
+ if (activePointerId !== null) return;
1774
+ if (e.button !== void 0 && e.button !== 0) return;
1775
+ activePointerId = e.pointerId;
1776
+ activePointerType = e.pointerType || "touch";
1777
+ startCoord = coordOf(e);
1778
+ lastCoord = startCoord;
1779
+ samples.reset();
1780
+ samples.push(e.timeStamp, startCoord);
1781
+ try {
1782
+ handle.setPointerCapture(e.pointerId);
1783
+ } catch {
1784
+ }
1785
+ callbacks.onStart(startCoord, activePointerType);
1786
+ };
1787
+ const onPointerMove = (e) => {
1788
+ if (e.pointerId !== activePointerId) return;
1789
+ const coord = coordOf(e);
1790
+ const rawDelta = coord - startCoord;
1791
+ const delta = rawDelta * sign;
1792
+ lastCoord = coord;
1793
+ samples.push(e.timeStamp, coord);
1794
+ const cutoff = e.timeStamp - VELOCITY_WINDOW_MS(activePointerType);
1795
+ samples.pruneBefore(cutoff, 2);
1796
+ callbacks.onMove(delta);
1797
+ };
1798
+ const finishGesture = (e) => {
1799
+ if (e.pointerId !== activePointerId) return;
1800
+ const rawDelta = lastCoord - startCoord;
1801
+ const delta = rawDelta * sign;
1802
+ let velocity = 0;
1803
+ if (samples.length >= 3) {
1804
+ const first = samples.oldest();
1805
+ const last = samples.newest();
1806
+ const dt = last.t - first.t;
1807
+ if (dt > 0) velocity = (last.v - first.v) / dt * sign;
1808
+ }
1809
+ const finishedKind = activePointerType;
1810
+ activePointerId = null;
1811
+ samples.reset();
1812
+ try {
1813
+ if (handle.hasPointerCapture(e.pointerId)) {
1814
+ handle.releasePointerCapture(e.pointerId);
1815
+ }
1816
+ } catch {
1817
+ }
1818
+ callbacks.onEnd(delta, velocity, finishedKind);
1819
+ };
1820
+ const onPointerCancel = (e) => {
1821
+ if (e.pointerId !== activePointerId) return;
1822
+ activePointerId = null;
1823
+ samples.reset();
1824
+ callbacks.onCancel?.();
1825
+ };
1826
+ handle.addEventListener("pointerdown", onPointerDown);
1827
+ handle.addEventListener("pointermove", onPointerMove);
1828
+ handle.addEventListener("pointerup", finishGesture);
1829
+ handle.addEventListener("pointercancel", onPointerCancel);
1830
+ handle.style.touchAction = isAxisVertical(mode) ? "pan-x" : "pan-y";
1831
+ return () => {
1832
+ handle.removeEventListener("pointerdown", onPointerDown);
1833
+ handle.removeEventListener("pointermove", onPointerMove);
1834
+ handle.removeEventListener("pointerup", finishGesture);
1835
+ handle.removeEventListener("pointercancel", onPointerCancel);
1836
+ if (activePointerId !== null && handle.hasPointerCapture(activePointerId)) {
1837
+ handle.releasePointerCapture(activePointerId);
1838
+ }
1839
+ };
1840
+ };
1841
+
1842
+ // src/core/primitives/rubber-band.ts
1843
+ var RUBBER_BAND_FACTOR = 0.55;
1844
+ function rubberBand(overshoot, maxAxisSize) {
1845
+ const cap = Math.min(maxAxisSize * 0.15, 80);
1846
+ return Math.sign(overshoot) * Math.pow(Math.abs(overshoot), RUBBER_BAND_FACTOR) * Math.min(6, cap / Math.max(Math.abs(overshoot), 1));
1847
+ }
1848
+
1849
+ // src/core/features/soft-keyboard.ts
1850
+ function dismissSoftKeyboardIfFocused(root) {
1851
+ if (typeof document === "undefined") return false;
1852
+ const active = document.activeElement;
1853
+ if (!active) return false;
1854
+ if (!root.contains(active)) return false;
1855
+ const tag = active.tagName;
1856
+ const isEditable = tag === "INPUT" || tag === "TEXTAREA" || active.isContentEditable === true;
1857
+ if (!isEditable) return false;
1858
+ try {
1859
+ active.blur();
1860
+ return true;
1861
+ } catch {
1862
+ return false;
1863
+ }
1864
+ }
1865
+
1866
+ // src/core/controllers/gesture-controller.ts
1867
+ var GestureController = class {
1868
+ constructor(deps) {
1869
+ __publicField(this, "deps");
1870
+ __publicField(this, "detach", null);
1871
+ __publicField(this, "isDragging_", false);
1872
+ __publicField(this, "dragStartSize", 0);
1873
+ // Only "touch" gestures are eligible for soft-keyboard dismissal —
1874
+ // mouse/trackpad users don't have a keyboard to dismiss.
1875
+ __publicField(this, "currentPointerKind", "touch");
1876
+ // One blur per drag — flipping focus every move event races the keyboard's
1877
+ // own animations on iOS and makes the page jitter.
1878
+ __publicField(this, "keyboardDismissed", false);
1879
+ // Reused payload object for the "drag" event — mutated each onMove instead
1880
+ // of allocating a fresh `{size, delta}` per frame. At 60-120Hz a long drag
1881
+ // would otherwise churn tens of KB through the GC. Mirrors browser
1882
+ // PointerEvent semantics: consumers must NOT retain the reference across
1883
+ // frames (clone if needed). See SheetEventMap.drag JSDoc.
1884
+ __publicField(this, "dragPayload", { size: 0, delta: 0 });
1885
+ this.deps = deps;
1886
+ }
1887
+ /** True between `dragstart` and `dragend`/`onCancel`. */
1888
+ get isDragging() {
1889
+ return this.isDragging_;
1890
+ }
1891
+ /**
1892
+ * Bind pointer listeners on the handle and return a teardown. Engine pushes
1893
+ * the teardown into its TeardownStack so destroy() drains it once.
1894
+ */
1895
+ install() {
1896
+ if (this.detach) return this.detach;
1897
+ this.detach = installGestures(this.deps.handle, this.deps.mode, {
1898
+ onStart: (_coord, kind) => {
1899
+ this.deps.cancelAnimation();
1900
+ this.isDragging_ = true;
1901
+ this.dragStartSize = this.deps.getDragContext().size;
1902
+ this.currentPointerKind = kind;
1903
+ this.keyboardDismissed = false;
1904
+ this.deps.getRoot()?.setAttribute("data-dragging", "true");
1905
+ this.deps.element.style.willChange = "transform";
1906
+ this.deps.emit("dragstart", { size: this.dragStartSize });
1907
+ },
1908
+ onMove: (delta) => {
1909
+ const ctx = this.deps.getDragContext();
1910
+ const { min, max } = ctx.range;
1911
+ const maxAxis = ctx.maxAxisSize;
1912
+ const rubberOn = ctx.rubberBandEnabled;
1913
+ let next = this.dragStartSize + delta;
1914
+ if (next > max) {
1915
+ next = rubberOn ? max + rubberBand(next - max, maxAxis) : max;
1916
+ } else if (next < min) {
1917
+ next = rubberOn ? min - rubberBand(min - next, maxAxis) : min;
1918
+ }
1919
+ this.deps.applySize(next);
1920
+ if (!this.keyboardDismissed && this.currentPointerKind === "touch" && this.deps.mode === "bottom" && next < this.dragStartSize) {
1921
+ if (dismissSoftKeyboardIfFocused(this.deps.element)) {
1922
+ this.keyboardDismissed = true;
1923
+ }
1924
+ }
1925
+ if (this.deps.listenerCount("drag") > 0) {
1926
+ this.dragPayload.size = next;
1927
+ this.dragPayload.delta = delta;
1928
+ this.deps.emit("drag", this.dragPayload);
1929
+ }
1930
+ },
1931
+ onEnd: (delta, velocity, kind) => {
1932
+ this.isDragging_ = false;
1933
+ this.keyboardDismissed = false;
1934
+ this.deps.getRoot()?.removeAttribute("data-dragging");
1935
+ this.deps.emit("dragend", {
1936
+ size: this.deps.getDragContext().size,
1937
+ velocity
1938
+ });
1939
+ this.deps.settleAfterDrag(delta, velocity, kind);
1940
+ },
1941
+ onCancel: () => {
1942
+ this.isDragging_ = false;
1943
+ this.keyboardDismissed = false;
1944
+ this.deps.getRoot()?.removeAttribute("data-dragging");
1945
+ const restoreTo = this.dragStartSize;
1946
+ void this.deps.animateTo(restoreTo, 0);
1947
+ }
1948
+ });
1949
+ return this.detach;
1950
+ }
1951
+ /**
1952
+ * Force-clear drag visual state. Engine calls from destroy() when destroyed
1953
+ * mid-drag — gesture detach won't synthesize an onCancel, so we have to
1954
+ * roll back the data-attribute + will-change ourselves.
1955
+ */
1956
+ forceClearDragState() {
1957
+ if (!this.isDragging_) return;
1958
+ this.isDragging_ = false;
1959
+ this.keyboardDismissed = false;
1960
+ this.deps.getRoot()?.removeAttribute("data-dragging");
1961
+ this.deps.element.style.willChange = "auto";
1962
+ }
1963
+ };
1964
+
1965
+ // src/core/primitives/aria-slider-writer.ts
1966
+ var AriaSliderWriter = class {
1967
+ constructor(handle, mode) {
1968
+ __publicField(this, "handle", handle);
1969
+ handle.setAttribute(
1970
+ "aria-orientation",
1971
+ mode === "bottom" || mode === "top" ? "vertical" : "horizontal"
1972
+ );
1973
+ }
1974
+ /**
1975
+ * Update slider position. `allowedIds` length determines `aria-valuemax`;
1976
+ * `activeId` indexes into it for `aria-valuenow` + `aria-valuetext`.
1977
+ * Empty list → strip every dynamic attr so AT skips the handle entirely.
1978
+ */
1979
+ setValue(allowedIds, activeId) {
1980
+ if (allowedIds.length === 0) {
1981
+ this.handle.removeAttribute("aria-valuemin");
1982
+ this.handle.removeAttribute("aria-valuemax");
1983
+ this.handle.removeAttribute("aria-valuenow");
1984
+ this.handle.removeAttribute("aria-valuetext");
1985
+ return;
1986
+ }
1987
+ const max = Math.max(allowedIds.length - 1, 0);
1988
+ const idx = Math.max(allowedIds.indexOf(activeId), 0);
1989
+ this.handle.setAttribute("aria-valuemin", "0");
1990
+ this.handle.setAttribute("aria-valuemax", String(max));
1991
+ this.handle.setAttribute("aria-valuenow", String(idx));
1992
+ this.handle.setAttribute("aria-valuetext", activeId);
1993
+ }
1994
+ };
1995
+
1996
+ // src/core/features/scroll-cache.ts
1997
+ function createScrollCache(deps) {
1998
+ const positions = /* @__PURE__ */ new Map();
1999
+ const isSmallSize = (size) => {
2000
+ const max = deps.getMaxAxisSize();
2001
+ if (max <= 0) return false;
2002
+ return size < max / 2;
2003
+ };
2004
+ return {
2005
+ cache(fromId, prevSize, nextSize) {
2006
+ const container = deps.scrollContainer;
2007
+ if (!container) return;
2008
+ if (isSmallSize(prevSize)) return;
2009
+ if (!isSmallSize(nextSize)) return;
2010
+ positions.set(fromId, container.scrollTop);
2011
+ },
2012
+ restore(toId, prevSize, nextSize) {
2013
+ const container = deps.scrollContainer;
2014
+ if (!container) return;
2015
+ if (isSmallSize(nextSize)) return;
2016
+ if (!isSmallSize(prevSize)) return;
2017
+ const cached = positions.get(toId);
2018
+ if (cached === void 0) return;
2019
+ container.scrollTop = cached;
2020
+ positions.delete(toId);
2021
+ },
2022
+ clear() {
2023
+ positions.clear();
2024
+ }
2025
+ };
2026
+ }
2027
+
2028
+ // src/core/primitives/engine-options.ts
2029
+ var DEFAULT_FLICK_VELOCITY = 0.65;
2030
+ var DEFAULT_DRAG_THRESHOLD = 18;
2031
+ function resolveEngineOptions(opts, extras) {
2032
+ const initialAllowed = opts.allowed ?? opts.snapPoints.map((p) => p.id);
2033
+ let initialId = opts.initial ?? initialAllowed[0] ?? opts.snapPoints[0]?.id ?? "default";
2034
+ if (opts.persistKey) {
2035
+ const restored = readPersistedId(opts.persistKey);
2036
+ if (restored && initialAllowed.includes(restored)) {
2037
+ initialId = restored;
2038
+ }
2039
+ }
2040
+ return {
2041
+ mode: opts.mode ?? "bottom",
2042
+ flickVelocity: opts.flickVelocity ?? DEFAULT_FLICK_VELOCITY,
2043
+ dragThreshold: opts.dragThreshold ?? DEFAULT_DRAG_THRESHOLD,
2044
+ rubberBandEnabled: opts.rubberBand ?? true,
2045
+ closeOnBack: opts.closeOnBack ?? false,
2046
+ initialAllowed,
2047
+ initialId,
2048
+ scrim: {
2049
+ scrimMode: opts.scrimMode,
2050
+ scrimColor: opts.scrimColor,
2051
+ scrimBlur: opts.scrimBlur,
2052
+ // Auto-promote pointer-events when tap-to-close is on so the click
2053
+ // listener actually receives events. Caller can still force `false`
2054
+ // explicitly to opt out — `??` only kicks in for `undefined`.
2055
+ scrimInteractive: opts.scrimInteractive ?? (opts.scrimTapToClose ? true : void 0),
2056
+ scrimTapToClose: opts.scrimTapToClose,
2057
+ scrimPreset: opts.scrimPreset,
2058
+ screenRange: opts.screenRange,
2059
+ backdropRange: opts.backdropRange
2060
+ },
2061
+ animation: {
2062
+ animation: opts.animation,
2063
+ duration: opts.duration,
2064
+ easing: opts.easing,
2065
+ spring: opts.spring,
2066
+ respectReducedMotion: opts.respectReducedMotion,
2067
+ viewTransitions: opts.viewTransitions
2068
+ },
2069
+ lifecycle: {
2070
+ focusTrap: opts.focusTrap,
2071
+ initialFocus: opts.initialFocus,
2072
+ closeOnEscape: opts.closeOnEscape,
2073
+ lockBodyScroll: opts.lockBodyScroll,
2074
+ inertSiblings: opts.inertSiblings,
2075
+ // Folded in from `extras` so the lifecycle bag is fully assembled at
2076
+ // the call site — engine no longer needs a spread+override at
2077
+ // controller construction. When `extras` is omitted, the field stays
2078
+ // undefined and the controller uses its own default predicate.
2079
+ shouldApplyInertSiblings: extras?.shouldApplyInertSiblings
2080
+ }
2081
+ };
2082
+ }
2083
+
2084
+ // src/core/BottomSheetEngine.ts
2085
+ var HAPTIC_DURATION_MS = 8;
2086
+ var TeardownStack = class {
2087
+ constructor() {
2088
+ __publicField(this, "fns", []);
2089
+ }
2090
+ add(fn) {
2091
+ if (fn) this.fns.push(fn);
2092
+ }
2093
+ drain() {
2094
+ while (this.fns.length) {
2095
+ try {
2096
+ this.fns.pop()();
2097
+ } catch (err) {
2098
+ queueMicrotask(() => {
2099
+ throw err;
2100
+ });
2101
+ }
2102
+ }
2103
+ }
2104
+ };
2105
+ var BottomSheetEngine = class {
2106
+ constructor(opts) {
2107
+ __publicField(this, "id", nextInstanceId("bs"));
2108
+ __publicField(this, "element");
2109
+ __publicField(this, "handle");
2110
+ __publicField(this, "scrollContainer");
2111
+ __publicField(this, "backdrop");
2112
+ __publicField(this, "screenComponent");
2113
+ __publicField(this, "mode");
2114
+ __publicField(this, "flickVelocity");
2115
+ __publicField(this, "dragThreshold");
2116
+ __publicField(this, "rubberBandEnabled");
2117
+ __publicField(this, "scrim");
2118
+ __publicField(this, "aria");
2119
+ __publicField(this, "animation");
2120
+ __publicField(this, "lifecycle");
2121
+ __publicField(this, "closeOnBack");
2122
+ __publicField(this, "routedTo");
2123
+ // Engine retains `snapPointsRaw` for the "find a closed-id" query in
2124
+ // close() (raw input, not resolved geometry). Resolver owns geometry.
2125
+ __publicField(this, "snapPointsRaw");
2126
+ __publicField(this, "snaps");
2127
+ __publicField(this, "activeId");
2128
+ __publicField(this, "size", 0);
2129
+ // Constructed in attach(); a plugin's install() could read `state` before
2130
+ // attach completes if the constructor throws partway through. State getter
2131
+ // null-guards via `this.gesture?.isDragging ?? false`.
2132
+ __publicField(this, "gesture");
2133
+ __publicField(this, "rootEl", null);
2134
+ __publicField(this, "destroyed", false);
2135
+ // In-flight ViewTransition handle. A second snapTo while a VT is in flight
2136
+ // would otherwise let Chromium reject the second's promise and flicker —
2137
+ // newCycle() calls skipTransition() to abort cleanly.
2138
+ __publicField(this, "currentViewTransition", null);
2139
+ // Each cycle captures the signal at entry; when a newer cycle aborts the
2140
+ // controller, the captured signal flips to `aborted=true` and post-await
2141
+ // guards short-circuit (prevents stale snap/open/close emits).
2142
+ __publicField(this, "currentAbort", new AbortController());
2143
+ // Sub-pixel `--bs-size` deltas and <1% `--bs-progress` deltas are not
2144
+ // visually distinguishable; gating CSSOM writes drops 30-50% of writes
2145
+ // during the spring's settle tail.
2146
+ __publicField(this, "sizeWriteSentinel", new WriteSentinel());
2147
+ __publicField(this, "progressWriteSentinel", new WriteSentinel());
2148
+ __publicField(this, "isTopSheet", true);
2149
+ // Pooled payload — identity documented in SheetEventMap.progress JSDoc;
2150
+ // consumers must not retain across frames.
2151
+ __publicField(this, "progressPayload", {
2152
+ value: 0,
2153
+ size: 0
2154
+ });
2155
+ // Pooled buffer for `getDragContext()` — onMove calls this 60-120×/s.
2156
+ // Inner `range` object identity is also stable (mutated in place).
2157
+ __publicField(this, "dragContextBuf", {
2158
+ size: 0,
2159
+ maxAxisSize: 0,
2160
+ range: { min: 0, max: 0 },
2161
+ rubberBandEnabled: false
2162
+ });
2163
+ __publicField(this, "bus", createEventBus());
2164
+ __publicField(this, "persistKey");
2165
+ __publicField(this, "linkedSheets", []);
2166
+ __publicField(this, "scrollCache");
2167
+ // Single LIFO stack for ALL destroy-only teardowns. Plugins (added last)
2168
+ // tear down first before the infrastructure they depend on. Toggle-semantic
2169
+ // listeners (focus-trap / scroll-lock / scrim tap-to-close) stay as named
2170
+ // fields on their controllers.
2171
+ __publicField(this, "teardowns", new TeardownStack());
2172
+ // Pre-computed transform template — built once per engine since `mode` is
2173
+ // fixed for its lifetime. Avoids the 4-arm switch at 60-120 Hz.
2174
+ __publicField(this, "transformTemplate");
2175
+ const resolved = resolveEngineOptions(opts, {
2176
+ shouldApplyInertSiblings: () => {
2177
+ if (typeof document === "undefined") return false;
2178
+ const bodyChildren = Array.from(document.body.children);
2179
+ return bodyChildren.some(
2180
+ (c) => c === opts.element || c.contains(opts.element)
2181
+ );
2182
+ }
2183
+ });
2184
+ this.element = opts.element;
2185
+ this.handle = opts.handle ?? opts.element;
2186
+ this.scrollContainer = opts.scrollContainer;
2187
+ this.backdrop = opts.backdrop;
2188
+ this.screenComponent = opts.screenComponent;
2189
+ this.mode = resolved.mode;
2190
+ this.transformTemplate = buildTransformTemplate(this.mode);
2191
+ this.aria = new AriaSliderWriter(this.handle, this.mode);
2192
+ this.flickVelocity = resolved.flickVelocity;
2193
+ this.dragThreshold = resolved.dragThreshold;
2194
+ this.rubberBandEnabled = resolved.rubberBandEnabled;
2195
+ this.scrim = new ScrimController(
2196
+ {
2197
+ mode: this.mode,
2198
+ screenComponent: this.screenComponent,
2199
+ backdrop: this.backdrop,
2200
+ isDestroyed: () => this.destroyed,
2201
+ isTopSheet: () => this.isTopSheet,
2202
+ getAllowedIds: () => this.snaps.getAllowedIds().slice(),
2203
+ getResolvedSnaps: () => this.snaps.getResolvedSnaps().slice(),
2204
+ snapTo: (id) => {
2205
+ void this.snapTo(id);
2206
+ }
2207
+ },
2208
+ resolved.scrim
2209
+ );
2210
+ this.animation = new AnimationRunner(
2211
+ {
2212
+ element: this.element,
2213
+ getRootEl: () => this.rootEl,
2214
+ applySize: (size) => this.applySize(size),
2215
+ getSize: () => this.size,
2216
+ // Optional chain protects synthetic test paths that drive animateTo
2217
+ // before attach() (gesture is constructed there).
2218
+ isDragging: () => this.gesture?.isDragging ?? false
2219
+ },
2220
+ resolved.animation
2221
+ );
2222
+ this.lifecycle = new LifecycleController(
2223
+ {
2224
+ element: this.element,
2225
+ close: () => this.close()
2226
+ },
2227
+ resolved.lifecycle
2228
+ );
2229
+ this.closeOnBack = resolved.closeOnBack;
2230
+ this.routedTo = opts.routedTo;
2231
+ this.snapPointsRaw = opts.snapPoints;
2232
+ this.persistKey = opts.persistKey;
2233
+ if (opts.linkedSheets) {
2234
+ this.linkedSheets = opts.linkedSheets;
2235
+ }
2236
+ this.activeId = resolved.initialId;
2237
+ auditVhUsage(this.snapPointsRaw);
2238
+ this.rootEl = this.element.closest(".bs-root");
2239
+ this.snaps = new SnapResolver(
2240
+ this.snapPointsRaw,
2241
+ resolved.initialAllowed,
2242
+ this.mode,
2243
+ () => this.handle.offsetHeight,
2244
+ (maxAxisSize) => {
2245
+ this.element.style[layoutAxis(this.mode)] = `${maxAxisSize}px`;
2246
+ }
2247
+ );
2248
+ const initial = this.snaps.findById(this.activeId);
2249
+ if (initial) this.size = initial.size;
2250
+ this.applySize(this.size);
2251
+ this.updateAriaSlider();
2252
+ this.scrollCache = createScrollCache({
2253
+ scrollContainer: this.scrollContainer,
2254
+ getMaxAxisSize: () => this.snaps.getMaxAxisSize()
2255
+ });
2256
+ this.attach();
2257
+ this.registerInStack();
2258
+ if (this.snaps.getMaxAxisSize() === 0 && typeof IntersectionObserver !== "undefined" && typeof document !== "undefined") {
2259
+ const io = new IntersectionObserver((entries) => {
2260
+ for (const entry of entries) {
2261
+ if (!entry.isIntersecting) continue;
2262
+ if (this.destroyed) return;
2263
+ this.snaps.recompute();
2264
+ const current = this.snaps.findById(this.activeId);
2265
+ if (current) {
2266
+ this.size = current.size;
2267
+ this.applySize(this.size);
2268
+ this.updateAriaSlider();
2269
+ }
2270
+ io.disconnect();
2271
+ return;
2272
+ }
2273
+ });
2274
+ io.observe(this.element);
2275
+ this.teardowns.add(() => io.disconnect());
2276
+ }
2277
+ if (this.persistKey) {
2278
+ this.teardowns.add(installPersist(this, this.persistKey));
2279
+ }
2280
+ this.teardowns.add(
2281
+ installAutoCollapse({
2282
+ ms: opts.autoCollapseAfter,
2283
+ isDestroyed: () => this.destroyed,
2284
+ isDragging: () => this.gesture?.isDragging ?? false,
2285
+ getAllowedIds: () => this.snaps.getAllowedIds().slice(),
2286
+ getActiveId: () => this.activeId,
2287
+ resolveSnap: (id) => this.snaps.findById(id),
2288
+ snapTo: (id) => {
2289
+ void this.snapTo(id);
2290
+ },
2291
+ on: (event, fn) => this.on(event, fn)
2292
+ })
2293
+ );
2294
+ this.teardowns.add(
2295
+ installRoute({
2296
+ routedTo: this.routedTo,
2297
+ closeOnBack: this.closeOnBack,
2298
+ isTopSheet: () => this.isTopSheet,
2299
+ getSize: () => this.size,
2300
+ isDestroyed: () => this.destroyed,
2301
+ close: () => this.close(),
2302
+ on: (event, fn) => this.on(event, fn),
2303
+ sheetId: this.id
2304
+ })
2305
+ );
2306
+ if (this.size > 0) {
2307
+ this.handleOpen();
2308
+ }
2309
+ }
2310
+ get state() {
2311
+ return {
2312
+ size: this.size,
2313
+ activeId: this.activeId,
2314
+ isDragging: this.gesture?.isDragging ?? false,
2315
+ isAnimating: this.animation.isAnimating,
2316
+ progress: this.computeProgress(this.size)
2317
+ };
2318
+ }
2319
+ on(event, fn) {
2320
+ return this.bus.on(event, fn);
2321
+ }
2322
+ /**
2323
+ * Register a plugin. `install` runs synchronously; if it returns a function,
2324
+ * it's captured for teardown during `destroy()`. No-op if already destroyed
2325
+ * — installing into a torn-down engine would leak listeners.
2326
+ *
2327
+ * Throws from `plugin.install` are caught and rethrown via `queueMicrotask`
2328
+ * so a buggy plugin can't take the engine down with it: the engine stays
2329
+ * usable, sibling plugins still install, and the error surfaces in dev tools
2330
+ * on the next tick instead of being swallowed. Mirrors the per-fn isolation
2331
+ * model used for teardowns.
2332
+ *
2333
+ * Plugins that accept the second `scope` argument get transactional cleanup:
2334
+ * push partial-install cleanups via `scope.add(fn)` and the engine drains
2335
+ * them on throw, OR merges them into destroy-time teardowns on success.
2336
+ */
2337
+ use(plugin) {
2338
+ if (this.destroyed) {
2339
+ console.warn(
2340
+ `[BottomSheet] use("${plugin.name}") called on destroyed engine \u2014 ignored.`
2341
+ );
2342
+ return this;
2343
+ }
2344
+ const scoped = [];
2345
+ const scope = {
2346
+ // typeof check — not just truthiness — so a JS-only plugin pushing a
2347
+ // bogus value is silently rejected instead of queueing a confusing
2348
+ // TypeError on destroy() drain.
2349
+ add: (fn) => {
2350
+ if (typeof fn === "function") scoped.push(fn);
2351
+ }
2352
+ };
2353
+ let teardown;
2354
+ try {
2355
+ teardown = plugin.install(this, scope);
2356
+ } catch (err) {
2357
+ for (let i = scoped.length - 1; i >= 0; i--) {
2358
+ try {
2359
+ scoped[i]();
2360
+ } catch (cleanupErr) {
2361
+ queueMicrotask(() => {
2362
+ throw cleanupErr;
2363
+ });
2364
+ }
2365
+ }
2366
+ queueMicrotask(() => {
2367
+ throw err;
2368
+ });
2369
+ return this;
2370
+ }
2371
+ for (const fn of scoped) this.teardowns.add(fn);
2372
+ if (typeof teardown === "function") {
2373
+ this.teardowns.add(teardown);
2374
+ }
2375
+ return this;
2376
+ }
2377
+ /**
2378
+ * Replace the linked-sheets list at runtime. Use when peer engines aren't
2379
+ * available at construction time (mounted later in the tree). The wiring
2380
+ * to the `open` event is independent of this list — it reads `linkedSheets`
2381
+ * lazily on emit, so this setter is a simple field swap.
2382
+ */
2383
+ setLinkedSheets(sheets) {
2384
+ if (this.destroyed) return;
2385
+ this.linkedSheets = sheets;
2386
+ }
2387
+ /** Read-only view of the current allow-list, for cross-sheet target negotiation. */
2388
+ getAllowedIds() {
2389
+ return this.snaps.getAllowedIds().slice();
2390
+ }
2391
+ /**
2392
+ * Animate to a snap point by id. Resolves when the animation completes.
2393
+ *
2394
+ * Two call shapes:
2395
+ * ```ts
2396
+ * engine.snapTo("full"); // default velocity
2397
+ * engine.snapTo("full", 0.5); // px/ms initial velocity
2398
+ * engine.snapTo("full", { velocity: 0.5, signal }); // abortable
2399
+ * ```
2400
+ *
2401
+ * When `opts.signal` is provided, calling `controller.abort()` cancels the
2402
+ * in-flight tween/spring and the returned promise resolves without firing
2403
+ * `snap`. The captured `AbortSignal` is checked after each await so external
2404
+ * aborts ride the same cycle invariant as internal ones (resize, destroy,
2405
+ * concurrent snapTo).
2406
+ */
2407
+ async snapTo(id, velocityOrOpts = 0, _skipBeforeSnap = false) {
2408
+ if (this.destroyed) return;
2409
+ const opts = typeof velocityOrOpts === "object" ? velocityOrOpts : { velocity: velocityOrOpts };
2410
+ const velocityPxPerMs = opts.velocity ?? 0;
2411
+ const externalSignal = opts.signal;
2412
+ if (externalSignal?.aborted) return;
2413
+ const target = this.snaps.findById(id);
2414
+ if (!target) {
2415
+ console.warn(`[BottomSheet] unknown snap id: ${id}`);
2416
+ return;
2417
+ }
2418
+ if (!this.snaps.getAllowedIds().includes(id)) {
2419
+ console.warn(`[BottomSheet] snap "${id}" is not in allowed list`);
2420
+ return;
2421
+ }
2422
+ if (!_skipBeforeSnap && this.emitBeforeSnap(target, this.activeId)) {
2423
+ return;
2424
+ }
2425
+ const signal = this.newCycle();
2426
+ const onExternalAbort = () => {
2427
+ this.animation.cancel();
2428
+ this.newCycle();
2429
+ };
2430
+ externalSignal?.addEventListener("abort", onExternalAbort, { once: true });
2431
+ const wasClosed = this.size === 0;
2432
+ const previousId = this.activeId;
2433
+ const previousSize = this.size;
2434
+ this.scrollCache.cache(previousId, previousSize, target.size);
2435
+ this.activeId = id;
2436
+ if (this.animation.viewTransitionsAvailable) {
2437
+ this.currentViewTransition?.skipTransition?.();
2438
+ const vt = document.startViewTransition(() => {
2439
+ this.applySize(target.size);
2440
+ });
2441
+ this.currentViewTransition = vt;
2442
+ try {
2443
+ await vt.finished;
2444
+ } catch {
2445
+ }
2446
+ if (this.currentViewTransition === vt) this.currentViewTransition = null;
2447
+ } else {
2448
+ await this.animation.animateTo(target.size, velocityPxPerMs);
2449
+ }
2450
+ externalSignal?.removeEventListener("abort", onExternalAbort);
2451
+ if (signal.aborted) return;
2452
+ this.scrollCache.restore(id, previousSize, target.size);
2453
+ this.updateAriaSlider();
2454
+ this.emit("snap", { id, size: target.size });
2455
+ if (wasClosed && target.size > 0) {
2456
+ this.emit("open", { id });
2457
+ this.handleOpen();
2458
+ notifyLinkedSheets(this.linkedSheets, this);
2459
+ }
2460
+ if (target.size === 0) {
2461
+ this.emit("close", void 0);
2462
+ this.handleClose();
2463
+ }
2464
+ }
2465
+ /**
2466
+ * Drive the sheet to an arbitrary px size, bypassing snap matching.
2467
+ * Useful for preview scrubs, animation chaining, or programmatic gestures.
2468
+ * Animates with the configured spring/tween. Resolves when the animation
2469
+ * completes. Does NOT update `activeId` — call `snapTo(id)` after to commit.
2470
+ *
2471
+ * Unlike `snapTo`, this does not fire `before-snap` (it isn't a snap commit)
2472
+ * nor `snap` (the sheet isn't settling to a known snap). `progress` events
2473
+ * still fire via applySize. Target is clamped to `[0, maxAxisSize]`.
2474
+ */
2475
+ async dragTo(targetSize, velocityOrOpts = 0) {
2476
+ if (this.destroyed) return;
2477
+ const opts = typeof velocityOrOpts === "object" ? velocityOrOpts : { velocity: velocityOrOpts };
2478
+ const velocityPxPerMs = opts.velocity ?? 0;
2479
+ const externalSignal = opts.signal;
2480
+ if (externalSignal?.aborted) return;
2481
+ this.newCycle();
2482
+ const onExternalAbort = () => {
2483
+ this.animation.cancel();
2484
+ this.newCycle();
2485
+ };
2486
+ externalSignal?.addEventListener("abort", onExternalAbort, { once: true });
2487
+ const clamped = Math.max(0, Math.min(targetSize, this.snaps.getMaxAxisSize()));
2488
+ await this.animation.animateTo(clamped, velocityPxPerMs);
2489
+ externalSignal?.removeEventListener("abort", onExternalAbort);
2490
+ if (this.destroyed || externalSignal?.aborted) return;
2491
+ }
2492
+ open(id) {
2493
+ if (this.destroyed) return Promise.resolve();
2494
+ const target = id ?? this.snaps.getAllowedIds().find((a) => a !== "closed") ?? this.activeId;
2495
+ return this.snapTo(target);
2496
+ }
2497
+ close() {
2498
+ if (this.destroyed) return Promise.resolve();
2499
+ const closedId = this.snapPointsRaw.find((p) => p.id === "closed")?.id ?? this.snaps.getAllowedIds()[0];
2500
+ return this.snapTo(closedId ?? this.activeId);
2501
+ }
2502
+ setAllowed(ids, snap) {
2503
+ if (this.destroyed) return;
2504
+ const willSnap = snap !== void 0 && ids.includes(snap) || !ids.includes(this.activeId) && ids.length > 0;
2505
+ if (!willSnap) {
2506
+ this.animation.cancel();
2507
+ this.newCycle();
2508
+ }
2509
+ this.snaps.setAllowedIds(ids);
2510
+ this.updateAriaSlider();
2511
+ if (snap && ids.includes(snap)) {
2512
+ void this.snapTo(
2513
+ snap,
2514
+ 0,
2515
+ /* internal */
2516
+ true
2517
+ );
2518
+ } else if (!ids.includes(this.activeId)) {
2519
+ const fallback = ids[0];
2520
+ if (fallback) void this.snapTo(
2521
+ fallback,
2522
+ 0,
2523
+ /* internal */
2524
+ true
2525
+ );
2526
+ }
2527
+ }
2528
+ setBackdropRange(range) {
2529
+ this.scrim.setBackdropRange(range, () => this.applySize(this.size));
2530
+ }
2531
+ setScreenRange(range) {
2532
+ this.scrim.setScreenRange(range, () => this.applySize(this.size));
2533
+ }
2534
+ setScrimColor(color) {
2535
+ this.scrim.setScrimColor(color);
2536
+ }
2537
+ setScrimBlur(blur) {
2538
+ this.scrim.setScrimBlur(blur);
2539
+ }
2540
+ setScrimInteractive(interactive) {
2541
+ this.scrim.setScrimInteractive(interactive);
2542
+ }
2543
+ /**
2544
+ * Batch-update multiple scrim fields in one call. Apply order is:
2545
+ * 1. `preset` — fills baseline color/blur/range/interactive.
2546
+ * 2. `mode` — re-positions the scrim (fixed inset / clear / hide).
2547
+ * 3. `enabled` — flips the opacity contribution on/off.
2548
+ * 4. `tapToClose` — installs/tears the click listener.
2549
+ * 5. `color` / `blur` / `interactive` / `range` — explicit overrides.
2550
+ * 6. ONE `applySize` so the per-frame opacity stays consistent.
2551
+ *
2552
+ * Performance: collecting changes here (vs calling individual setters)
2553
+ * avoids repeated `applySize` calls during a multi-field swap. Setters
2554
+ * called here suppress their own internal `applySize` either by passing
2555
+ * through fast-paths (mode/enabled no-op when value unchanged) or by
2556
+ * being visual-only (color/blur/interactive don't influence opacity).
2557
+ */
2558
+ setScrim(opts) {
2559
+ this.scrim.setScrim(opts, () => this.applySize(this.size));
2560
+ }
2561
+ setScrimMode(mode) {
2562
+ this.scrim.setScrimMode(mode, () => this.applySize(this.size));
2563
+ }
2564
+ setScrimTapToClose(enabled) {
2565
+ this.scrim.setScrimTapToClose(enabled);
2566
+ }
2567
+ setScrimEnabled(enabled) {
2568
+ this.scrim.setScrimEnabled(enabled, () => this.applySize(this.size));
2569
+ }
2570
+ setScrimOverlay(opts) {
2571
+ return this.scrim.setScrimOverlay(opts);
2572
+ }
2573
+ /**
2574
+ * Read-only snapshot of scrim state. Use the `setScrim*` setters to mutate.
2575
+ * Stable public API — internals (e.g. cached opacity sentinels) are NOT
2576
+ * exposed so consumers can't accidentally couple to ScrimController shape.
2577
+ */
2578
+ getScrimState() {
2579
+ return { mode: this.scrim.scrimMode, enabled: this.scrim.scrimEnabled };
2580
+ }
2581
+ setSnapPoints(points, allowed) {
2582
+ if (this.destroyed) return;
2583
+ this.animation.cancel();
2584
+ this.newCycle();
2585
+ this.snapPointsRaw = points;
2586
+ auditVhUsage(points);
2587
+ this.snaps.setRaw(points);
2588
+ if (allowed) this.snaps.setAllowedIds(allowed);
2589
+ this.scrollCache.clear();
2590
+ this.scrim.invalidateOpacityCache();
2591
+ const current = this.snaps.findById(this.activeId);
2592
+ if (current) {
2593
+ this.applySize(current.size);
2594
+ }
2595
+ this.updateAriaSlider();
2596
+ }
2597
+ destroy() {
2598
+ this.destroyed = true;
2599
+ this.currentAbort.abort();
2600
+ this.currentViewTransition?.skipTransition?.();
2601
+ this.currentViewTransition = null;
2602
+ this.bus.clear();
2603
+ this.animation.cancel();
2604
+ this.gesture?.forceClearDragState();
2605
+ this.teardowns.drain();
2606
+ this.scrim.destroy();
2607
+ this.animation.destroy();
2608
+ this.lifecycle.destroy();
2609
+ if (this.backdrop) {
2610
+ this.backdrop.style.opacity = "";
2611
+ this.backdrop.style.pointerEvents = "";
2612
+ }
2613
+ if (this.screenComponent) {
2614
+ this.screenComponent.style.opacity = "";
2615
+ this.screenComponent.style.display = "";
2616
+ }
2617
+ this.sizeWriteSentinel.invalidate();
2618
+ this.progressWriteSentinel.invalidate();
2619
+ }
2620
+ emit(event, payload) {
2621
+ this.bus.emit(event, payload);
2622
+ }
2623
+ /**
2624
+ * Abort the current cycle's signal and replace the controller. Returns the
2625
+ * fresh signal so the caller can capture it locally before any await — when
2626
+ * a future newCycle() / destroy aborts our controller, the captured signal
2627
+ * flips to aborted and post-await guards short-circuit.
2628
+ */
2629
+ newCycle() {
2630
+ this.currentAbort.abort();
2631
+ this.currentAbort = new AbortController();
2632
+ return this.currentAbort.signal;
2633
+ }
2634
+ /**
2635
+ * Fire `before-snap` and report whether a listener cancelled it. The
2636
+ * `cancel()` callback exposed to listeners is frozen after the synchronous
2637
+ * emit phase so async callers can't silently miss — they get a console
2638
+ * warning. Returns `true` when cancelled so callers can early-return /
2639
+ * spring-back without re-implementing the cancel/frozen pattern.
2640
+ */
2641
+ emitBeforeSnap(target, previousId) {
2642
+ let cancelled = false;
2643
+ let frozen = false;
2644
+ this.emit("before-snap", {
2645
+ id: target.id,
2646
+ size: target.size,
2647
+ previousId,
2648
+ cancel: () => {
2649
+ if (frozen) {
2650
+ console.warn(
2651
+ "[BottomSheet] before-snap.cancel() called asynchronously \u2014 ignored. cancel() must be invoked synchronously inside the listener."
2652
+ );
2653
+ return;
2654
+ }
2655
+ cancelled = true;
2656
+ }
2657
+ });
2658
+ frozen = true;
2659
+ return cancelled;
2660
+ }
2661
+ recomputeSnaps() {
2662
+ const seen = /* @__PURE__ */ new Set();
2663
+ for (const p of this.snapPointsRaw) {
2664
+ if (seen.has(p.id)) {
2665
+ console.warn(
2666
+ `[BottomSheet] duplicate snap id "${p.id}" \u2014 only the first occurrence is reachable.`
2667
+ );
2668
+ }
2669
+ seen.add(p.id);
2670
+ }
2671
+ this.snaps.setRaw(this.snapPointsRaw);
2672
+ this.scrim.invalidateOpacityCache();
2673
+ }
2674
+ /**
2675
+ * Memoised `allowedRange()` — delegates to SnapResolver which owns the cache.
2676
+ * Engine wrapper kept so existing call sites don't all need updating;
2677
+ * resolver-level memoization survives across method invocations.
2678
+ */
2679
+ getAllowedRange() {
2680
+ return this.snaps.getAllowedRange();
2681
+ }
2682
+ /**
2683
+ * Write ARIA slider value attributes onto the handle so the engine itself
2684
+ * is the source of truth for screen-reader announcements. Called from the
2685
+ * constructor and from every code path that mutates `activeId` /
2686
+ * `allowedIds`. WAI-ARIA 1.2 requires `aria-valuenow` for `role="slider"` —
2687
+ * without it screen readers can't announce drag/snap progress to keyboard
2688
+ * + AT users (WCAG 4.1.2 Name, Role, Value).
2689
+ *
2690
+ * Engine does NOT set `role="slider"` itself — that's the adapter's or
2691
+ * consumer markup's responsibility. We only decorate with dynamic values.
2692
+ *
2693
+ * Empty allowed-list is malformed input (settable via `setAllowed([])`);
2694
+ * short-circuit to remove ARIA value attributes so screen readers see a
2695
+ * no-value slider rather than a degenerate `min=max=now=0` (WAI-ARIA 1.2
2696
+ * requires `valuemax > valuemin` for `role="slider"`).
2697
+ */
2698
+ updateAriaSlider() {
2699
+ this.aria.setValue(this.snaps.getAllowedIds(), this.activeId);
2700
+ }
2701
+ registerInStack() {
2702
+ this.teardowns.add(sheetStack.push({
2703
+ id: this.id,
2704
+ setZIndex: (z) => {
2705
+ this.element.style.zIndex = String(z);
2706
+ if (this.backdrop) this.backdrop.style.zIndex = String(z - 1);
2707
+ },
2708
+ setIsTop: (isTop) => {
2709
+ this.isTopSheet = isTop;
2710
+ if (this.backdrop) {
2711
+ this.backdrop.style.display = isTop ? "" : "none";
2712
+ }
2713
+ }
2714
+ }));
2715
+ }
2716
+ attach() {
2717
+ this.gesture = new GestureController({
2718
+ handle: this.handle,
2719
+ element: this.element,
2720
+ mode: this.mode,
2721
+ getRoot: () => this.rootEl,
2722
+ // Single coalesced reader — narrows the DI surface and removes 3 getter
2723
+ // dispatches per onMove frame at 60-120Hz. Returns a SHARED buffer
2724
+ // (this.dragContextBuf) — see field JSDoc for the retention contract.
2725
+ // Inner `range` object is mutated in place too so callers caching its
2726
+ // identity between frames stay valid.
2727
+ getDragContext: () => {
2728
+ const buf = this.dragContextBuf;
2729
+ const r = this.getAllowedRange();
2730
+ buf.size = this.size;
2731
+ buf.maxAxisSize = this.snaps.getMaxAxisSize();
2732
+ buf.range.min = r.min;
2733
+ buf.range.max = r.max;
2734
+ buf.rubberBandEnabled = this.rubberBandEnabled;
2735
+ return buf;
2736
+ },
2737
+ cancelAnimation: () => this.animation.cancel(),
2738
+ applySize: (size) => this.applySize(size),
2739
+ animateTo: (size, velocity) => this.animation.animateTo(size, velocity),
2740
+ settleAfterDrag: (delta, velocity, kind) => this.settleAfterDrag(delta, velocity, kind),
2741
+ emit: (event, payload) => this.emit(event, payload),
2742
+ listenerCount: (event) => this.bus.listenerCount(event)
2743
+ });
2744
+ this.teardowns.add(this.gesture.install());
2745
+ try {
2746
+ this.attachFeatures();
2747
+ } catch (err) {
2748
+ this.teardowns.drain();
2749
+ try {
2750
+ this.scrim.destroy();
2751
+ } catch (destroyErr) {
2752
+ queueMicrotask(() => {
2753
+ throw destroyErr;
2754
+ });
2755
+ }
2756
+ try {
2757
+ this.animation.destroy();
2758
+ } catch (destroyErr) {
2759
+ queueMicrotask(() => {
2760
+ throw destroyErr;
2761
+ });
2762
+ }
2763
+ try {
2764
+ this.lifecycle.destroy();
2765
+ } catch (destroyErr) {
2766
+ queueMicrotask(() => {
2767
+ throw destroyErr;
2768
+ });
2769
+ }
2770
+ this.destroyed = true;
2771
+ throw err;
2772
+ }
2773
+ }
2774
+ attachFeatures() {
2775
+ if (this.scrollContainer) {
2776
+ this.teardowns.add(installContentSwipe({
2777
+ container: this.scrollContainer,
2778
+ isDragging: () => this.gesture?.isDragging ?? false,
2779
+ isAnimating: () => this.animation.isAnimating,
2780
+ getAllowedIds: () => this.snaps.getAllowedIds(),
2781
+ getActiveId: () => this.activeId,
2782
+ snapTo: (id) => {
2783
+ void this.snapTo(id);
2784
+ }
2785
+ }));
2786
+ }
2787
+ if (typeof window !== "undefined") {
2788
+ this.teardowns.add(installResizeObserver({
2789
+ element: this.element,
2790
+ getMode: () => this.mode,
2791
+ isDestroyed: () => this.destroyed,
2792
+ isDragging: () => this.gesture?.isDragging ?? false,
2793
+ resolveActiveSnap: () => this.snaps.findById(this.activeId),
2794
+ getMaxAxisSize: () => this.snaps.getMaxAxisSize(),
2795
+ getSize: () => this.size,
2796
+ setMaxAxisSize: (size) => {
2797
+ this.snaps.setMaxAxisSize(size);
2798
+ },
2799
+ setSize: (size) => {
2800
+ this.size = size;
2801
+ },
2802
+ recomputeSnaps: () => this.recomputeSnaps(),
2803
+ applySize: (size) => this.applySize(size),
2804
+ cancelInFlight: () => {
2805
+ this.animation.cancel();
2806
+ },
2807
+ newCycle: () => {
2808
+ this.newCycle();
2809
+ }
2810
+ }));
2811
+ if (this.lifecycle.closeOnEscape) {
2812
+ const onKey = (e) => {
2813
+ if (this.destroyed) return;
2814
+ if (e.key === "Escape" && this.isTopSheet && this.size > 0) {
2815
+ void this.close();
2816
+ }
2817
+ };
2818
+ document.addEventListener("keydown", onKey);
2819
+ this.teardowns.add(
2820
+ () => document.removeEventListener("keydown", onKey)
2821
+ );
2822
+ }
2823
+ this.teardowns.add(installVisualViewport({
2824
+ element: this.element,
2825
+ isVerticalAxis: () => this.mode === "bottom" || this.mode === "top",
2826
+ isDestroyed: () => this.destroyed,
2827
+ isDragging: () => this.gesture?.isDragging ?? false,
2828
+ recomputeSnaps: () => this.recomputeSnaps(),
2829
+ resolveActiveSnap: () => this.snaps.findById(this.activeId),
2830
+ getMaxAxisSize: () => this.snaps.getMaxAxisSize(),
2831
+ getSize: () => this.size,
2832
+ setMaxAxisSize: (size) => {
2833
+ this.snaps.setMaxAxisSize(size);
2834
+ },
2835
+ setSize: (size) => {
2836
+ this.size = size;
2837
+ },
2838
+ applySize: (size) => this.applySize(size)
2839
+ }));
2840
+ }
2841
+ this.teardowns.add(installSliderKeyboard({
2842
+ handle: this.handle,
2843
+ mode: this.mode,
2844
+ isDestroyed: () => this.destroyed,
2845
+ getAllowedIds: () => this.snaps.getAllowedIds(),
2846
+ getActiveId: () => this.activeId,
2847
+ snapTo: (id) => {
2848
+ void this.snapTo(id);
2849
+ }
2850
+ }));
2851
+ this.scrim.attach();
2852
+ }
2853
+ settleAfterDrag(delta, velocity, kind = "touch") {
2854
+ const signal = this.newCycle();
2855
+ const target = this.snaps.findDragSettleTarget({
2856
+ delta,
2857
+ velocity,
2858
+ pointerKind: kind,
2859
+ size: this.size,
2860
+ activeId: this.activeId,
2861
+ flickVelocity: this.flickVelocity,
2862
+ dragThreshold: this.dragThreshold
2863
+ });
2864
+ if (!target) return;
2865
+ const previousId = this.activeId;
2866
+ if (this.emitBeforeSnap(target, previousId)) {
2867
+ const restore = this.snaps.findById(previousId);
2868
+ if (restore) {
2869
+ void this.animation.animateTo(restore.size, 0);
2870
+ }
2871
+ return;
2872
+ }
2873
+ const previousSize = this.size;
2874
+ this.scrollCache.cache(previousId, previousSize, target.size);
2875
+ this.activeId = target.id;
2876
+ void this.animation.animateTo(target.size, velocity).then(() => {
2877
+ if (signal.aborted) return;
2878
+ this.scrollCache.restore(target.id, previousSize, target.size);
2879
+ this.updateAriaSlider();
2880
+ this.emit("snap", { id: target.id, size: target.size });
2881
+ this.haptic();
2882
+ if (previousId === "closed" && target.size > 0) {
2883
+ this.emit("open", { id: target.id });
2884
+ this.handleOpen();
2885
+ }
2886
+ if (target.size === 0) {
2887
+ this.emit("close", void 0);
2888
+ this.handleClose();
2889
+ }
2890
+ });
2891
+ }
2892
+ /** Trigger a brief haptic tick (iOS Safari + Android Chrome support). */
2893
+ haptic() {
2894
+ if (typeof navigator !== "undefined" && "vibrate" in navigator) {
2895
+ try {
2896
+ navigator.vibrate(HAPTIC_DURATION_MS);
2897
+ } catch {
2898
+ }
2899
+ }
2900
+ }
2901
+ applySize(size) {
2902
+ this.size = size;
2903
+ const offset = this.snaps.getMaxAxisSize() - size;
2904
+ const style = this.element.style;
2905
+ style.transform = this.transformTemplate(offset);
2906
+ if (this.sizeWriteSentinel.shouldWrite(size, SIZE_WRITE_EPSILON)) {
2907
+ style.setProperty("--bs-size", `${size}px`);
2908
+ }
2909
+ const progress = this.computeProgress(size);
2910
+ const progressChanged = this.progressWriteSentinel.shouldWrite(
2911
+ progress,
2912
+ OPACITY_WRITE_EPSILON
2913
+ );
2914
+ if (progressChanged) {
2915
+ style.setProperty("--bs-progress", String(progress));
2916
+ }
2917
+ this.scrim.applyOpacity(progress, progressChanged);
2918
+ if (progressChanged && this.bus.listenerCount("progress") > 0) {
2919
+ this.progressPayload.value = progress;
2920
+ this.progressPayload.size = size;
2921
+ this.emit("progress", this.progressPayload);
2922
+ }
2923
+ }
2924
+ computeProgress(size) {
2925
+ const { min, max } = this.getAllowedRange();
2926
+ if (max <= min) return 0;
2927
+ return Math.min(Math.max((size - min) / (max - min), 0), 1);
2928
+ }
2929
+ handleOpen() {
2930
+ try {
2931
+ this.lifecycle.install();
2932
+ } catch (err) {
2933
+ if (!this.destroyed) this.newCycle();
2934
+ this.handleClose();
2935
+ this.applySize(0);
2936
+ this.activeId = this.snapPointsRaw.find((p) => p.id === "closed")?.id ?? this.activeId;
2937
+ this.size = 0;
2938
+ queueMicrotask(() => {
2939
+ throw err;
2940
+ });
2941
+ }
2942
+ }
2943
+ handleClose() {
2944
+ this.lifecycle.release();
2945
+ }
2946
+ };
2947
+
2948
+ // src/vue/useBottomSheet.ts
2949
+ function useBottomSheet(opts) {
2950
+ const sheetRef = ref(null);
2951
+ const handleRef = ref(null);
2952
+ const contentRef = ref(null);
2953
+ const backdropRef = ref(null);
2954
+ const screenRef = ref(null);
2955
+ let engine = null;
2956
+ const pending = [];
2957
+ const state = reactive({
2958
+ size: 0,
2959
+ activeId: opts.initial ?? opts.snapPoints[0]?.id ?? "default",
2960
+ isDragging: false,
2961
+ isAnimating: false,
2962
+ progress: 0
2963
+ });
2964
+ const sync = () => {
2965
+ if (!engine) return;
2966
+ Object.assign(state, engine.state);
2967
+ };
2968
+ onMounted(() => {
2969
+ if (!sheetRef.value) return;
2970
+ const { onSnap, ...engineOpts } = opts;
2971
+ engine = new BottomSheetEngine({
2972
+ ...engineOpts,
2973
+ element: sheetRef.value,
2974
+ handle: handleRef.value ?? void 0,
2975
+ scrollContainer: contentRef.value ?? void 0,
2976
+ backdrop: backdropRef.value ?? void 0,
2977
+ screenComponent: screenRef.value ?? void 0
2978
+ });
2979
+ sync();
2980
+ engine.on("snap", (payload) => {
2981
+ sync();
2982
+ onSnap?.(payload.id);
2983
+ });
2984
+ engine.on("dragstart", sync);
2985
+ engine.on("dragend", sync);
2986
+ for (const entry of pending) {
2987
+ entry.engineUnsub = engine.on(
2988
+ entry.event,
2989
+ entry.fn
2990
+ );
2991
+ }
2992
+ pending.length = 0;
2993
+ });
2994
+ onBeforeUnmount(() => {
2995
+ engine?.destroy();
2996
+ engine = null;
2997
+ });
2998
+ return {
2999
+ sheetRef,
3000
+ handleRef,
3001
+ contentRef,
3002
+ backdropRef,
3003
+ screenRef,
3004
+ state,
3005
+ snapTo: (id) => engine?.snapTo(id) ?? Promise.resolve(),
3006
+ open: (id) => engine?.open(id) ?? Promise.resolve(),
3007
+ close: () => engine?.close() ?? Promise.resolve(),
3008
+ setAllowed: (ids, snap) => engine?.setAllowed(ids, snap),
3009
+ setSnapPoints: (points, allowed) => engine?.setSnapPoints(points, allowed),
3010
+ on: (event, fn) => {
3011
+ if (engine) return engine.on(event, fn);
3012
+ const entry = {
3013
+ event,
3014
+ fn,
3015
+ engineUnsub: null
3016
+ };
3017
+ pending.push(entry);
3018
+ return () => {
3019
+ if (entry.engineUnsub) {
3020
+ entry.engineUnsub();
3021
+ entry.engineUnsub = null;
3022
+ } else {
3023
+ const idx = pending.indexOf(entry);
3024
+ if (idx !== -1) pending.splice(idx, 1);
3025
+ }
3026
+ };
3027
+ }
3028
+ };
3029
+ }
3030
+
3031
+ // unplugin-vue:/plugin-vue/export-helper
3032
+ var export_helper_default = (sfc, props) => {
3033
+ const target = sfc.__vccOpts || sfc;
3034
+ for (const [key, val] of props) {
3035
+ target[key] = val;
3036
+ }
3037
+ return target;
3038
+ };
3039
+
3040
+ // src/vue/BottomSheet.vue
3041
+ var _sfc_main = /* @__PURE__ */ defineComponent({
3042
+ __name: "BottomSheet",
3043
+ props: {
3044
+ mode: {
3045
+ type: String,
3046
+ required: false
3047
+ },
3048
+ duration: {
3049
+ type: Number,
3050
+ required: false
3051
+ },
3052
+ easing: {
3053
+ type: Function,
3054
+ required: false
3055
+ },
3056
+ respectReducedMotion: {
3057
+ type: Boolean,
3058
+ required: false
3059
+ },
3060
+ flickVelocity: {
3061
+ type: Number,
3062
+ required: false
3063
+ },
3064
+ dragThreshold: {
3065
+ type: Number,
3066
+ required: false
3067
+ },
3068
+ rubberBand: {
3069
+ type: Boolean,
3070
+ required: false
3071
+ },
3072
+ backdropRange: {
3073
+ type: Array,
3074
+ required: false
3075
+ },
3076
+ screenRange: {
3077
+ type: Array,
3078
+ required: false
3079
+ },
3080
+ scrimMode: {
3081
+ type: String,
3082
+ required: false
3083
+ },
3084
+ scrimColor: {
3085
+ type: String,
3086
+ required: false
3087
+ },
3088
+ scrimBlur: {
3089
+ type: String,
3090
+ required: false
3091
+ },
3092
+ scrimInteractive: {
3093
+ type: Boolean,
3094
+ required: false
3095
+ },
3096
+ scrimTapToClose: {
3097
+ type: Boolean,
3098
+ required: false
3099
+ },
3100
+ scrimPreset: {
3101
+ type: String,
3102
+ required: false
3103
+ },
3104
+ animation: {
3105
+ type: String,
3106
+ required: false
3107
+ },
3108
+ spring: {
3109
+ type: Object,
3110
+ required: false
3111
+ },
3112
+ focusTrap: {
3113
+ type: Boolean,
3114
+ required: false
3115
+ },
3116
+ initialFocus: {
3117
+ type: null,
3118
+ required: false
3119
+ },
3120
+ closeOnEscape: {
3121
+ type: Boolean,
3122
+ required: false
3123
+ },
3124
+ lockBodyScroll: {
3125
+ type: Boolean,
3126
+ required: false
3127
+ },
3128
+ closeOnBack: {
3129
+ type: Boolean,
3130
+ required: false
3131
+ },
3132
+ routedTo: {
3133
+ type: String,
3134
+ required: false
3135
+ },
3136
+ inertSiblings: {
3137
+ type: Boolean,
3138
+ required: false
3139
+ },
3140
+ persistKey: {
3141
+ type: String,
3142
+ required: false
3143
+ },
3144
+ autoCollapseAfter: {
3145
+ type: Number,
3146
+ required: false
3147
+ },
3148
+ linkedSheets: {
3149
+ type: Array,
3150
+ required: false
3151
+ },
3152
+ viewTransitions: {
3153
+ type: Boolean,
3154
+ required: false
3155
+ },
3156
+ snapPoints: {
3157
+ type: Array,
3158
+ required: true
3159
+ },
3160
+ allowed: {
3161
+ type: Array,
3162
+ required: false
3163
+ },
3164
+ initial: {
3165
+ type: null,
3166
+ required: false
3167
+ },
3168
+ onSnap: {
3169
+ type: Function,
3170
+ required: false
3171
+ },
3172
+ backdrop: {
3173
+ type: Boolean,
3174
+ required: false,
3175
+ default: true
3176
+ },
3177
+ closeOnBackdrop: {
3178
+ type: Boolean,
3179
+ required: false,
3180
+ default: true
3181
+ },
3182
+ ariaLabel: {
3183
+ type: String,
3184
+ required: false,
3185
+ default: "Bottom sheet"
3186
+ }
3187
+ },
3188
+ emits: [
3189
+ "change",
3190
+ "snap",
3191
+ "open",
3192
+ "close"
3193
+ ],
3194
+ setup(__props, { expose: __expose, emit: __emit }) {
3195
+ const props = __props;
3196
+ const emit = __emit;
3197
+ const { sheetRef, handleRef, contentRef, backdropRef, screenRef, state, snapTo, open, close, setAllowed, setSnapPoints, on } = useBottomSheet(props);
3198
+ watch(() => ({ ...state }), (next) => emit("change", next), { deep: false });
3199
+ on("snap", (payload) => emit("snap", payload.id));
3200
+ on("open", (payload) => emit("open", payload.id));
3201
+ on("close", () => emit("close"));
3202
+ const isVerticalAxis = computed(() => {
3203
+ const mode = props.mode ?? "bottom";
3204
+ return mode === "bottom" || mode === "top";
3205
+ });
3206
+ const allowedIds = computed(() => props.allowed ?? props.snapPoints.map((p) => p.id));
3207
+ const activeIdx = computed(() => {
3208
+ const idx = allowedIds.value.indexOf(state.activeId);
3209
+ return idx === -1 ? 0 : idx;
3210
+ });
3211
+ const ariaModal = computed(() => props.focusTrap === true);
3212
+ __expose({
3213
+ snapTo,
3214
+ open,
3215
+ close,
3216
+ setAllowed,
3217
+ setSnapPoints,
3218
+ on,
3219
+ // readonly() prevents external write-through (e.g. `bsRef.value.state.size = 999`)
3220
+ // that would desync the local view-state proxy from the engine's truth.
3221
+ // Mirrors React's getter-based exposure and Svelte's getState() snapshot.
3222
+ state: readonly(state)
3223
+ });
3224
+ const __returned__ = {
3225
+ props,
3226
+ emit,
3227
+ sheetRef,
3228
+ handleRef,
3229
+ contentRef,
3230
+ backdropRef,
3231
+ screenRef,
3232
+ state,
3233
+ snapTo,
3234
+ open,
3235
+ close,
3236
+ setAllowed,
3237
+ setSnapPoints,
3238
+ on,
3239
+ isVerticalAxis,
3240
+ allowedIds,
3241
+ activeIdx,
3242
+ ariaModal
3243
+ };
3244
+ Object.defineProperty(__returned__, "__isScriptSetup", {
3245
+ enumerable: false,
3246
+ value: true
3247
+ });
3248
+ return __returned__;
3249
+ }
3250
+ });
3251
+ var _hoisted_1 = { class: "bs-root" };
3252
+ var _hoisted_2 = {
3253
+ key: 1,
3254
+ ref: "screenRef",
3255
+ class: "bs-screen"
3256
+ };
3257
+ var _hoisted_3 = [
3258
+ "data-mode",
3259
+ "data-active",
3260
+ "role",
3261
+ "aria-modal",
3262
+ "aria-label"
3263
+ ];
3264
+ var _hoisted_4 = {
3265
+ key: 0,
3266
+ class: "bs-button-slot",
3267
+ "data-side": "left"
3268
+ };
3269
+ var _hoisted_5 = {
3270
+ key: 1,
3271
+ class: "bs-button-slot",
3272
+ "data-side": "right"
3273
+ };
3274
+ var _hoisted_6 = [
3275
+ "aria-orientation",
3276
+ "aria-valuemax",
3277
+ "aria-valuenow",
3278
+ "aria-valuetext"
3279
+ ];
3280
+ var _hoisted_7 = {
3281
+ ref: "contentRef",
3282
+ class: "bs-content",
3283
+ tabindex: "0",
3284
+ role: "region",
3285
+ "aria-label": "Sheet content"
3286
+ };
3287
+ var _hoisted_8 = {
3288
+ class: "bs-sr-only",
3289
+ role: "status",
3290
+ "aria-live": "polite"
3291
+ };
3292
+ function _sfc_render(_ctx, _cache, $props, $setup, $data, $options) {
3293
+ return openBlock(), createElementBlock("div", _hoisted_1, [
3294
+ $props.backdrop ? (openBlock(), createElementBlock(
3295
+ "div",
3296
+ {
3297
+ key: 0,
3298
+ ref: "backdropRef",
3299
+ class: "bs-backdrop",
3300
+ "aria-hidden": "true",
3301
+ onClick: _cache[0] || (_cache[0] = ($event) => $props.closeOnBackdrop ? $setup.close() : void 0)
3302
+ },
3303
+ null,
3304
+ 512
3305
+ /* NEED_PATCH */
3306
+ )) : createCommentVNode("v-if", true),
3307
+ _ctx.$slots.screen ? (openBlock(), createElementBlock(
3308
+ "div",
3309
+ _hoisted_2,
3310
+ [renderSlot(_ctx.$slots, "screen")],
3311
+ 512
3312
+ /* NEED_PATCH */
3313
+ )) : createCommentVNode("v-if", true),
3314
+ createElementVNode("section", {
3315
+ ref: "sheetRef",
3316
+ class: normalizeClass(["bs-sheet"]),
3317
+ "data-mode": $setup.props.mode ?? "bottom",
3318
+ "data-active": $setup.state.activeId,
3319
+ role: $setup.ariaModal ? "dialog" : "region",
3320
+ "aria-modal": $setup.ariaModal ? "true" : void 0,
3321
+ "aria-label": $props.ariaLabel
3322
+ }, [
3323
+ _ctx.$slots["button-left"] ? (openBlock(), createElementBlock("div", _hoisted_4, [renderSlot(_ctx.$slots, "button-left")])) : createCommentVNode("v-if", true),
3324
+ _ctx.$slots["button-right"] ? (openBlock(), createElementBlock("div", _hoisted_5, [renderSlot(_ctx.$slots, "button-right")])) : createCommentVNode("v-if", true),
3325
+ createElementVNode("div", {
3326
+ ref: "handleRef",
3327
+ class: "bs-handle",
3328
+ role: "slider",
3329
+ tabindex: "0",
3330
+ "aria-orientation": $setup.isVerticalAxis ? "vertical" : "horizontal",
3331
+ "aria-valuemin": "0",
3332
+ "aria-valuemax": Math.max(0, $setup.allowedIds.length - 1),
3333
+ "aria-valuenow": $setup.activeIdx,
3334
+ "aria-valuetext": $setup.state.activeId,
3335
+ "aria-label": "Resize sheet"
3336
+ }, [renderSlot(_ctx.$slots, "header", { state: $setup.state })], 8, _hoisted_6),
3337
+ createElementVNode(
3338
+ "div",
3339
+ _hoisted_7,
3340
+ [renderSlot(_ctx.$slots, "default")],
3341
+ 512
3342
+ /* NEED_PATCH */
3343
+ ),
3344
+ createElementVNode(
3345
+ "span",
3346
+ _hoisted_8,
3347
+ toDisplayString($setup.state.activeId),
3348
+ 1
3349
+ /* TEXT */
3350
+ )
3351
+ ], 8, _hoisted_3)
3352
+ ]);
3353
+ }
3354
+ var BottomSheet_default = /* @__PURE__ */ export_helper_default(_sfc_main, [["render", _sfc_render], ["__file", "/Users/maksimkravcov/Desktop/\u043F\u0440\u043E\u0435\u043A\u0442\u044B/BottomSheet/src/vue/BottomSheet.vue"]]);
3355
+
3356
+ export { BottomSheet_default as BottomSheet, useBottomSheet };
3357
+ //# sourceMappingURL=vue.js.map
3358
+ //# sourceMappingURL=vue.js.map