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