@panyam/tsappkit-dock 0.7.8 → 0.7.10

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 CHANGED
@@ -1,41 +1,80 @@
1
1
  import { DockviewComponent, themeDark, themeLight } from "dockview-core";
2
- import type { DockviewApi, IContentRenderer } from "dockview-core";
2
+ import type { DockviewApi, DockviewGroupPanel, IContentRenderer, IHeaderActionsRenderer } from "dockview-core";
3
+ import { DRAWER_DEFAULT, type DrawerEdge } from "./drawer.js";
4
+ import { DrawerView, type DrawerConfig } from "./drawerView.js";
3
5
  import {
4
6
  documentTheme,
5
7
  loadLayout,
6
- panelsToPrune,
7
8
  panelsToReconcile,
8
9
  saveLayout,
9
10
  type DockStorage,
10
11
  type PanelDef,
11
12
  type PanelPosition,
12
13
  type PanelSpec,
14
+ type Placement,
15
+ type SavedDrawers,
13
16
  } from "./layout.js";
14
17
 
18
+ const EDGES: readonly DrawerEdge[] = ["left", "right", "top", "bottom"];
19
+
20
+ /**
21
+ * Where a panel is: a `Placement`, or a dockview popout window. Popouts come from `dock.api`, since
22
+ * the dock doesn't place panels there itself (see the dock experiments page for why).
23
+ */
24
+ export type PanelLocation = Placement | { kind: "popout" };
25
+
26
+ /** What `moved` gets besides the panel and its old and new place. */
27
+ export interface MoveInfo {
28
+ /**
29
+ * True when the panel's element is in a different document from the last time the dock saw it,
30
+ * which happens on the way into a popout window and on the way back. A canvas can't draw again
31
+ * once the window it was in has closed, so rebuild canvases (and WebGL contexts) when this is
32
+ * true. Moves within one document leave canvases working.
33
+ */
34
+ documentChanged: boolean;
35
+ }
36
+
15
37
  /** What `createDock` needs. */
