@panyam/tsappkit-dock 0.0.0-stage → 0.7.9

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.
package/src/dock.ts ADDED
@@ -0,0 +1,566 @@
1
+ import { DockviewComponent, themeDark, themeLight } from "dockview-core";
2
+ import type { DockviewApi, IContentRenderer, IHeaderActionsRenderer } from "dockview-core";
3
+ import { DRAWER_DEFAULT, type DrawerEdge } from "./drawer.js";
4
+ import { DrawerView, type DrawerConfig } from "./drawerView.js";
5
+ import {
6
+ documentTheme,
7
+ loadLayout,
8
+ panelsToReconcile,
9
+ saveLayout,
10
+ type DockStorage,
11
+ type PanelDef,
12
+ type PanelPosition,
13
+ type PanelSpec,
14
+ type Placement,
15
+ type SavedDrawers,
16
+ } from "./layout.js";
17
+
18
+ const EDGES: readonly DrawerEdge[] = ["left", "right", "top", "bottom"];
19
+
20
+ /** What `createDock` needs. */
21
+ export interface DockOptions {
22
+ /** The element dockview renders into. It needs a size, as dockview fills it. */
23
+ container: HTMLElement;
24
+ /** The panel registry, in a stable order. These are the panels the Panels menu lists. */
25
+ panels: readonly PanelDef[];
26
+ /**
27
+ * Describes a panel the registry doesn't list, such as one per document the reader opens.
28
+ * Return undefined for an id that isn't one. A resolvable panel opens with `show(id)`, can be
29
+ * placed anywhere, and is kept when a saved layout names it. The Panels menu lists it while it's
30
+ * open.
31
+ */
32
+ resolve?: (id: string) => PanelDef | undefined;
33
+ /**
34
+ * The arrangement used when nothing is saved, after a rejected save, and on `reset`. Either
35
+ * `addPanel` specs as data, or a function that builds it on the api, for an app that sizes
36
+ * groups after adding them. Registry panels whose `defaultPlacement` is a drawer or a float go
37
+ * there afterwards, whichever form this takes.
38
+ */
39
+ defaultLayout: readonly PanelSpec[] | ((api: DockviewApi) => void);
40
+ /**
41
+ * Returns the element a panel shows. The dock calls it each time the panel arrives somewhere: in
42
+ * the grid, in a float, or in a drawer. Return the same element every time if its content should
43
+ * survive a move, a close and a reopen. It's only called with ids the registry or `resolve` knows.
44
+ */
45
+ hostFor: (id: string) => HTMLElement;
46
+ /**
47
+ * Called when a panel leaves where it was, with the element `hostFor` gave it, already detached.
48
+ * Closing a panel calls it, and so does moving it between the grid and a drawer, before `hostFor`
49
+ * is called for the new place. Moving it between the grid and a float doesn't, since dockview
50
+ * keeps the element. Clearing the layout, as `reset` does, calls it for every open panel.
51
+ */
52
+ release?: (id: string, el: HTMLElement) => void;
53
+ /** Where the layout is saved, usually `localStorage`. Null or absent: nothing is saved. */
54
+ storage?: DockStorage | null;
55
+ /** The storage key. Required with `storage`. */
56
+ key?: string;
57
+ /**
58
+ * Returns the dock's theme. It is read at creation, when `<html data-theme>` changes, when the
59
+ * OS colour scheme changes, and on `applyTheme()`. Default: `documentTheme()`.
60
+ */
61
+ theme?: () => "light" | "dark";
62
+ /** Each edge's drawer size and bounds. An edge left out gets the defaults from drawer.ts. */
63
+ drawers?: Partial<Record<DrawerEdge, DrawerConfig>>;
64
+ /**
65
+ * The element drawers are laid over, and the box their sizes are measured against. Default
66
+ * `container`. The dock makes it `position: relative` if it's static.
67
+ */
68
+ drawerHost?: HTMLElement;
69
+ /**
70
+ * Whether each dockview group gets a ⋯ button with Dock, Float and the four drawers for its
71
+ * active panel. Default true. Drawer tabs always have one.
72
+ */
73
+ moveMenu?: boolean;
74
+ }
75
+
76
+ /** A dock made by `createDock`. */
77
+ export interface Dock {
78
+ /** The dockview api, for anything the dock doesn't wrap. */
79
+ readonly api: DockviewApi;
80
+ /**
81
+ * Brings a panel to the front wherever it is, opening its drawer if it's in one. A closed panel
82
+ * opens at its `defaultPlacement`. It returns false, and does nothing, for an id that neither the
83
+ * registry nor `resolve` knows.
84
+ */
85
+ show(id: string): boolean;
86
+ /**
87
+ * Moves a panel to `target` and brings it to the front. A closed panel opens there. False for an
88
+ * unknown id.
89
+ */
90
+ place(id: string, target: Placement): boolean;
91
+ /** Where a panel is now, or null when it's closed. */
92
+ where(id: string): Placement | null;
93
+ /** Opens a closed panel or closes an open one. False for an unknown id. */
94
+ toggle(id: string): boolean;
95
+ /**
96
+ * Opens or closes the drawer on `edge`, or flips it when `open` is absent. An empty drawer stays
97
+ * closed. Returns whether it's open afterwards.
98
+ */
99
+ toggleDrawer(edge: DrawerEdge, open?: boolean): boolean;
100
+ /**
101
+ * Forgets the saved layout and applies the default one, drawers included. Panels keep their
102
+ * `hostFor` elements.
103
+ */
104
+ reset(): void;
105
+ /** Reads `theme` again and applies it. For a theme setting the dock doesn't watch. */
106
+ applyTheme(): void;
107
+ /**
108
+ * Adds a Panels menu button to `host`. Its list has one item per registry panel and per open
109
+ * resolved panel, each toggling its panel, with a ✓ on the open ones and where a panel is when
110
+ * it's not in the grid, and then Reset layout. Returns a function that removes it. The elements
111
+ * carry `dock-panels-*` classes and no styles beyond showing and hiding the list.
112
+ */
113
+ panelsMenu(host: HTMLElement): () => void;
114
+ /**
115
+ * Saves the layout, stops watching the theme, removes the menus and drawers, and disposes of
116
+ * dockview. Panels in drawers are released. Changes are otherwise saved a microtask after
117
+ * dockview reports them. A second call does nothing.
118
+ */
119
+ dispose(): void;
120
+ }
121
+
122
+ const placementLabel = (p: Placement | null): string =>
123
+ !p || p.kind === "grid" ? "" : p.kind === "float" ? " · float" : ` · ${p.edge} drawer`;
124
+
125
+ /**
126
+ * Builds a dockview dock from a panel registry. It restores the saved layout when there is one,
127
+ * drawers included, opens the panels added to the registry since it was saved, and closes the
128
+ * ones nothing knows any more. A save that dockview rejects is removed and the default layout
129
+ * applied. Every change after that is saved.
130
+ *
131
+ * Content lives outside dockview. `hostFor` hands an element to a panel when it arrives somewhere,
132
+ * and `release` hands it back when it leaves, so an app can keep a panel's content alive while the
133
+ * panel is closed or moving between the grid and a drawer.
134
+ */
135
+ export function createDock(opts: DockOptions): Dock {
136
+ const { container, panels, hostFor, release } = opts;
137
+ const storage = opts.storage ?? null;
138
+ const key = opts.key ?? "";
139
+ if (storage && !key) throw new Error("createDock: storage needs a key");
140
+ const theme = opts.theme ?? (() => documentTheme(container.ownerDocument));
141
+ const doc = container.ownerDocument;
142
+ const byId = new Map(panels.map((p) => [p.id, p]));
143
+ const specs = Array.isArray(opts.defaultLayout) ? (opts.defaultLayout as readonly PanelSpec[]) : null;
144
+ const cleanups: (() => void)[] = [];
145
+ const drawerHost = opts.drawerHost ?? container;
146
+ const drawers = new Map<DrawerEdge, DrawerView>();
147
+ let disposed = false;
148
+ // Set while the dock rebuilds itself, so the drawers' change hooks don't save a half-built state.
149
+ let quiet = 0;
150
+
151
+ const defOf = (id: string): PanelDef | undefined => {
152
+ const known = byId.get(id);
153
+ if (known) return known;
154
+ const def = opts.resolve?.(id);
155
+ return def && def.id === id ? def : undefined;
156
+ };
157
+
158
+ const renderer = (id: string): IContentRenderer => {
159
+ if (!defOf(id)) return { element: doc.createElement("div"), init: () => {} };
160
+ const element = hostFor(id);
161
+ return { element, init: () => {}, dispose: () => release?.(id, element) };
162
+ };
163
+
164
+ const component = new DockviewComponent(container, {
165
+ createComponent: (o) => renderer(o.id),
166
+ // "always" keeps a background tab's content attached, only hidden, in a layer dockview
167
+ // positions over the group. The default detaches it, and an app that finds its content by id
168
+ // at startup would miss the panels behind a tab. The layer also means dragging a tab between
169
+ // groups doesn't re-parent the content, so an iframe in it doesn't reload.
170
+ defaultRenderer: "always",
171
+ theme: theme() === "dark" ? themeDark : themeLight,
172
+ ...(opts.moveMenu === false ? {} : { createRightHeaderActionComponent: () => headerMenu() }),
173
+ });
174
+ const api = component.api;
175
+
176
+ // ---- where panels are ----
177
+
178
+ const drawerWith = (id: string): DrawerView | undefined => [...drawers.values()].find((d) => d.has(id));
179
+
180
+ const where = (id: string): Placement | null => {
181
+ const d = drawerWith(id);
182
+ if (d) return { kind: "drawer", edge: d.edge };
183
+ const panel = api.getPanel(id);
184
+ if (!panel) return null;
185
+ return panel.group.api.location.type === "floating" ? { kind: "float" } : { kind: "grid" };
186
+ };
187
+
188
+ const same = (a: Placement | null, b: Placement): boolean =>
189
+ !!a && a.kind === b.kind && (a.kind !== "drawer" || (b.kind === "drawer" && a.edge === b.edge));
190
+
191
+ // ---- drawers ----
192
+
193
+ const drawer = (edge: DrawerEdge): DrawerView => {
194
+ let d = drawers.get(edge);
195
+ if (!d) {
196
+ if (doc.defaultView?.getComputedStyle(drawerHost).position === "static") drawerHost.style.position = "relative";
197
+ d = new DrawerView(edge, drawerHost, opts.drawers?.[edge] ?? {}, { changed: () => save(), menu: (anchor, id) => moveMenu(anchor, id) });
198
+ drawers.set(edge, d);
199
+ }
200
+ return d;
201
+ };
202
+
203
+ const drawerStates = (): SavedDrawers => {
204
+ const out: SavedDrawers = {};
205
+ // A drawer is saved once it has held a panel or been resized, so an empty one keeps its size.
206
+ for (const [edge, d] of drawers) if (d.ids.length || d.size !== (opts.drawers?.[edge]?.size ?? DRAWER_DEFAULT)) out[edge] = d.state();
207
+ return out;
208
+ };
209
+
210
+ // ---- moving panels ----
211
+
212
+ const usable = (p?: PanelPosition): p is PanelPosition => !!p && (!p.referencePanel || !!api.getPanel(p.referencePanel));
213
+
214
+ const addToGrid = (id: string): void => {
215
+ const def = defOf(id)!;
216
+ const spec = specs?.find((s) => s.id === id);
217
+ const position = [def.position, spec?.position].find(usable);
218
+ api.addPanel({ id, component: id, title: def.title, ...(position ? { position } : {}) });
219
+ };
220
+
221
+ const enter = (id: string, target: Placement): void => {
222
+ if (target.kind === "drawer") {
223
+ drawer(target.edge).add(id, defOf(id)!.title, hostFor(id));
224
+ return;
225
+ }
226
+ if (!api.getPanel(id)) addToGrid(id);
227
+ const panel = api.getPanel(id)!;
228
+ if (target.kind === "float" && panel.group.api.location.type !== "floating") api.addFloatingGroup(panel);
229
+ };
230
+
231
+ const leave = (id: string): void => {
232
+ const d = drawerWith(id);
233
+ if (d) {
234
+ const el = d.remove(id);
235
+ if (el) release?.(id, el);
236
+ return;
237
+ }
238
+ const panel = api.getPanel(id);
239
+ if (panel) api.removePanel(panel);
240
+ };
241
+
242
+ const reveal = (id: string): void => {
243
+ const d = drawerWith(id);
244
+ if (d) {
245
+ d.activate(id);
246
+ d.setOpen(true);
247
+ return;
248
+ }
249
+ api.getPanel(id)?.api.setActive();
250
+ };
251
+
252
+ const place = (id: string, target: Placement): boolean => {
253
+ if (!defOf(id)) return false;
254
+ const now = where(id);
255
+ if (!same(now, target)) {
256
+ // Grid to float stays inside dockview, which moves the group and keeps the element. Every
257
+ // other move goes out through release and back in through hostFor.
258
+ if (!(now?.kind === "grid" && target.kind === "float")) leave(id);
259
+ enter(id, target);
260
+ }
261
+ reveal(id);
262
+ save();
263
+ return true;
264
+ };
265
+
266
+ const show = (id: string): boolean => {
267
+ const def = defOf(id);
268
+ if (!def) return false;
269
+ if (!where(id)) enter(id, def.defaultPlacement ?? { kind: "grid" });
270
+ reveal(id);
271
+ save();
272
+ return true;
273
+ };
274
+
275
+ const toggle = (id: string): boolean => {
276
+ if (!defOf(id)) return false;
277
+ if (where(id)) {
278
+ leave(id);
279
+ save();
280
+ return true;
281
+ }
282
+ return show(id);
283
+ };
284
+
285
+ // ---- default layout, restore, reset ----
286
+
287
+ const applyDefault = (): void => {
288
+ const elsewhere = (def?: PanelDef) => !!def?.defaultPlacement && def.defaultPlacement.kind === "drawer";
289
+ if (specs) {
290
+ for (const spec of specs) {
291
+ const def = byId.get(spec.id);
292
+ if (!def || elsewhere(def) || api.getPanel(spec.id)) continue;
293
+ const position = usable(spec.position) ? spec.position : undefined;
294
+ api.addPanel({ id: spec.id, component: spec.id, title: spec.title ?? def.title, ...(position ? { position } : {}) });
295
+ }
296
+ } else {
297
+ (opts.defaultLayout as (api: DockviewApi) => void)(api);
298
+ }
299
+ for (const def of panels) {
300
+ const p = def.defaultPlacement;
301
+ if (!p || p.kind === "grid") continue;
302
+ if (p.kind === "drawer" && !where(def.id)) enter(def.id, p);
303
+ if (p.kind === "float" && (where(def.id)?.kind ?? "grid") === "grid") enter(def.id, p);
304
+ }
305
+ };
306
+
307
+ const clearDrawers = (): void => {
308
+ for (const d of drawers.values()) {
309
+ for (const id of d.ids) leave(id);
310
+ d.setOpen(false, false);
311
+ d.setSize(opts.drawers?.[d.edge]?.size ?? DRAWER_DEFAULT, false);
312
+ }
313
+ };
314
+
315
+ const restoreDrawers = (saved: SavedDrawers): void => {
316
+ for (const edge of EDGES) {
317
+ const s = saved[edge];
318
+ if (!s) continue;
319
+ const d = drawer(edge);
320
+ if (typeof s.size === "number" && s.size > 0) d.setSize(s.size, false);
321
+ for (const id of Array.isArray(s.panels) ? s.panels : []) {
322
+ const def = defOf(id);
323
+ if (def && !where(id)) d.add(id, def.title, hostFor(id));
324
+ }
325
+ if (s.active) d.activate(s.active, false);
326
+ if (s.open) d.setOpen(true, false);
327
+ }
328
+ };
329
+
330
+ const restore = (): void => {
331
+ const saved = storage ? loadLayout(storage, key) : null;
332
+ if (!saved) {
333
+ applyDefault();
334
+ return;
335
+ }
336
+ try {
337
+ api.fromJSON(saved.layout as Parameters<DockviewApi["fromJSON"]>[0]);
338
+ for (const panel of [...api.panels]) if (!defOf(panel.id)) api.removePanel(panel);
339
+ restoreDrawers(saved.drawers);
340
+ for (const id of panelsToReconcile(saved.savedPanels, panels)) {
341
+ if (!where(id)) enter(id, byId.get(id)!.defaultPlacement ?? { kind: "grid" });
342
+ }
343
+ } catch (err) {
344
+ console.warn("tsappkit-dock: saved layout rejected, using the default", err);
345
+ storage?.removeItem(key);
346
+ clearDrawers();
347
+ api.clear();
348
+ applyDefault();
349
+ }
350
+ };
351
+
352
+ const save = (): void => {
353
+ if (quiet || disposed || !storage) return;
354
+ saveLayout(storage, key, panels, api.toJSON(), drawerStates());
355
+ };
356
+
357
+ const reset = (): void => {
358
+ quiet++;
359
+ try {
360
+ storage?.removeItem(key);
361
+ clearDrawers();
362
+ api.clear();
363
+ applyDefault();
364
+ } finally {
365
+ quiet--;
366
+ }
367
+ save();
368
+ };
369
+
370
+ quiet++;
371
+ try {
372
+ restore();
373
+ } finally {
374
+ quiet--;
375
+ }
376
+ if (storage) {
377
+ // Save what restore built, so the save names today's registry and a rejected save is replaced.
378
+ save();
379
+ const sub = api.onDidLayoutChange(() => save());
380
+ cleanups.push(() => sub.dispose());
381
+ }
382
+
383
+ // ---- theme ----
384
+
385
+ const applyTheme = (): void => component.updateOptions({ theme: theme() === "dark" ? themeDark : themeLight });
386
+ const view = doc.defaultView;
387
+ if (view?.MutationObserver) {
388
+ const mo = new view.MutationObserver(applyTheme);
389
+ mo.observe(doc.documentElement, { attributes: true, attributeFilter: ["data-theme"] });
390
+ cleanups.push(() => mo.disconnect());
391
+ }
392
+ const mq = view?.matchMedia?.("(prefers-color-scheme: dark)");
393
+ if (mq?.addEventListener) {
394
+ mq.addEventListener("change", applyTheme);
395
+ cleanups.push(() => mq.removeEventListener("change", applyTheme));
396
+ }
397
+
398
+ const escape = (e: KeyboardEvent): void => {
399
+ if (e.key !== "Escape") return;
400
+ closeMenu();
401
+ for (const d of drawers.values()) d.setOpen(false);
402
+ };
403
+ doc.addEventListener("keydown", escape);
404
+ cleanups.push(() => doc.removeEventListener("keydown", escape));
405
+
406
+ // ---- menus ----
407
+
408
+ let menu: HTMLElement | null = null;
409
+ const closeMenu = (): void => {
410
+ menu?.remove();
411
+ menu = null;
412
+ };
413
+ const outside = (e: Event): void => {
414
+ if (menu && !menu.contains(e.target as Node)) closeMenu();
415
+ };
416
+ doc.addEventListener("pointerdown", outside, true);
417
+ cleanups.push(() => doc.removeEventListener("pointerdown", outside, true), closeMenu);
418
+
419
+ const moveItems = (id: string): [string, Placement | null][] => {
420
+ const now = where(id);
421
+ const items: [string, Placement | null][] = [];
422
+ if (now?.kind !== "grid") items.push(["Dock", { kind: "grid" }]);
423
+ if (now?.kind !== "float") items.push(["Float", { kind: "float" }]);
424
+ for (const edge of EDGES) {
425
+ if (!(now?.kind === "drawer" && now.edge === edge)) items.push([`Move to ${edge} drawer`, { kind: "drawer", edge }]);
426
+ }
427
+ items.push(["Close", null]);
428
+ return items;
429
+ };
430
+
431
+ // The ⋯ menu for one panel: Dock, Float, the four drawers and Close, leaving out where it is.
432
+ const moveMenu = (anchor: HTMLElement, id: string): void => {
433
+ closeMenu();
434
+ const list = doc.createElement("div");
435
+ list.className = "dock-menu";
436
+ list.setAttribute("role", "menu");
437
+ list.dataset.panel = id;
438
+ const r = anchor.getBoundingClientRect();
439
+ Object.assign(list.style, { position: "fixed", left: `${Math.round(r.left)}px`, top: `${Math.round(r.bottom + 2)}px`, zIndex: "calc(var(--dv-overlay-z-index, 999) + 300)" });
440
+ for (const [label, target] of moveItems(id)) {
441
+ const b = doc.createElement("button");
442
+ b.type = "button";
443
+ b.className = "dock-menu-item";
444
+ b.setAttribute("role", "menuitem");
445
+ b.textContent = label;
446
+ b.addEventListener("click", () => {
447
+ closeMenu();
448
+ if (target) place(id, target);
449
+ else toggle(id);
450
+ });
451
+ list.appendChild(b);
452
+ }
453
+ doc.body.appendChild(list);
454
+ menu = list;
455
+ };
456
+
457
+ function headerMenu(): IHeaderActionsRenderer {
458
+ const btn = doc.createElement("button");
459
+ btn.type = "button";
460
+ btn.className = "dock-move-btn";
461
+ btn.textContent = "⋯";
462
+ btn.title = "Move this panel";
463
+ let group: { activePanel?: { id: string } } | undefined;
464
+ btn.addEventListener("click", (e) => {
465
+ e.stopPropagation();
466
+ const id = group?.activePanel?.id;
467
+ if (id && defOf(id)) moveMenu(btn, id);
468
+ });
469
+ return {
470
+ element: btn,
471
+ init: (params) => {
472
+ group = params.group as unknown as { activePanel?: { id: string } };
473
+ },
474
+ dispose: () => btn.remove(),
475
+ };
476
+ }
477
+
478
+ const panelsMenu = (host: HTMLElement): (() => void) => {
479
+ const btn = doc.createElement("button");
480
+ btn.type = "button";
481
+ btn.className = "dock-panels-btn";
482
+ btn.textContent = "Panels ▾";
483
+ btn.setAttribute("aria-haspopup", "true");
484
+ btn.setAttribute("aria-expanded", "false");
485
+ const list = doc.createElement("div");
486
+ list.className = "dock-panels-list";
487
+ list.style.display = "none";
488
+ const setOpen = (show: boolean): void => {
489
+ list.style.display = show ? "block" : "none";
490
+ btn.setAttribute("aria-expanded", String(show));
491
+ };
492
+ const item = (label: string, cls: string, act: () => void): HTMLButtonElement => {
493
+ const b = doc.createElement("button");
494
+ b.type = "button";
495
+ b.className = cls;
496
+ b.textContent = label;
497
+ b.addEventListener("click", () => {
498
+ act();
499
+ setOpen(false);
500
+ });
501
+ return b;
502
+ };
503
+ const rebuild = (): void => {
504
+ const open = new Set([...api.panels.map((p) => p.id), ...[...drawers.values()].flatMap((d) => d.ids)]);
505
+ const listed = [...panels, ...[...open].filter((id) => !byId.has(id)).map((id) => defOf(id)).filter((d): d is PanelDef => !!d)];
506
+ list.replaceChildren(
507
+ ...listed.map((def) => {
508
+ const at = where(def.id);
509
+ return item(`${at ? "✓" : " "} ${def.title}${placementLabel(at)}`, "dock-panels-item", () => toggle(def.id));
510
+ }),
511
+ item(" Reset layout", "dock-panels-item dock-panels-reset", reset),
512
+ );
513
+ };
514
+ btn.addEventListener("click", () => {
515
+ const show = list.style.display === "none";
516
+ if (show) rebuild();
517
+ setOpen(show);
518
+ });
519
+ const close = (e: Event): void => {
520
+ if (e instanceof KeyboardEvent ? e.key === "Escape" : !host.contains(e.target as Node)) setOpen(false);
521
+ };
522
+ doc.addEventListener("click", close);
523
+ doc.addEventListener("keydown", close);
524
+ host.append(btn, list);
525
+ const remove = (): void => {
526
+ doc.removeEventListener("click", close);
527
+ doc.removeEventListener("keydown", close);
528
+ btn.remove();
529
+ list.remove();
530
+ };
531
+ cleanups.push(remove);
532
+ return remove;
533
+ };
534
+
535
+ return {
536
+ api,
537
+ show,
538
+ place,
539
+ where,
540
+ toggle,
541
+ toggleDrawer(edge, open) {
542
+ const d = drawers.get(edge);
543
+ if (!d) return false;
544
+ d.setOpen(open ?? !d.open);
545
+ return d.open;
546
+ },
547
+ reset,
548
+ applyTheme,
549
+ panelsMenu,
550
+ dispose() {
551
+ if (disposed) return;
552
+ // dockview reports layout changes a microtask late, so save now or lose the last change.
553
+ save();
554
+ disposed = true;
555
+ for (const c of cleanups.splice(0)) c();
556
+ for (const d of drawers.values()) {
557
+ for (const id of d.ids) {
558
+ const el = d.remove(id);
559
+ if (el) release?.(id, el);
560
+ }
561
+ d.dispose();
562
+ }
563
+ component.dispose();
564
+ },
565
+ };
566
+ }
package/src/drawer.ts ADDED
@@ -0,0 +1,68 @@
1
+ // The DOM-free half of a drawer: its size from a drag on any of the four edges, clamped, and saved.
2
+ // The drawer element itself comes in a later release (#133).
3
+
4
+ /** The page edge a drawer is anchored to. */
5
+ export type DrawerEdge = "left" | "right" | "top" | "bottom";
6
+
7
+ /** The smallest a drawer gets, in px, unless the caller passes its own `min`. */
8
+ export const DRAWER_MIN = 280;
9
+ /** The largest share of the viewport a drawer takes, unless the caller passes its own `maxFrac`. */
10
+ export const DRAWER_MAX_FRAC = 0.9;
11
+ /** A drawer's size when nothing is saved. */
12
+ export const DRAWER_DEFAULT = 420;
13
+
14
+ /** Bounds for `clampSize` and `drawerSize`. */
15
+ export interface DrawerBounds {
16
+ min?: number;
17
+ maxFrac?: number;
18
+ }
19
+
20
+ /**
21
+ * Clamps `px` to `[min, viewport * maxFrac]` and rounds it. A viewport too small for the minimum
22
+ * gets the minimum, so the drawer can overflow a tiny window rather than vanish.
23
+ */
24
+ export function clampSize(px: number, viewport: number, bounds: DrawerBounds = {}): number {
25
+ const min = bounds.min ?? DRAWER_MIN;
26
+ const max = Math.max(min, Math.floor(viewport * (bounds.maxFrac ?? DRAWER_MAX_FRAC)));
27
+ return Math.min(max, Math.max(min, Math.round(px)));
28
+ }
29
+
30
+ /**
31
+ * Turns a drag on a drawer's inner edge into its size. The size is the distance from the pointer
32
+ * to the anchored edge, then clamped. Pass the pointer's `clientX` and the viewport's width for a
33
+ * left or right drawer, and `clientY` and the height for a top or bottom one.
34
+ */
35
+ export function drawerSize(edge: DrawerEdge, pointer: number, viewport: number, bounds?: DrawerBounds): number {
36
+ const fromEdge = edge === "left" || edge === "top" ? pointer : viewport - pointer;
37
+ return clampSize(fromEdge, viewport, bounds);
38
+ }
39
+
40
+ /** The part of Web Storage drawer sizes need. A null storage means sizes aren't saved. */
41
+ export interface DrawerStorage {
42
+ getItem(key: string): string | null;
43
+ setItem(key: string, value: string): void;
44
+ }
45
+
46
+ /**
47
+ * Reads a saved size, or `fallback` when nothing is saved or the value isn't a positive number.
48
+ * It doesn't clamp, since the viewport may have changed; clamp against the live one when applying.
49
+ */
50
+ export function loadDrawerSize(storage: DrawerStorage | null, key: string, fallback = DRAWER_DEFAULT): number {
51
+ let raw: string | null = null;
52
+ try {
53
+ raw = storage?.getItem(key) ?? null;
54
+ } catch {
55
+ return fallback;
56
+ }
57
+ const n = raw == null ? NaN : parseInt(raw, 10);
58
+ return Number.isFinite(n) && n > 0 ? n : fallback;
59
+ }
60
+
61
+ /** Saves a size, rounded. A storage that throws is ignored. */
62
+ export function saveDrawerSize(storage: DrawerStorage | null, key: string, px: number): void {
63
+ try {
64
+ storage?.setItem(key, String(Math.round(px)));
65
+ } catch {
66
+ // best effort
67
+ }
68
+ }