staffa 0.7.4 → 0.8.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,933 @@
1
+ import A from "aberdeen";
2
+ import * as route from "aberdeen/route";
3
+ import { NARROW_PX } from "../core.js";
4
+ /**
5
+ * The matchers a `[name=matcher]` segment can use. A matcher returns the param's
6
+ * value, or `undefined` to fail the match, in which case the path falls through
7
+ * to a later route (or to `notFound`) instead of reaching a handler.
8
+ *
9
+ * `integer` deliberately refuses anything that wouldn't survive a round trip
10
+ * back to the same URL: no leading zeroes ("007"), no "-0", no "1.5", "1e3" or
11
+ * "0x10", and nothing past `Number.MAX_SAFE_INTEGER` (where the number would no
12
+ * longer hold the id it came from). Two spellings of one id would otherwise be
13
+ * two different paths, so the same record could sit open in two panels at once.
14
+ * Use a plain `[id]` for ids that aren't safe integers, such as snowflakes.
15
+ */
16
+ const MATCHERS = {
17
+ integer(segment) {
18
+ if (!/^(0|-?[1-9]\d*)$/.test(segment))
19
+ return undefined;
20
+ const n = Number(segment);
21
+ return Number.isSafeInteger(n) ? n : undefined;
22
+ },
23
+ };
24
+ /** Leading slash, no trailing slash (except for the root itself) — as `route.current.path` is. */
25
+ function normalizePath(path) {
26
+ let p = String(path).replace(/\/+$/, "");
27
+ if (!p.startsWith("/"))
28
+ p = `/${p}`;
29
+ return p;
30
+ }
31
+ function splitPath(path) {
32
+ const p = normalizePath(path);
33
+ return p === "/" ? [] : p.slice(1).split("/");
34
+ }
35
+ /**
36
+ * Turn a route key into segment tokens, throwing on malformed templates. A
37
+ * segment is a param only when it is *entirely* a bracket group, so a literal
38
+ * segment that merely contains brackets (`/v[1]beta`) stays literal.
39
+ */
40
+ function compileRoute(key, draw) {
41
+ const parts = splitPath(key);
42
+ const segs = parts.map((part, i) => {
43
+ if (!part.startsWith("[") || !part.endsWith("]"))
44
+ return { kind: "lit", value: part };
45
+ const rest = /^\[\.\.\.([A-Za-z_$][\w$]*)\]$/.exec(part);
46
+ if (rest) {
47
+ if (i !== parts.length - 1)
48
+ throw new Error(`Staffa: "${part}" must be the last segment of route "${key}"`);
49
+ return { kind: "rest", name: rest[1] };
50
+ }
51
+ const param = /^\[([A-Za-z_$][\w$]*)(?:=([A-Za-z_$][\w$]*))?\]$/.exec(part);
52
+ if (!param)
53
+ throw new Error(`Staffa: malformed param "${part}" in route "${key}"`);
54
+ const [, name, matcher] = param;
55
+ if (matcher && !(matcher in MATCHERS)) {
56
+ throw new Error(`Staffa: unknown matcher "${matcher}" in route "${key}" (known: ${Object.keys(MATCHERS).join(", ")})`);
57
+ }
58
+ return { kind: "param", name, matcher };
59
+ });
60
+ return { key, segs, draw };
61
+ }
62
+ /** Percent-decode a path segment, leaving it alone when it isn't valid encoding. */
63
+ function decodeSeg(value) {
64
+ try {
65
+ return decodeURIComponent(value);
66
+ }
67
+ catch {
68
+ return value;
69
+ }
70
+ }
71
+ function matchRoute(r, segments) {
72
+ const params = {};
73
+ for (let i = 0; i < r.segs.length; i++) {
74
+ const seg = r.segs[i];
75
+ if (seg.kind === "rest") {
76
+ // One-or-more remaining segments, handed over exactly as they appear in
77
+ // the URL. Decoding first and joining would be lossy: an encoded slash
78
+ // inside a segment would come back indistinguishable from a separator.
79
+ if (i >= segments.length)
80
+ return null;
81
+ params[seg.name] = segments.slice(i).join("/");
82
+ return params;
83
+ }
84
+ if (i >= segments.length)
85
+ return null;
86
+ const value = segments[i];
87
+ if (seg.kind === "lit") {
88
+ if (value !== seg.value)
89
+ return null;
90
+ }
91
+ else if (seg.matcher) {
92
+ // A segment the matcher rejects fails the match, so junk falls through
93
+ // to later routes (or notFound) instead of reaching a handler.
94
+ const matched = MATCHERS[seg.matcher](value);
95
+ if (matched === undefined)
96
+ return null;
97
+ params[seg.name] = matched;
98
+ }
99
+ else {
100
+ params[seg.name] = decodeSeg(value);
101
+ }
102
+ }
103
+ return r.segs.length === segments.length ? params : null;
104
+ }
105
+ // ─── Constants ───────────────────────────────────────────────────────────────
106
+ /**
107
+ * The one duration every bit of panel motion shares: the enter/exit fades, the
108
+ * `left` moves of columns shifting sideways, and the ensemble-width transition
109
+ * the chrome follows (see `--s-shell-w` in main.ts). Published as the
110
+ * `--s-panel-ms` custom property below, so CSS and JS can't drift apart.
111
+ */
112
+ const PANEL_MS = 450;
113
+ /** How long a freshly pushed `loading` panel holds its enter animation. */
114
+ const LOADING_HOLD_MS = 300;
115
+ /**
116
+ * The standard page width: sidebar plus content area, capped by the window.
117
+ * `"medium"` fills the content-area part of this exactly; only a `"large"`
118
+ * panel makes the shell grow past it.
119
+ */
120
+ const SHELL_PX = 1280;
121
+ /** The gap between two `"small"` panels sitting two-up. */
122
+ const GUTTER_PX = 24;
123
+ /** Don't pair smalls when half the content area would be narrower than this. */
124
+ const PAIR_MIN_PX = 360;
125
+ // ─── Module-level styling ────────────────────────────────────────────────────
126
+ A.insertGlobalCss({
127
+ ":root": `--s-panel-ms:${PANEL_MS}ms`,
128
+ // The clipping viewport that the columns slide through. Panels are absolutely
129
+ // positioned inside it, with their width and x offset set from JS (see
130
+ // `layout()`), so they can animate between arrangements.
131
+ ".s-panels": "flex:1 min-width:0 min-height:0 position:relative overflow:hidden",
132
+ ".s-panel": {
133
+ // A panel rests at a plain `left` offset and carries no transform: a
134
+ // transformed element is composited, which costs it subpixel text
135
+ // antialiasing. `transform` is used only to play the enter/exit slides,
136
+ // where the compositing is what makes them cheap. There is deliberately
137
+ // no `width` transition: widths depend only on the window, change only in
138
+ // `.s-shell-snap` passes, and a column's content never reflows while the
139
+ // arrangement moves.
140
+ // Every duration is `--s-panel-ms`, so a column's move, its neighbour's fade
141
+ // and the chrome recentering around them all run as one motion. The drift
142
+ // eases out (it should read as a slow settle) while the fade runs *linear*
143
+ // across the whole duration — an eased opacity spends its last stretch near
144
+ // zero, which looks like the panel vanishing rather than fading.
145
+ // No `overflow:hidden` here: the scroll container below clips the content
146
+ // itself, and the pair hairline sits in the gutter *outside* the panel.
147
+ "&": "position:absolute top:0 bottom:0 left:0 display:flex flex-direction:column " +
148
+ "visibility:visible transition: left var(--s-panel-ms) ease, transform var(--s-panel-ms) ease-out, opacity var(--s-panel-ms) linear, visibility 0s;",
149
+ // The scroll container. Mirrors content mode's `main > .s-content`: same
150
+ // padding, and the same scrollbar inset (see `.s-scroll-y` in main.ts) so a
151
+ // single-column shell is pixel-identical to a non-routed one.
152
+ "> .s-content": "flex:1 min-height:0 overflow-y:auto overflow-x:hidden p:$3",
153
+ "> .s-content.s-scroll-y": "margin-right:$3",
154
+ // A vertical hairline centred in the gutter between two paired smalls,
155
+ // fading out at both ends — the same treatment as the sidebar's `.s-nav-sep`.
156
+ "&.s-panel-sep::before": `content:'' position:absolute left:-${GUTTER_PX / 2}px top:0.6rem bottom:0.6rem width:1px ` +
157
+ "background: linear-gradient(to bottom, transparent, $s-faint 18%, $s-faint 82%, transparent);",
158
+ // One vocabulary for every arrival and departure: a gradual fade over a short,
159
+ // slow drift — 8cqw (`cqw`: `.s-main` is the container). Panels appear and
160
+ // leave at the right edge; being crowded out at the left edge is its mirror.
161
+ //
162
+ // The start state of an enter, adopted with transitions off and then
163
+ // dropped, which is what makes the panel settle instead of jumping.
164
+ "&.s-panel-enter": "opacity:0 transition:none transform: translateX(8cqw);",
165
+ // On its way out: fading where it stands, drifting the same short distance,
166
+ // and out of reach while it does. It is removed from the DOM when the fade
167
+ // itself ends (see `beginClose`), never part-way through it.
168
+ "&.s-panel-closing": "opacity:0 pointer-events:none transform: translateX(8cqw);",
169
+ // Crowded out from under the visible run. It keeps its DOM (and thus its
170
+ // scroll position and half-typed forms), so `display:none` is out —
171
+ // `visibility` takes it out of the rendering instead, but only once the fade
172
+ // has played: a transitioned `visibility` counts as *visible* for the whole
173
+ // duration and flips at the very end. Revealing it again uses the rule above
174
+ // (`visibility 0s`), so it comes back instantly.
175
+ "&.s-panel-hidden": "opacity:0 visibility:hidden transform: translateX(-8cqw); " +
176
+ "transition: left var(--s-panel-ms) ease, transform var(--s-panel-ms) ease-out, opacity var(--s-panel-ms) linear, visibility var(--s-panel-ms);",
177
+ },
178
+ // A window resize (and the very first pass) must track the window instantly,
179
+ // not rubber-band 450ms behind it: the layout engine raises this class on the
180
+ // shell for exactly those passes, applies the new geometry, and drops it
181
+ // after a forced reflow. Beats the standing transitions on specificity.
182
+ ".s-main.s-shell-snap .s-panel": "transition:none",
183
+ // On a narrow shell the single column is edge-to-edge, so there is no inset
184
+ // chrome for the scrollbar to line up with — cancel the `.s-scroll-y` margin
185
+ // (the twin of content mode's rule in main.ts).
186
+ [`@container (max-width: ${NARROW_PX}px)`]: {
187
+ ".s-panel > .s-content.s-scroll-y": "margin-right:0",
188
+ },
189
+ // A minimal "still fetching" hint, centred over the panel's content (which
190
+ // stays mounted underneath, so it can fill in reactively).
191
+ ".s-panel-loading": {
192
+ "&": "position:absolute inset:0 display:flex align-items:center justify-content:center gap:$1 pointer-events:none",
193
+ "i": "width:0.5rem height:0.5rem r:50% background:$s-muted opacity:0.45 animation: s-panel-pulse 1s ease-in-out infinite;",
194
+ "i:nth-child(2)": "animation-delay:0.15s",
195
+ "i:nth-child(3)": "animation-delay:0.3s",
196
+ },
197
+ "@keyframes s-panel-pulse": {
198
+ "0%, 100%": "opacity:0.25 transform:scale(0.8)",
199
+ "50%": "opacity:0.7 transform:scale(1)",
200
+ },
201
+ });
202
+ /** At most one routed shell per app — that's what `S.panels` is bound to. */
203
+ let active = null;
204
+ export class PanelController {
205
+ compiled;
206
+ opts;
207
+ /** The live stack, shallow-to-deep. Closing panels are no longer part of it. */
208
+ live = [];
209
+ byId = new Map();
210
+ nextId = 1;
211
+ /** Drives rendering: panel id → its `order` (used only as the sort key). */
212
+ $ids = A.proxy({});
213
+ /**
214
+ * The live stack's paths and its top panel, for reactive readers: the
215
+ * `document.title` watcher, `main()`'s Escape handling and `S.panels.stack`.
216
+ */
217
+ $state = A.proxy({ paths: [], topId: 0 });
218
+ containerEl;
219
+ /** The body width at the last layout; a change means a window resize → snap. */
220
+ lastBodyW = -1;
221
+ layoutQueued = false;
222
+ timers = new Set();
223
+ constructor(opts) {
224
+ if (active) {
225
+ throw new Error("Staffa: only one routed S.main() (one with `routes`) can be active at a time");
226
+ }
227
+ active = this;
228
+ this.opts = opts;
229
+ this.compiled = Object.entries(opts.routes).map(([key, draw]) => compileRoute(key, draw));
230
+ // The router consults this guard before any navigation is applied — ours,
231
+ // a link's, browser back/forward, even a direct route.go() by app code —
232
+ // so every panel the change would remove gets its requestClose asked,
233
+ // exactly once, and a veto leaves the URL and the stack untouched (the
234
+ // router holds the route steady while an async guard is pending, and
235
+ // knows the exact history depth to restore on a vetoed popstate). A
236
+ // guard the app registered before mounting keeps working: it is chained
237
+ // in front of ours — an app veto (or redirect) wins without the panels
238
+ // being asked — and handed back when the shell unmounts.
239
+ const appGuard = route.setGuard((to, from) => {
240
+ const outer = appGuard ? appGuard(to, from) : true;
241
+ if (outer === false)
242
+ return false;
243
+ if (outer === true)
244
+ return this.checkChange(to);
245
+ return outer.then((ok) => (ok === false ? false : this.checkChange(to)));
246
+ });
247
+ // Commit the stack whenever the URL or its snapshot changes — the initial
248
+ // load, our own navigations, and browser back/forward. Anything that
249
+ // reaches this point has already passed the guard above.
250
+ A(() => {
251
+ const target = this.computeTarget();
252
+ A.peek(() => this.propose(target));
253
+ });
254
+ this.interceptLinks();
255
+ this.watchTitle();
256
+ A.clean(() => {
257
+ for (const t of this.timers)
258
+ clearTimeout(t);
259
+ this.timers.clear();
260
+ route.setGuard(appGuard);
261
+ if (active === this)
262
+ active = null;
263
+ });
264
+ }
265
+ // ── Stack derivation ───────────────────────────────────────────────────
266
+ /** Resolve a path to its route handler + params, falling back to `notFound`. */
267
+ resolve(path) {
268
+ const segments = splitPath(path);
269
+ for (const r of this.compiled) {
270
+ const params = matchRoute(r, segments);
271
+ if (params)
272
+ return { draw: r.draw, params };
273
+ }
274
+ return { draw: this.opts.notFound ?? drawDefaultNotFound, params: {} };
275
+ }
276
+ matches(path) {
277
+ const segments = splitPath(path);
278
+ return this.compiled.some((r) => matchRoute(r, segments) != null);
279
+ }
280
+ /**
281
+ * The one derivation rule for origin-less navigation (§2.8): probe every
282
+ * prefix of the path against the route table; the matching prefixes become
283
+ * the stack. Prefixes without a route are simply skipped, so an app that
284
+ * doesn't want one screen stacked under another just doesn't route that
285
+ * prefix. The path itself is always the top panel, matched or not.
286
+ */
287
+ deriveStack(path) {
288
+ const segments = splitPath(path);
289
+ const stack = [];
290
+ for (let i = 1; i < segments.length; i++) {
291
+ const prefix = "/" + segments.slice(0, i).join("/");
292
+ if (this.matches(prefix))
293
+ stack.push(prefix);
294
+ }
295
+ stack.push(normalizePath(path));
296
+ return stack;
297
+ }
298
+ /** The stack a route implies: its snapshot topped by its path, or — without a snapshot — derived. */
299
+ targetFor(path, snapshot) {
300
+ if (Array.isArray(snapshot))
301
+ return snapshot.map(String).concat(normalizePath(path));
302
+ return this.deriveStack(path);
303
+ }
304
+ /** The stack the current history entry asks for. Subscribes to path + snapshot. */
305
+ computeTarget() {
306
+ return this.targetFor(route.current.path, route.current.state.panels);
307
+ }
308
+ /**
309
+ * The route guard (see `route.setGuard` in the constructor): asked before any
310
+ * route change lands, wherever it came from. Runs the {@link Page.requestClose}
311
+ * guard of every panel the new route's stack would remove — a set defined by
312
+ * the target (the commit reconciles by path), so a derived stack that shares
313
+ * nothing with the live one still asks exactly the panels that are closing.
314
+ */
315
+ checkChange(to) {
316
+ const removed = this.removedBy(this.targetFor(to.path, to.state.panels));
317
+ return removed.length ? runGuards(removed) : true;
318
+ }
319
+ // ── Commit pipeline ────────────────────────────────────────────────────
320
+ paths() {
321
+ return this.live.map((e) => e.path);
322
+ }
323
+ /** The live panels a target stack drops — by path, so a splice removes only its own column. */
324
+ removedBy(target) {
325
+ return this.live.filter((entry) => !target.includes(entry.path));
326
+ }
327
+ /**
328
+ * Adopt a stack proposed by the URL. Close guards have already been run (and
329
+ * have passed) by the time a route change is visible here — `checkChange` is
330
+ * consulted by the router itself, before anything is applied.
331
+ */
332
+ propose(target) {
333
+ if (sameStack(this.paths(), target))
334
+ return;
335
+ this.commit(target, A.peek(route.current, "nav"));
336
+ }
337
+ /**
338
+ * Apply a target stack: unmount what's gone, mount what's new, animate the
339
+ * difference.
340
+ *
341
+ * Reconciliation is BY PATH (a stack can't hold the same path twice, so that's
342
+ * well-defined): a panel present in both stacks stays mounted *even if its
343
+ * index shifted*, which is what lets a panel be spliced out of the middle
344
+ * (§7) without disturbing the columns above it. A common-prefix diff would
345
+ * remount every one of them, throwing away exactly the scroll and form state
346
+ * rule 5 promises to keep.
347
+ */
348
+ commit(target, nav) {
349
+ const existing = new Map(this.live.map((entry) => [entry.path, entry]));
350
+ const next = [];
351
+ for (const path of target) {
352
+ const kept = existing.get(path);
353
+ if (kept) {
354
+ // Retained: it just takes its new place in the stack. Its `order` (the
355
+ // DOM sort key) deliberately stays put — see PanelEntry.order.
356
+ existing.delete(path);
357
+ next.push(kept);
358
+ continue;
359
+ }
360
+ const entry = this.createEntry(path, next.length);
361
+ // An initial load just appears, and so do panels *revealed* by a back —
362
+ // they belong underneath the ones sliding away. Everything else enters at
363
+ // the right edge, a replacement exactly like a push.
364
+ if (nav !== "load" && nav !== "back")
365
+ entry.enter = true;
366
+ next.push(entry);
367
+ this.byId.set(entry.id, entry);
368
+ }
369
+ // Whatever the target no longer holds leaves the same way: fading out over
370
+ // the right edge, which is also where its replacement (if any) comes in from.
371
+ for (const entry of existing.values())
372
+ this.beginClose(entry);
373
+ this.live = next;
374
+ A.merge(this.$state, { paths: this.paths(), topId: this.live.length ? this.live[this.live.length - 1].id : 0 });
375
+ for (const entry of this.live)
376
+ this.$ids[String(entry.id)] = entry.order;
377
+ this.scheduleLayout();
378
+ }
379
+ createEntry(path, order) {
380
+ const { draw, params } = this.resolve(path);
381
+ const entry = {
382
+ id: this.nextId++,
383
+ order,
384
+ path,
385
+ draw,
386
+ $ui: A.proxy({ holding: false }),
387
+ layout: "medium",
388
+ width: 0,
389
+ };
390
+ // `close` closes *this* panel, top of the stack or not. It resolves the
391
+ // panel's current depth at call time, so it keeps working after a splice has
392
+ // moved it — and quietly resolves false once the panel is gone.
393
+ entry.$page = A.proxy({
394
+ params,
395
+ path,
396
+ close: () => this.closePanelAt(this.live.indexOf(entry)),
397
+ });
398
+ return entry;
399
+ }
400
+ /**
401
+ * Start a panel's exit: it lingers in the DOM, inert and fading, and is dropped
402
+ * only when the fade itself ends. Removing it on a fixed timer instead would
403
+ * race the transition — pull the element a frame early and the panel appears to
404
+ * fade half-way and then vanish. The timeout is just a fallback for when no
405
+ * `transitionend` is coming at all (transitions off, or an element that never
406
+ * got placed).
407
+ */
408
+ beginClose(entry) {
409
+ entry.closing = true;
410
+ const el = entry.el;
411
+ const drop = () => {
412
+ if (!this.byId.has(entry.id))
413
+ return;
414
+ this.byId.delete(entry.id);
415
+ delete this.$ids[String(entry.id)];
416
+ };
417
+ if (el) {
418
+ el.classList.add("s-panel-closing");
419
+ el.setAttribute("inert", "");
420
+ el.addEventListener("transitionend", (e) => {
421
+ if (e.target === el && e.propertyName === "opacity")
422
+ drop();
423
+ });
424
+ }
425
+ const timer = setTimeout(() => {
426
+ this.timers.delete(timer);
427
+ drop();
428
+ }, PANEL_MS + 80);
429
+ this.timers.add(timer);
430
+ }
431
+ // ── Navigation ─────────────────────────────────────────────────────────
432
+ /**
433
+ * Navigate back to a stack that is a truncation of the current one — the shared
434
+ * implementation of Escape, a page closing itself, return-links and
435
+ * `S.panels.close()`. `route.back()` prefers the history entry where that
436
+ * panel was on top (with its scroll state intact); when there is no such entry
437
+ * it replaces the current one, carrying the snapshot passed as the fallback.
438
+ * Either way the route guard asks the closing panels first, and the returned
439
+ * promise reports its verdict.
440
+ */
441
+ goBackTo(target) {
442
+ return route.back({ path: target[target.length - 1] }, { state: { panels: target.slice(0, -1) } });
443
+ }
444
+ /** Close every panel above `index` (guarded). Resolves `false` when vetoed. */
445
+ closeDownTo(index) {
446
+ if (index < 0 || index >= this.live.length - 1)
447
+ return Promise.resolve(false);
448
+ return this.goBackTo(this.paths().slice(0, index + 1));
449
+ }
450
+ /** Guarded close of the top panel. */
451
+ closeTop() {
452
+ return this.closeDownTo(this.live.length - 2);
453
+ }
454
+ /**
455
+ * Guarded close of the panel at `index`, top of the stack or not — what a
456
+ * page's own close affordances ({@link Page.close}, a box's ✕) come down to.
457
+ *
458
+ * The top panel pops back to the snapshot beneath it. Any other panel is
459
+ * *spliced* out: its guard runs, the columns above it keep their place and
460
+ * state (the commit reconciles by path), and the URL doesn't change, since the
461
+ * top panel didn't. That still gets its own history entry, so the browser's
462
+ * back button restores the closed column like any other snapshot — which is
463
+ * why it goes through `route.go` here rather than through `navigate()`, whose
464
+ * "link to the panel we're already on" check would see a no-op.
465
+ */
466
+ closePanelAt(index) {
467
+ if (index < 0 || index >= this.live.length)
468
+ return Promise.resolve(false);
469
+ if (index === this.live.length - 1)
470
+ return this.closeTop();
471
+ const target = this.paths().filter((_, i) => i !== index);
472
+ return Promise.resolve(route.go({
473
+ path: target[target.length - 1],
474
+ // The top panel keeps its search params and hash: it isn't going
475
+ // anywhere, and `go()` would otherwise default them away.
476
+ search: A.peek(() => ({ ...route.current.search })),
477
+ hash: A.peek(route.current, "hash"),
478
+ state: { panels: target.slice(0, -1) },
479
+ }));
480
+ }
481
+ /** Guarded close of whichever panel `path` is open as. False when it isn't open. */
482
+ closeByPath(path) {
483
+ const wanted = normalizePath(path);
484
+ return this.closePanelAt(this.live.findIndex((entry) => entry.path === wanted));
485
+ }
486
+ /** Guarded close of the panel whose `.s-panel` element this is. */
487
+ closePanelEl(el) {
488
+ return this.closePanelAt(this.live.findIndex((entry) => entry.el === el));
489
+ }
490
+ /**
491
+ * Navigate to `href`. `originIndex` is the depth of the panel the link lives
492
+ * in (−1 when it has none — a nav item or a programmatic call, which derives
493
+ * the whole stack instead). `replace` swaps the originating panel rather than
494
+ * stacking on top of it.
495
+ */
496
+ navigate(href, originIndex, replace = false) {
497
+ let url;
498
+ try {
499
+ url = new URL(href, location.href);
500
+ }
501
+ catch {
502
+ return;
503
+ }
504
+ const path = normalizePath(url.pathname);
505
+ const search = Object.fromEntries(new URLSearchParams(url.search));
506
+ const hash = url.hash;
507
+ // A link to a panel that is already open is a return, not a navigation —
508
+ // so a stack can never hold the same path twice.
509
+ const open = this.live.findIndex((e) => e.path === path);
510
+ if (open >= 0 && open < this.live.length - 1) {
511
+ void this.closeDownTo(open);
512
+ return;
513
+ }
514
+ if (open >= 0) {
515
+ // The target is the panel we're already on. Going nowhere — but the link
516
+ // may still carry a different search or hash, which belong to the top
517
+ // panel: record that as a history entry, leaving the stack alone (the
518
+ // panel reconciles by path, so it isn't even redrawn).
519
+ if (url.search === location.search && (url.hash || "") === (location.hash || ""))
520
+ return;
521
+ route.go({ path, search, hash, state: { panels: this.paths().slice(0, -1) } });
522
+ return;
523
+ }
524
+ // Without an originating panel there is no stack to build on, so derive
525
+ // one — a nav click and a deep link to the same URL land identically.
526
+ // The route guard (checkChange) asks every panel this removes — a set
527
+ // defined by the target stack, wherever those panels happen to sit —
528
+ // before the change is applied; a veto leaves everything untouched.
529
+ const beneath = originIndex < 0
530
+ ? this.deriveStack(path).slice(0, -1)
531
+ : this.paths().slice(0, replace ? originIndex : originIndex + 1);
532
+ route.go({ path, search, hash, state: { panels: beneath } });
533
+ }
534
+ /** Programmatic push/replace, with the top panel as the implied origin. */
535
+ pushPath(path, replace) {
536
+ this.navigate(path, this.live.length - 1, replace);
537
+ }
538
+ // ── Link interception ──────────────────────────────────────────────────
539
+ /**
540
+ * Link handling through `route.interceptLinks()`, whose handler hook hands us
541
+ * the anchor so we can decide what the click *means*: the originating
542
+ * `.s-panel` (which decides what the click truncates), `data-panel=replace`,
543
+ * and return-to-an-open-panel semantics. The exclusion rules (targets,
544
+ * downloads, modified clicks, external URLs) live in Aberdeen; the close
545
+ * guards run in `checkChange` when our navigation reaches the router.
546
+ */
547
+ interceptLinks() {
548
+ route.interceptLinks((url, anchor) => {
549
+ const panel = anchor.closest(".s-panel");
550
+ const originIndex = panel ? this.live.findIndex((entry) => entry.el === panel) : -1;
551
+ this.navigate(url.href, originIndex, anchor.getAttribute("data-panel") === "replace");
552
+ return true;
553
+ });
554
+ }
555
+ // ── document.title ─────────────────────────────────────────────────────
556
+ /** `"<page title> · <app title>"`, kept in sync with the top panel. */
557
+ watchTitle() {
558
+ const original = document.title;
559
+ A(() => {
560
+ const entry = this.byId.get(this.$state.topId);
561
+ const pageTitle = entry?.$page.title;
562
+ const appTitle = typeof this.opts.title === "string" ? this.opts.title : undefined;
563
+ const title = pageTitle && appTitle ? `${pageTitle} · ${appTitle}` : pageTitle || appTitle;
564
+ if (title)
565
+ document.title = title;
566
+ });
567
+ A.clean(() => { document.title = original; });
568
+ }
569
+ // ── Rendering ──────────────────────────────────────────────────────────
570
+ /**
571
+ * Draw the panel viewport into the current element. Called by `main()`.
572
+ *
573
+ * There is deliberately no close chrome here — no back rail, no ←: pages
574
+ * provide their own way out (see {@link Page.close} and `S.box`'s `close`
575
+ * option). The shell contributes Escape and the browser's own back button.
576
+ */
577
+ drawStack() {
578
+ const container = A("div.s-panels role=main", () => {
579
+ A.onEach(this.$ids, (_order, id) => this.drawPanel(Number(id)), (order, id) => [order, Number(id)]);
580
+ });
581
+ this.containerEl = container;
582
+ if (typeof ResizeObserver !== "undefined") {
583
+ const ro = new ResizeObserver(() => this.layout());
584
+ // The region *and* the body it sits in: the region alone misses a shell
585
+ // resize that the columns happen to absorb, which still re-resolves widths.
586
+ ro.observe(container);
587
+ const body = container.parentElement?.parentElement;
588
+ if (body)
589
+ ro.observe(body);
590
+ A.clean(() => ro.disconnect());
591
+ }
592
+ A.clean(() => { if (this.containerEl === container)
593
+ this.containerEl = undefined; });
594
+ this.scheduleLayout();
595
+ }
596
+ drawPanel(id) {
597
+ const entry = this.byId.get(id);
598
+ if (!entry)
599
+ return;
600
+ const el = A("section.s-panel", () => {
601
+ const contentEl = A("div.s-content", () => {
602
+ entry.draw(entry.$page);
603
+ // After the content, so there is something to scroll when restoring.
604
+ route.persistScroll(entry.path);
605
+ });
606
+ watchVerticalOverflow(contentEl);
607
+ // The loading hint, in its own scope so flipping the flag doesn't
608
+ // redraw the panel's content. Held-back panels show nothing yet: they
609
+ // are still parked off screen, waiting to slide in with real content.
610
+ A(() => {
611
+ if (!entry.$page.loading || entry.$ui.holding)
612
+ return;
613
+ A("div.s-panel-loading aria-hidden=true", () => { A("i"); A("i"); A("i"); });
614
+ });
615
+ });
616
+ // How much room the panel wants, settled right after its handler's
617
+ // synchronous run — deliberately once: a column that changed its mind
618
+ // later would reflow itself and shove its neighbours around.
619
+ const asked = A.peek(entry.$page, "layout");
620
+ entry.layout = asked === "small" || asked === "large" ? asked : "medium";
621
+ entry.el = el;
622
+ // Nothing animates from the arbitrary initial position; `layout()` gives
623
+ // the panel its real geometry (and turns transitions back on) in the
624
+ // upcoming frame, before anything is painted. A redraw (a reactive
625
+ // dependency inside the handler) lands here too, with a brand-new element
626
+ // that has to be placed again before it may animate.
627
+ entry.placed = false;
628
+ el.style.transition = "none";
629
+ A.clean(() => { if (entry.el === el)
630
+ entry.el = undefined; });
631
+ // A held-back panel that finishes loading gets to play its enter animation.
632
+ A(() => {
633
+ void entry.$page.loading;
634
+ this.scheduleLayout();
635
+ });
636
+ this.scheduleLayout();
637
+ }
638
+ // ── Layout engine ──────────────────────────────────────────────────────
639
+ scheduleLayout() {
640
+ if (this.layoutQueued)
641
+ return;
642
+ this.layoutQueued = true;
643
+ requestAnimationFrame(() => {
644
+ this.layoutQueued = false;
645
+ this.layout();
646
+ });
647
+ }
648
+ /**
649
+ * Size and position every panel, and publish the width of the whole ensemble
650
+ * (sidebar + separator + columns) for the shell to centre itself on.
651
+ *
652
+ * This is everything CSS can't work out for itself: which panels exist, which
653
+ * of them are visible, how wide each one is and where it sits. All the motion
654
+ * between two of these arrangements is CSS's job.
655
+ */
656
+ layout() {
657
+ const container = this.containerEl;
658
+ const inner = container?.parentElement;
659
+ const body = inner?.parentElement;
660
+ const shell = container?.closest(".s-main");
661
+ if (!container || !inner || !body || !shell)
662
+ return;
663
+ const n = this.live.length;
664
+ // A panel that hasn't drawn yet has no width to contribute, which would make
665
+ // this pass's arithmetic (and any enter animation it triggers) meaningless.
666
+ // Every mount schedules another pass, so simply wait for it.
667
+ if (!n || this.live.some((entry) => !entry.el))
668
+ return;
669
+ // Measured on the *shell*, not on the region: the region's width is this
670
+ // function's own output, so reading it back would nail the layout to
671
+ // whatever it happened to be a frame ago. Fractional widths throughout — a
672
+ // rounded column edge would drift a pixel away from the chrome above it.
673
+ const total = body.getBoundingClientRect().width;
674
+ if (!total)
675
+ return;
676
+ const stacking = this.opts.stacking !== false;
677
+ // A window resize (or the very first pass) must be adopted instantly —
678
+ // geometry tracking the window through a 450ms transition reads as lag,
679
+ // and a shell animating itself into place on load reads as a glitch.
680
+ // `.s-shell-snap` suppresses every standing transition for this one pass.
681
+ const snap = this.lastBodyW !== total;
682
+ if (snap) {
683
+ this.lastBodyW = total;
684
+ shell.classList.add("s-shell-snap");
685
+ }
686
+ // Everything that sits beside the columns: the sidebar and its hairline,
687
+ // either of which may be display:none on a narrow shell.
688
+ let chrome = 0;
689
+ for (const child of inner.children) {
690
+ if (child !== container)
691
+ chrome += child.getBoundingClientRect().width;
692
+ }
693
+ // The standard page is SHELL_PX wide, capped by the window; what it leaves
694
+ // beside the sidebar is the *standard* content area. Widths are a pure
695
+ // function of the window — never of what else is open — so a panel NEVER
696
+ // resizes because a neighbour came or went; only a window resize (the
697
+ // snap pass above) changes them:
698
+ // - "medium" fills the standard content area exactly;
699
+ // - "small" is half of it (minus the gutter) whenever that half is still
700
+ // a usable column, and the whole of it on narrower screens;
701
+ // - "large" ignores the standard width and takes everything the window
702
+ // has — which also means nothing ever fits beside it.
703
+ const stdRoom = Math.max(0, Math.min(SHELL_PX, total) - chrome);
704
+ const fullRoom = Math.max(0, total - chrome);
705
+ const halfW = (stdRoom - GUTTER_PX) / 2;
706
+ const smallW = halfW >= PAIR_MIN_PX ? halfW : stdRoom;
707
+ const width = (entry) => entry.layout === "small" ? smallW : entry.layout === "large" ? fullRoom : stdRoom;
708
+ // The visible run: as many top-of-stack panels as the window fits, at the
709
+ // sizes the window gives them. The top panel always shows.
710
+ let first = n - 1;
711
+ let runSum = width(this.live[first]);
712
+ if (stacking) {
713
+ for (let i = n - 2; i >= 0; i--) {
714
+ const sum = runSum + GUTTER_PX + width(this.live[i]);
715
+ if (sum > fullRoom)
716
+ break;
717
+ runSum = sum;
718
+ first = i;
719
+ }
720
+ }
721
+ // The content area holds the run, but is never smaller than the standard
722
+ // page (a lone small leaves its other half open — which is exactly where
723
+ // the next small lands, without anything on screen moving) and never
724
+ // wider than the window. So the page is the familiar 1280px until extra
725
+ // columns genuinely fit, and stretches — centred — to hold the ones that
726
+ // do; with a "large" up that's the window's edges.
727
+ const area = Math.min(fullRoom, Math.max(stdRoom, runSum));
728
+ for (let i = first; i < n; i++)
729
+ this.live[i].width = width(this.live[i]);
730
+ // Panels that have never been visible get their would-be width too, so a
731
+ // reveal doesn't start from nothing.
732
+ for (const entry of this.live) {
733
+ if (!entry.width)
734
+ entry.width = width(entry);
735
+ }
736
+ // The chrome above and below the body caps itself to the ensemble width,
737
+ // keeping everything centred and aligned however far the area stretches.
738
+ // The consumers transition their max-width (see main.ts), so the
739
+ // recentring plays along with the panel that caused it instead of
740
+ // snapping.
741
+ shell.style.setProperty("--s-shell-w", `${chrome + area}px`);
742
+ // Phase 1 — every panel's *start* state for this frame. Panels already on
743
+ // screen simply move (their standing transition animates it); freshly
744
+ // mounted ones still have transitions switched off, so what we set here is
745
+ // adopted instantly and becomes the "before" of their enter animation.
746
+ const fresh = [];
747
+ let x = 0;
748
+ for (let i = 0; i < n; i++) {
749
+ const entry = this.live[i];
750
+ const el = entry.el;
751
+ const shown = i >= first;
752
+ // Visible panels are left-aligned in the content area, a gutter apart;
753
+ // hidden ones park at its left edge, keeping their last width.
754
+ place(el, shown ? x : 0, entry.width);
755
+ if (shown)
756
+ x += entry.width + GUTTER_PX;
757
+ el.classList.toggle("s-panel-sep", shown && i > first);
758
+ // Hidden panels fade out over the left edge and, once faded, stop being
759
+ // rendered at all — but they keep their DOM, and their scroll position.
760
+ el.classList.toggle("s-panel-hidden", !shown);
761
+ el.toggleAttribute("inert", !shown);
762
+ if (entry.placed)
763
+ continue;
764
+ fresh.push(entry);
765
+ // A panel that mounts while still fetching holds here for a moment, so
766
+ // it can enter with real content instead of an empty column.
767
+ if (!A.peek(entry.$page, "loading") || entry.holdDone)
768
+ entry.$ui.holding = false;
769
+ else if (!entry.$ui.holding) {
770
+ entry.$ui.holding = true;
771
+ this.holdEnter(entry);
772
+ }
773
+ // Already at its resting place; the enter animation is the offset (and
774
+ // the transparency) it starts from, one edge to the right.
775
+ if (entry.enter && shown)
776
+ el.classList.add("s-panel-enter");
777
+ }
778
+ // Phase 2 — force the browser to adopt those start states (and, on a snap
779
+ // pass, the transition-free geometry) as the ones to animate *from*.
780
+ // (Reading a layout property is what does it.)
781
+ if (fresh.length || snap)
782
+ void container.offsetWidth;
783
+ if (snap)
784
+ shell.classList.remove("s-shell-snap");
785
+ // Phase 3 — transitions back on, start state dropped, and off they go.
786
+ for (const entry of fresh) {
787
+ if (entry.$ui.holding)
788
+ continue;
789
+ entry.el.style.transition = "";
790
+ entry.el.classList.remove("s-panel-enter");
791
+ entry.enter = false;
792
+ entry.placed = true;
793
+ }
794
+ }
795
+ /** Let a `loading` panel's enter animation wait — but not indefinitely. */
796
+ holdEnter(entry) {
797
+ const timer = setTimeout(() => {
798
+ this.timers.delete(timer);
799
+ entry.holdDone = true;
800
+ if (entry.$ui.holding) {
801
+ entry.$ui.holding = false;
802
+ this.scheduleLayout();
803
+ }
804
+ }, LOADING_HOLD_MS);
805
+ this.timers.add(timer);
806
+ }
807
+ }
808
+ /** Put a panel at rest: `x` from the region's left edge, `width` pixels wide. */
809
+ function place(el, x, width) {
810
+ el.style.left = `${x}px`;
811
+ el.style.width = `${width}px`;
812
+ }
813
+ // ─── Guards ──────────────────────────────────────────────────────────────────
814
+ /**
815
+ * Ask every panel being removed, deepest first, whether it may go. Returns a
816
+ * plain boolean when no guard needs awaiting, so the common case stays
817
+ * synchronous (and screenshots stay deterministic).
818
+ */
819
+ function runGuards(removed) {
820
+ const list = [...removed].reverse();
821
+ let i = 0;
822
+ const step = () => {
823
+ while (i < list.length) {
824
+ const guard = A.peek(list[i++].$page, "requestClose");
825
+ if (!guard)
826
+ continue;
827
+ let verdict;
828
+ try {
829
+ verdict = guard();
830
+ }
831
+ catch (e) {
832
+ console.error(e);
833
+ return false;
834
+ }
835
+ if (verdict === false)
836
+ return false;
837
+ if (verdict !== true)
838
+ return Promise.resolve(verdict).then((ok) => (ok === false ? false : step()));
839
+ }
840
+ return true;
841
+ };
842
+ return step();
843
+ }
844
+ // ─── Helpers ─────────────────────────────────────────────────────────────────
845
+ function sameStack(a, b) {
846
+ return a.length === b.length && a.every((v, i) => v === b[i]);
847
+ }
848
+ function drawDefaultNotFound($page) {
849
+ A("p fg:$s-muted", () => A("#", `No page at ${$page.path}`));
850
+ }
851
+ /**
852
+ * Toggle `.s-scroll-y` on `el` whenever a vertical scrollbar is eating into its
853
+ * width, so CSS can inset the bar from the panel's edge. Same trick (and the
854
+ * same reasoning) as content mode's `watchVerticalOverflow` in main.ts.
855
+ */
856
+ function watchVerticalOverflow(el) {
857
+ if (typeof ResizeObserver === "undefined")
858
+ return;
859
+ const update = () => el.classList.toggle("s-scroll-y", el.offsetWidth > el.clientWidth);
860
+ const ro = new ResizeObserver(update);
861
+ ro.observe(el);
862
+ if (el.firstElementChild)
863
+ ro.observe(el.firstElementChild);
864
+ update();
865
+ A.clean(() => ro.disconnect());
866
+ }
867
+ // ─── Public helpers ──────────────────────────────────────────────────────────
868
+ /**
869
+ * Navigating the routed `S.main()` shell from code, for the times it isn't a
870
+ * link click, such as opening the screen for a record you just created.
871
+ *
872
+ * The same rules as a link click apply: pushing a path that is already open
873
+ * goes back to it rather than opening it twice, and anything that would close a
874
+ * panel asks its {@link Page.requestClose} first.
875
+ *
876
+ * @example
877
+ * ```ts
878
+ * S.button({ content: "New task", click: async () => {
879
+ * const task = await createTask();
880
+ * S.panels.push(`/tasks/${task.id}`);
881
+ * }});
882
+ * ```
883
+ */
884
+ export const panels = {
885
+ /** Opens `path` in a new panel on top of the top one. */
886
+ push(path) {
887
+ requireActive().pushPath(path, false);
888
+ },
889
+ /**
890
+ * Opens `path` in place of the top panel, which closes (asking its
891
+ * {@link Page.requestClose} first). The panels beneath it stay as they are.
892
+ */
893
+ replace(path) {
894
+ requireActive().pushPath(path, true);
895
+ },
896
+ /**
897
+ * Closes the top panel, or, given a `path`, whichever panel is open at it,
898
+ * asking {@link Page.requestClose} first. A panel that isn't on top is taken
899
+ * out on its own, leaving the columns to its right exactly as they are.
900
+ *
901
+ * Resolves `false` if the panel didn't close: `requestClose` said no, `path`
902
+ * isn't open, or another navigation got there first.
903
+ */
904
+ close(path) {
905
+ const ctl = requireActive();
906
+ return path == null ? ctl.closeTop() : ctl.closeByPath(path);
907
+ },
908
+ /** The paths of the open panels, oldest first. Reactive: safe to read in a scope. */
909
+ get stack() {
910
+ return active ? active.$state.paths : [];
911
+ },
912
+ };
913
+ function requireActive() {
914
+ if (!active)
915
+ throw new Error("Staffa: S.panels needs a routed S.main() (one with `routes`) to be mounted");
916
+ return active;
917
+ }
918
+ /**
919
+ * Closes the panel `el` sits in, working out which one that is from the DOM.
920
+ * That is what lets a close button work without being handed a `$page`, from
921
+ * any column, whether or not it is on top. Used by `S.box`'s `close: true`.
922
+ *
923
+ * Outside a routed shell (or outside any panel, such as a box in a dialog) there is
924
+ * nothing to close: it warns and resolves `false`.
925
+ */
926
+ export function closeContainingPanel(el) {
927
+ const panelEl = el?.closest(".s-panel");
928
+ if (!active || !panelEl) {
929
+ console.warn("Staffa: `close: true` needs to be drawn inside a panel of a routed S.main()");
930
+ return Promise.resolve(false);
931
+ }
932
+ return active.closePanelEl(panelEl);
933
+ }