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