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