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