staffa 0.7.4 → 0.8.1

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,1292 @@
1
+ import A from "aberdeen";
2
+ import * as route from "aberdeen/route";
3
+ import { NARROW_PX } from "../core.js";
4
+
5
+ /**
6
+ * Routed, multi-column panel navigation for {@link main}.
7
+ *
8
+ * Each route draws one screen of the app, called a panel, and as many panels as
9
+ * fit are shown at a time. On a phone that is one, so a link opens a new panel
10
+ * on top and closing it brings the previous one back. On a wider screen the
11
+ * panels that would have covered each other sit side by side instead, oldest on
12
+ * the left. The app's own code is the same either way.
13
+ *
14
+ * Navigation runs through `aberdeen/route`: the URL holds the top panel, and
15
+ * the ones beneath it are stored beside it in the history entry. So back and
16
+ * forward step through whole arrangements of columns, and a reload (or a shared
17
+ * link) brings the same columns back.
18
+ */
19
+
20
+ // ─── Route table typing ──────────────────────────────────────────────────────
21
+
22
+ /** Flattens an intersection into a single object type, so hovers read nicely. */
23
+ type Prettify<T> = { [K in keyof T]: T[K] } & {};
24
+
25
+ /**
26
+ * What a `[name=matcher]` matcher name yields. An unrecognised name resolves to
27
+ * `never`, which shows up as an unusable param at the handler rather than
28
+ * quietly typing as `string` (the route key itself throws at mount time).
29
+ */
30
+ export type MatcherType<M extends string> = M extends "integer" ? number : never;
31
+
32
+ /**
33
+ * The params contributed by a single path-template segment: `[x]` a string,
34
+ * `[x=integer]` a number, `[...x]` the rest of the path as one raw string.
35
+ */
36
+ export type SegParams<S extends string> =
37
+ S extends `[...${infer Name}]` ? { [K in Name]: string } :
38
+ S extends `[${infer Name}=${infer Matcher}]` ? { [K in Name]: MatcherType<Matcher> } :
39
+ S extends `[${infer Name}]` ? { [K in Name]: string } : {};
40
+
41
+ /**
42
+ * The params object described by a path template, e.g.
43
+ * `PathParams<"/projects/[id]/tasks/[taskId=integer]">` is
44
+ * `{ id: string; taskId: number }`.
45
+ */
46
+ export type PathParams<P extends string> =
47
+ P extends `${infer Head}/${infer Rest}` ? SegParams<Head> & PathParams<Rest> : SegParams<P>;
48
+
49
+ /** A panel draw function: it receives the panel's {@link Page} and draws into the current scope. */
50
+ export type RouteHandler<P = any> = (page: Page<P>) => void;
51
+
52
+ /**
53
+ * A route table: path templates mapped to panel draw functions. Used as the
54
+ * loose (non-inferred) type; `S.main()` infers a more precise type from the
55
+ * literal you pass, so each handler's `$page.params` is typed per its key.
56
+ */
57
+ export type Routes = Record<string, RouteHandler>;
58
+
59
+ /**
60
+ * The shape `S.main()`'s `routes` option is checked against: every key types its
61
+ * own handler's `params`. Used as a self-referential generic constraint, which
62
+ * is what makes `$page.params` infer from the route key.
63
+ */
64
+ export type RouteTable<R> = { [K in keyof R & string]: (page: Page<Prettify<PathParams<K>>>) => void };
65
+
66
+ // ─── The Page object ─────────────────────────────────────────────────────────
67
+
68
+ /**
69
+ * What a route handler gets: the params from its route, plus everything the
70
+ * shell needs to know about the panel it is drawing. It's an Aberdeen proxy, so
71
+ * you can set things later, such as a `title` that arrives with your data or
72
+ * `loading` going back to `false`, and the shell keeps up.
73
+ *
74
+ * Search params and the `#hash` belong to the top panel only. A panel with
75
+ * another one on top of it keeps just its path, so anything a panel needs in
76
+ * order to redraw itself has to live in that path.
77
+ */
78
+ export interface Page<P = Record<string, string | number | string[]>> {
79
+ /**
80
+ * The params matched from this panel's path, typed per its route key:
81
+ * `[x]` is a `string`, `[x=integer]` a `number`, `[...x]` a `string`.
82
+ * Read-only.
83
+ */
84
+ readonly params: P;
85
+ /** This panel's path, e.g. `"/projects/7"`. Read-only. */
86
+ readonly path: string;
87
+ /** Shown in `document.title` while this panel is top-most. */
88
+ title?: string;
89
+ /**
90
+ * How much room this panel takes. The content area is the page, at most
91
+ * 1280px wide, minus the nav sidebar; the widths below assume a sidebar of
92
+ * around 170px, so without one add that back.
93
+ *
94
+ * - `"small"` is 360 to 540px once two panels fit side by side, which is
95
+ * what makes it right for lists, detail forms, and anything else that
96
+ * reads well at phone width. Below that it takes the whole content area
97
+ * (so up to ~730px), like a medium does. A lone small leaves its other
98
+ * half empty, and that is exactly where the next small lands, without
99
+ * anything on screen moving.
100
+ * - `"medium"` (the default) takes the whole content area: up to ~1100px,
101
+ * and the screen width on a phone. The safe default for ordinary screens.
102
+ * Nothing fits beside a medium on a standard 1280px page, though on a wide
103
+ * enough window a small still can.
104
+ * - `"large"` takes the whole window, with no upper limit (~1750px on a
105
+ * 1920px screen): for boards, wide tables and dense dashboards. While it's
106
+ * open the whole shell (top bar, content and footer) stretches to the
107
+ * screen edges rather than stopping at 1280px.
108
+ *
109
+ * When more columns fit than the standard page holds (three smalls, or a
110
+ * medium and a small) the page itself grows, staying centred, to hold them.
111
+ *
112
+ * A panel's width depends only on the size of the window, never on what else
113
+ * is open, so opening or closing a panel never resizes the ones already on
114
+ * screen.
115
+ *
116
+ * The panel is sized from this **before** your handler runs, so anything that
117
+ * measures its own box has a real one from the first frame. What it is sized
118
+ * at is whatever this says at that moment, which for a brand-new panel is the
119
+ * default: a handler that *assigns* `layout` is drawn at the medium width and
120
+ * reflowed immediately after — in time for the frame, but not for a
121
+ * measurement taken in the same breath.
122
+ *
123
+ * Assigning it later works just as well. When your data arrives and you find
124
+ * you want the wide one, the panel reflows to its new width without being
125
+ * redrawn — so nothing in it is rebuilt or loses its state — and the columns
126
+ * beside it move over.
127
+ */
128
+ layout?: "small" | "medium" | "large";
129
+ /**
130
+ * Set this while you're fetching what the panel needs, and back to `false`
131
+ * when you're done. A new panel waits a moment before sliding in, so it can
132
+ * arrive with real content instead of empty; if the wait drags on it slides
133
+ * in anyway and shows a loading indicator until the flag clears. It only
134
+ * affects the animation; the stack, the URL and `requestClose` never wait
135
+ * for it.
136
+ */
137
+ loading?: boolean;
138
+ /**
139
+ * Your chance to say no. Everything that would close this panel waits for
140
+ * it: Escape, the panel's own ✕ or Cancel button ({@link Page.close}, or a
141
+ * box with `close: true`), the browser's back button, a link that would
142
+ * close it, and {@link panels}.`close()`. Return `false` to keep the panel
143
+ * open, usually after a dirty check and a {@link confirm}.
144
+ */
145
+ requestClose?: () => boolean | Promise<boolean>;
146
+ /**
147
+ * Closes **this** panel, wherever it sits in the stack. The top panel goes
148
+ * back to whatever was underneath it; any other panel is taken out on its
149
+ * own, leaving the columns to its right where they are, with their state,
150
+ * and the URL alone, since the top panel didn't move. Either way it
151
+ * becomes a history entry, so the browser's back button brings it back.
152
+ *
153
+ * Resolves `false` if the panel didn't close: {@link Page.requestClose} said
154
+ * no, it was the only panel on the stack (so there's nothing to go back to),
155
+ * or another navigation got there first. The shell draws no back arrows or
156
+ * ✕ of its own, so this (or `S.box`'s `close` option) is how a panel gives
157
+ * the user a way out.
158
+ *
159
+ * @example
160
+ * ```ts
161
+ * S.button({ content: "Cancel", attrs: ".neutral", click: () => void $page.close() });
162
+ * ```
163
+ */
164
+ close(): Promise<boolean>;
165
+ }
166
+
167
+ // ─── Path matching ───────────────────────────────────────────────────────────
168
+
169
+ type Seg =
170
+ | { kind: "lit"; value: string }
171
+ | { kind: "param"; name: string; matcher?: string }
172
+ | { kind: "rest"; name: string };
173
+
174
+ /**
175
+ * The matchers a `[name=matcher]` segment can use. A matcher returns the param's
176
+ * value, or `undefined` to fail the match, in which case the path falls through
177
+ * to a later route (or to `notFound`) instead of reaching a handler.
178
+ *
179
+ * `integer` deliberately refuses anything that wouldn't survive a round trip
180
+ * back to the same URL: no leading zeroes ("007"), no "-0", no "1.5", "1e3" or
181
+ * "0x10", and nothing past `Number.MAX_SAFE_INTEGER` (where the number would no
182
+ * longer hold the id it came from). Two spellings of one id would otherwise be
183
+ * two different paths, so the same record could sit open in two panels at once.
184
+ * Use a plain `[id]` for ids that aren't safe integers, such as snowflakes.
185
+ */
186
+ const MATCHERS: Record<string, (segment: string) => unknown> = {
187
+ integer(segment) {
188
+ if (!/^(0|-?[1-9]\d*)$/.test(segment)) return undefined;
189
+ const n = Number(segment);
190
+ return Number.isSafeInteger(n) ? n : undefined;
191
+ },
192
+ };
193
+
194
+ interface CompiledRoute {
195
+ key: string;
196
+ segs: Seg[];
197
+ draw: RouteHandler;
198
+ }
199
+
200
+ /** Leading slash, no trailing slash (except for the root itself) — as `route.current.path` is. */
201
+ function normalizePath(path: string): string {
202
+ let p = String(path).replace(/\/+$/, "");
203
+ if (!p.startsWith("/")) p = `/${p}`;
204
+ return p;
205
+ }
206
+
207
+ function splitPath(path: string): string[] {
208
+ const p = normalizePath(path);
209
+ return p === "/" ? [] : p.slice(1).split("/");
210
+ }
211
+
212
+ /**
213
+ * Turn a route key into segment tokens, throwing on malformed templates. A
214
+ * segment is a param only when it is *entirely* a bracket group, so a literal
215
+ * segment that merely contains brackets (`/v[1]beta`) stays literal.
216
+ */
217
+ function compileRoute(key: string, draw: RouteHandler): CompiledRoute {
218
+ const parts = splitPath(key);
219
+ const segs = parts.map((part, i): Seg => {
220
+ if (!part.startsWith("[") || !part.endsWith("]")) return { kind: "lit", value: part };
221
+
222
+ const rest = /^\[\.\.\.([A-Za-z_$][\w$]*)\]$/.exec(part);
223
+ if (rest) {
224
+ if (i !== parts.length - 1) throw new Error(`Staffa: "${part}" must be the last segment of route "${key}"`);
225
+ return { kind: "rest", name: rest[1] };
226
+ }
227
+ const param = /^\[([A-Za-z_$][\w$]*)(?:=([A-Za-z_$][\w$]*))?\]$/.exec(part);
228
+ if (!param) throw new Error(`Staffa: malformed param "${part}" in route "${key}"`);
229
+ const [, name, matcher] = param;
230
+ if (matcher && !(matcher in MATCHERS)) {
231
+ throw new Error(`Staffa: unknown matcher "${matcher}" in route "${key}" (known: ${Object.keys(MATCHERS).join(", ")})`);
232
+ }
233
+ return { kind: "param", name, matcher };
234
+ });
235
+ return { key, segs, draw };
236
+ }
237
+
238
+ /** Percent-decode a path segment, leaving it alone when it isn't valid encoding. */
239
+ function decodeSeg(value: string): string {
240
+ try { return decodeURIComponent(value); } catch { return value; }
241
+ }
242
+
243
+ function matchRoute(r: CompiledRoute, segments: string[]): Record<string, any> | null {
244
+ const params: Record<string, any> = {};
245
+ for (let i = 0; i < r.segs.length; i++) {
246
+ const seg = r.segs[i];
247
+ if (seg.kind === "rest") {
248
+ // One-or-more remaining segments, handed over exactly as they appear in
249
+ // the URL. Decoding first and joining would be lossy: an encoded slash
250
+ // inside a segment would come back indistinguishable from a separator.
251
+ if (i >= segments.length) return null;
252
+ params[seg.name] = segments.slice(i).join("/");
253
+ return params;
254
+ }
255
+ if (i >= segments.length) return null;
256
+ const value = segments[i];
257
+ if (seg.kind === "lit") {
258
+ if (value !== seg.value) return null;
259
+ } else if (seg.matcher) {
260
+ // A segment the matcher rejects fails the match, so junk falls through
261
+ // to later routes (or notFound) instead of reaching a handler.
262
+ const matched = MATCHERS[seg.matcher](value);
263
+ if (matched === undefined) return null;
264
+ params[seg.name] = matched;
265
+ } else {
266
+ params[seg.name] = decodeSeg(value);
267
+ }
268
+ }
269
+ return r.segs.length === segments.length ? params : null;
270
+ }
271
+
272
+ // ─── Constants ───────────────────────────────────────────────────────────────
273
+
274
+ /**
275
+ * The one duration every bit of panel motion shares: the enter/exit fades, the
276
+ * `left` moves of columns shifting sideways, and the ensemble-width transition
277
+ * the chrome follows (see `--s-shell-w` in main.ts). Published as the
278
+ * `--s-panel-ms` custom property below, so CSS and JS can't drift apart.
279
+ */
280
+ const PANEL_MS = 450;
281
+ /** How long a freshly pushed `loading` panel holds its enter animation. */
282
+ const LOADING_HOLD_MS = 300;
283
+ /**
284
+ * The standard page width: sidebar plus content area, capped by the window.
285
+ * `"medium"` fills the content-area part of this exactly; only a `"large"`
286
+ * panel makes the shell grow past it.
287
+ */
288
+ const SHELL_PX = 1280;
289
+ /** The gap between two `"small"` panels sitting two-up. */
290
+ const GUTTER_PX = 24;
291
+ /** Don't pair smalls when half the content area would be narrower than this. */
292
+ const PAIR_MIN_PX = 360;
293
+ /**
294
+ * Panels are layered by their depth in the stack, two `z-index` steps per panel:
295
+ * a panel sits on the odd layer for its depth, and a *closing* one drops to the
296
+ * even layer just below, where it is frozen for the length of its fade. So a
297
+ * panel that replaces another comes in over it, while one that closes fades out
298
+ * over whatever it was covering — which is the way round both should read.
299
+ */
300
+ const LAYER_STEP = 2;
301
+
302
+ // ─── Module-level styling ────────────────────────────────────────────────────
303
+
304
+ A.insertGlobalCss({
305
+ ":root": `--s-panel-ms:${PANEL_MS}ms`,
306
+ // The clipping viewport that the columns slide through. Panels are absolutely
307
+ // positioned inside it, with their width and x offset set from JS (see
308
+ // `layout()`), so they can animate between arrangements. `isolation` keeps the
309
+ // layers they stack themselves in (see LAYER_STEP) to themselves: the region
310
+ // as a whole still sits under the shell's own chrome — the sticky top bar, and
311
+ // the nav page that slides across the body — however deep the stack gets.
312
+ ".s-panels": "flex:1 min-width:0 min-height:0 position:relative overflow:hidden isolation:isolate",
313
+ ".s-panel": {
314
+ // A panel rests at a plain `left` offset and carries no transform: a
315
+ // transformed element is composited, which costs it subpixel text
316
+ // antialiasing. `transform` is used only to play the enter/exit slides,
317
+ // where the compositing is what makes them cheap. There is deliberately no
318
+ // `width` transition: a width changes only when the window resizes or when
319
+ // the page itself asks for another layout, and animating one would reflow
320
+ // the column's content on every frame of it.
321
+ // Every duration is `--s-panel-ms`, so a column's move, its neighbour's fade
322
+ // and the chrome recentering around them all run as one motion. The drift
323
+ // eases out (it should read as a slow settle) while the fade runs *linear*
324
+ // across the whole duration — an eased opacity spends its last stretch near
325
+ // zero, which looks like the panel vanishing rather than fading.
326
+ // No `overflow:hidden` here: the scroll container below clips the content
327
+ // itself, and the pair hairline sits in the gutter *outside* the panel.
328
+ // Layering is set from JS (`layout()` and `beginClose`) rather than left to
329
+ // DOM order: a closing panel is no longer part of the reactive list, so
330
+ // where its element sits among the live ones is Aberdeen's business, not a
331
+ // thing to depend on. `LAYER_*` says what the numbers mean.
332
+ "&":
333
+ "position:absolute top:0 bottom:0 left:0 display:flex flex-direction:column " +
334
+ "visibility:visible transition: left var(--s-panel-ms) ease, transform var(--s-panel-ms) ease-out, opacity var(--s-panel-ms) linear, visibility 0s;",
335
+ // The scroll container. Mirrors content mode's `main > .s-content`: same
336
+ // padding, and the same scrollbar inset (see `.s-scroll-y` in main.ts) so a
337
+ // single-column shell is pixel-identical to a non-routed one.
338
+ "> .s-content": "flex:1 min-height:0 overflow-y:auto overflow-x:hidden p:$3",
339
+ "> .s-content.s-scroll-y": "margin-right:$3",
340
+ // A vertical hairline centred in the gutter between two paired smalls,
341
+ // fading out at both ends — the same treatment as the sidebar's `.s-nav-sep`.
342
+ "&.s-panel-sep::before":
343
+ `content:'' position:absolute left:-${GUTTER_PX / 2}px top:0.6rem bottom:0.6rem width:1px ` +
344
+ "background: linear-gradient(to bottom, transparent, $s-faint 18%, $s-faint 82%, transparent);",
345
+ // One vocabulary for every arrival and departure: a gradual fade over a short,
346
+ // slow drift — 8cqw (`cqw`: `.s-main` is the container). Panels appear and
347
+ // leave at the right edge; being crowded out at the left edge is its mirror.
348
+ //
349
+ // The start state of an enter, adopted with transitions off and then
350
+ // dropped, which is what makes the panel settle instead of jumping.
351
+ "&.s-panel-enter": "opacity:0 transition:none transform: translateX(8cqw);",
352
+ // On its way out: fading where it stands, drifting the same short distance,
353
+ // and out of reach while it does. It leaves the DOM when the fade itself
354
+ // ends (see `playExit`), never part-way through it.
355
+ "&.s-panel-closing": "opacity:0 pointer-events:none transform: translateX(8cqw);",
356
+ // Crowded out from under the visible run. It keeps its DOM (and thus its
357
+ // scroll position and half-typed forms), so `display:none` is out —
358
+ // `visibility` takes it out of the rendering instead, but only once the fade
359
+ // has played: a transitioned `visibility` counts as *visible* for the whole
360
+ // duration and flips at the very end. Revealing it again uses the rule above
361
+ // (`visibility 0s`), so it comes back instantly.
362
+ "&.s-panel-hidden":
363
+ "opacity:0 visibility:hidden transform: translateX(-8cqw); " +
364
+ "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);",
365
+ },
366
+ // A window resize (and the very first pass) must track the window instantly,
367
+ // not rubber-band 450ms behind it: the layout engine raises this class on the
368
+ // shell for exactly those passes, applies the new geometry, and drops it
369
+ // after a forced reflow. Beats the standing transitions on specificity.
370
+ ".s-main.s-shell-snap .s-panel": "transition:none",
371
+ // On a narrow shell the single column is edge-to-edge, so there is no inset
372
+ // chrome for the scrollbar to line up with — cancel the `.s-scroll-y` margin
373
+ // (the twin of content mode's rule in main.ts).
374
+ [`@container (max-width: ${NARROW_PX}px)`]: {
375
+ ".s-panel > .s-content.s-scroll-y": "margin-right:0",
376
+ },
377
+ // A minimal "still fetching" hint, centred over the panel's content (which
378
+ // stays mounted underneath, so it can fill in reactively).
379
+ ".s-panel-loading": {
380
+ "&": "position:absolute inset:0 display:flex align-items:center justify-content:center gap:$1 pointer-events:none",
381
+ "i": "width:0.5rem height:0.5rem r:50% background:$s-muted opacity:0.45 animation: s-panel-pulse 1s ease-in-out infinite;",
382
+ "i:nth-child(2)": "animation-delay:0.15s",
383
+ "i:nth-child(3)": "animation-delay:0.3s",
384
+ },
385
+ "@keyframes s-panel-pulse": {
386
+ "0%, 100%": "opacity:0.25 transform:scale(0.8)",
387
+ "50%": "opacity:0.7 transform:scale(1)",
388
+ },
389
+ });
390
+
391
+ // ─── Panel entries ───────────────────────────────────────────────────────────
392
+
393
+ interface PanelEntry {
394
+ /** Unique and stable; the key `$ids` (and thus the DOM) is keyed by. */
395
+ id: number;
396
+ /**
397
+ * Depth in the stack at creation time, and the DOM sort key. Deliberately never
398
+ * updated: rewriting it would make Aberdeen redraw the panel, throwing away the
399
+ * scroll position and half-typed forms rule 5 promises to keep. So after a
400
+ * panel is spliced out of the middle of the stack (see `closePanelAt`) the DOM
401
+ * order goes slightly stale — invisible, since panels are absolutely
402
+ * positioned, beyond a small drift in tab order.
403
+ */
404
+ order: number;
405
+ path: string;
406
+ $page: Page<any>;
407
+ draw: RouteHandler;
408
+ /** Extra per-panel UI state that the panel's own render scope observes. */
409
+ $ui: { holding: boolean };
410
+ el?: HTMLElement;
411
+ /** Set once the panel is on its way out, playing its exit animation. */
412
+ closing?: boolean;
413
+ /** Set while an enter animation is still to be played. */
414
+ enter?: boolean;
415
+ /** Whether the panel has been through a full layout pass (and so may animate). */
416
+ placed?: boolean;
417
+ /** Whether its `loading` hold has already expired, so it can't hold again. */
418
+ holdDone?: boolean;
419
+ /** What the panel asks for, kept in step with its `$page.layout`. */
420
+ layout: "small" | "medium" | "large";
421
+ /**
422
+ * The width it was last laid out at. Set before the panel's content is first
423
+ * drawn, so that content has a real box to measure itself against. Visible
424
+ * panels get a fresh value every pass (widths are a pure function of the
425
+ * content area and small-pairing); hidden and closing panels keep this, so
426
+ * nothing invisible ever reflows.
427
+ */
428
+ width: number;
429
+ }
430
+
431
+ /**
432
+ * What the shell measures out to, and with it the width every panel size gets.
433
+ * A pure function of the window, so it is the same for every panel in a pass.
434
+ */
435
+ interface Geometry {
436
+ /** The body row: everything the columns and the sidebar share. */
437
+ total: number;
438
+ /** What sits beside the columns — the sidebar and its hairline, if shown. */
439
+ chrome: number;
440
+ /** Half the standard content area, or all of it when a half would be too narrow. */
441
+ small: number;
442
+ /** The standard content area: the 1280px page minus the chrome. */
443
+ medium: number;
444
+ /** Everything the window has beside the chrome, with no upper limit. */
445
+ large: number;
446
+ }
447
+
448
+ // ─── Controller ──────────────────────────────────────────────────────────────
449
+
450
+ /** Options the panel stack needs from its shell. */
451
+ export interface PanelStackOptions {
452
+ routes: Routes;
453
+ notFound?: RouteHandler<{}>;
454
+ /** Set `false` to show only the top panel, however much room there is. */
455
+ stacking?: boolean;
456
+ /** The shell's own title, used as the suffix of `document.title`. */
457
+ title?: unknown;
458
+ }
459
+
460
+ /** At most one routed shell per app — that's what `S.panels` is bound to. */
461
+ let active: PanelController | null = null;
462
+
463
+ export class PanelController {
464
+ private compiled: CompiledRoute[];
465
+ private opts: PanelStackOptions;
466
+ /** The live stack, shallow-to-deep. Closing panels are no longer part of it. */
467
+ private live: PanelEntry[] = [];
468
+ private byId = new Map<number, PanelEntry>();
469
+ private nextId = 1;
470
+ /** Drives rendering: panel id → its `order` (used only as the sort key). */
471
+ $ids = A.proxy<Record<string, number>>({});
472
+ /**
473
+ * The live stack's paths and its top panel, for reactive readers: the
474
+ * `document.title` watcher, `main()`'s Escape handling and `S.panels.stack`.
475
+ */
476
+ $state = A.proxy({ paths: [] as string[], topId: 0 });
477
+ private containerEl?: HTMLElement;
478
+ /** The shell's measurements, shared by everything drawn since they were taken. */
479
+ private geom?: Geometry;
480
+ /** The body width at the last layout; a change means a window resize → snap. */
481
+ private lastBodyW = -1;
482
+ private layoutQueued = false;
483
+ private timers = new Set<ReturnType<typeof setTimeout>>();
484
+
485
+ constructor(opts: PanelStackOptions) {
486
+ if (active) {
487
+ throw new Error("Staffa: only one routed S.main() (one with `routes`) can be active at a time");
488
+ }
489
+ active = this;
490
+ this.opts = opts;
491
+ this.compiled = Object.entries(opts.routes).map(([key, draw]) => compileRoute(key, draw));
492
+
493
+ // The router consults this guard before any navigation is applied — ours,
494
+ // a link's, browser back/forward, even a direct route.go() by app code —
495
+ // so every panel the change would remove gets its requestClose asked,
496
+ // exactly once, and a veto leaves the URL and the stack untouched (the
497
+ // router holds the route steady while an async guard is pending, and
498
+ // knows the exact history depth to restore on a vetoed popstate). A
499
+ // guard the app registered before mounting keeps working: it is chained
500
+ // in front of ours — an app veto (or redirect) wins without the panels
501
+ // being asked — and handed back when the shell unmounts.
502
+ const appGuard = route.setGuard((to, from) => {
503
+ const outer = appGuard ? appGuard(to, from) : true;
504
+ if (outer === false) return false;
505
+ if (outer === true) return this.checkChange(to);
506
+ return outer.then((ok) => (ok === false ? false : this.checkChange(to)));
507
+ });
508
+
509
+ // Commit the stack whenever the URL or its snapshot changes — the initial
510
+ // load, our own navigations, and browser back/forward. Anything that
511
+ // reaches this point has already passed the guard above.
512
+ A(() => {
513
+ const target = this.computeTarget();
514
+ A.peek(() => this.propose(target));
515
+ });
516
+
517
+ this.interceptLinks();
518
+ this.watchTitle();
519
+
520
+ A.clean(() => {
521
+ for (const t of this.timers) clearTimeout(t);
522
+ this.timers.clear();
523
+ route.setGuard(appGuard);
524
+ if (active === this) active = null;
525
+ });
526
+ }
527
+
528
+ // ── Stack derivation ───────────────────────────────────────────────────
529
+
530
+ /** Resolve a path to its route handler + params, falling back to `notFound`. */
531
+ private resolve(path: string): { draw: RouteHandler; params: Record<string, any> } {
532
+ const segments = splitPath(path);
533
+ for (const r of this.compiled) {
534
+ const params = matchRoute(r, segments);
535
+ if (params) return { draw: r.draw, params };
536
+ }
537
+ return { draw: this.opts.notFound ?? drawDefaultNotFound, params: {} };
538
+ }
539
+
540
+ private matches(path: string): boolean {
541
+ const segments = splitPath(path);
542
+ return this.compiled.some((r) => matchRoute(r, segments) != null);
543
+ }
544
+
545
+ /**
546
+ * The one derivation rule for origin-less navigation (§2.8): probe every
547
+ * prefix of the path against the route table; the matching prefixes become
548
+ * the stack. Prefixes without a route are simply skipped, so an app that
549
+ * doesn't want one screen stacked under another just doesn't route that
550
+ * prefix. The path itself is always the top panel, matched or not.
551
+ */
552
+ deriveStack(path: string): string[] {
553
+ const segments = splitPath(path);
554
+ const stack: string[] = [];
555
+ for (let i = 1; i < segments.length; i++) {
556
+ const prefix = "/" + segments.slice(0, i).join("/");
557
+ if (this.matches(prefix)) stack.push(prefix);
558
+ }
559
+ stack.push(normalizePath(path));
560
+ return stack;
561
+ }
562
+
563
+ /** The stack a route implies: its snapshot topped by its path, or — without a snapshot — derived. */
564
+ private targetFor(path: string, snapshot: unknown): string[] {
565
+ if (Array.isArray(snapshot)) return snapshot.map(String).concat(normalizePath(path));
566
+ return this.deriveStack(path);
567
+ }
568
+
569
+ /** The stack the current history entry asks for. Subscribes to path + snapshot. */
570
+ private computeTarget(): string[] {
571
+ return this.targetFor(route.current.path, route.current.state.panels);
572
+ }
573
+
574
+ /**
575
+ * The route guard (see `route.setGuard` in the constructor): asked before any
576
+ * route change lands, wherever it came from. Runs the {@link Page.requestClose}
577
+ * guard of every panel the new route's stack would remove — a set defined by
578
+ * the target (the commit reconciles by path), so a derived stack that shares
579
+ * nothing with the live one still asks exactly the panels that are closing.
580
+ */
581
+ private checkChange(to: route.Route): boolean | Promise<boolean> {
582
+ const removed = this.removedBy(this.targetFor(to.path, to.state.panels));
583
+ return removed.length ? runGuards(removed) : true;
584
+ }
585
+
586
+ // ── Commit pipeline ────────────────────────────────────────────────────
587
+
588
+ private paths(): string[] {
589
+ return this.live.map((e) => e.path);
590
+ }
591
+
592
+ /** The live panels a target stack drops — by path, so a splice removes only its own column. */
593
+ private removedBy(target: string[]): PanelEntry[] {
594
+ return this.live.filter((entry) => !target.includes(entry.path));
595
+ }
596
+
597
+ /**
598
+ * Adopt a stack proposed by the URL. Close guards have already been run (and
599
+ * have passed) by the time a route change is visible here — `checkChange` is
600
+ * consulted by the router itself, before anything is applied.
601
+ */
602
+ private propose(target: string[]): void {
603
+ if (sameStack(this.paths(), target)) return;
604
+ this.commit(target, A.peek(route.current, "nav"));
605
+ }
606
+
607
+ /**
608
+ * Apply a target stack: unmount what's gone, mount what's new, animate the
609
+ * difference.
610
+ *
611
+ * Reconciliation is BY PATH (a stack can't hold the same path twice, so that's
612
+ * well-defined): a panel present in both stacks stays mounted *even if its
613
+ * index shifted*, which is what lets a panel be spliced out of the middle
614
+ * (§7) without disturbing the columns above it. A common-prefix diff would
615
+ * remount every one of them, throwing away exactly the scroll and form state
616
+ * rule 5 promises to keep.
617
+ */
618
+ private commit(target: string[], nav: string): void {
619
+ // The panels this commit mounts size themselves as they draw, so make them
620
+ // measure the shell as it is now rather than trusting the last pass's numbers.
621
+ this.geom = undefined;
622
+ const existing = new Map(this.live.map((entry) => [entry.path, entry]));
623
+ const next: PanelEntry[] = [];
624
+ for (const path of target) {
625
+ const kept = existing.get(path);
626
+ if (kept) {
627
+ // Retained: it just takes its new place in the stack. Its `order` (the
628
+ // DOM sort key) deliberately stays put — see PanelEntry.order.
629
+ existing.delete(path);
630
+ next.push(kept);
631
+ continue;
632
+ }
633
+ const entry = this.createEntry(path, next.length);
634
+ // An initial load just appears, and so do panels *revealed* by a back —
635
+ // they belong underneath the ones sliding away. Everything else enters at
636
+ // the right edge, a replacement exactly like a push.
637
+ if (nav !== "load" && nav !== "back") entry.enter = true;
638
+ next.push(entry);
639
+ this.byId.set(entry.id, entry);
640
+ }
641
+ // Whatever the target no longer holds leaves the same way: fading out over
642
+ // the right edge, which is also where its replacement (if any) comes in from.
643
+ for (const entry of existing.values()) this.beginClose(entry);
644
+ this.live = next;
645
+
646
+ A.merge(this.$state, { paths: this.paths(), topId: this.live.length ? this.live[this.live.length - 1].id : 0 });
647
+ for (const entry of this.live) this.$ids[String(entry.id)] = entry.order;
648
+ this.scheduleLayout();
649
+ }
650
+
651
+ private createEntry(path: string, order: number): PanelEntry {
652
+ const { draw, params } = this.resolve(path);
653
+ const entry = {
654
+ id: this.nextId++,
655
+ order,
656
+ path,
657
+ draw,
658
+ $ui: A.proxy({ holding: false }),
659
+ layout: "medium" as const,
660
+ width: 0,
661
+ } as PanelEntry;
662
+ // `close` closes *this* panel, top of the stack or not. It resolves the
663
+ // panel's current depth at call time, so it keeps working after a splice has
664
+ // moved it — and quietly resolves false once the panel is gone.
665
+ entry.$page = A.proxy({
666
+ params,
667
+ path,
668
+ close: () => this.closePanelAt(this.live.indexOf(entry)),
669
+ }) as Page<any>;
670
+ return entry;
671
+ }
672
+
673
+ /**
674
+ * Take a panel out of the shell. The *scope* goes now: its cleaners run this
675
+ * tick, so whatever the panel registered with `A.clean` — subscriptions,
676
+ * timers, an open portal — is torn down when the panel closes, not when its
677
+ * animation is over. Only the element lingers, to play that animation, which
678
+ * is what the `destroy=` hook in `drawPanel` is for: Aberdeen hands the
679
+ * element to {@link playExit} instead of removing it.
680
+ */
681
+ private beginClose(entry: PanelEntry): void {
682
+ entry.closing = true;
683
+ // Frozen one layer below where it was, which is still above everything it
684
+ // was covering: it fades out over the panel it uncovers, and under the one
685
+ // that takes its place (see LAYER_STEP). Set here, while the element is
686
+ // still ours — a moment later the scope, and with it `entry.el`, is gone.
687
+ if (entry.el) entry.el.style.zIndex = String(LAYER_STEP * this.live.indexOf(entry));
688
+ this.byId.delete(entry.id);
689
+ delete this.$ids[String(entry.id)];
690
+ }
691
+
692
+ /**
693
+ * A closed panel's send-off, run by Aberdeen once the panel's scope is gone (so
694
+ * the content it shows is frozen, which is exactly what a departing column
695
+ * should be): it fades where it stands, inert, and leaves the DOM when the fade
696
+ * itself ends. Removing it on a fixed timer instead would race the transition —
697
+ * pull the element a frame early and the panel appears to fade half-way and
698
+ * then vanish. The timeout is just a fallback for when no `transitionend` is
699
+ * coming at all (transitions off, or an element that never got placed).
700
+ */
701
+ private playExit(entry: PanelEntry, el: HTMLElement): void {
702
+ // Only a close is worth animating. A panel being *redrawn* (a reactive
703
+ // dependency in its handler) replaces its element through here too, and that
704
+ // one simply goes, so the new one isn't drawn over a ghost of the old.
705
+ if (!entry.closing) { el.remove(); return; }
706
+ el.classList.add("s-panel-closing");
707
+ el.setAttribute("inert", "");
708
+ const drop = () => {
709
+ clearTimeout(timer);
710
+ this.timers.delete(timer);
711
+ el.remove();
712
+ };
713
+ el.addEventListener("transitionend", (e: TransitionEvent) => {
714
+ if (e.target === el && e.propertyName === "opacity") drop();
715
+ });
716
+ const timer = setTimeout(drop, PANEL_MS + 80);
717
+ this.timers.add(timer);
718
+ }
719
+
720
+ // ── Navigation ─────────────────────────────────────────────────────────
721
+
722
+ /**
723
+ * Navigate back to a stack that is a truncation of the current one — the shared
724
+ * implementation of Escape, a page closing itself, return-links and
725
+ * `S.panels.close()`. `route.back()` prefers the history entry where that
726
+ * panel was on top (with its scroll state intact); when there is no such entry
727
+ * it replaces the current one, carrying the snapshot passed as the fallback.
728
+ * Either way the route guard asks the closing panels first, and the returned
729
+ * promise reports its verdict.
730
+ */
731
+ private goBackTo(target: string[]): Promise<boolean> {
732
+ return route.back({ path: target[target.length - 1] }, { state: { panels: target.slice(0, -1) } });
733
+ }
734
+
735
+ /** Close every panel above `index` (guarded). Resolves `false` when vetoed. */
736
+ closeDownTo(index: number): Promise<boolean> {
737
+ if (index < 0 || index >= this.live.length - 1) return Promise.resolve(false);
738
+ return this.goBackTo(this.paths().slice(0, index + 1));
739
+ }
740
+
741
+ /** Guarded close of the top panel. */
742
+ closeTop(): Promise<boolean> {
743
+ return this.closeDownTo(this.live.length - 2);
744
+ }
745
+
746
+ /**
747
+ * Guarded close of the panel at `index`, top of the stack or not — what a
748
+ * page's own close affordances ({@link Page.close}, a box's ✕) come down to.
749
+ *
750
+ * The top panel pops back to the snapshot beneath it. Any other panel is
751
+ * *spliced* out: its guard runs, the columns above it keep their place and
752
+ * state (the commit reconciles by path), and the URL doesn't change, since the
753
+ * top panel didn't. That still gets its own history entry, so the browser's
754
+ * back button restores the closed column like any other snapshot — which is
755
+ * why it goes through `route.go` here rather than through `navigate()`, whose
756
+ * "link to the panel we're already on" check would see a no-op.
757
+ */
758
+ closePanelAt(index: number): Promise<boolean> {
759
+ if (index < 0 || index >= this.live.length) return Promise.resolve(false);
760
+ if (index === this.live.length - 1) return this.closeTop();
761
+ const target = this.paths().filter((_, i) => i !== index);
762
+ return Promise.resolve(route.go({
763
+ path: target[target.length - 1],
764
+ // The top panel keeps its search params and hash: it isn't going
765
+ // anywhere, and `go()` would otherwise default them away.
766
+ search: A.peek(() => ({ ...route.current.search })),
767
+ hash: A.peek(route.current, "hash"),
768
+ state: { panels: target.slice(0, -1) },
769
+ }));
770
+ }
771
+
772
+ /** Guarded close of whichever panel `path` is open as. False when it isn't open. */
773
+ closeByPath(path: string): Promise<boolean> {
774
+ const wanted = normalizePath(path);
775
+ return this.closePanelAt(this.live.findIndex((entry) => entry.path === wanted));
776
+ }
777
+
778
+ /** Guarded close of the panel whose `.s-panel` element this is. */
779
+ closePanelEl(el: HTMLElement): Promise<boolean> {
780
+ return this.closePanelAt(this.live.findIndex((entry) => entry.el === el));
781
+ }
782
+
783
+ /**
784
+ * Navigate to `href`. `originIndex` is the depth of the panel the link lives
785
+ * in (−1 when it has none — a nav item or a programmatic call, which derives
786
+ * the whole stack instead). `replace` swaps the originating panel rather than
787
+ * stacking on top of it.
788
+ */
789
+ navigate(href: string, originIndex: number, replace = false): void {
790
+ let url: URL;
791
+ try { url = new URL(href, location.href); } catch { return; }
792
+ const path = normalizePath(url.pathname);
793
+ const search = Object.fromEntries(new URLSearchParams(url.search));
794
+ const hash = url.hash;
795
+
796
+ // A link to a panel that is already open is a return, not a navigation —
797
+ // so a stack can never hold the same path twice.
798
+ const open = this.live.findIndex((e) => e.path === path);
799
+ if (open >= 0 && open < this.live.length - 1) { void this.closeDownTo(open); return; }
800
+ if (open >= 0) {
801
+ // The target is the panel we're already on. Going nowhere — but the link
802
+ // may still carry a different search or hash, which belong to the top
803
+ // panel: record that as a history entry, leaving the stack alone (the
804
+ // panel reconciles by path, so it isn't even redrawn).
805
+ if (url.search === location.search && (url.hash || "") === (location.hash || "")) return;
806
+ route.go({ path, search, hash, state: { panels: this.paths().slice(0, -1) } });
807
+ return;
808
+ }
809
+
810
+ // Without an originating panel there is no stack to build on, so derive
811
+ // one — a nav click and a deep link to the same URL land identically.
812
+ // The route guard (checkChange) asks every panel this removes — a set
813
+ // defined by the target stack, wherever those panels happen to sit —
814
+ // before the change is applied; a veto leaves everything untouched.
815
+ const beneath = originIndex < 0
816
+ ? this.deriveStack(path).slice(0, -1)
817
+ : this.paths().slice(0, replace ? originIndex : originIndex + 1);
818
+ route.go({ path, search, hash, state: { panels: beneath } });
819
+ }
820
+
821
+ /** Programmatic push/replace, with the top panel as the implied origin. */
822
+ pushPath(path: string, replace: boolean): void {
823
+ this.navigate(path, this.live.length - 1, replace);
824
+ }
825
+
826
+ // ── Link interception ──────────────────────────────────────────────────
827
+
828
+ /**
829
+ * Link handling through `route.interceptLinks()`, whose handler hook hands us
830
+ * the anchor so we can decide what the click *means*: the originating
831
+ * `.s-panel` (which decides what the click truncates), `data-panel=replace`,
832
+ * and return-to-an-open-panel semantics. The exclusion rules (targets,
833
+ * downloads, modified clicks, external URLs) live in Aberdeen; the close
834
+ * guards run in `checkChange` when our navigation reaches the router.
835
+ */
836
+ private interceptLinks(): void {
837
+ route.interceptLinks((url, anchor) => {
838
+ const panel = anchor.closest<HTMLElement>(".s-panel");
839
+ const originIndex = panel ? this.live.findIndex((entry) => entry.el === panel) : -1;
840
+ this.navigate(url.href, originIndex, anchor.getAttribute("data-panel") === "replace");
841
+ return true;
842
+ });
843
+ }
844
+
845
+ // ── document.title ─────────────────────────────────────────────────────
846
+
847
+ /** `"<page title> · <app title>"`, kept in sync with the top panel. */
848
+ private watchTitle(): void {
849
+ const original = document.title;
850
+ A(() => {
851
+ const entry = this.byId.get(this.$state.topId);
852
+ const pageTitle = entry?.$page.title;
853
+ const appTitle = typeof this.opts.title === "string" ? this.opts.title : undefined;
854
+ const title = pageTitle && appTitle ? `${pageTitle} · ${appTitle}` : pageTitle || appTitle;
855
+ if (title) document.title = title;
856
+ });
857
+ A.clean(() => { document.title = original; });
858
+ }
859
+
860
+ // ── Rendering ──────────────────────────────────────────────────────────
861
+
862
+ /**
863
+ * Draw the panel viewport into the current element. Called by `main()`.
864
+ *
865
+ * There is deliberately no close chrome here — no back rail, no ←: pages
866
+ * provide their own way out (see {@link Page.close} and `S.box`'s `close`
867
+ * option). The shell contributes Escape and the browser's own back button.
868
+ */
869
+ drawStack(): void {
870
+ const container = A("div.s-panels role=main", () => {
871
+ // Published before the first panel draws, rather than from the return
872
+ // value below: a panel sizes itself from the shell's measurements (see
873
+ // `measure`), and the first ones do that while this very call is still
874
+ // running. `A()` without arguments is "the element we're in".
875
+ this.containerEl = A() as HTMLElement;
876
+ A.onEach(
877
+ this.$ids,
878
+ (_order, id) => this.drawPanel(Number(id)),
879
+ (order, id) => [order, Number(id)],
880
+ );
881
+ }) as HTMLElement;
882
+
883
+ if (typeof ResizeObserver !== "undefined") {
884
+ const ro = new ResizeObserver(() => this.layout());
885
+ // The region *and* the body it sits in: the region alone misses a shell
886
+ // resize that the columns happen to absorb, which still re-resolves widths.
887
+ ro.observe(container);
888
+ const body = container.parentElement?.parentElement;
889
+ if (body) ro.observe(body);
890
+ A.clean(() => ro.disconnect());
891
+ }
892
+ A.clean(() => { if (this.containerEl === container) this.containerEl = undefined; });
893
+ this.scheduleLayout();
894
+ }
895
+
896
+ private drawPanel(id: number): void {
897
+ const entry = this.byId.get(id);
898
+ if (!entry) return;
899
+ let el: HTMLElement | undefined;
900
+
901
+ // How much room the panel wants, resolved *before* its content is drawn: an
902
+ // element that arrives without a width has no box for its content to measure
903
+ // itself against until the next frame's layout pass, which is a frame too
904
+ // late for anything that sizes itself from its container. So the panel is
905
+ // created at the width the window gives its layout — "medium" until the page
906
+ // says otherwise. Reactively, too: a page that changes its mind later (when
907
+ // its data arrives, say) reflows in place rather than being redrawn, and the
908
+ // columns beside it slide over to make room.
909
+ A(() => {
910
+ const asked = entry.$page.layout;
911
+ entry.layout = asked === "small" || asked === "large" ? asked : "medium";
912
+ const width = this.roomFor(entry.layout);
913
+ if (!width) return;
914
+ entry.width = width;
915
+ // The first run has no element to put it on yet — it's created with this
916
+ // width, just below. Later runs are the page changing its layout.
917
+ if (!el) return;
918
+ el.style.width = `${width}px`;
919
+ this.scheduleLayout();
920
+ });
921
+
922
+ el = A(`section.s-panel${entry.width ? ` w:${entry.width}px` : ""}`, "destroy=", (node: HTMLElement) => this.playExit(entry, node), () => {
923
+ const contentEl = A("div.s-content", () => {
924
+ entry.draw(entry.$page);
925
+ // After the content, so there is something to scroll when restoring.
926
+ route.persistScroll(entry.path);
927
+ }) as HTMLElement;
928
+ watchVerticalOverflow(contentEl);
929
+
930
+ // The loading hint, in its own scope so flipping the flag doesn't
931
+ // redraw the panel's content. Held-back panels show nothing yet: they
932
+ // are still parked off screen, waiting to slide in with real content.
933
+ A(() => {
934
+ if (!entry.$page.loading || entry.$ui.holding) return;
935
+ A("div.s-panel-loading aria-hidden=true", () => { A("i"); A("i"); A("i"); });
936
+ });
937
+ }) as HTMLElement;
938
+
939
+ entry.el = el;
940
+ // It has its width, but nothing animates from the arbitrary initial spot;
941
+ // `layout()` gives the panel its place in the run (and turns transitions
942
+ // back on) in the upcoming frame, before anything is painted. A redraw (a
943
+ // reactive dependency inside the handler) lands here too, with a brand-new
944
+ // element that has to be placed again before it may animate.
945
+ entry.placed = false;
946
+ el.style.transition = "none";
947
+ A.clean(() => { if (entry.el === el) entry.el = undefined; });
948
+
949
+ // A held-back panel that finishes loading gets to play its enter animation.
950
+ A(() => {
951
+ void entry.$page.loading;
952
+ this.scheduleLayout();
953
+ });
954
+
955
+ this.scheduleLayout();
956
+ }
957
+
958
+ // ── Layout engine ──────────────────────────────────────────────────────
959
+
960
+ scheduleLayout(): void {
961
+ if (this.layoutQueued) return;
962
+ this.layoutQueued = true;
963
+ requestAnimationFrame(() => {
964
+ this.layoutQueued = false;
965
+ this.layout();
966
+ });
967
+ }
968
+
969
+ /**
970
+ * Measure the shell, and with it the width the window gives a panel of each
971
+ * layout. Measured on the *shell*, not on the panel region: the region's width
972
+ * is the layout engine's own output, so reading it back would nail the layout
973
+ * to whatever it happened to be a frame ago. Fractional widths throughout — a
974
+ * rounded column edge would drift a pixel away from the chrome above it.
975
+ *
976
+ * `undefined` while the shell has no width to speak of (it isn't in a document
977
+ * yet, or it's `display:none`); the next pass tries again.
978
+ */
979
+ private measure(): Geometry | undefined {
980
+ const container = this.containerEl;
981
+ const inner = container?.parentElement;
982
+ const body = inner?.parentElement;
983
+ if (!container || !inner || !body) return undefined;
984
+ const total = body.getBoundingClientRect().width;
985
+ if (!total) return undefined;
986
+
987
+ // Everything that sits beside the columns: the sidebar and its hairline,
988
+ // either of which may be display:none on a narrow shell.
989
+ let chrome = 0;
990
+ for (const child of inner.children) {
991
+ if (child !== container) chrome += child.getBoundingClientRect().width;
992
+ }
993
+
994
+ // The standard page is SHELL_PX wide, capped by the window; what it leaves
995
+ // beside the sidebar is the *standard* content area. Widths are a pure
996
+ // function of the window — never of what else is open — so a panel NEVER
997
+ // resizes because a neighbour came or went; only a window resize (the
998
+ // snap pass in `layout`) changes them:
999
+ // - "medium" fills the standard content area exactly;
1000
+ // - "small" is half of it (minus the gutter) whenever that half is still
1001
+ // a usable column, and the whole of it on narrower screens;
1002
+ // - "large" ignores the standard width and takes everything the window
1003
+ // has — which also means nothing ever fits beside it.
1004
+ const medium = Math.max(0, Math.min(SHELL_PX, total) - chrome);
1005
+ const half = (medium - GUTTER_PX) / 2;
1006
+ return {
1007
+ total,
1008
+ chrome,
1009
+ small: half >= PAIR_MIN_PX ? half : medium,
1010
+ medium,
1011
+ large: Math.max(0, total - chrome),
1012
+ };
1013
+ }
1014
+
1015
+ /**
1016
+ * The measurements this pass runs on. Taken once per layout pass and per
1017
+ * commit, and shared with the panels drawn in between — they all size
1018
+ * themselves against the same shell, and a `getBoundingClientRect()` each
1019
+ * would be a forced reflow each, in the middle of building their DOM.
1020
+ */
1021
+ private geometry(): Geometry | undefined {
1022
+ return (this.geom ??= this.measure());
1023
+ }
1024
+
1025
+ /** How wide a panel of this layout is, right now; 0 while the shell can't be measured. */
1026
+ private roomFor(layout: PanelEntry["layout"]): number {
1027
+ return this.geometry()?.[layout] ?? 0;
1028
+ }
1029
+
1030
+ /**
1031
+ * Size and position every panel, and publish the width of the whole ensemble
1032
+ * (sidebar + separator + columns) for the shell to centre itself on.
1033
+ *
1034
+ * This is everything CSS can't work out for itself: which panels exist, which
1035
+ * of them are visible, how wide each one is and where it sits. All the motion
1036
+ * between two of these arrangements is CSS's job.
1037
+ */
1038
+ private layout(): void {
1039
+ const container = this.containerEl;
1040
+ const shell = container?.closest<HTMLElement>(".s-main");
1041
+ if (!container || !shell) return;
1042
+ const n = this.live.length;
1043
+ // A panel that hasn't drawn yet has no width to contribute, which would make
1044
+ // this pass's arithmetic (and any enter animation it triggers) meaningless.
1045
+ // Every mount schedules another pass, so simply wait for it.
1046
+ if (!n || this.live.some((entry) => !entry.el)) return;
1047
+
1048
+ // This pass measures afresh — it is the one thing that runs after a resize.
1049
+ this.geom = undefined;
1050
+ const geom = this.geometry();
1051
+ if (!geom) return;
1052
+
1053
+ const stacking = this.opts.stacking !== false;
1054
+
1055
+ // A window resize (or the very first pass) must be adopted instantly —
1056
+ // geometry tracking the window through a 450ms transition reads as lag,
1057
+ // and a shell animating itself into place on load reads as a glitch.
1058
+ // `.s-shell-snap` suppresses every standing transition for this one pass.
1059
+ const snap = this.lastBodyW !== geom.total;
1060
+ if (snap) {
1061
+ this.lastBodyW = geom.total;
1062
+ shell.classList.add("s-shell-snap");
1063
+ }
1064
+
1065
+ const width = (entry: PanelEntry) => geom[entry.layout];
1066
+
1067
+ // The visible run: as many top-of-stack panels as the window fits, at the
1068
+ // sizes the window gives them. The top panel always shows.
1069
+ let first = n - 1;
1070
+ let runSum = width(this.live[first]);
1071
+ if (stacking) {
1072
+ for (let i = n - 2; i >= 0; i--) {
1073
+ const sum = runSum + GUTTER_PX + width(this.live[i]);
1074
+ if (sum > geom.large) break;
1075
+ runSum = sum;
1076
+ first = i;
1077
+ }
1078
+ }
1079
+
1080
+ // The content area holds the run, but is never smaller than the standard
1081
+ // page (a lone small leaves its other half open — which is exactly where
1082
+ // the next small lands, without anything on screen moving) and never
1083
+ // wider than the window. So the page is the familiar 1280px until extra
1084
+ // columns genuinely fit, and stretches — centred — to hold the ones that
1085
+ // do; with a "large" up that's the window's edges.
1086
+ const area = Math.min(geom.large, Math.max(geom.medium, runSum));
1087
+
1088
+ for (let i = first; i < n; i++) this.live[i].width = width(this.live[i]);
1089
+ // Panels that have never been visible get their would-be width too, so a
1090
+ // reveal doesn't start from nothing.
1091
+ for (const entry of this.live) {
1092
+ if (!entry.width) entry.width = width(entry);
1093
+ }
1094
+
1095
+ // The chrome above and below the body caps itself to the ensemble width,
1096
+ // keeping everything centred and aligned however far the area stretches.
1097
+ // The consumers transition their max-width (see main.ts), so the
1098
+ // recentring plays along with the panel that caused it instead of
1099
+ // snapping.
1100
+ shell.style.setProperty("--s-shell-w", `${geom.chrome + area}px`);
1101
+
1102
+ // Phase 1 — every panel's *start* state for this frame. Panels already on
1103
+ // screen simply move (their standing transition animates it); freshly
1104
+ // mounted ones still have transitions switched off, so what we set here is
1105
+ // adopted instantly and becomes the "before" of their enter animation.
1106
+ const fresh: PanelEntry[] = [];
1107
+ let x = 0;
1108
+ for (let i = 0; i < n; i++) {
1109
+ const entry = this.live[i];
1110
+ const el = entry.el!;
1111
+ const shown = i >= first;
1112
+ // Visible panels are left-aligned in the content area, a gutter apart;
1113
+ // hidden ones park at its left edge, keeping their last width. Deeper
1114
+ // panels layer over shallower ones, each on the odd layer for its depth
1115
+ // (see LAYER_STEP).
1116
+ place(el, shown ? x : 0, entry.width, LAYER_STEP * i + 1);
1117
+ if (shown) x += entry.width + GUTTER_PX;
1118
+ el.classList.toggle("s-panel-sep", shown && i > first);
1119
+ // Hidden panels fade out over the left edge and, once faded, stop being
1120
+ // rendered at all — but they keep their DOM, and their scroll position.
1121
+ el.classList.toggle("s-panel-hidden", !shown);
1122
+ el.toggleAttribute("inert", !shown);
1123
+ if (entry.placed) continue;
1124
+ fresh.push(entry);
1125
+ // A panel that mounts while still fetching holds here for a moment, so
1126
+ // it can enter with real content instead of an empty column.
1127
+ if (!A.peek(entry.$page, "loading") || entry.holdDone) entry.$ui.holding = false;
1128
+ else if (!entry.$ui.holding) { entry.$ui.holding = true; this.holdEnter(entry); }
1129
+ // Already at its resting place; the enter animation is the offset (and
1130
+ // the transparency) it starts from, one edge to the right.
1131
+ if (entry.enter && shown) el.classList.add("s-panel-enter");
1132
+ }
1133
+
1134
+ // Phase 2 — force the browser to adopt those start states (and, on a snap
1135
+ // pass, the transition-free geometry) as the ones to animate *from*.
1136
+ // (Reading a layout property is what does it.)
1137
+ if (fresh.length || snap) void container.offsetWidth;
1138
+ if (snap) shell.classList.remove("s-shell-snap");
1139
+ // Phase 3 — transitions back on, start state dropped, and off they go.
1140
+ for (const entry of fresh) {
1141
+ if (entry.$ui.holding) continue;
1142
+ entry.el!.style.transition = "";
1143
+ entry.el!.classList.remove("s-panel-enter");
1144
+ entry.enter = false;
1145
+ entry.placed = true;
1146
+ }
1147
+ }
1148
+
1149
+ /** Let a `loading` panel's enter animation wait — but not indefinitely. */
1150
+ private holdEnter(entry: PanelEntry): void {
1151
+ const timer = setTimeout(() => {
1152
+ this.timers.delete(timer);
1153
+ entry.holdDone = true;
1154
+ if (entry.$ui.holding) {
1155
+ entry.$ui.holding = false;
1156
+ this.scheduleLayout();
1157
+ }
1158
+ }, LOADING_HOLD_MS);
1159
+ this.timers.add(timer);
1160
+ }
1161
+ }
1162
+
1163
+ /** Put a panel at rest: `x` from the region's left edge, `width` pixels wide, on layer `z`. */
1164
+ function place(el: HTMLElement, x: number, width: number, z: number): void {
1165
+ el.style.left = `${x}px`;
1166
+ el.style.width = `${width}px`;
1167
+ el.style.zIndex = String(z);
1168
+ }
1169
+
1170
+ // ─── Guards ──────────────────────────────────────────────────────────────────
1171
+
1172
+ /**
1173
+ * Ask every panel being removed, deepest first, whether it may go. Returns a
1174
+ * plain boolean when no guard needs awaiting, so the common case stays
1175
+ * synchronous (and screenshots stay deterministic).
1176
+ */
1177
+ function runGuards(removed: PanelEntry[]): boolean | Promise<boolean> {
1178
+ const list = [...removed].reverse();
1179
+ let i = 0;
1180
+ const step = (): boolean | Promise<boolean> => {
1181
+ while (i < list.length) {
1182
+ const guard = A.peek(list[i++].$page, "requestClose");
1183
+ if (!guard) continue;
1184
+ let verdict: boolean | Promise<boolean>;
1185
+ try {
1186
+ verdict = guard();
1187
+ } catch (e) {
1188
+ console.error(e);
1189
+ return false;
1190
+ }
1191
+ if (verdict === false) return false;
1192
+ if (verdict !== true) return Promise.resolve(verdict).then((ok) => (ok === false ? false : step()));
1193
+ }
1194
+ return true;
1195
+ };
1196
+ return step();
1197
+ }
1198
+
1199
+ // ─── Helpers ─────────────────────────────────────────────────────────────────
1200
+
1201
+ function sameStack(a: string[], b: string[]): boolean {
1202
+ return a.length === b.length && a.every((v, i) => v === b[i]);
1203
+ }
1204
+
1205
+ function drawDefaultNotFound($page: Page<{}>): void {
1206
+ A("p fg:$s-muted", () => A("#", `No page at ${$page.path}`));
1207
+ }
1208
+
1209
+ /**
1210
+ * Toggle `.s-scroll-y` on `el` whenever a vertical scrollbar is eating into its
1211
+ * width, so CSS can inset the bar from the panel's edge. Same trick (and the
1212
+ * same reasoning) as content mode's `watchVerticalOverflow` in main.ts.
1213
+ */
1214
+ function watchVerticalOverflow(el: HTMLElement): void {
1215
+ if (typeof ResizeObserver === "undefined") return;
1216
+ const update = () => el.classList.toggle("s-scroll-y", el.offsetWidth > el.clientWidth);
1217
+ const ro = new ResizeObserver(update);
1218
+ ro.observe(el);
1219
+ if (el.firstElementChild) ro.observe(el.firstElementChild);
1220
+ update();
1221
+ A.clean(() => ro.disconnect());
1222
+ }
1223
+
1224
+ // ─── Public helpers ──────────────────────────────────────────────────────────
1225
+
1226
+ /**
1227
+ * Navigating the routed `S.main()` shell from code, for the times it isn't a
1228
+ * link click, such as opening the screen for a record you just created.
1229
+ *
1230
+ * The same rules as a link click apply: pushing a path that is already open
1231
+ * goes back to it rather than opening it twice, and anything that would close a
1232
+ * panel asks its {@link Page.requestClose} first.
1233
+ *
1234
+ * @example
1235
+ * ```ts
1236
+ * S.button({ content: "New task", click: async () => {
1237
+ * const task = await createTask();
1238
+ * S.panels.push(`/tasks/${task.id}`);
1239
+ * }});
1240
+ * ```
1241
+ */
1242
+ export const panels = {
1243
+ /** Opens `path` in a new panel on top of the top one. */
1244
+ push(path: string): void {
1245
+ requireActive().pushPath(path, false);
1246
+ },
1247
+ /**
1248
+ * Opens `path` in place of the top panel, which closes (asking its
1249
+ * {@link Page.requestClose} first). The panels beneath it stay as they are.
1250
+ */
1251
+ replace(path: string): void {
1252
+ requireActive().pushPath(path, true);
1253
+ },
1254
+ /**
1255
+ * Closes the top panel, or, given a `path`, whichever panel is open at it,
1256
+ * asking {@link Page.requestClose} first. A panel that isn't on top is taken
1257
+ * out on its own, leaving the columns to its right exactly as they are.
1258
+ *
1259
+ * Resolves `false` if the panel didn't close: `requestClose` said no, `path`
1260
+ * isn't open, or another navigation got there first.
1261
+ */
1262
+ close(path?: string): Promise<boolean> {
1263
+ const ctl = requireActive();
1264
+ return path == null ? ctl.closeTop() : ctl.closeByPath(path);
1265
+ },
1266
+ /** The paths of the open panels, oldest first. Reactive: safe to read in a scope. */
1267
+ get stack(): readonly string[] {
1268
+ return active ? active.$state.paths : [];
1269
+ },
1270
+ };
1271
+
1272
+ function requireActive(): PanelController {
1273
+ if (!active) throw new Error("Staffa: S.panels needs a routed S.main() (one with `routes`) to be mounted");
1274
+ return active;
1275
+ }
1276
+
1277
+ /**
1278
+ * Closes the panel `el` sits in, working out which one that is from the DOM.
1279
+ * That is what lets a close button work without being handed a `$page`, from
1280
+ * any column, whether or not it is on top. Used by `S.box`'s `close: true`.
1281
+ *
1282
+ * Outside a routed shell (or outside any panel, such as a box in a dialog) there is
1283
+ * nothing to close: it warns and resolves `false`.
1284
+ */
1285
+ export function closeContainingPanel(el: Element | null | undefined): Promise<boolean> {
1286
+ const panelEl = el?.closest<HTMLElement>(".s-panel");
1287
+ if (!active || !panelEl) {
1288
+ console.warn("Staffa: `close: true` needs to be drawn inside a panel of a routed S.main()");
1289
+ return Promise.resolve(false);
1290
+ }
1291
+ return active.closePanelEl(panelEl);
1292
+ }