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