16
38
  export interface DockOptions {
17
39
  /** The element dockview renders into. It needs a size, as dockview fills it. */
18
40
  container: HTMLElement;
19
- /** The panel registry, in a stable order. Only these ids get content. */
41
+ /** The panel registry, in a stable order. These are the panels the Panels menu lists. */
20
42
  panels: readonly PanelDef[];
43
+ /**
44
+ * Describes a panel the registry doesn't list, such as one per document the reader opens.
45
+ * Return undefined for an id that isn't one. A resolvable panel opens with `show(id)`, can be
46
+ * placed anywhere, and is kept when a saved layout names it. The Panels menu lists it while it's
47
+ * open.
48
+ */
49
+ resolve?: (id: string) => PanelDef | undefined;
21
50
  /**
22
51
  * The arrangement used when nothing is saved, after a rejected save, and on `reset`. Either
23
52
  * `addPanel` specs as data, or a function that builds it on the api, for an app that sizes
24
- * groups after adding them.
53
+ * groups after adding them. Registry panels whose `defaultPlacement` is a drawer or a float go
54
+ * there afterwards, whichever form this takes.
25
55
  */
26
56
  defaultLayout: readonly PanelSpec[] | ((api: DockviewApi) => void);
27
57
  /**
28
- * Returns the element a panel shows. The dock calls it each time the panel enters the grid, so
29
- * return the same element every time if its content should survive a close and reopen. It is
30
- * only called with registry ids.
58
+ * Returns the element a panel shows. The dock calls it each time the panel arrives somewhere: in
59
+ * the grid, in a float, or in a drawer. Return the same element every time if its content should
60
+ * survive a move, a close and a reopen. It's only called with ids the registry or `resolve` knows.
31
61
  */
32
62
  hostFor: (id: string) => HTMLElement;
33
63
  /**
34
- * Called when a panel leaves the grid, with the element `hostFor` gave it. dockview has already
35
- * detached it, so this is where an app parks the element somewhere hidden, or tears its content
36
- * down. Clearing the layout, as `reset` does, calls it for every open panel.
64
+ * Called when a panel leaves where it was, with the element `hostFor` gave it, already detached.
65
+ * Closing a panel calls it, and so does moving it between the grid and a drawer, before `hostFor`
66
+ * is called for the new place. Moving it between the grid and a float doesn't, since dockview
67
+ * keeps the element. Clearing the layout, as `reset` does, calls it for every open panel.
37
68
  */
38
69
  release?: (id: string, el: HTMLElement) => void;
70
+ /**
71
+ * Called after a panel ends up somewhere new, with its element already in place. `to` and
72
+ * `from` are where it is and where it was, and null means closed. It covers every way a panel
73
+ * moves: `place`, `show`, `toggle`, Reset layout, the reader dragging a tab into a float, a popout
74
+ * made through `dock.api`, and a popout window closing. It isn't called for the layout the dock
75
+ * starts with. See `MoveInfo.documentChanged` for the one move that breaks a canvas.
76
+ */
77
+ moved?: (id: string, el: HTMLElement, to: PanelLocation | null, from: PanelLocation | null, info: MoveInfo) => void;
39
78
  /** Where the layout is saved, usually `localStorage`. Null or absent: nothing is saved. */
40
79
  storage?: DockStorage | null;
41
80
  /** The storage key. Required with `storage`. */
@@ -45,6 +84,18 @@ export interface DockOptions {
45
84
  * OS colour scheme changes, and on `applyTheme()`. Default: `documentTheme()`.
46
85
  */
47
86
  theme?: () => "light" | "dark";
87
+ /** Each edge's drawer size and bounds. An edge left out gets the defaults from drawer.ts. */
88
+ drawers?: Partial<Record<DrawerEdge, DrawerConfig>>;
89
+ /**
90
+ * The element drawers are laid over, and the box their sizes are measured against. Default
91
+ * `container`. The dock makes it `position: relative` if it's static.
92
+ */
93
+ drawerHost?: HTMLElement;
94
+ /**
95
+ * Whether each dockview group gets a ⋯ button with Dock, Float and the four drawers for its
96
+ * active panel. Default true. Drawer tabs always have one.
97
+ */
98
+ moveMenu?: boolean;
48
99
  }
49
100
 
50
101
  /** A dock made by `createDock`. */
@@ -52,40 +103,61 @@ export interface Dock {
52
103
  /** The dockview api, for anything the dock doesn't wrap. */
53
104
  readonly api: DockviewApi;
54
105
  /**
55
- * Brings a panel to the front, opening it first if it's closed. It returns false, and does
56
- * nothing, for an id the registry lacks.
106
+ * Brings a panel to the front wherever it is, opening its drawer if it's in one. A closed panel
107
+ * opens at its `defaultPlacement`. It returns false, and does nothing, for an id that neither the
108
+ * registry nor `resolve` knows.
57
109
  */
58
110
  show(id: string): boolean;
59
- /** Opens a closed panel or closes an open one. False for an id the registry lacks. */
111
+ /**
112
+ * Moves a panel to `target` and brings it to the front. A closed panel opens there. False for an
113
+ * unknown id.
114
+ */
115
+ place(id: string, target: Placement): boolean;
116
+ /** Where a panel is now, or null when it's closed. A panel in a dockview popout reports `popout`. */
117
+ where(id: string): PanelLocation | null;
118
+ /** Opens a closed panel or closes an open one. False for an unknown id. */
60
119
  toggle(id: string): boolean;
61
- /** Forgets the saved layout and applies the default one. Panels keep their `hostFor` elements. */
120
+ /**
121
+ * Opens or closes the drawer on `edge`, or flips it when `open` is absent. An empty drawer stays
122
+ * closed. Returns whether it's open afterwards.
123
+ */
124
+ toggleDrawer(edge: DrawerEdge, open?: boolean): boolean;
125
+ /**
126
+ * Forgets the saved layout and applies the default one, drawers included. Panels keep their
127
+ * `hostFor` elements.
128
+ */
62
129
  reset(): void;
63
130
  /** Reads `theme` again and applies it. For a theme setting the dock doesn't watch. */
64
131
  applyTheme(): void;
65
132
  /**
66
- * Adds a Panels menu button to `host`. Its list has one item per registry panel, each toggling
67
- * its panel, with a ✓ on the open ones, and then Reset layout. Returns a function that removes
68
- * it. The elements carry `dock-panels-*` classes and no styles beyond showing and hiding the
69
- * list, so the app styles them.
133
+ * Adds a Panels menu button to `host`. Its list has one item per registry panel and per open
134
+ * resolved panel, each toggling its panel, with a ✓ on the open ones and where a panel is when
135
+ * it's not in the grid, and then Reset layout. Returns a function that removes it. The elements
136
+ * carry `dock-panels-*` classes and no styles beyond showing and hiding the list.
70
137
  */
71
138
  panelsMenu(host: HTMLElement): () => void;
72
139
  /**
73
- * Saves the layout, stops watching the theme, removes any Panels menus, and disposes of
74
- * dockview. Changes are otherwise saved a microtask after dockview reports them. A second call
75
- * does nothing.
140
+ * Saves the layout, stops watching the theme, removes the menus and drawers, and disposes of
141
+ * dockview. Panels in drawers are released. Changes are otherwise saved a microtask after
142
+ * dockview reports them. A second call does nothing.
76
143
  */
77
144
  dispose(): void;
78
145
  }
79
146
 
147
+ const placementLabel = (p: PanelLocation | null): string =>
148
+ !p || p.kind === "grid" ? "" : p.kind === "drawer" ? ` · ${p.edge} drawer` : ` · ${p.kind}`;
149
+
150
+ const TOWARD_EDGE: Record<DrawerEdge, PanelPosition["direction"]> = { left: "left", right: "right", top: "above", bottom: "below" };
151
+
80
152
  /**
81
153
  * Builds a dockview dock from a panel registry. It restores the saved layout when there is one,
82
- * opens the panels added to the registry since it was saved, and closes the ones the registry
83
- * dropped. A save that dockview rejects is removed and the default layout applied. Every layout
84
- * change after that is saved.
154
+ * drawers included, opens the panels added to the registry since it was saved, and closes the
155
+ * ones nothing knows any more. A save that dockview rejects is removed and the default layout
156
+ * applied. Every change after that is saved.
85
157
  *
86
- * Content lives outside dockview. `hostFor` hands an element to a panel when it enters the grid,
87
- * and `release` hands it back when it leaves, so an app can keep a panel's content alive while
88
- * the panel is closed.
158
+ * Content lives outside dockview. `hostFor` hands an element to a panel when it arrives somewhere,
159
+ * and `release` hands it back when it leaves, so an app can keep a panel's content alive while the
160
+ * panel is closed or moving between the grid and a drawer.
89
161
  */
90
162
  export function createDock(opts: DockOptions): Dock {
91
163
  const { container, panels, hostFor, release } = opts;
@@ -97,42 +169,233 @@ export function createDock(opts: DockOptions): Dock {
97
169
  const byId = new Map(panels.map((p) => [p.id, p]));
98
170
  const specs = Array.isArray(opts.defaultLayout) ? (opts.defaultLayout as readonly PanelSpec[]) : null;
99
171
  const cleanups: (() => void)[] = [];
172
+ const drawerHost = opts.drawerHost ?? container;
173
+ const drawers = new Map<DrawerEdge, DrawerView>();
100
174
  let disposed = false;
175
+ // Set while the dock rebuilds itself, so the drawers' change hooks don't save a half-built state.
176
+ let quiet = 0;
177
+
178
+ const defOf = (id: string): PanelDef | undefined => {
179
+ const known = byId.get(id);
180
+ if (known) return known;
181
+ const def = opts.resolve?.(id);
182
+ return def && def.id === id ? def : undefined;
183
+ };
101
184
 
102
185
  const renderer = (id: string): IContentRenderer => {
103
- if (!byId.has(id)) return { element: doc.createElement("div"), init: () => {} };
186
+ if (!defOf(id)) return { element: doc.createElement("div"), init: () => {} };
104
187
  const element = hostFor(id);
105
188
  return { element, init: () => {}, dispose: () => release?.(id, element) };
106
189
  };
107
190
 
108
191
  const component = new DockviewComponent(container, {
109
192
  createComponent: (o) => renderer(o.id),
110
- // "always" keeps a background tab's content attached, only hidden. The default detaches it,
111
- // and an app that finds its content by id at startup would miss the panels behind a tab.
193
+ // "always" keeps a background tab's content attached, only hidden, in a layer dockview
194
+ // positions over the group. The default detaches it, and an app that finds its content by id
195
+ // at startup would miss the panels behind a tab. The layer also means dragging a tab between
196
+ // groups doesn't re-parent the content, so an iframe in it doesn't reload.
112
197
  defaultRenderer: "always",
113
198
  theme: theme() === "dark" ? themeDark : themeLight,
199
+ ...(opts.moveMenu === false ? {} : { createRightHeaderActionComponent: () => headerMenu() }),
114
200
  });
115
201
  const api = component.api;
116
202
 
203
+ // ---- where panels are ----
204
+
205
+ const drawerWith = (id: string): DrawerView | undefined => [...drawers.values()].find((d) => d.has(id));
206
+
207
+ const where = (id: string): PanelLocation | null => {
208
+ const d = drawerWith(id);
209
+ if (d) return { kind: "drawer", edge: d.edge };
210
+ const panel = api.getPanel(id);
211
+ if (!panel) return null;
212
+ const type = panel.group.api.location.type;
213
+ return type === "floating" ? { kind: "float" } : type === "popout" ? { kind: "popout" } : { kind: "grid" };
214
+ };
215
+
216
+ const elementOf = (id: string): HTMLElement | undefined =>
217
+ drawerWith(id)?.elementOf(id) ?? (api.getPanel(id)?.view.content.element as HTMLElement | undefined);
218
+
219
+ const same = (a: PanelLocation | null, b: Placement): boolean =>
220
+ !!a && a.kind === b.kind && (a.kind !== "drawer" || (b.kind === "drawer" && a.edge === b.edge));
221
+
222
+ // ---- drawers ----
223
+
224
+ const drawer = (edge: DrawerEdge): DrawerView => {
225
+ let d = drawers.get(edge);
226
+ if (!d) {
227
+ if (doc.defaultView?.getComputedStyle(drawerHost).position === "static") drawerHost.style.position = "relative";
228
+ d = new DrawerView(edge, drawerHost, opts.drawers?.[edge] ?? {}, { changed: () => changed(), menu: (anchor, id) => moveMenu(anchor, id) });
229
+ drawers.set(edge, d);
230
+ }
231
+ return d;
232
+ };
233
+
234
+ const drawerStates = (): SavedDrawers => {
235
+ const out: SavedDrawers = {};
236
+ // A drawer is saved once it has held a panel or been resized, so an empty one keeps its size.
237
+ for (const [edge, d] of drawers) if (d.ids.length || d.size !== (opts.drawers?.[edge]?.size ?? DRAWER_DEFAULT)) out[edge] = d.state();
238
+ return out;
239
+ };
240
+
241
+ // ---- moving panels ----
242
+
117
243
  const usable = (p?: PanelPosition): p is PanelPosition => !!p && (!p.referencePanel || !!api.getPanel(p.referencePanel));
244
+ const inGrid = (p?: PanelPosition): p is PanelPosition =>
245
+ !!p && (!p.referencePanel || (api.getPanel(p.referencePanel)?.group.api.location.type === "grid" && api.getPanel(p.referencePanel)!.group.api.isVisible));
118
246
 
119
- const open = (id: string): void => {
120
- const def = byId.get(id)!;
247
+ // Puts a panel in the grid, never in a float, a popout, or a popout's hidden placeholder. A position
248
+ // counts only if its reference panel is in the grid. Without one the panel tabs into the active group, or the first grid group
249
+ // when the active one is a float or a popout, and goes to the grid's edge when the grid is empty.
250
+ const addToGrid = (id: string, prefer?: PanelPosition): void => {
251
+ const def = defOf(id)!;
121
252
  const spec = specs?.find((s) => s.id === id);
122
- const position = [def.position, spec?.position].find(usable);
123
- api.addPanel({ id, component: id, title: def.title, ...(position ? { position } : {}) });
253
+ const position = [prefer, def.position, spec?.position].find(inGrid);
254
+ if (position) {
255
+ api.addPanel({ id, component: id, title: def.title, position });
256
+ return;
257
+ }
258
+ // While a group is popped out, dockview keeps a hidden placeholder for it in the grid, and a
259
+ // panel tabbed into that would be invisible.
260
+ const showing = (g?: DockviewGroupPanel) => !!g && g.api.location.type === "grid" && g.api.isVisible;
261
+ const active = api.activeGroup;
262
+ const group = showing(active) ? active : api.groups.find(showing);
263
+ api.addPanel({
264
+ id,
265
+ component: id,
266
+ title: def.title,
267
+ position: group ? { referenceGroup: group, direction: "within" } : { direction: "right" },
268
+ });
269
+ };
270
+
271
+ const enter = (id: string, target: Placement): void => {
272
+ if (target.kind === "drawer") {
273
+ drawer(target.edge).add(id, defOf(id)!.title, hostFor(id));
274
+ return;
275
+ }
276
+ if (!api.getPanel(id)) addToGrid(id);
277
+ const panel = api.getPanel(id)!;
278
+ if (target.kind === "float" && panel.group.api.location.type !== "floating") api.addFloatingGroup(panel);
279
+ };
280
+
281
+ const leave = (id: string): void => {
282
+ const d = drawerWith(id);
283
+ if (d) {
284
+ const el = d.remove(id);
285
+ if (el) release?.(id, el);
286
+ return;
287
+ }
288
+ const panel = api.getPanel(id);
289
+ if (panel) api.removePanel(panel);
290
+ };
291
+
292
+ const reveal = (id: string): void => {
293
+ const d = drawerWith(id);
294
+ if (d) {
295
+ d.activate(id);
296
+ d.setOpen(true);
297
+ return;
298
+ }
299
+ api.getPanel(id)?.api.setActive();
300
+ };
301
+
302
+ // Runs a move with saving and moved held back, then does both once, so a move that passes through
303
+ // a closed state on its way (leave, then enter) reports only where it ended up.
304
+ const batch = (fn: () => void): void => {
305
+ quiet++;
306
+ try {
307
+ fn();
308
+ } finally {
309
+ quiet--;
310
+ }
311
+ changed();
312
+ };
313
+
314
+ const place = (id: string, target: Placement): boolean => {
315
+ if (!defOf(id)) return false;
316
+ batch(() => placeNow(id, target));
317
+ return true;
318
+ };
319
+
320
+ const placeNow = (id: string, target: Placement): void => {
321
+ const now = where(id);
322
+ if (!same(now, target)) {
323
+ if (now?.kind === "drawer" && target.kind === "grid") {
324
+ // Docking from a drawer puts the panel where the drawer was: on its edge, at its size.
325
+ const size = drawer(now.edge).size;
326
+ leave(id);
327
+ addToGrid(id, { direction: TOWARD_EDGE[now.edge] });
328
+ const horizontal = now.edge === "left" || now.edge === "right";
329
+ api.getPanel(id)?.api.setSize(horizontal ? { width: size } : { height: size });
330
+ } else {
331
+ // Grid to float stays inside dockview, which moves the group and keeps the element. Every
332
+ // other move goes out through release and back in through hostFor.
333
+ if (!(now?.kind === "grid" && target.kind === "float")) leave(id);
334
+ enter(id, target);
335
+ }
336
+ }
337
+ reveal(id);
124
338
  };
125
339
 
340
+ const show = (id: string): boolean => {
341
+ const def = defOf(id);
342
+ if (!def) return false;
343
+ batch(() => {
344
+ if (!where(id)) enter(id, def.defaultPlacement ?? { kind: "grid" });
345
+ reveal(id);
346
+ });
347
+ return true;
348
+ };
349
+
350
+ const toggle = (id: string): boolean => {
351
+ if (!defOf(id)) return false;
352
+ if (!where(id)) return show(id);
353
+ batch(() => leave(id));
354
+ return true;
355
+ };
356
+
357
+ // ---- default layout, restore, reset ----
358
+
126
359
  const applyDefault = (): void => {
127
- if (!specs) {
360
+ const elsewhere = (def?: PanelDef) => !!def?.defaultPlacement && def.defaultPlacement.kind === "drawer";
361
+ if (specs) {
362
+ for (const spec of specs) {
363
+ const def = byId.get(spec.id);
364
+ if (!def || elsewhere(def) || api.getPanel(spec.id)) continue;
365
+ const position = usable(spec.position) ? spec.position : undefined;
366
+ api.addPanel({ id: spec.id, component: spec.id, title: spec.title ?? def.title, ...(position ? { position } : {}) });
367
+ }
368
+ } else {
128
369
  (opts.defaultLayout as (api: DockviewApi) => void)(api);
129
- return;
130
370
  }
131
- for (const spec of specs) {
132
- const def = byId.get(spec.id);
133
- if (!def || api.getPanel(spec.id)) continue;
134
- const position = usable(spec.position) ? spec.position : undefined;
135
- api.addPanel({ id: spec.id, component: spec.id, title: spec.title ?? def.title, ...(position ? { position } : {}) });
371
+ for (const def of panels) {
372
+ const p = def.defaultPlacement;
373
+ if (!p || p.kind === "grid") continue;
374
+ if (p.kind === "drawer" && !where(def.id)) enter(def.id, p);
375
+ if (p.kind === "float" && (where(def.id)?.kind ?? "grid") === "grid") enter(def.id, p);
376
+ }
377
+ };
378
+
379
+ const clearDrawers = (): void => {
380
+ for (const d of drawers.values()) {
381
+ for (const id of d.ids) leave(id);
382
+ d.setOpen(false, false);
383
+ d.setSize(opts.drawers?.[d.edge]?.size ?? DRAWER_DEFAULT, false);
384
+ }
385
+ };
386
+
387
+ const restoreDrawers = (saved: SavedDrawers): void => {
388
+ for (const edge of EDGES) {
389
+ const s = saved[edge];
390
+ if (!s) continue;
391
+ const d = drawer(edge);
392
+ if (typeof s.size === "number" && s.size > 0) d.setSize(s.size, false);
393
+ for (const id of Array.isArray(s.panels) ? s.panels : []) {
394
+ const def = defOf(id);
395
+ if (def && !where(id)) d.add(id, def.title, hostFor(id));
396
+ }
397
+ if (s.active) d.activate(s.active, false);
398
+ if (s.open) d.setOpen(true, false);
136
399
  }
137
400
  };
138
401
 
@@ -144,28 +407,80 @@ export function createDock(opts: DockOptions): Dock {
144
407
  }
145
408
  try {
146
409
  api.fromJSON(saved.layout as Parameters<DockviewApi["fromJSON"]>[0]);
147
- for (const id of panelsToPrune(api.panels.map((p) => p.id), panels)) {
148
- const panel = api.getPanel(id);
149
- if (panel) api.removePanel(panel);
150
- }
410
+ for (const panel of [...api.panels]) if (!defOf(panel.id)) api.removePanel(panel);
411
+ restoreDrawers(saved.drawers);
151
412
  for (const id of panelsToReconcile(saved.savedPanels, panels)) {
152
- if (!api.getPanel(id)) open(id);
413
+ if (!where(id)) enter(id, byId.get(id)!.defaultPlacement ?? { kind: "grid" });
153
414
  }
154
415
  } catch (err) {
155
416
  console.warn("tsappkit-dock: saved layout rejected, using the default", err);
156
417
  storage?.removeItem(key);
418
+ clearDrawers();
157
419
  api.clear();
158
420
  applyDefault();
159
421
  }
160
422
  };
161
423
 
162
- restore();
163
- if (storage) {
164
- // Save what restore built, so the save names today's registry and a rejected save is replaced.
165
- saveLayout(storage, key, panels, api.toJSON());
166
- const sub = api.onDidLayoutChange(() => saveLayout(storage, key, panels, api.toJSON()));
167
- cleanups.push(() => sub.dispose());
424
+ const save = (): void => {
425
+ if (quiet || disposed || !storage) return;
426
+ saveLayout(storage, key, panels, api.toJSON(), drawerStates());
427
+ };
428
+
429
+ // What `moved` compares against: each panel's last place, element and document.
430
+ const seen = new Map<string, { at: PanelLocation | null; el?: HTMLElement; doc?: Document }>();
431
+ const key0 = (p: PanelLocation | null) => JSON.stringify(p);
432
+
433
+ // Compares every panel's place and document with the last ones seen, and calls `moved` for each
434
+ // that differs. Running it after every change, whatever made it, catches moves made through
435
+ // dock.api and by dockview itself as well as the dock's own.
436
+ const sync = (notify = true): void => {
437
+ if (disposed || quiet) return;
438
+ const ids = new Set([...panels.map((p) => p.id), ...api.panels.map((p) => p.id), ...[...drawers.values()].flatMap((d) => d.ids), ...seen.keys()]);
439
+ for (const id of ids) {
440
+ if (!defOf(id)) continue;
441
+ const at = where(id);
442
+ const prev = seen.get(id);
443
+ const el = at ? elementOf(id) : prev?.el;
444
+ const doc = at && el ? el.ownerDocument : prev?.doc;
445
+ seen.set(id, { at, el, doc });
446
+ if (!notify || !opts.moved || !el) continue;
447
+ if (key0(at) === key0(prev?.at ?? null) && doc === prev?.doc) continue;
448
+ opts.moved(id, el, at, prev?.at ?? null, { documentChanged: !!prev?.doc && doc !== prev.doc });
449
+ }
450
+ };
451
+
452
+ const changed = (): void => {
453
+ save();
454
+ sync();
455
+ };
456
+
457
+ const reset = (): void => {
458
+ quiet++;
459
+ try {
460
+ storage?.removeItem(key);
461
+ clearDrawers();
462
+ api.clear();
463
+ applyDefault();
464
+ } finally {
465
+ quiet--;
466
+ }
467
+ changed();
468
+ };
469
+
470
+ quiet++;
471
+ try {
472
+ restore();
473
+ } finally {
474
+ quiet--;
168
475
  }
476
+ // Save what restore built, so the save names today's registry and a rejected save is replaced,
477
+ // and note where everything starts without calling moved for it.
478
+ save();
479
+ sync(false);
480
+ const sub = api.onDidLayoutChange(() => changed());
481
+ cleanups.push(() => sub.dispose());
482
+
483
+ // ---- theme ----
169
484
 
170
485
  const applyTheme = (): void => component.updateOptions({ theme: theme() === "dark" ? themeDark : themeLight });
171
486
  const view = doc.defaultView;
@@ -180,19 +495,85 @@ export function createDock(opts: DockOptions): Dock {
180
495
  cleanups.push(() => mq.removeEventListener("change", applyTheme));
181
496
  }
182
497
 
183
- const reset = (): void => {
184
- storage?.removeItem(key);
185
- api.clear();
186
- applyDefault();
498
+ const escape = (e: KeyboardEvent): void => {
499
+ if (e.key !== "Escape") return;
500
+ closeMenu();
501
+ for (const d of drawers.values()) d.setOpen(false);
187
502
  };
503
+ doc.addEventListener("keydown", escape);
504
+ cleanups.push(() => doc.removeEventListener("keydown", escape));
188
505
 
189
- const toggle = (id: string): boolean => {
190
- if (!byId.has(id)) return false;
191
- const panel = api.getPanel(id);
192
- if (panel) api.removePanel(panel);
193
- else open(id);
194
- return true;
506
+ // ---- menus ----
507
+
508
+ let menu: HTMLElement | null = null;
509
+ const closeMenu = (): void => {
510
+ menu?.remove();
511
+ menu = null;
512
+ };
513
+ const outside = (e: Event): void => {
514
+ if (menu && !menu.contains(e.target as Node)) closeMenu();
195
515
  };
516
+ doc.addEventListener("pointerdown", outside, true);
517
+ cleanups.push(() => doc.removeEventListener("pointerdown", outside, true), closeMenu);
518
+
519
+ const moveItems = (id: string): [string, Placement | null][] => {
520
+ const now = where(id);
521
+ const items: [string, Placement | null][] = [];
522
+ if (now?.kind !== "grid") items.push(["Dock", { kind: "grid" }]);
523
+ if (now?.kind !== "float") items.push(["Float", { kind: "float" }]);
524
+ for (const edge of EDGES) {
525
+ if (!(now?.kind === "drawer" && now.edge === edge)) items.push([`Move to ${edge} drawer`, { kind: "drawer", edge }]);
526
+ }
527
+ items.push(["Close", null]);
528
+ return items;
529
+ };
530
+
531
+ // The ⋯ menu for one panel: Dock, Float, the four drawers and Close, leaving out where it is.
532
+ const moveMenu = (anchor: HTMLElement, id: string): void => {
533
+ closeMenu();
534
+ const list = doc.createElement("div");
535
+ list.className = "dock-menu";
536
+ list.setAttribute("role", "menu");
537
+ list.dataset.panel = id;
538
+ const r = anchor.getBoundingClientRect();
539
+ 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)" });
540
+ for (const [label, target] of moveItems(id)) {
541
+ const b = doc.createElement("button");
542
+ b.type = "button";
543
+ b.className = "dock-menu-item";
544
+ b.setAttribute("role", "menuitem");
545
+ b.textContent = label;
546
+ b.addEventListener("click", () => {
547
+ closeMenu();
548
+ if (target) place(id, target);
549
+ else toggle(id);
550
+ });
551
+ list.appendChild(b);
552
+ }
553
+ doc.body.appendChild(list);
554
+ menu = list;
555
+ };
556
+
557
+ function headerMenu(): IHeaderActionsRenderer {
558
+ const btn = doc.createElement("button");
559
+ btn.type = "button";
560
+ btn.className = "dock-move-btn";
561
+ btn.textContent = "⋯";
562
+ btn.title = "Move this panel";
563
+ let group: { activePanel?: { id: string } } | undefined;
564
+ btn.addEventListener("click", (e) => {
565
+ e.stopPropagation();
566
+ const id = group?.activePanel?.id;
567
+ if (id && defOf(id)) moveMenu(btn, id);
568
+ });
569
+ return {
570
+ element: btn,
571
+ init: (params) => {
572
+ group = params.group as unknown as { activePanel?: { id: string } };
573
+ },
574
+ dispose: () => btn.remove(),
575
+ };
576
+ }
196
577
 
197
578
  const panelsMenu = (host: HTMLElement): (() => void) => {
198
579
  const btn = doc.createElement("button");
@@ -220,10 +601,13 @@ export function createDock(opts: DockOptions): Dock {
220
601
  return b;
221
602
  };
222
603
  const rebuild = (): void => {
604
+ const open = new Set([...api.panels.map((p) => p.id), ...[...drawers.values()].flatMap((d) => d.ids)]);
605
+ const listed = [...panels, ...[...open].filter((id) => !byId.has(id)).map((id) => defOf(id)).filter((d): d is PanelDef => !!d)];
223
606
  list.replaceChildren(
224
- ...panels.map((def) =>
225
- item(`${api.getPanel(def.id) ? "✓" : " "} ${def.title}`, "dock-panels-item", () => toggle(def.id)),
226
- ),
607
+ ...listed.map((def) => {
608
+ const at = where(def.id);
609
+ return item(`${at ? "✓" : " "} ${def.title}${placementLabel(at)}`, "dock-panels-item", () => toggle(def.id));
610
+ }),
227
611
  item(" Reset layout", "dock-panels-item dock-panels-reset", reset),
228
612
  );
229
613
  };
@@ -232,18 +616,15 @@ export function createDock(opts: DockOptions): Dock {
232
616
  if (show) rebuild();
233
617
  setOpen(show);
234
618
  });
235
- const outside = (e: Event): void => {
236
- if (!host.contains(e.target as Node)) setOpen(false);
619
+ const close = (e: Event): void => {
620
+ if (e instanceof KeyboardEvent ? e.key === "Escape" : !host.contains(e.target as Node)) setOpen(false);
237
621
  };
238
- const escape = (e: KeyboardEvent): void => {
239
- if (e.key === "Escape") setOpen(false);
240
- };
241
- doc.addEventListener("click", outside);
242
- doc.addEventListener("keydown", escape);
622
+ doc.addEventListener("click", close);
623
+ doc.addEventListener("keydown", close);
243
624
  host.append(btn, list);
244
625
  const remove = (): void => {
245
- doc.removeEventListener("click", outside);
246
- doc.removeEventListener("keydown", escape);
626
+ doc.removeEventListener("click", close);
627
+ doc.removeEventListener("keydown", close);
247
628
  btn.remove();
248
629
  list.remove();
249
630
  };
@@ -253,22 +634,32 @@ export function createDock(opts: DockOptions): Dock {
253
634
 
254
635
  return {
255
636
  api,
256
- show(id) {
257
- if (!byId.has(id)) return false;
258
- if (!api.getPanel(id)) open(id);
259
- api.getPanel(id)?.api.setActive();
260
- return true;
261
- },
637
+ show,
638
+ place,
639
+ where,
262
640
  toggle,
641
+ toggleDrawer(edge, open) {
642
+ const d = drawers.get(edge);
643
+ if (!d) return false;
644
+ d.setOpen(open ?? !d.open);
645
+ return d.open;
646
+ },
263
647
  reset,
264
648
  applyTheme,
265
649
  panelsMenu,
266
650
  dispose() {
267
651
  if (disposed) return;
652
+ // dockview reports layout changes a microtask late, so save now or lose the last change.
653
+ save();
268
654
  disposed = true;
269
655
  for (const c of cleanups.splice(0)) c();
270
- // dockview reports layout changes a microtask late, so save now or lose the last change.
271
- if (storage) saveLayout(storage, key, panels, api.toJSON());
656
+ for (const d of drawers.values()) {
657
+ for (const id of d.ids) {
658
+ const el = d.remove(id);
659
+ if (el) release?.(id, el);
660
+ }
661
+ d.dispose();
662
+ }
272
663
  component.dispose();
273
664
  },
274
665
  };