@vcarl/sashay 0.0.0-stage → 0.0.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.
@@ -0,0 +1,1401 @@
1
+ // src/engine.ts
2
+ const MAX_DEN = 6;
3
+ const SNAPS = (() => {
4
+ const seen = /* @__PURE__ */ new Map();
5
+ for (let n = 1; n <= MAX_DEN; n++) for (let k = 0; k <= n; k++) if (!seen.has(k / n)) seen.set(k / n, {
6
+ k,
7
+ n,
8
+ v: k / n
9
+ });
10
+ return [...seen.values()].sort((a, b) => a.v - b.v);
11
+ })();
12
+ /** Snap index → fraction. */
13
+ const snapV = (i) => SNAPS[i].v;
14
+ const UNIT_PX = 220;
15
+ const gridOrder = (contentPx) => Math.max(1, Math.min(MAX_DEN, Math.floor(contentPx / UNIT_PX)));
16
+ const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
17
+ const allowedIdx = (order) => SNAPS.map((_, i) => i).filter((i) => SNAPS[i].n <= order);
18
+ function nearest(v, order) {
19
+ let best = 0;
20
+ for (const i of allowedIdx(order)) if (Math.abs(SNAPS[i].v - v) < Math.abs(SNAPS[best].v - v)) best = i;
21
+ return best;
22
+ }
23
+ function snapToward(v, dir, order) {
24
+ const hits = allowedIdx(order).filter((i) => dir * (SNAPS[i].v - v) >= -1e-9);
25
+ return hits[dir > 0 ? 0 : hits.length - 1];
26
+ }
27
+ function beyond(v, dir, order) {
28
+ const hits = allowedIdx(order).filter((i) => dir * (SNAPS[i].v - v) > 1e-9);
29
+ return hits.length ? hits[dir > 0 ? 0 : hits.length - 1] : nearest(v, order);
30
+ }
31
+ /** Keyboard: the next allowed snap left (-1) or right (+1). */
32
+ const step = (i, dir, order) => beyond(SNAPS[i].v, dir, order);
33
+ const toWidths = (d) => [...d, 1].map((x, k) => x - (k ? d[k - 1] : 0));
34
+ const toDividers = (w) => {
35
+ let a = 0;
36
+ return w.slice(0, -1).map((x) => {
37
+ a += x;
38
+ return a;
39
+ });
40
+ };
41
+ const isOpen = (w) => w > 1e-9;
42
+ const byDistance = (p, P) => {
43
+ const out = [];
44
+ for (let r = 1; r < P; r++) {
45
+ if (p - r >= 0) out.push(p - r);
46
+ if (p + r < P) out.push(p + r);
47
+ }
48
+ return out;
49
+ };
50
+ function take(w0, S, donors, need0, keep) {
51
+ const w = w0.slice();
52
+ let need = need0;
53
+ const outer = [...donors].reverse();
54
+ for (const lo of keep ? [
55
+ keep,
56
+ S.min,
57
+ null
58
+ ] : [S.min, null]) for (const k of outer) {
59
+ const t = Math.min(need, Math.max(0, w[k] - (lo?.[k] ?? 0)));
60
+ w[k] -= t;
61
+ need -= t;
62
+ }
63
+ return {
64
+ w,
65
+ short: need
66
+ };
67
+ }
68
+ function fill(w, receivers, amount, max) {
69
+ for (const k of receivers) {
70
+ const t = Math.min(amount, Math.max(0, max[k] - w[k]));
71
+ w[k] += t;
72
+ amount -= t;
73
+ }
74
+ w[receivers[0]] += amount;
75
+ }
76
+ function drag(dividers, i, v, S) {
77
+ const w = toWidths(dividers);
78
+ const P = w.length;
79
+ const delta = clamp(v, 0, 1) - dividers[i];
80
+ if (Math.abs(delta) < 1e-12) return dividers.slice();
81
+ const left = delta < 0;
82
+ const r = take(w, S, left ? [...Array(i + 1).keys()].reverse() : [...Array(P - i - 1).keys()].map((k) => i + 1 + k), Math.abs(delta));
83
+ r.w[left ? i + 1 : i] += Math.abs(delta) - r.short;
84
+ return toDividers(r.w);
85
+ }
86
+ function enforceMin(vals, S, prefer) {
87
+ const w = toWidths(vals);
88
+ for (let k = 0; k < w.length; k++) {
89
+ const x = w[k];
90
+ if (!isOpen(x) || x >= S.min[k] - 1e-9) continue;
91
+ const near = byDistance(k, w.length).filter((j) => isOpen(w[j]));
92
+ const to = near.find((j) => j !== prefer && Math.sign(j - prefer) === Math.sign(k - prefer)) ?? (prefer !== k && isOpen(w[prefer] ?? 0) ? prefer : near[0]);
93
+ if (to == null) continue;
94
+ w[k] = 0;
95
+ fill(w, [to, ...near.filter((j) => j !== to)], x, S.max);
96
+ }
97
+ return toDividers(w);
98
+ }
99
+ const snapAll = (vals, order) => vals.map((x) => SNAPS[nearest(x, order)].v);
100
+ const toIdx = (vals, order) => vals.map((x) => nearest(x, order));
101
+ /** Close pane p: its whole width goes to the nearest open pane. Returns snap indices. */
102
+ function closePane(dividers, p, S, order) {
103
+ const w = toWidths(dividers);
104
+ const near = byDistance(p, w.length).filter((j) => isOpen(w[j]));
105
+ if (!near.length) return toIdx(dividers, order);
106
+ const freed = w[p];
107
+ w[p] = 0;
108
+ fill(w, near, freed, S.max);
109
+ return toIdx(enforceMin(snapAll(toDividers(w), order), S, near[0]), order);
110
+ }
111
+ /** Snap any layout (presets, restored layouts) and enforce minimums. Returns snap indices. */
112
+ const fit = (vals, S, order) => toIdx(enforceMin(snapAll(vals, order), S, -1), order);
113
+ function focusPane(dividers, p, S, order) {
114
+ const w = toWidths(dividers);
115
+ let d = dividers.slice();
116
+ let need = Math.min(S.max[p], Math.max(S.focus[p], S.min[p])) - w[p];
117
+ const up = w.map((_, k) => SNAPS[snapToward(Math.max(S.focus[k], S.min[k]), 1, order)].v);
118
+ const room = w.reduce((s, x, k) => s + (k === p || isOpen(x) ? up[k] : 0), 0) <= 1 + 1e-9;
119
+ const out = !room && !isOpen(w[p]) && need > 1e-9 ? byDistance(p, w.length).findLast((k) => isOpen(w[k])) : void 0;
120
+ if (out !== void 0) {
121
+ const x = w[out];
122
+ const g = Math.min(x, need);
123
+ w[out] = 0;
124
+ w[p] += g;
125
+ need -= g;
126
+ fill(w, [...byDistance(out, w.length).filter((j) => j !== p && isOpen(w[j])), p], x - g, S.max);
127
+ d = toDividers(w);
128
+ }
129
+ if (need > 1e-9) {
130
+ const r = take(w, S, byDistance(p, w.length), need, room ? up : void 0);
131
+ r.w[p] += need - r.short;
132
+ d = enforceMin(toDividers(r.w), S, p);
133
+ }
134
+ const open = toWidths(d).map(isOpen);
135
+ const s = d.map((x, k) => SNAPS[k === p - 1 ? snapToward(x, -1, order) : k === p ? snapToward(x, 1, order) : nearest(x, order)].v);
136
+ for (let k = p - 1; k >= 0; k--) {
137
+ s[k] = Math.min(s[k], s[k + 1] ?? 1);
138
+ if (k < p - 1 && open[k + 1] && s[k + 1] - s[k] < S.min[k + 1] - 1e-9) s[k] = SNAPS[snapToward(Math.max(0, s[k + 1] - S.min[k + 1]), -1, order)].v;
139
+ }
140
+ for (let k = p; k < s.length; k++) {
141
+ s[k] = Math.max(s[k], s[k - 1] ?? 0);
142
+ if (k > p && open[k] && s[k] - s[k - 1] < S.min[k] - 1e-9) s[k] = SNAPS[snapToward(Math.min(1, s[k - 1] + S.min[k]), 1, order)].v;
143
+ }
144
+ return toIdx(enforceMin(s, S, p), order);
145
+ }
146
+ const FLING = [.45, 1.4];
147
+ const VELOCITY_WINDOW_MS = 90;
148
+ function velocity(samples, now) {
149
+ const s = samples.filter((p) => now - p.t <= VELOCITY_WINDOW_MS);
150
+ if (s.length < 2) return 0;
151
+ const a = s[0];
152
+ const b = s[s.length - 1];
153
+ return b.t > a.t ? (b.x - a.x) / (b.t - a.t) : 0;
154
+ }
155
+ function releaseTarget(v, vel, order) {
156
+ const speed = Math.abs(vel);
157
+ if (speed < FLING[0]) return nearest(v, order);
158
+ const dir = Math.sign(vel);
159
+ const j = beyond(v, dir, order);
160
+ return speed >= FLING[1] ? step(j, dir, order) : j;
161
+ }
162
+ const flingReach = (vel) => Math.min(1, Math.max(0, (Math.abs(vel) - FLING[0]) / (FLING[1] - FLING[0])));
163
+ function settle(start, i, raw, vel, order, S) {
164
+ const T = SNAPS[releaseTarget(raw, vel, order)].v;
165
+ const aim = Math.abs(vel) < FLING[0] ? raw : T;
166
+ const aimed = toWidths(drag(start, i, aim, S));
167
+ const closable = aimed.map((w, k) => !isOpen(w) || w < S.min[k] - 1e-9);
168
+ const cap = aimed.map((w, k) => Math.max(S.max[k], w));
169
+ const ok = (idx) => toWidths(idx.map((k) => SNAPS[k].v)).every((w, k) => isOpen(w) ? w >= S.min[k] - 1e-9 && w <= cap[k] + 1e-9 : closable[k]);
170
+ const byNear = allowedIdx(order).sort((a, b) => Math.abs(SNAPS[a].v - T) - Math.abs(SNAPS[b].v - T));
171
+ for (const c of byNear) {
172
+ const r = resolve(start, i, SNAPS[c].v, order, S);
173
+ if (ok(r)) return r;
174
+ }
175
+ return resolve(start, i, T, order, S);
176
+ }
177
+ function resolve(start, i, target, order, S) {
178
+ const left = target < start[i];
179
+ const grower = left ? i + 1 : i;
180
+ const d = enforceMin(drag(start, i, target, S), S, grower);
181
+ const s = snapAll(d, order);
182
+ const over = (vals) => toWidths(vals)[grower] > S.max[grower] + 1e-9;
183
+ if (over(s) && !over(d)) s[i] = SNAPS[snapToward(d[i], left ? 1 : -1, order)].v;
184
+ const ws = toWidths(s);
185
+ for (let k = 0; k < ws.length; k++) {
186
+ if (k === grower || !isOpen(ws[k]) || ws[k] >= S.min[k] - 1e-9) continue;
187
+ if (k > grower) s[k - 1] = SNAPS[snapToward((s[k] ?? 1) - S.min[k], -1, order)].v;
188
+ else s[k] = SNAPS[snapToward((s[k - 1] ?? 0) + S.min[k], 1, order)].v;
189
+ }
190
+ for (let k = 1; k < s.length; k++) s[k] = Math.max(s[k], s[k - 1]);
191
+ return toIdx(s, order);
192
+ }
193
+ const edgeWidth$1 = (e) => e.open && e.openPx ? e.openPx : e.closedPx;
194
+ const contentWidth = (W, edges) => Math.max(0, W - edges.reduce((s, e) => s + edgeWidth$1(e), 0));
195
+ function layout(W, dividers, edges, panes) {
196
+ const C = contentWidth(W, edges);
197
+ const frac = (i) => i === 0 ? 0 : i === panes.length ? 1 : dividers[i - 1];
198
+ const through = (b) => edges.slice(0, b + 1).reduce((s, e) => s + edgeWidth$1(e), 0);
199
+ return {
200
+ C,
201
+ edgeBoxes: edges.map((e, b) => {
202
+ const w = edgeWidth$1(e);
203
+ return {
204
+ x: frac(b) * C + through(b) - w,
205
+ w
206
+ };
207
+ }),
208
+ paneBoxes: panes.map((p, i) => {
209
+ const x = frac(i) * C + through(i);
210
+ const visible = Math.max(0, frac(i + 1) * C + through(i) - x);
211
+ return {
212
+ x,
213
+ visible,
214
+ width: Math.max(visible, p.focus * C)
215
+ };
216
+ })
217
+ };
218
+ }
219
+ const FOCUS_MARGIN = 28;
220
+ function focusShift(width, visible, x) {
221
+ if (width <= visible) return 0;
222
+ const m = Math.min(FOCUS_MARGIN, visible / 2);
223
+ return clamp(x + m - visible, 0, width - visible);
224
+ }
225
+ const encode = (div, bitsets) => div.map((i) => i.toString(16)).join("") + bitsets.map((bs) => bs.reduce((b, o, i) => b | (o ? 1 << i : 0), 0).toString(16)).join("");
226
+ function decode(s, dividerCount, bitCounts) {
227
+ if (typeof s !== "string" || !/^[0-9a-f]+$/.test(s) || s.length !== dividerCount + bitCounts.length) return null;
228
+ const n = [...s].map((c) => Number.parseInt(c, 16));
229
+ const div = n.slice(0, dividerCount);
230
+ const bits = n.slice(dividerCount);
231
+ if (div.some((i, j) => i >= SNAPS.length || j > 0 && i < div[j - 1])) return null;
232
+ if (bits.some((b, j) => b >= 1 << bitCounts[j])) return null;
233
+ return {
234
+ div,
235
+ bits: bits.map((b, j) => Array.from({ length: bitCounts[j] }, (_, i) => Boolean(b >> i & 1)))
236
+ };
237
+ }
238
+ /** Human label for a layout: pane widths as the smallest integer ratio. */
239
+ function ratio(divIdx) {
240
+ const edges = [
241
+ SNAPS[0],
242
+ ...divIdx.map((i) => SNAPS[i]),
243
+ SNAPS[SNAPS.length - 1]
244
+ ];
245
+ const gcd = (a, b) => b ? gcd(b, a % b) : a;
246
+ const L = edges.reduce((l, e) => l * e.n / gcd(l, e.n), 1);
247
+ const segs = edges.slice(1).map((e, i) => e.k * L / e.n - edges[i].k * L / edges[i].n);
248
+ const g = segs.reduce((a, b) => gcd(a, b), 0) || 1;
249
+ return segs.map((s) => s / g).join(":");
250
+ }
251
+ // src/length.ts
252
+ const valid = /* @__PURE__ */ new Set();
253
+ const KEYWORD = /^\s*(inherit|initial|unset|revert|revert-layer|auto|fit-content|min-content|max-content)\s*$/i;
254
+ function checkLength(v) {
255
+ if (!(typeof v === "number" ? Number.isFinite(v) && v >= 0 : valid.has(v) || typeof v === "string" && !KEYWORD.test(v) && CSS.supports("width", v) && !!valid.add(v))) throw new TypeError(`sashay: invalid length ${JSON.stringify(v)}`);
256
+ }
257
+ /**
258
+ * Measures Lengths in place. `px(v, ref)`: `%` resolves against `ref` px (a pane's width)
259
+ * when given, else the frame's width.
260
+ */
261
+ function createMeasure(frame) {
262
+ let box;
263
+ let probe;
264
+ const cache = /* @__PURE__ */ new Map();
265
+ return {
266
+ px(v, ref) {
267
+ if (typeof v === "number") return v;
268
+ const key = `${ref ?? ""}|${v}`;
269
+ let n = cache.get(key);
270
+ if (n === void 0) {
271
+ if (!box) {
272
+ box = document.createElement("div");
273
+ box.setAttribute("data-sashay-probe", "");
274
+ box.style.cssText = "position:absolute;visibility:hidden;height:0;pointer-events:none;overflow:hidden";
275
+ probe = document.createElement("div");
276
+ box.append(probe);
277
+ frame.append(box);
278
+ }
279
+ box.style.width = ref === void 0 ? "100%" : `${ref}px`;
280
+ probe.style.width = v;
281
+ n = Number.parseFloat(getComputedStyle(probe).width);
282
+ cache.set(key, n);
283
+ }
284
+ return n;
285
+ },
286
+ clear: () => cache.clear(),
287
+ destroy() {
288
+ box?.remove();
289
+ box = void 0;
290
+ }
291
+ };
292
+ }
293
+ // src/window.ts
294
+ const LAST = 12;
295
+ const windowEnd = (v) => v.offset + v.div.length + 1;
296
+ const eff = (div, order) => div.map((i) => snapV(nearest(snapV(i), order)));
297
+ const widths = (div) => toWidths(div.map(snapV));
298
+ /** Keep one closed edge after the window when panes follow it. */
299
+ function normalize({ offset, div }, n) {
300
+ const w = widths(div);
301
+ if (isOpen(w[w.length - 1]) && offset + div.length + 1 < n) div = [...div, LAST];
302
+ return {
303
+ offset,
304
+ div
305
+ };
306
+ }
307
+ function fold({ offset, div }, cap) {
308
+ const w = widths(div);
309
+ if (cap) {
310
+ let a = 0;
311
+ let b = w.length;
312
+ while (b - a > cap && !isOpen(w[a])) a++;
313
+ while (b - a > cap && !isOpen(w[b - 1])) b--;
314
+ return {
315
+ offset: offset + a,
316
+ div: div.slice(a, b - 1)
317
+ };
318
+ }
319
+ let r = 0;
320
+ while (r < w.length - 1 && !isOpen(w[r])) r++;
321
+ if (offset > 0 ? r >= 1 : r >= 2) {
322
+ offset += r;
323
+ div = div.slice(r);
324
+ }
325
+ const w2 = widths(div);
326
+ let t = 0;
327
+ while (t < w2.length - 1 && !isOpen(w2[w2.length - 1 - t])) t++;
328
+ if (t >= 2) div = div.slice(0, div.length - (t - 1));
329
+ return {
330
+ offset,
331
+ div
332
+ };
333
+ }
334
+ /**
335
+ * Open pane p, or uncover it. In the window: focus it. Next to the window:
336
+ * extend the window by it, then focus it. Anywhere else (a spine tab): the window
337
+ * jumps to start at it, then opens the panes after it, then before it, until one
338
+ * more is open than before or the frame is at capacity.
339
+ */
340
+ function reveal(v, p, n, sizes, order, opensTo, cap) {
341
+ if (p < 0 || p >= n) return v;
342
+ let { offset, div } = v;
343
+ const end = windowEnd(v);
344
+ if (p < offset - 1 || p > end) {
345
+ const want = openAt(v, order).length + 1;
346
+ let j = normalize({
347
+ offset: p,
348
+ div: []
349
+ }, n);
350
+ for (const dir of [1, -1]) for (let q = p + dir; q >= 0 && q < n && openAt(j, order).length < want; q += dir) {
351
+ const r = reveal(j, q, n, sizes, order, void 0, cap);
352
+ if (openAt(r, order).length <= openAt(j, order).length) break;
353
+ j = r;
354
+ }
355
+ return j;
356
+ }
357
+ if (p === offset - 1) {
358
+ offset = p;
359
+ div = [0, ...div];
360
+ } else if (p === end) div = [...div, LAST];
361
+ const k = p - offset;
362
+ const e = eff(div, order);
363
+ const before = toWidths(e);
364
+ const S = sizes(offset, offset + div.length + 1);
365
+ if (isOpen(before[k]) && before[k] >= Math.min(S.max[k], Math.max(S.focus[k], S.min[k])) - 1e-9) return v;
366
+ const opened = opensTo?.length === div.length ? fit(opensTo, S, order) : null;
367
+ const d = opened && isOpen(widths(opened)[k]) ? opened : focusPane(e, k, S, order);
368
+ const after = widths(d);
369
+ const squeezed = before.some((x, j) => isOpen(x) && !isOpen(after[j]));
370
+ const next = {
371
+ offset,
372
+ div: d
373
+ };
374
+ return normalize(squeezed || cap ? fold(next, cap) : next, n);
375
+ }
376
+ const openAt = (v, order) => toWidths(eff(v.div, order)).flatMap((x, k) => isOpen(x) ? [v.offset + k] : []);
377
+ /**
378
+ * Expand collapsed panes until `target` are open: a closed window pane, the newest in the
379
+ * spine, or the pane after the window, nearest `at` first (left at ties, so the most
380
+ * recently folded wins). A pane that can't open without closing another is skipped.
381
+ */
382
+ function refill(v, target, at, n, sizes, order, cap) {
383
+ for (let have = openAt(v, order).length; have < target;) {
384
+ const shut = toWidths(eff(v.div, order)).flatMap((x, k) => isOpen(x) ? [] : [v.offset + k]);
385
+ const next = [
386
+ v.offset - 1,
387
+ windowEnd(v),
388
+ ...shut
389
+ ].filter((p) => p >= 0 && p < n && p !== at).sort((a, b) => Math.abs(a - at) - Math.abs(b - at) || a - b).map((p) => reveal(v, p, n, sizes, order, void 0, cap)).find((r) => openAt(r, order).length > have);
390
+ if (!next) break;
391
+ v = next;
392
+ have = openAt(v, order).length;
393
+ }
394
+ return v;
395
+ }
396
+ /** After `next` replaces `prev` (same list), keep the open count: see refill. */
397
+ function keepOpen(prev, next, n, sizes, order, cap) {
398
+ const now = new Set(openAt(next, order));
399
+ const shut = openAt(prev, order).filter((p) => !now.has(p));
400
+ return shut.length ? refill(next, openAt(prev, order).length, shut[0], n, sizes, order, cap) : next;
401
+ }
402
+ /** Close pane p, giving its width to the nearest open pane, then keep the open count (refill). */
403
+ function close(v, p, n, sizes, order, cap) {
404
+ const k = p - v.offset;
405
+ if (k < 0 || k > v.div.length) return v;
406
+ const e = eff(v.div, order);
407
+ if (!isOpen(toWidths(e)[k])) return v;
408
+ return keepOpen(v, normalize({
409
+ offset: v.offset,
410
+ div: closePane(e, k, sizes(v.offset, windowEnd(v)), order)
411
+ }, n), n, sizes, order, cap);
412
+ }
413
+ /** A closed pane is inserted at index `at`; later indices shift. */
414
+ function insert(v, at) {
415
+ const end = windowEnd(v);
416
+ if (at < v.offset) return {
417
+ offset: v.offset + 1,
418
+ div: v.div
419
+ };
420
+ if (at > end) return v;
421
+ if (at === end) return {
422
+ offset: v.offset,
423
+ div: [...v.div, LAST]
424
+ };
425
+ const k = at - v.offset;
426
+ const div = v.div.slice();
427
+ div.splice(k, 0, k ? div[k - 1] : 0);
428
+ return {
429
+ offset: v.offset,
430
+ div
431
+ };
432
+ }
433
+ /**
434
+ * Pane p is removed. `n` is the count after removal; `sizes` still indexes the
435
+ * list before it. An open pane gives its width away the way close() does.
436
+ */
437
+ function remove(v, p, n, sizes, order) {
438
+ if (p < v.offset) return {
439
+ offset: v.offset - 1,
440
+ div: v.div
441
+ };
442
+ if (p >= windowEnd(v)) return v;
443
+ if (!v.div.length) return n ? normalize({
444
+ offset: Math.min(p, n - 1),
445
+ div: []
446
+ }, n) : {
447
+ offset: 0,
448
+ div: []
449
+ };
450
+ const k = p - v.offset;
451
+ const e = eff(v.div, order);
452
+ const d = isOpen(toWidths(e)[k]) ? closePane(e, k, sizes(v.offset, windowEnd(v)), order) : e.map((x) => nearest(x, order));
453
+ d.splice(Math.max(0, k - 1), 1);
454
+ return normalize({
455
+ offset: v.offset,
456
+ div: d
457
+ }, n);
458
+ }
459
+ /**
460
+ * Carry a view across a pane-list change, matching panes by id. Null when the
461
+ * survivors were reordered or no window pane survived: use defaultView.
462
+ */
463
+ function diff(prev, next, v, order, sizes, cap) {
464
+ const nextIds = new Set(next.map((p) => p.id));
465
+ const prevIds = new Set(prev.map((p) => p.id));
466
+ const kept = prev.filter((p) => nextIds.has(p.id));
467
+ const kept2 = next.filter((p) => prevIds.has(p.id));
468
+ if (kept.some((p, i) => p.id !== kept2[i].id)) return null;
469
+ if (!prev.slice(v.offset, windowEnd(v)).some((p) => nextIds.has(p.id))) return null;
470
+ let list = prev;
471
+ let view = v;
472
+ for (let i = prev.length - 1; i >= 0; i--) {
473
+ if (nextIds.has(prev[i].id)) continue;
474
+ const old = list;
475
+ const cur = list.toSpliced(i, 1);
476
+ list = cur;
477
+ const had = openAt(view, order).length;
478
+ view = remove(view, i, cur.length, (a, b) => sizes(old, a, b), order);
479
+ view = refill(view, had, i - .5, cur.length, (a, b) => sizes(cur, a, b), order, cap);
480
+ }
481
+ for (let i = 0; i < next.length; i++) {
482
+ if (prevIds.has(next[i].id)) continue;
483
+ const cur = list.toSpliced(i, 0, next[i]);
484
+ list = cur;
485
+ view = reveal(insert(view, i), i, cur.length, (a, b) => sizes(cur, a, b), order, next[i].opensTo, cap);
486
+ }
487
+ return view;
488
+ }
489
+ /**
490
+ * defaultLayout when it fits the list, else an equal split of the last six panes, or of
491
+ * fewer while `fits` rejects the split (panes under their minimums).
492
+ */
493
+ function defaultView(n, defaultLayout, fits) {
494
+ if (!n) return {
495
+ offset: 0,
496
+ div: []
497
+ };
498
+ if (defaultLayout?.length === n - 1) return normalize({
499
+ offset: 0,
500
+ div: defaultLayout.map((x) => nearest(x, 6))
501
+ }, n);
502
+ for (let m = Math.min(n, 6);; m--) {
503
+ const v = normalize({
504
+ offset: n - m,
505
+ div: Array.from({ length: m - 1 }, (_, k) => nearest((k + 1) / m, 6))
506
+ }, n);
507
+ if (m === 1 || !fits || fits(v)) return v;
508
+ }
509
+ }
510
+ const chunks = (a) => Array.from({ length: Math.ceil(a.length / 4) }, (_, j) => a.slice(4 * j, 4 * j + 4));
511
+ /** drawers: open state of the window panes that have a drawer, in order. */
512
+ const encodeLayout = (v, drawers) => (v.offset ? `${v.offset}-` : "") + encode(v.div, []) + (drawers.length ? `.${encode([], chunks(drawers))}` : "");
513
+ /** Untrusted input: anything malformed, or a window past the list's end, is null. */
514
+ function decodeLayout(code, n, hasDrawer) {
515
+ const m = typeof code === "string" ? /^(?:([1-9]\d*)-)?([0-9a-c]*)(?:\.([0-9a-f]+))?$/.exec(code) : null;
516
+ if (!m) return null;
517
+ const offset = m[1] ? Number(m[1]) : 0;
518
+ const V = m[2].length;
519
+ if (offset + V + 1 > n) return null;
520
+ let D = 0;
521
+ for (let p = offset; p <= offset + V; p++) if (hasDrawer(p)) D++;
522
+ if (m[3] !== void 0 !== D > 0) return null;
523
+ const counts = chunks(Array(D).fill(0)).map((c) => c.length);
524
+ if (!V && !D) return {
525
+ view: {
526
+ offset,
527
+ div: []
528
+ },
529
+ drawers: []
530
+ };
531
+ const r = decode(m[2] + (m[3] ?? ""), V, counts);
532
+ return r && {
533
+ view: {
534
+ offset,
535
+ div: r.div
536
+ },
537
+ drawers: r.bits.flat()
538
+ };
539
+ }
540
+ // src/controller.ts
541
+ const EDGE = "0.75rem";
542
+ /** An edge's width: a drawer's edge defaults wide enough for its toggle. Internal, shared with react.tsx. */
543
+ const edgeWidth = (e) => e?.width ?? (e?.drawer ? "2.75rem" : EDGE);
544
+ const COMPACT = "40rem";
545
+ const TABS = "var(--sashay-tabs-width, 2.75rem)";
546
+ const SPINE = "var(--sashay-spine-width, 1.5rem)";
547
+ const COMPACT_CAP = 6;
548
+ const CHEVRON = "<svg viewBox=\"0 0 16 16\" aria-hidden=\"true\"><path d=\"M6 3l5 5-5 5\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.8\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>";
549
+ const own = (frame, sel) => [...frame.querySelectorAll(sel)].filter((el) => el.closest("[data-sashay-frame]") === frame);
550
+ function scan(frame, list) {
551
+ const els = new Map(own(frame, "[data-sashay-pane]").map((el) => [el.dataset.sashayPane ?? "", el]));
552
+ const drawerEls = new Map(own(frame, "[data-sashay-drawer]").map((el) => [el.dataset.sashayDrawer ?? "", el]));
553
+ const seen = /* @__PURE__ */ new Set();
554
+ for (const p of list) {
555
+ if (seen.has(p.id)) throw new Error(`sashay: duplicate pane id "${p.id}"`);
556
+ seen.add(p.id);
557
+ if (!els.has(p.id)) throw new Error(`sashay: no [data-sashay-pane="${p.id}"] element`);
558
+ for (const v of [
559
+ p.minWidth,
560
+ p.maxWidth,
561
+ p.edge?.width,
562
+ p.edge?.drawer?.width
563
+ ]) if (v !== void 0) checkLength(v);
564
+ }
565
+ return {
566
+ els,
567
+ drawerEls
568
+ };
569
+ }
570
+ function createSashay(frame, options) {
571
+ const opts = {
572
+ ...options,
573
+ compactBelow: options.compactBelow ?? "40rem"
574
+ };
575
+ checkLength(opts.compactBelow);
576
+ const dl = options.defaultLayout;
577
+ if (dl?.some((x, i) => !(x >= 0 && x <= 1) || i > 0 && x < dl[i - 1])) throw new RangeError(`sashay: defaultLayout must be ascending fractions from 0 to 1, got ${JSON.stringify(dl)}`);
578
+ frame.setAttribute("data-sashay-frame", "");
579
+ let found;
580
+ try {
581
+ found = scan(frame, options.panes);
582
+ } catch (e) {
583
+ frame.removeAttribute("data-sashay-frame");
584
+ throw e;
585
+ }
586
+ let panes = options.panes;
587
+ let { els, drawerEls } = found;
588
+ let view;
589
+ let drawers = /* @__PURE__ */ new Map();
590
+ const keep = /* @__PURE__ */ new Map();
591
+ const edges = /* @__PURE__ */ new Map();
592
+ const ctls = /* @__PURE__ */ new Map();
593
+ const measure = createMeasure(frame);
594
+ const px = measure.px;
595
+ let W = frame.clientWidth;
596
+ let live = null;
597
+ let rubber = 0;
598
+ let preview = null;
599
+ let gesture = null;
600
+ let dirty = false;
601
+ let destroyed = false;
602
+ let lastCode = "";
603
+ const lastX = /* @__PURE__ */ new Map();
604
+ const entering = /* @__PURE__ */ new Set();
605
+ const leaving = /* @__PURE__ */ new Map();
606
+ const lastW = /* @__PURE__ */ new WeakMap();
607
+ let hold = false;
608
+ let holdT;
609
+ const size = (el, w) => {
610
+ const v = hold && !live ? Math.max(w, lastW.get(el) ?? 0) : w;
611
+ lastW.set(el, v);
612
+ el.style.width = `${v}px`;
613
+ };
614
+ const orig = /* @__PURE__ */ new Map();
615
+ const touch = (el) => {
616
+ if (!orig.has(el)) orig.set(el, el.getAttribute("style"));
617
+ return el.style;
618
+ };
619
+ const win = () => panes.slice(view.offset, windowEnd(view));
620
+ const compact = () => W > 0 && W < px(opts.compactBelow);
621
+ const spineW = (from, to, n) => (from > 0 ? px(SPINE) : 0) + (to < n ? px(SPINE) : 0);
622
+ const spinesW = () => spineW(view.offset, windowEnd(view), panes.length);
623
+ const edgeSpecs = (list) => {
624
+ const c = compact();
625
+ return list.map((p, k) => {
626
+ const dr = p.edge?.drawer;
627
+ return {
628
+ closedPx: px(c ? k === 0 ? TABS : EDGE : edgeWidth(p.edge)),
629
+ openPx: !c && dr ? px(dr.width) : void 0,
630
+ open: Boolean(drawers.get(p.id))
631
+ };
632
+ });
633
+ };
634
+ const sizesOf = (list, from, to) => {
635
+ const w = list.slice(from, to);
636
+ const C = Math.max(1, contentWidth(W - spineW(from, to, list.length), edgeSpecs(w)));
637
+ return {
638
+ focus: w.map((p) => p.focus),
639
+ min: w.map((p) => Math.min(1, px(p.minWidth ?? 0) / C)),
640
+ max: w.map((p) => p.maxWidth === void 0 ? 1 : Math.min(1, px(p.maxWidth) / C))
641
+ };
642
+ };
643
+ const content = () => contentWidth(W - spinesW(), edgeSpecs(win()));
644
+ const order = () => gridOrder(content() + spinesW());
645
+ const sizes = () => sizesOf(panes, view.offset, windowEnd(view));
646
+ const sizesFor = (a, b) => sizesOf(panes, a, b);
647
+ const fits = (v) => {
648
+ if (W <= 0 || compact()) return true;
649
+ const to = windowEnd(v);
650
+ const o = gridOrder(contentWidth(W, edgeSpecs(panes.slice(v.offset, to))));
651
+ return toWidths(fit(v.div.map(snapV), sizesFor(v.offset, to), o).map(snapV)).every(isOpen);
652
+ };
653
+ const effIdx = () => view.div.map((i) => nearest(snapV(i), order()));
654
+ const effective = () => live ?? effIdx().map(snapV);
655
+ const openIds = () => {
656
+ const w = toWidths(effIdx().map(snapV));
657
+ return new Set(win().flatMap((p, k) => isOpen(w[k]) ? [p.id] : []));
658
+ };
659
+ const keepPx = (v, w) => {
660
+ const a = px(v, 0);
661
+ return a + (px(v, 1e3) - a) * w / 1e3;
662
+ };
663
+ const extent = (el, s) => {
664
+ const left = el.getBoundingClientRect().left;
665
+ let r = 0;
666
+ for (const c of el.children) r = Math.max(r, c.getBoundingClientRect().right - left + s);
667
+ return r;
668
+ };
669
+ const code = () => encodeLayout(view, win().filter((p) => p.edge?.drawer).map((p) => Boolean(drawers.get(p.id))));
670
+ const decodeState = (c) => {
671
+ const d = decodeLayout(c, panes.length, (p) => Boolean(panes[p].edge?.drawer));
672
+ const v = normalize(d?.view ?? defaultView(panes.length, opts.defaultLayout, fits), panes.length);
673
+ const m = /* @__PURE__ */ new Map();
674
+ if (d) panes.slice(v.offset, windowEnd(v)).filter((p) => p.edge?.drawer).forEach((p, j) => {
675
+ m.set(p.id, d.drawers[j]);
676
+ });
677
+ return {
678
+ v,
679
+ m
680
+ };
681
+ };
682
+ const spines = ["start", "end"].map((side) => {
683
+ const n = document.createElement("nav");
684
+ n.setAttribute("data-spine", side);
685
+ n.setAttribute("aria-label", side === "start" ? "Earlier panes" : "Later panes");
686
+ return n;
687
+ });
688
+ const spineTabs = /* @__PURE__ */ new Map();
689
+ const leaf = document.createElement("button");
690
+ leaf.type = "button";
691
+ leaf.setAttribute("data-sashay-close", "");
692
+ leaf.textContent = "×";
693
+ frame.prepend(leaf);
694
+ let lone = false;
695
+ const marks = [];
696
+ const tabs = document.createElement("div");
697
+ tabs.setAttribute("data-sashay-tabs", "");
698
+ let tabsKey = "";
699
+ const sheetHead = document.createElement("div");
700
+ sheetHead.setAttribute("data-sashay-sheet-head", "");
701
+ const sheetTitle = document.createElement("span");
702
+ const sheetClose = document.createElement("button");
703
+ sheetClose.type = "button";
704
+ sheetClose.setAttribute("data-sashay-sheet-close", "");
705
+ sheetClose.textContent = "×";
706
+ sheetHead.append(sheetTitle, sheetClose);
707
+ let sheet;
708
+ const offscreen = (el) => {
709
+ if (!el) return;
710
+ el.setAttribute("data-offscreen", "");
711
+ el.removeAttribute("data-covered");
712
+ el.removeAttribute("data-closed");
713
+ el.inert = true;
714
+ };
715
+ const makeEdge = (ctl, dr) => {
716
+ const t = ctl.querySelector("[data-sashay-title]");
717
+ if (Boolean(dr) === Boolean(t) && (!t || t.textContent === dr?.title)) return;
718
+ ctl.replaceChildren();
719
+ if (!dr) return;
720
+ const toggle = document.createElement("button");
721
+ toggle.type = "button";
722
+ toggle.setAttribute("data-sashay-toggle", "");
723
+ toggle.innerHTML = CHEVRON;
724
+ const title = document.createElement("span");
725
+ title.setAttribute("data-sashay-title", "");
726
+ title.setAttribute("aria-hidden", "true");
727
+ title.textContent = dr.title;
728
+ ctl.append(toggle, title);
729
+ };
730
+ const rove = (s, t) => {
731
+ for (const x of s.querySelectorAll("[tabindex=\"0\"]")) x.tabIndex = -1;
732
+ t.tabIndex = 0;
733
+ };
734
+ const fillSpine = (s, list, near) => {
735
+ const want = new Set(list.map((p) => p.id));
736
+ const drop = (el) => {
737
+ while (el) {
738
+ const next = el.nextElementSibling;
739
+ if (want.has(el.dataset.sashaySpineTab)) return el;
740
+ el.remove();
741
+ el = next;
742
+ }
743
+ return null;
744
+ };
745
+ let cur = s.firstElementChild;
746
+ let added = false;
747
+ for (const p of list) {
748
+ cur = drop(cur);
749
+ let b = spineTabs.get(p.id);
750
+ if (!b) {
751
+ b = document.createElement("button");
752
+ b.type = "button";
753
+ b.tabIndex = -1;
754
+ b.setAttribute("data-sashay-spine-tab", p.id);
755
+ spineTabs.set(p.id, b);
756
+ }
757
+ if (b.textContent !== p.title) {
758
+ b.textContent = p.title;
759
+ b.setAttribute("aria-label", `${p.title}, collapsed`);
760
+ }
761
+ if (b === cur) cur = cur.nextElementSibling;
762
+ else {
763
+ b.tabIndex = -1;
764
+ s.insertBefore(b, cur);
765
+ added = true;
766
+ }
767
+ }
768
+ drop(cur);
769
+ if (!list.length) s.remove();
770
+ else if (!s.isConnected) frame.prepend(s);
771
+ const t = near === "last" ? s.lastElementChild : s.firstElementChild;
772
+ if (!t) return;
773
+ rove(s, s.contains(document.activeElement) ? document.activeElement : t);
774
+ if (added) s.scrollTop = near === "last" ? s.scrollHeight : 0;
775
+ };
776
+ const sync = () => {
777
+ const c = compact();
778
+ frame.toggleAttribute("data-compact", c);
779
+ const focused = document.activeElement;
780
+ const fromSpine = focused?.hasAttribute("data-sashay-spine-tab") ? focused.parentElement : null;
781
+ fillSpine(spines[0], panes.slice(0, view.offset), "last");
782
+ fillSpine(spines[1], panes.slice(windowEnd(view)), "first");
783
+ for (const [id, b] of spineTabs) if (!b.isConnected) spineTabs.delete(id);
784
+ const w = win();
785
+ const ids = new Set(w.map((p) => p.id));
786
+ for (const [id, e] of edges) {
787
+ if (ids.has(id)) continue;
788
+ e.remove();
789
+ edges.delete(id);
790
+ ctls.get(id)?.remove();
791
+ ctls.delete(id);
792
+ offscreen(els.get(id));
793
+ const x = lastX.get(id);
794
+ if (x !== void 0) leaving.set(id, x);
795
+ lastX.delete(id);
796
+ drawers.delete(id);
797
+ drawerEls.get(id)?.removeAttribute("data-open");
798
+ }
799
+ sheet = c ? w.findLast((p) => p.edge?.drawer && drawers.get(p.id) && drawerEls.has(p.id))?.id : void 0;
800
+ const idx = effIdx();
801
+ const widths = toWidths(idx.map(snapV));
802
+ w.forEach((p, k) => {
803
+ const el = els.get(p.id);
804
+ let e = edges.get(p.id);
805
+ if (!e) {
806
+ e = document.createElement("div");
807
+ e.setAttribute("data-sashay-edge", p.id);
808
+ e.tabIndex = 0;
809
+ e.append(document.createElement("span"));
810
+ e.firstElementChild?.setAttribute("data-sashay-dots", "");
811
+ const ctl = document.createElement("div");
812
+ ctl.setAttribute("data-sashay-controls", p.id);
813
+ el.before(e, ctl);
814
+ edges.set(p.id, e);
815
+ ctls.set(p.id, ctl);
816
+ el.removeAttribute("data-offscreen");
817
+ el.inert = false;
818
+ entering.add(p.id);
819
+ lastW.delete(el);
820
+ }
821
+ const ctl = ctls.get(p.id);
822
+ makeEdge(ctl, c ? void 0 : p.edge?.drawer);
823
+ e.setAttribute("aria-label", p.title);
824
+ if (k === 0) {
825
+ e.setAttribute("role", "button");
826
+ e.setAttribute("aria-expanded", String(isOpen(widths[0])));
827
+ for (const a of [
828
+ "aria-orientation",
829
+ "aria-valuemin",
830
+ "aria-valuemax",
831
+ "aria-valuenow",
832
+ "aria-valuetext"
833
+ ]) e.removeAttribute(a);
834
+ } else {
835
+ e.setAttribute("role", "separator");
836
+ e.removeAttribute("aria-expanded");
837
+ e.setAttribute("aria-orientation", "vertical");
838
+ e.setAttribute("aria-valuemin", "0");
839
+ e.setAttribute("aria-valuemax", "100");
840
+ e.setAttribute("aria-valuenow", String(Math.round(snapV(idx[k - 1]) * 100)));
841
+ e.setAttribute("aria-valuetext", ratio(idx));
842
+ }
843
+ const dr = p.edge?.drawer;
844
+ const open = Boolean(dr && drawers.get(p.id));
845
+ e.toggleAttribute("data-drawer", Boolean(dr));
846
+ e.toggleAttribute("data-open", open && !c);
847
+ ctl.toggleAttribute("data-open", open && !c);
848
+ const t = ctl.querySelector("[data-sashay-toggle]");
849
+ t?.setAttribute("aria-expanded", String(open));
850
+ t?.setAttribute("aria-label", `${open ? "Close" : "Open"} ${dr?.title}`);
851
+ const de = drawerEls.get(p.id);
852
+ de?.toggleAttribute("data-open", c ? p.id === sheet : open);
853
+ de?.toggleAttribute("data-sheet", p.id === sheet);
854
+ if (p.id === sheet) {
855
+ sheetTitle.textContent = dr?.title ?? "";
856
+ sheetClose.setAttribute("aria-label", `Close ${dr?.title}`);
857
+ }
858
+ });
859
+ if (!sheet) sheetHead.remove();
860
+ else if (!sheetHead.isConnected) frame.append(sheetHead);
861
+ const e0 = c && w.length ? ctls.get(w[0].id) : void 0;
862
+ if (!e0) tabs.remove();
863
+ else {
864
+ const k = JSON.stringify(w.map((p) => [
865
+ p.id,
866
+ p.title,
867
+ p.edge?.drawer?.title
868
+ ]));
869
+ if (k !== tabsKey) {
870
+ tabsKey = k;
871
+ tabs.replaceChildren(...w.flatMap((p) => {
872
+ const b = document.createElement("button");
873
+ b.type = "button";
874
+ b.setAttribute("data-sashay-tab", p.id);
875
+ b.textContent = p.title;
876
+ const dr = p.edge?.drawer;
877
+ if (!dr) return [b];
878
+ const t = document.createElement("button");
879
+ t.type = "button";
880
+ t.setAttribute("data-sashay-drawer-tab", p.id);
881
+ t.innerHTML = CHEVRON;
882
+ t.append(dr.title);
883
+ return [b, t];
884
+ }));
885
+ }
886
+ if (tabs.parentElement !== e0) e0.append(tabs);
887
+ w.forEach((p, k) => {
888
+ tabs.querySelector(`[data-sashay-tab="${CSS.escape(p.id)}"]`)?.setAttribute("aria-pressed", String(isOpen(widths[k])));
889
+ const t = tabs.querySelector(`[data-sashay-drawer-tab="${CSS.escape(p.id)}"]`);
890
+ const open = p.id === sheet;
891
+ t?.setAttribute("aria-expanded", String(open));
892
+ t?.setAttribute("aria-label", `${open ? "Close" : "Open"} ${p.edge?.drawer?.title}`);
893
+ });
894
+ }
895
+ while (marks.length < w.length - 1) {
896
+ const m = document.createElement("div");
897
+ m.setAttribute("data-sashay-mark", "");
898
+ m.setAttribute("aria-hidden", "true");
899
+ m.innerHTML = "<svg viewBox=\"0 0 1 100\" preserveAspectRatio=\"none\"><path d=\"M0 0Q0 25 1 50Q0 75 0 100\"/></svg>";
900
+ frame.append(m);
901
+ marks.push(m);
902
+ }
903
+ while (marks.length > Math.max(0, w.length - 1)) marks.pop()?.remove();
904
+ if (fromSpine && document.activeElement !== focused) {
905
+ const start = fromSpine === spines[0];
906
+ (!fromSpine.isConnected ? edges.get(w[start ? 0 : w.length - 1]?.id) : fromSpine.querySelector("[tabindex=\"0\"]"))?.focus({ preventScroll: true });
907
+ }
908
+ const open = [...openIds()];
909
+ lone = c || open.length < 2;
910
+ if (lone && document.activeElement === leaf) edges.get(open.pop() ?? w[0]?.id)?.focus({ preventScroll: true });
911
+ };
912
+ const paint = () => {
913
+ const w = win();
914
+ if (W <= 0 || !w.length) {
915
+ leaf.hidden = true;
916
+ return;
917
+ }
918
+ const sw = view.offset > 0 ? px(SPINE) : 0;
919
+ const sr = spinesW() - sw;
920
+ const specs = edgeSpecs(w);
921
+ const c = compact();
922
+ const { paneBoxes, edgeBoxes } = layout(W - sw - sr, effective(), specs, w.map((p) => ({ focus: p.focus })));
923
+ const moved = w.flatMap((p, k) => {
924
+ const x0 = entering.has(p.id) ? void 0 : lastX.get(p.id);
925
+ return x0 === void 0 ? [] : [[k, paneBoxes[k].x + sw - x0]];
926
+ });
927
+ const delta = (k) => {
928
+ let best;
929
+ for (const m of moved) if (!best || Math.abs(m[0] - k) < Math.abs(best[0] - k)) best = m;
930
+ return best?.[1] ?? 0;
931
+ };
932
+ for (const [id, x] of leaving) {
933
+ const el = els.get(id);
934
+ if (el) touch(el).transform = `translateX(${x + delta(indexOf(id) < view.offset ? -1 : w.length)}px)`;
935
+ }
936
+ leaving.clear();
937
+ if (entering.size) {
938
+ const start = w.flatMap((p, k) => {
939
+ if (!entering.has(p.id)) return [];
940
+ const d = delta(k);
941
+ const e = edgeBoxes[k].x + sw - d;
942
+ return [
943
+ [els.get(p.id), paneBoxes[k].x + sw - d],
944
+ [edges.get(p.id), e],
945
+ [ctls.get(p.id), e]
946
+ ];
947
+ });
948
+ for (const [el, x] of start) {
949
+ const s = touch(el);
950
+ s.transition = "none";
951
+ s.transform = `translateX(${x}px)`;
952
+ }
953
+ frame.offsetWidth;
954
+ for (const [el] of start) el.style.transition = "";
955
+ entering.clear();
956
+ }
957
+ let right = -1;
958
+ let last = "";
959
+ const active = document.activeElement;
960
+ w.forEach((p, k) => {
961
+ const b = paneBoxes[k];
962
+ const el = els.get(p.id);
963
+ const x = b.x + sw + rubber;
964
+ const s = touch(el);
965
+ s.transform = `translateX(${x}px)`;
966
+ size(el, b.width + Math.max(0, hold ? x - (lastX.get(p.id) ?? x) : 0));
967
+ const kv = keep.get(p.id);
968
+ if (kv) {
969
+ kv.w ??= extent(el, kv.s);
970
+ const shift = b.width ? focusShift(Math.max(b.width, kv.w), b.visible, keepPx(kv.x, b.width)) : 0;
971
+ if (shift !== kv.s) s.setProperty("--sashay-shift", shift ? `${-shift}px` : "");
972
+ kv.s = shift;
973
+ }
974
+ lastX.set(p.id, x);
975
+ s.zIndex = String(2 * k);
976
+ const closed = b.visible < 1;
977
+ const covered = !closed && b.width - b.visible > .5;
978
+ el.toggleAttribute("data-closed", closed);
979
+ el.toggleAttribute("data-covered", covered);
980
+ if (closed && !el.inert && el.contains(active)) edges.get(p.id)?.focus({ preventScroll: true });
981
+ el.inert = closed;
982
+ if (!closed) {
983
+ right = x + b.visible;
984
+ last = p.title;
985
+ }
986
+ const eb = edgeBoxes[k];
987
+ const es = edges.get(p.id).style;
988
+ es.transform = `translateX(${eb.x + sw + rubber}px)`;
989
+ es.width = `${eb.w}px`;
990
+ es.zIndex = String(2 * k + 1);
991
+ const cs = ctls.get(p.id).style;
992
+ cs.transform = es.transform;
993
+ cs.width = es.width;
994
+ cs.zIndex = es.zIndex;
995
+ const d = drawerEls.get(p.id);
996
+ if (d && (c ? p.id === sheet : drawers.get(p.id))) {
997
+ const ds = touch(d);
998
+ if (c) {
999
+ const tw = px(TABS);
1000
+ ds.transform = `translateX(${sw + tw}px)`;
1001
+ ds.width = `${Math.min(px(p.edge?.drawer?.width ?? 0), W - sw - sr - tw - px(EDGE))}px`;
1002
+ ds.zIndex = "";
1003
+ sheetHead.style.transform = ds.transform;
1004
+ sheetHead.style.width = ds.width;
1005
+ } else {
1006
+ ds.transform = es.transform;
1007
+ ds.width = es.width;
1008
+ ds.zIndex = es.zIndex;
1009
+ }
1010
+ }
1011
+ });
1012
+ if (preview) {
1013
+ const rest = layout(W - sw - sr, preview.rest.map(snapV), specs, []).edgeBoxes;
1014
+ const fly = layout(W - sw - sr, preview.idx.map(snapV), specs, []).edgeBoxes;
1015
+ const t = preview.t;
1016
+ marks.forEach((m, k) => {
1017
+ const x = rest[k + 1]?.x ?? 0;
1018
+ const b = k === preview?.d ? t * ((fly[k + 1]?.x ?? 0) - x) / 2 : 0;
1019
+ m.style.transform = `translateX(${x + sw}px)`;
1020
+ m.style.setProperty("--sashay-fling", String(b));
1021
+ m.toggleAttribute("data-fling", b !== 0);
1022
+ m.toggleAttribute("data-primary", k === preview?.d);
1023
+ });
1024
+ }
1025
+ leaf.hidden = right < 0 || lone;
1026
+ leaf.style.transform = `translateX(${right}px)`;
1027
+ if (leaf.getAttribute("aria-label") !== `Close ${last}`) leaf.setAttribute("aria-label", `Close ${last}`);
1028
+ };
1029
+ const refresh = (resize = false) => {
1030
+ if (!live && !resize) {
1031
+ hold = true;
1032
+ clearTimeout(holdT);
1033
+ holdT = setTimeout(() => {
1034
+ hold = false;
1035
+ for (const k of keep.values()) k.w = void 0;
1036
+ if (!destroyed) paint();
1037
+ }, 240);
1038
+ }
1039
+ if (dirty && !live) {
1040
+ dirty = false;
1041
+ W = frame.clientWidth;
1042
+ measure.clear();
1043
+ for (const k of keep.values()) k.w = void 0;
1044
+ }
1045
+ sync();
1046
+ paint();
1047
+ };
1048
+ /**
1049
+ * Apply a view; report it if the code changed. `closing`: report as closed the pane with
1050
+ * this id (a close the user aimed at), or with `true` every pane it shut (a drag or arrow key).
1051
+ * `to` computes the view only once any drag has settled, so it never starts from a stale one.
1052
+ */
1053
+ const commit = (to, next, closing) => {
1054
+ gesture?.end(null);
1055
+ const before = closing ? openIds() : null;
1056
+ view = normalize(to(), panes.length);
1057
+ if (next) drawers = next;
1058
+ refresh();
1059
+ const c = code();
1060
+ if (c !== lastCode) {
1061
+ lastCode = c;
1062
+ opts.onChange?.(c);
1063
+ }
1064
+ if (before) {
1065
+ const after = openIds();
1066
+ for (const id of before) if (!after.has(id) && (closing === true || id === closing)) opts.onClose?.(id);
1067
+ }
1068
+ };
1069
+ const indexOf = (id) => panes.findIndex((p) => p.id === id);
1070
+ const cap = () => compact() ? COMPACT_CAP : void 0;
1071
+ const revealAt = (p) => commit(() => reveal(view, p, panes.length, sizesFor, order(), panes[p]?.opensTo, cap()));
1072
+ const closeAt = (p, user = false) => commit(() => close(view, p, panes.length, sizesFor, order(), cap()), void 0, user ? panes[p]?.id : void 0);
1073
+ const toggle = (k) => isOpen(toWidths(effective())[k]) ? closeAt(view.offset + k, true) : revealAt(view.offset + k);
1074
+ const setDrawer = (id, open) => {
1075
+ if (!panes.find((q) => q.id === id)?.edge?.drawer || !edges.has(id)) return;
1076
+ const on = open ?? !drawers.get(id);
1077
+ const next = new Map(drawers).set(id, on);
1078
+ if (on && compact()) {
1079
+ const w = win();
1080
+ for (const q of [...w.slice(w.findIndex((q) => q.id === id) + 1), { id: sheet }]) if (q.id && q.id !== id) next.delete(q.id);
1081
+ }
1082
+ commit(() => view, next);
1083
+ };
1084
+ const winIndex = (id) => id === void 0 ? -1 : win().findIndex((p) => p.id === id);
1085
+ const onClick = (e) => {
1086
+ const t = e.target;
1087
+ if (t.closest("[data-sashay-frame]") !== frame) return;
1088
+ const at = (name) => t.closest(`[${name}]`)?.getAttribute(name);
1089
+ const tab = at("data-sashay-tab");
1090
+ const drawerTab = at("data-sashay-drawer-tab");
1091
+ const spineTab = at("data-sashay-spine-tab");
1092
+ if (spineTab != null) revealAt(indexOf(spineTab));
1093
+ else if (t.closest("[data-sashay-close]")) {
1094
+ const k = toWidths(effIdx().map(snapV)).findLastIndex(isOpen);
1095
+ if (k >= 0) closeAt(view.offset + k, true);
1096
+ } else if (t.closest("[data-sashay-toggle]")) setDrawer(at("data-sashay-controls") ?? "");
1097
+ else if (tab != null) revealAt(indexOf(tab));
1098
+ else if (drawerTab != null) setDrawer(drawerTab);
1099
+ else if (t.closest("[data-sashay-sheet-close]")) setDrawer(sheet ?? "", false);
1100
+ };
1101
+ const onPointerDown = (e) => {
1102
+ const t = e.target;
1103
+ if (e.button !== 0 || gesture || t.closest("[data-sashay-frame]") !== frame) return;
1104
+ if (t.closest("button, input, label, select, textarea, a")) return;
1105
+ const dr = t.closest("[data-sashay-drawer]");
1106
+ if (dr && (!dr.hasAttribute("data-open") || dr.hasAttribute("data-sheet"))) return;
1107
+ const pid = dr || t.closest("[data-sashay-edge]") ? void 0 : t.closest("[data-sashay-pane]")?.dataset.sashayPane;
1108
+ const body = pid !== void 0;
1109
+ const src = dr ?? (body ? edges.get(pid) : t.closest("[data-sashay-edge]"));
1110
+ const id = dr ? dr.dataset.sashayDrawer : src?.dataset.sashayEdge;
1111
+ const k = winIndex(id);
1112
+ if (!src || k < 0 || body && k < 1) return;
1113
+ const d = k - 1;
1114
+ const fr = frame.getBoundingClientRect();
1115
+ const scale = fr.width / frame.offsetWidth || 1;
1116
+ if (body && e.clientX - fr.left - (frame.clientLeft + (lastX.get(pid) ?? 0)) * scale >= 20) return;
1117
+ const on = body ? document : src;
1118
+ if (!body) src.setPointerCapture(e.pointerId);
1119
+ const x0 = e.clientX / scale;
1120
+ const C = Math.max(content(), 1);
1121
+ const w = win();
1122
+ const start = effective().map((v, j) => {
1123
+ const el = edges.get(w[j + 1]?.id);
1124
+ if (!el?.style.transform) return v;
1125
+ const off = new DOMMatrix(getComputedStyle(el).transform).m41 - new DOMMatrix(el.style.transform).m41;
1126
+ return Math.abs(off) > .5 ? v + off / C : v;
1127
+ });
1128
+ const S = sizes();
1129
+ const o = order();
1130
+ const samples = [{
1131
+ t: e.timeStamp,
1132
+ x: x0
1133
+ }];
1134
+ let moved;
1135
+ let raw = start[d];
1136
+ const move = (ev) => {
1137
+ if (ev.pointerId !== e.pointerId) return;
1138
+ const x = ev.clientX / scale;
1139
+ samples.push({
1140
+ t: ev.timeStamp,
1141
+ x
1142
+ });
1143
+ if (samples.length > 32) samples.shift();
1144
+ const dx = x - x0;
1145
+ if (moved === void 0) {
1146
+ const [mx, my] = [ev.clientX - e.clientX, ev.clientY - e.clientY];
1147
+ if (mx * mx + my * my < 16) return;
1148
+ moved = d >= 0 && Math.abs(mx) >= Math.abs(my);
1149
+ if (moved) frame.setAttribute("data-dragging", "");
1150
+ if (moved && body) src.setPointerCapture(e.pointerId);
1151
+ }
1152
+ if (!moved) return;
1153
+ raw = start[d] + dx / C;
1154
+ live = drag(start, d, raw, S);
1155
+ rubber = (raw < 0 ? raw : raw > 1 ? raw - 1 : 0) * C / 4;
1156
+ const v = velocity(samples, ev.timeStamp);
1157
+ const rest = settle(start, d, raw, 0, o, S);
1158
+ preview = {
1159
+ d,
1160
+ rest,
1161
+ idx: Math.abs(v) < FLING[0] ? rest : settle(start, d, raw, v, o, S),
1162
+ t: flingReach(v)
1163
+ };
1164
+ paint();
1165
+ };
1166
+ const stop = () => {
1167
+ on.removeEventListener("pointermove", move);
1168
+ on.removeEventListener("pointerup", end);
1169
+ on.removeEventListener("pointercancel", end);
1170
+ on.removeEventListener("lostpointercapture", lost);
1171
+ frame.removeAttribute("data-dragging");
1172
+ gesture = null;
1173
+ live = null;
1174
+ rubber = 0;
1175
+ preview = null;
1176
+ for (const m of marks) {
1177
+ m.style.setProperty("--sashay-fling", "0");
1178
+ m.removeAttribute("data-fling");
1179
+ }
1180
+ };
1181
+ const lost = (ev) => ev.pointerId === e.pointerId && end(null);
1182
+ function end(ev) {
1183
+ if (ev && ev.pointerId !== e.pointerId) return;
1184
+ stop();
1185
+ if (!moved) {
1186
+ if (moved === void 0 && ev?.type === "pointerup" && !dr && !body) toggle(k);
1187
+ return;
1188
+ }
1189
+ const v = ev?.type === "pointerup" ? velocity(samples, ev.timeStamp) : 0;
1190
+ commit(() => keepOpen(view, {
1191
+ offset: view.offset,
1192
+ div: settle(start, d, raw, v, o, S)
1193
+ }, panes.length, sizesFor, o, cap()), void 0, true);
1194
+ }
1195
+ on.addEventListener("pointermove", move);
1196
+ on.addEventListener("pointerup", end);
1197
+ on.addEventListener("pointercancel", end);
1198
+ on.addEventListener("lostpointercapture", lost);
1199
+ gesture = {
1200
+ end,
1201
+ stop
1202
+ };
1203
+ };
1204
+ const onKeyDown = (e) => {
1205
+ const t = e.target;
1206
+ if (t.closest("[data-sashay-frame]") !== frame) return;
1207
+ if (t.hasAttribute("data-sashay-spine-tab")) {
1208
+ const s = t.parentElement;
1209
+ const to = {
1210
+ ArrowUp: t.previousElementSibling,
1211
+ ArrowDown: t.nextElementSibling,
1212
+ Home: s.firstElementChild,
1213
+ End: s.lastElementChild
1214
+ }[e.key];
1215
+ if (!(to instanceof HTMLElement)) return;
1216
+ e.preventDefault();
1217
+ rove(s, to);
1218
+ to.focus();
1219
+ return;
1220
+ }
1221
+ const id = t.dataset.sashayEdge;
1222
+ const k = winIndex(id);
1223
+ if (k < 0) return;
1224
+ if (e.key === "Enter" || e.key === " ") {
1225
+ e.preventDefault();
1226
+ toggle(k);
1227
+ return;
1228
+ }
1229
+ const dir = e.key === "ArrowLeft" ? -1 : e.key === "ArrowRight" ? 1 : 0;
1230
+ if (!dir || k < 1) return;
1231
+ e.preventDefault();
1232
+ commit(() => {
1233
+ const d = winIndex(id) - 1;
1234
+ if (d < 0) return view;
1235
+ const o = order();
1236
+ const cur = effIdx();
1237
+ const div = settle(cur.map(snapV), d, snapV(step(cur[d], dir, o)), 0, o, sizes());
1238
+ return keepOpen(view, {
1239
+ offset: view.offset,
1240
+ div
1241
+ }, panes.length, sizesFor, o, cap());
1242
+ }, void 0, true);
1243
+ };
1244
+ let keyed;
1245
+ const onModality = (e) => {
1246
+ keyed = e.type === "keydown";
1247
+ };
1248
+ const onFocusIn = (e) => {
1249
+ const t = e.target;
1250
+ if (keyed === false) return;
1251
+ const w = win();
1252
+ const k = w.findIndex((p) => els.get(p.id)?.contains(t));
1253
+ const next = k < 0 ? null : els.get(w[k + 1]?.id);
1254
+ if (next && t.matches(":focus-visible") && t.getBoundingClientRect().right > next.getBoundingClientRect().left) revealAt(view.offset + k);
1255
+ };
1256
+ const onResize = () => {
1257
+ dirty = true;
1258
+ if (live) return;
1259
+ if (frame.clientWidth === W) return refresh();
1260
+ const still = (v) => {
1261
+ for (const p of win()) for (const el of [
1262
+ els.get(p.id),
1263
+ edges.get(p.id),
1264
+ ctls.get(p.id),
1265
+ drawerEls.get(p.id)
1266
+ ]) if (el) touch(el).transition = v;
1267
+ };
1268
+ still("none");
1269
+ refresh(true);
1270
+ frame.offsetWidth;
1271
+ still("");
1272
+ };
1273
+ const ro = new ResizeObserver(onResize);
1274
+ frame.addEventListener("click", onClick);
1275
+ frame.addEventListener("pointerdown", onPointerDown);
1276
+ frame.addEventListener("keydown", onKeyDown);
1277
+ frame.addEventListener("focusin", onFocusIn);
1278
+ for (const type of ["keydown", "pointerdown"]) document.addEventListener(type, onModality, true);
1279
+ document.fonts?.addEventListener("loadingdone", onResize);
1280
+ ({v: view, m: drawers} = decodeState(options.layout));
1281
+ const w0 = new Set(win().map((p) => p.id));
1282
+ for (const p of panes) if (!w0.has(p.id)) offscreen(els.get(p.id));
1283
+ sync();
1284
+ paint();
1285
+ lastCode = code();
1286
+ ro.observe(frame);
1287
+ frame.setAttribute("data-sashay-ready", "");
1288
+ return {
1289
+ get layout() {
1290
+ return lastCode;
1291
+ },
1292
+ reveal(id) {
1293
+ if (destroyed) return;
1294
+ const p = indexOf(id);
1295
+ if (p >= 0) revealAt(p);
1296
+ },
1297
+ close(id) {
1298
+ if (destroyed) return;
1299
+ const p = indexOf(id);
1300
+ if (p >= 0) closeAt(p);
1301
+ },
1302
+ toggleDrawer(id, open) {
1303
+ if (!destroyed) setDrawer(id, open);
1304
+ },
1305
+ keepInView(id, x) {
1306
+ if (destroyed) return;
1307
+ if (x !== null) checkLength(x);
1308
+ const s = keep.get(id)?.s ?? 0;
1309
+ if (x !== null) keep.set(id, {
1310
+ x,
1311
+ s
1312
+ });
1313
+ else if (keep.delete(id) && s) els.get(id)?.style.removeProperty("--sashay-shift");
1314
+ paint();
1315
+ },
1316
+ setLayout(c) {
1317
+ if (destroyed) return;
1318
+ gesture?.end(null);
1319
+ ({v: view, m: drawers} = decodeState(c));
1320
+ refresh();
1321
+ lastCode = code();
1322
+ },
1323
+ fit(fractions) {
1324
+ if (destroyed) return;
1325
+ if (fractions.length !== view.div.length) throw new RangeError(`sashay: fit() needs ${view.div.length} fractions, got ${fractions.length}`);
1326
+ const f = fractions.map((x) => Math.min(1, Math.max(0, x)) || 0).sort((a, b) => a - b);
1327
+ commit(() => f.length === view.div.length ? {
1328
+ offset: view.offset,
1329
+ div: fit(f, sizes(), order())
1330
+ } : view);
1331
+ },
1332
+ update(o) {
1333
+ if (destroyed) return;
1334
+ if (o.compactBelow !== void 0) checkLength(o.compactBelow);
1335
+ const f = o.panes && scan(frame, o.panes);
1336
+ if (o.panes || o.compactBelow !== void 0) gesture?.end(null);
1337
+ if ("onChange" in o) opts.onChange = o.onChange;
1338
+ if ("onClose" in o) opts.onClose = o.onClose;
1339
+ if (o.compactBelow !== void 0) opts.compactBelow = o.compactBelow;
1340
+ if (!o.panes || !f) {
1341
+ if (o.compactBelow !== void 0) refresh();
1342
+ return;
1343
+ }
1344
+ const prev = panes;
1345
+ const ord = order();
1346
+ const old = new Set(prev.map((p) => p.id));
1347
+ panes = o.panes;
1348
+ ({els, drawerEls} = f);
1349
+ for (const p of panes) if (!old.has(p.id)) offscreen(els.get(p.id));
1350
+ const ids = new Set(panes.map((p) => p.id));
1351
+ for (const id of keep.keys()) if (!ids.has(id)) keep.delete(id);
1352
+ for (const el of orig.keys()) if (!el.isConnected) orig.delete(el);
1353
+ commit(() => diff(prev, panes, view, ord, sizesOf, cap()) ?? defaultView(panes.length, opts.defaultLayout, fits));
1354
+ },
1355
+ destroy() {
1356
+ if (destroyed) return;
1357
+ destroyed = true;
1358
+ gesture?.stop();
1359
+ ro.disconnect();
1360
+ clearTimeout(holdT);
1361
+ frame.removeEventListener("click", onClick);
1362
+ frame.removeEventListener("pointerdown", onPointerDown);
1363
+ frame.removeEventListener("keydown", onKeyDown);
1364
+ frame.removeEventListener("focusin", onFocusIn);
1365
+ for (const type of ["keydown", "pointerdown"]) document.removeEventListener(type, onModality, true);
1366
+ document.fonts?.removeEventListener("loadingdone", onResize);
1367
+ for (const e of [...edges.values(), ...ctls.values()]) e.remove();
1368
+ edges.clear();
1369
+ ctls.clear();
1370
+ for (const s of spines) s.remove();
1371
+ spineTabs.clear();
1372
+ leaf.remove();
1373
+ tabs.remove();
1374
+ sheetHead.remove();
1375
+ for (const m of marks) m.remove();
1376
+ measure.destroy();
1377
+ for (const el of [...els.values(), ...drawerEls.values()]) {
1378
+ for (const a of [
1379
+ "data-covered",
1380
+ "data-closed",
1381
+ "data-offscreen",
1382
+ "data-open",
1383
+ "data-sheet"
1384
+ ]) el.removeAttribute(a);
1385
+ el.inert = false;
1386
+ }
1387
+ for (const [el, s] of orig) {
1388
+ el.setAttribute("style", s ?? "");
1389
+ if (s === null) el.removeAttribute("style");
1390
+ }
1391
+ orig.clear();
1392
+ for (const a of [
1393
+ "data-sashay-frame",
1394
+ "data-sashay-ready",
1395
+ "data-dragging",
1396
+ "data-compact"
1397
+ ]) frame.removeAttribute(a);
1398
+ }
1399
+ };
1400
+ }
1401
+ export { decodeLayout as a, windowEnd as c, edgeWidth as i, snapV as l, SPINE as n, defaultView as o, createSashay as r, normalize as s, COMPACT as t, toWidths as u };