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