@kubohiroya/turbowarp-plus-editor-workbench 0.18.1 → 0.19.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.
package/README.ja.md CHANGED
@@ -108,6 +108,8 @@ useSpriteTabs({...props, workspaceLayout: {...workspaceLayout, screenState}});
108
108
  - 保存すると、`project.json` の隣に ZIP エントリ `tw-plus/workspace.json`(`{"version": 1, "savedAt": <ms>, "slices": {...}}`)を加える。Scratch と TurboWarp はこのエントリを無視するので、ファイルの互換性は変わらない。別のエディターで保存し直すと、エントリが消えるだけである。`project.json` は変えない。
109
109
  - エディターの各部分は、自分のキーで `register(key, {capture, apply})` によりスライスを登録する。`capture` は保存中に同期で呼ばれる。`apply` は、そのスライスを含む作品を VM が読み込み終えたあとに作品ごとに1回呼ばれる。読み込み後に登録したスライスには、登録したときに呼ばれる。キーは `^[a-z][a-zA-Z0-9-]{0,63}$` に合うものとする。
110
110
  - このパッケージは `drawer`(左側ドロワーで選んだ表示)と `workspace`([Dockview のレイアウトの保存](#dockview-のレイアウトの保存) の作業領域)を登録する。ファイルの作業領域は、このブラウザーがその作品について保存したレイアウトより新しいとき、またはブラウザーに記録がないときに使う。ファイルの保存後にレイアウトを変え、保存せずに開き直した場合は、ブラウザーの記録が使われる。
111
+ - 各スプライトのタブは、選んでいたコスチュームと音も、一覧での位置で保存する。ホストのタブアダプターが `serialize(view, snapshot)` と `deserialize(view, value)` を持つときは、スクロール位置やズームなどのコードエリアも保存する。画面に出ているタブについては、`serialize` をスナップショットなしで呼ぶので、コードエリアを変えずに読む。画面に出ているタブを読むのは作品ファイルの保存時だけなので、ブラウザーが保存するレイアウトには、ほかのタブのコードエリアだけが入る。
112
+ - SB3 として保存しない作品は、同じ状態を別の場所に保存する。`serialize()` は保存時に ZIP エントリへ書くテキストを返す。`prepareLoad(text)` を呼ぶと、次の `loadProject` は入力を読まずにこのテキストを使う。作品フォルダーは、これを `.tw-plus/workspace.json` として書く。
111
113
  - `save: false` では、保存時にエントリを書かず、読み込んだファイルから引き継いだエントリも取り除く。読み込みは有効のままなので、以前に保存したファイルは保存時の画面で開く。
112
114
  - 512 KiB を超えるエントリ、別の版のもの、形の合わないものは無視し、作品は通常の画面で開く。
113
115
 
package/README.md CHANGED
@@ -110,6 +110,8 @@ useSpriteTabs({...props, workspaceLayout: {...workspaceLayout, screenState}});
110
110
  - Saving adds the ZIP entry `tw-plus/workspace.json` next to `project.json`: `{"version": 1, "savedAt": <ms>, "slices": {...}}`. Scratch and TurboWarp ignore the entry, so the file stays compatible. Saving it in another editor only drops the entry. `project.json` is not changed.
111
111
  - Each part of the editor registers a slice under its own key with `register(key, {capture, apply})`. `capture` is called synchronously while saving; `apply` is called once for each loaded project that carries the slice, after the VM finished loading it, or when the slice is registered later. Keys match `^[a-z][a-zA-Z0-9-]{0,63}$`.
112
112
  - This package registers `drawer` (the selected left drawer view) and `workspace` (the Dockview workspace described under [Saved Dockview layout](#saved-dockview-layout)). The workspace from the file is used when it is newer than the layout this browser kept for the project, or when the browser has none. A layout changed after the file was saved, and reloaded without saving, therefore still wins.
113
+ - Each sprite tab also keeps the costume and sound it had selected, by their index in the list. When the host's tab adapter has `serialize(view, snapshot)` and `deserialize(view, value)`, the tab keeps its code area too, such as its scroll position and zoom; `serialize` is called without a snapshot for the tab on screen, and must then read the code area without changing it. The tab on screen is read only while saving the project file, so the layout this browser keeps has the code areas of the other tabs.
114
+ - A project that is not saved as an SB3 keeps the same state elsewhere: `serialize()` returns the text a save writes into the ZIP entry, and `prepareLoad(text)` makes the next `loadProject` use that text instead of reading its input. The project folder writes it as `.tw-plus/workspace.json`.
113
115
  - With `save: false`, saving writes no entry and removes one carried over from the loaded file. Reading stays on, so files saved earlier still open as they were.
114
116
  - Entries larger than 512 KiB, of another version or of another shape are ignored, and the project opens with its usual screen.
115
117
 
@@ -62,6 +62,16 @@ export interface ProjectScreenState {
62
62
  whenLoaded(): Promise<SavedScreenState | undefined>;
63
63
  /** The state a save would write now. */
64
64
  capture(): SavedScreenState | undefined;
65
+ /**
66
+ * The text a save writes, as in the ZIP entry, for a project saved somewhere else such as a project folder.
67
+ * Nothing while saving is turned off, nothing is registered or the state is too large.
68
+ */
69
+ serialize(): string | undefined;
70
+ /**
71
+ * Use the state in `text` for the next project load instead of reading the input, for a project that is not
72
+ * loaded from an SB3, such as a project folder. Text that is not a screen state opens the default screen.
73
+ */
74
+ prepareLoad(text: string | undefined): void;
65
75
  /** Put the VM methods back. Hooks installed later on the same methods must be removed first. */
66
76
  dispose(): void;
67
77
  }
@@ -81,6 +81,8 @@ export function installProjectScreenState(vm, { Zip, save = true, now = Date.now
81
81
  let current;
82
82
  /** Slices already given the current project's state, so registering again does not apply it twice. */
83
83
  let applied = new Set();
84
+ /** The state the next load uses instead of its input, set by `prepareLoad`. */
85
+ let prepared;
84
86
  const apply = (slice, key) => {
85
87
  if (!current || applied.has(slice) || !Object.hasOwn(current.slices, key))
86
88
  return;
@@ -116,7 +118,8 @@ export function installProjectScreenState(vm, { Zip, save = true, now = Date.now
116
118
  current = undefined;
117
119
  applied = new Set();
118
120
  // Read in parallel with the VM, which keeps its own copy of the bytes.
119
- const reading = readScreenState(input, Zip);
121
+ const reading = prepared ? Promise.resolve(prepared.state) : readScreenState(input, Zip);
122
+ prepared = undefined;
120
123
  const result = original.loadProject.call(this, input, ...args);
121
124
  const done = result.then(() => reading, () => undefined).then(state => {
122
125
  if (mine !== generation)
@@ -163,6 +166,10 @@ export function installProjectScreenState(vm, { Zip, save = true, now = Date.now
163
166
  },
164
167
  whenLoaded: () => loaded,
165
168
  capture,
169
+ serialize: serialized,
170
+ prepareLoad(text) {
171
+ prepared = { state: text === undefined ? undefined : parseScreenState(text) };
172
+ },
166
173
  dispose() {
167
174
  vm.loadProject = original.loadProject;
168
175
  vm._saveProjectZip = original._saveProjectZip;
@@ -28,6 +28,7 @@ interface Target {
28
28
  getCostumes?(): {
29
29
  assetId?: string;
30
30
  }[];
31
+ getSounds?(): object[];
31
32
  getCurrentCostume?(): {
32
33
  asset?: CostumeAsset;
33
34
  } | undefined;
@@ -57,6 +58,13 @@ export interface SpriteTabAdapter<Snapshot = unknown> {
57
58
  renderInactive(container: HTMLElement, view: SpriteTabView, snapshot: Snapshot | undefined): void | (() => void);
58
59
  restore(view: SpriteTabView, snapshot: Snapshot | undefined): void;
59
60
  dispose?(view: SpriteTabView, snapshot: Snapshot): void;
61
+ /**
62
+ * Describe a snapshot of the code area as a small JSON object for the saved workspace, such as its scroll
63
+ * position and zoom. Without a snapshot, describe the mounted surface as it is now, without changing it.
64
+ */
65
+ serialize?(view: SpriteTabView, snapshot: Snapshot | undefined): Record<string, unknown> | undefined;
66
+ /** Turn a value `serialize` wrote back into a snapshot. The value comes from a file, so check its shape. */
67
+ deserialize?(view: SpriteTabView, value: Record<string, unknown>): Snapshot | undefined;
60
68
  }
61
69
  /** Optional bridge used by a native asset editor to restore and report its selection. */
62
70
  export interface SpriteAssetSelection {
@@ -1,6 +1,7 @@
1
1
  import React from 'react';
2
2
  import { createPortal } from 'react-dom';
3
3
  import { createDockview, DefaultTab, themeLight } from 'dockview';
4
+ import { connectOpenerDocument } from '@kubohiroya/turbowarp-plus-editor-windows/opener-document';
4
5
  import { createSpriteLayoutMenu } from "./sprite-layout-menu.js";
5
6
  import { NativeAssetPanel, SpriteAssetPane } from '@kubohiroya/turbowarp-plus-editor-sprite-panes/sprite-asset-pane';
6
7
  import { SpriteEditorToolbar, spriteEditorSections } from '@kubohiroya/turbowarp-plus-editor-sprite-panes/sprite-editor-toolbar';
@@ -174,6 +175,8 @@ export function mountSpriteTabs(root, content, options) {
174
175
  const openingGroups = new Set();
175
176
  /** Panels that were in a separate window when the layout was saved, until the user reopens them. */
176
177
  const reopenable = new Map();
178
+ // Each open panel window, connected to this document while it is open.
179
+ const openerConnections = new Map();
177
180
  const originalTargets = () => vm.runtime.targets.filter(target => target.isOriginal);
178
181
  // Whether tabs stand in a column at the left of each split. It is the user's preference for every project.
179
182
  let verticalTabs = false;
@@ -382,7 +385,13 @@ export function mountSpriteTabs(root, content, options) {
382
385
  doc.documentElement.lang = document.documentElement.lang;
383
386
  doc.documentElement.style.cssText = document.documentElement.style.cssText;
384
387
  doc.body.className = `${document.body.className} ${popouts.className ?? ''}`;
388
+ // Dockview copied the styles present now; views opened later bring their own.
389
+ openerConnections.set(child, connectOpenerDocument(doc, { opener: document, mirrorNewStyles: true }));
385
390
  }, { once: true });
391
+ },
392
+ onWillClose({ window: child }) {
393
+ openerConnections.get(child)?.();
394
+ openerConnections.delete(child);
386
395
  }
387
396
  })
388
397
  .then(opened => { if (opened)
@@ -881,8 +890,57 @@ export function mountSpriteTabs(root, content, options) {
881
890
  refreshSurfaces();
882
891
  scheduleSave();
883
892
  }
884
- /** The current workspace as it is saved, or nothing while it cannot be described yet. */
885
- function captureLayout() {
893
+ /** The selected costume and sound of a tab, and its code area, as the workspace saves them. */
894
+ function capturePane(view, live) {
895
+ const pane = {};
896
+ const lists = { costumes: view.target.getCostumes?.(), sounds: view.target.getSounds?.() };
897
+ for (const [kind, field] of [['costumes', 'costume'], ['sounds', 'sound']]) {
898
+ const index = lists[kind]?.indexOf(view.assets.selected.get(kind)) ?? -1;
899
+ if (index >= 0)
900
+ pane[field] = index;
901
+ }
902
+ if (viewAdapter?.serialize) {
903
+ const stored = view.snapshots?.get(0);
904
+ // The tab on screen keeps its code area in the shared editor, which only a save reads.
905
+ const showing = view === active && view.section === 0 && Boolean(slots.get(view.id)?.body.contains(content));
906
+ try {
907
+ const code = showing ? (live ? viewAdapter.serialize(describe(view), undefined) : undefined) :
908
+ stored && viewAdapter.serialize(stored.view, stored.snapshot);
909
+ if (code)
910
+ pane.code = code;
911
+ }
912
+ catch { /* The code area is left as the tab opens by default. */ }
913
+ }
914
+ return Object.keys(pane).length ? pane : undefined;
915
+ }
916
+ /** The asset selections and code snapshot a restored tab opens with. */
917
+ function restorePane(id, target, pane) {
918
+ const selected = new Map();
919
+ const costume = pane?.costume === undefined ? undefined : target.getCostumes?.()[pane.costume];
920
+ const sound = pane?.sound === undefined ? undefined : target.getSounds?.()[pane.sound];
921
+ if (costume)
922
+ selected.set('costumes', costume);
923
+ if (sound)
924
+ selected.set('sounds', sound);
925
+ const assets = createAssetSelections(target, locale, { selected, layouts: new Map(), scroll: new Map() });
926
+ let snapshots;
927
+ if (pane?.code && viewAdapter?.deserialize && pane.code !== null && typeof pane.code === 'object') {
928
+ const view = { id, targetId: target.id, isStage: target.isStage, section: 0, groupId: '',
929
+ active: false, groupActive: false };
930
+ try {
931
+ const snapshot = viewAdapter.deserialize(view, pane.code);
932
+ if (snapshot !== undefined)
933
+ snapshots = new Map([[0, { snapshot, view }]]);
934
+ }
935
+ catch { /* The code area opens as it does by default. */ }
936
+ }
937
+ return { assets, snapshots };
938
+ }
939
+ /**
940
+ * The current workspace as it is saved, or nothing while it cannot be described yet. `live` also reads the code
941
+ * area on screen, which only a save of the project file does.
942
+ */
943
+ function captureLayout(live = false) {
886
944
  const targets = originalTargets();
887
945
  if (!targets.length)
888
946
  return;
@@ -894,8 +952,9 @@ export function mountSpriteTabs(root, content, options) {
894
952
  return;
895
953
  const panels = Object.create(null);
896
954
  for (const [id, view] of views) {
955
+ const pane = capturePane(view, live);
897
956
  panels[id] = { kind: 'sprite', name: targetName(view.target), stage: view.target.isStage, section: view.section,
898
- number: view.number };
957
+ number: view.number, ...(pane && { pane }) };
899
958
  }
900
959
  if (dockview.getPanel(stagePanelId))
901
960
  panels[stagePanelId] = { kind: 'stage' };
@@ -1002,7 +1061,8 @@ export function mountSpriteTabs(root, content, options) {
1002
1061
  }
1003
1062
  /** The tab arrangement and drawer state used to detect a change from the initial layout. */
1004
1063
  function layoutShape(layout) {
1005
- const reference = (id) => layout.panels[id] ?? null;
1064
+ // What a tab shows inside its panes is not a change of the arrangement.
1065
+ const reference = (id) => layout.panels[id] ? { ...layout.panels[id], pane: undefined } : null;
1006
1066
  const shape = (node) => Array.isArray(node.data) ? node.data.map(shape) :
1007
1067
  node.data.views.map(reference);
1008
1068
  return JSON.stringify([layout.grid.orientation, shape(layout.grid.root),
@@ -1049,7 +1109,7 @@ export function mountSpriteTabs(root, content, options) {
1049
1109
  // Until the opened project's layout is restored, the tabs on screen are not that project's.
1050
1110
  if (pendingRestore || !layoutSession)
1051
1111
  return fileLayout ? JSON.parse(fileLayout.layout) : undefined;
1052
- return captureLayout();
1112
+ return captureLayout(true);
1053
1113
  }
1054
1114
  /** Keep the layout the project opened with, so leaving it unchanged adds no record. */
1055
1115
  function keepInitialLayout() {
@@ -1101,7 +1161,7 @@ export function mountSpriteTabs(root, content, options) {
1101
1161
  continue;
1102
1162
  }
1103
1163
  resolvedSprites.set(id, { id, target, section: reference.section, number: reference.number,
1104
- assets: createAssetSelections(target, locale) });
1164
+ ...restorePane(id, target, reference.pane) });
1105
1165
  panels[id] = { id, contentComponent: 'sprite', params: { icon: getIcon(target) } };
1106
1166
  }
1107
1167
  else if (reference.kind === 'stage') {
@@ -1388,6 +1448,9 @@ export function mountSpriteTabs(root, content, options) {
1388
1448
  disposeView(view);
1389
1449
  content.remove();
1390
1450
  dockview.dispose();
1451
+ for (const disconnect of openerConnections.values())
1452
+ disconnect();
1453
+ openerConnections.clear();
1391
1454
  }
1392
1455
  };
1393
1456
  }
@@ -1,12 +1,21 @@
1
1
  import type { SerializedDockview } from 'dockview';
2
2
  import type { DocumentPanelRequest } from './document-workspace.ts';
3
3
  type Grid = SerializedDockview['grid'];
4
+ /** What a sprite tab showed inside its panes. Every field is optional, and a missing one keeps the default. */
5
+ export interface SpritePaneState {
6
+ /** The index of the costume or sound the tab had selected in that list. */
7
+ costume?: number;
8
+ sound?: number;
9
+ /** The code area as the host's tab adapter serialized it, such as its scroll position and zoom. */
10
+ code?: unknown;
11
+ }
4
12
  export type PanelReference = {
5
13
  kind: 'sprite';
6
14
  name: string;
7
15
  stage: boolean;
8
16
  section: number;
9
17
  number?: number;
18
+ pane?: SpritePaneState;
10
19
  } | {
11
20
  kind: 'stage';
12
21
  } | ({
@@ -166,8 +166,9 @@ export function readWorkspaceLayout(raw, project) {
166
166
  const number = panel.number;
167
167
  if (number !== undefined && (typeof number !== 'number' || !Number.isSafeInteger(number) || number < 2))
168
168
  return;
169
+ const pane = readPaneState(panel.pane);
169
170
  panels[id] = { kind: 'sprite', name: panel.name, stage: panel.stage, section: panel.section,
170
- ...(typeof number === 'number' && { number }) };
171
+ ...(typeof number === 'number' && { number }), ...(pane && { pane }) };
171
172
  }
172
173
  else if (panel.kind === 'stage' && !hasStage) {
173
174
  hasStage = true;
@@ -195,6 +196,20 @@ export function readWorkspaceLayout(raw, project) {
195
196
  ...(stageDrawer && { stageDrawer }),
196
197
  ...(popouts.length && { popouts }) };
197
198
  }
199
+ const assetIndex = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 && value <= 100000;
200
+ /** Keep only the fields of a pane state that have the right shape. The code state is checked by the host. */
201
+ function readPaneState(input) {
202
+ if (!record(input))
203
+ return;
204
+ const pane = {};
205
+ if (assetIndex(input.costume))
206
+ pane.costume = input.costume;
207
+ if (assetIndex(input.sound))
208
+ pane.sound = input.sound;
209
+ if (record(input.code))
210
+ pane.code = input.code;
211
+ return Object.keys(pane).length ? pane : undefined;
212
+ }
198
213
  function readStageDrawer(input) {
199
214
  if (!record(input) || typeof input.open !== 'boolean' || typeof input.selected !== 'boolean')
200
215
  return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-plus-editor-workbench",
3
- "version": "0.18.1",
3
+ "version": "0.19.1",
4
4
  "description": "The TurboWarp Plus Editor workbench: layout, dockable sprite tabs, stage, debugger tab and file menu",
5
5
  "type": "module",
6
6
  "license": "MPL-2.0",
@@ -126,7 +126,7 @@
126
126
  },
127
127
  "devDependencies": {
128
128
  "@kubohiroya/turbowarp-plus-editor-git": "0.22.0",
129
- "@kubohiroya/turbowarp-plus-editor-windows": "0.2.0",
129
+ "@kubohiroya/turbowarp-plus-editor-windows": "0.2.1",
130
130
  "@playwright/test": "1.64.1",
131
131
  "@types/react": "18.3.31",
132
132
  "@types/react-dom": "18.3.7",
@@ -148,7 +148,7 @@
148
148
  },
149
149
  "peerDependencies": {
150
150
  "@kubohiroya/turbowarp-plus-editor-git": ">=0.21.0 <0.23.0",
151
- "@kubohiroya/turbowarp-plus-editor-windows": ">=0.2.0 <0.3.0",
151
+ "@kubohiroya/turbowarp-plus-editor-windows": ">=0.2.1 <0.3.0",
152
152
  "react": ">=16.14",
153
153
  "react-dom": ">=16.14"
154
154
  },
@@ -65,6 +65,16 @@ export interface ProjectScreenState {
65
65
  whenLoaded(): Promise<SavedScreenState | undefined>;
66
66
  /** The state a save would write now. */
67
67
  capture(): SavedScreenState | undefined;
68
+ /**
69
+ * The text a save writes, as in the ZIP entry, for a project saved somewhere else such as a project folder.
70
+ * Nothing while saving is turned off, nothing is registered or the state is too large.
71
+ */
72
+ serialize(): string | undefined;
73
+ /**
74
+ * Use the state in `text` for the next project load instead of reading the input, for a project that is not
75
+ * loaded from an SB3, such as a project folder. Text that is not a screen state opens the default screen.
76
+ */
77
+ prepareLoad(text: string | undefined): void;
68
78
  /** Put the VM methods back. Hooks installed later on the same methods must be removed first. */
69
79
  dispose(): void;
70
80
  }
@@ -129,6 +139,8 @@ export function installProjectScreenState(vm: ScreenStateVM, {Zip, save = true,
129
139
  let current: SavedScreenState | undefined;
130
140
  /** Slices already given the current project's state, so registering again does not apply it twice. */
131
141
  let applied = new Set<ScreenStateSlice>();
142
+ /** The state the next load uses instead of its input, set by `prepareLoad`. */
143
+ let prepared: {state: SavedScreenState | undefined} | undefined;
132
144
 
133
145
  const apply = (slice: ScreenStateSlice, key: string) => {
134
146
  if (!current || applied.has(slice) || !Object.hasOwn(current.slices, key)) return;
@@ -162,7 +174,8 @@ export function installProjectScreenState(vm: ScreenStateVM, {Zip, save = true,
162
174
  current = undefined;
163
175
  applied = new Set();
164
176
  // Read in parallel with the VM, which keeps its own copy of the bytes.
165
- const reading = readScreenState(input, Zip);
177
+ const reading = prepared ? Promise.resolve(prepared.state) : readScreenState(input, Zip);
178
+ prepared = undefined;
166
179
  const result = original.loadProject.call(this, input, ...args);
167
180
  const done = result.then(() => reading, () => undefined).then(state => {
168
181
  if (mine !== generation) return;
@@ -202,6 +215,10 @@ export function installProjectScreenState(vm: ScreenStateVM, {Zip, save = true,
202
215
  },
203
216
  whenLoaded: () => loaded,
204
217
  capture,
218
+ serialize: serialized,
219
+ prepareLoad(text) {
220
+ prepared = {state: text === undefined ? undefined : parseScreenState(text)};
221
+ },
205
222
  dispose() {
206
223
  vm.loadProject = original.loadProject;
207
224
  vm._saveProjectZip = original._saveProjectZip;
@@ -2,6 +2,7 @@ import React from 'react';
2
2
  import {createPortal} from 'react-dom';
3
3
  import {createDockview, DefaultTab, themeLight} from 'dockview';
4
4
  import type {DockviewGroupPanel, GroupPanelPartInitParameters, IDockviewPanel, SerializedDockview} from 'dockview';
5
+ import {connectOpenerDocument} from '@kubohiroya/turbowarp-plus-editor-windows/opener-document';
5
6
  import {createSpriteLayoutMenu} from './sprite-layout-menu.ts';
6
7
  import {NativeAssetPanel, SpriteAssetPane} from '@kubohiroya/turbowarp-plus-editor-sprite-panes/sprite-asset-pane';
7
8
  import type {NativeAssetPanelRenderer, NativeAssetSelector, SpriteAssetKind, SpriteAssetLayout, SpriteAssetPreviewItem,
@@ -15,7 +16,7 @@ import type {DocumentPanelRequest} from './document-workspace.ts';
15
16
  import {projectFolderIconPath} from './drawer-views.ts';
16
17
  import {dockPopoutGroups, positionOnScreen, readWorkspaceLayout, workspaceWithoutTransientPanels}
17
18
  from './workspace-layout.ts';
18
- import type {PanelReference, SavedPopout, WorkspaceLayout} from './workspace-layout.ts';
19
+ import type {PanelReference, SavedPopout, SpritePaneState, WorkspaceLayout} from './workspace-layout.ts';
19
20
  import {createWorkspaceLayoutStore} from './workspace-layout-store.ts';
20
21
  import type {WorkspaceLayoutSession, WorkspaceLayoutStore, WorkspaceProjectIdentity} from './workspace-layout-store.ts';
21
22
  import type {ProjectScreenState, SavedScreenState} from './project-screen-state.ts';
@@ -46,6 +47,7 @@ interface Target {
46
47
  isStage: boolean;
47
48
  getName(): string;
48
49
  getCostumes?(): {assetId?: string}[];
50
+ getSounds?(): object[];
49
51
  getCurrentCostume?(): {asset?: CostumeAsset} | undefined;
50
52
  }
51
53
 
@@ -74,6 +76,13 @@ export interface SpriteTabAdapter<Snapshot = unknown> {
74
76
  renderInactive(container: HTMLElement, view: SpriteTabView, snapshot: Snapshot | undefined): void | (() => void);
75
77
  restore(view: SpriteTabView, snapshot: Snapshot | undefined): void;
76
78
  dispose?(view: SpriteTabView, snapshot: Snapshot): void;
79
+ /**
80
+ * Describe a snapshot of the code area as a small JSON object for the saved workspace, such as its scroll
81
+ * position and zoom. Without a snapshot, describe the mounted surface as it is now, without changing it.
82
+ */
83
+ serialize?(view: SpriteTabView, snapshot: Snapshot | undefined): Record<string, unknown> | undefined;
84
+ /** Turn a value `serialize` wrote back into a snapshot. The value comes from a file, so check its shape. */
85
+ deserialize?(view: SpriteTabView, value: Record<string, unknown>): Snapshot | undefined;
77
86
  }
78
87
 
79
88
  /** Optional bridge used by a native asset editor to restore and report its selection. */
@@ -333,6 +342,8 @@ export function mountSpriteTabs<Snapshot>(root: HTMLElement, content: HTMLElemen
333
342
  const openingGroups = new Set<string>();
334
343
  /** Panels that were in a separate window when the layout was saved, until the user reopens them. */
335
344
  const reopenable = new Map<string, SavedPopout>();
345
+ // Each open panel window, connected to this document while it is open.
346
+ const openerConnections = new Map<Window, () => void>();
336
347
  const originalTargets = () => vm.runtime.targets.filter(target => target.isOriginal);
337
348
  // Whether tabs stand in a column at the left of each split. It is the user's preference for every project.
338
349
  let verticalTabs = false;
@@ -523,7 +534,13 @@ export function mountSpriteTabs<Snapshot>(root: HTMLElement, content: HTMLElemen
523
534
  doc.documentElement.lang = document.documentElement.lang;
524
535
  doc.documentElement.style.cssText = document.documentElement.style.cssText;
525
536
  doc.body.className = `${document.body.className} ${popouts.className ?? ''}`;
537
+ // Dockview copied the styles present now; views opened later bring their own.
538
+ openerConnections.set(child, connectOpenerDocument(doc, {opener: document, mirrorNewStyles: true}));
526
539
  }, {once: true});
540
+ },
541
+ onWillClose({window: child}) {
542
+ openerConnections.get(child)?.();
543
+ openerConnections.delete(child);
527
544
  }
528
545
  })
529
546
  .then(opened => { if (opened) reopenable.delete(panel.id); })
@@ -998,8 +1015,52 @@ export function mountSpriteTabs<Snapshot>(root: HTMLElement, content: HTMLElemen
998
1015
  scheduleSave();
999
1016
  }
1000
1017
 
1001
- /** The current workspace as it is saved, or nothing while it cannot be described yet. */
1002
- function captureLayout(): WorkspaceLayout | undefined {
1018
+ /** The selected costume and sound of a tab, and its code area, as the workspace saves them. */
1019
+ function capturePane(view: View<Snapshot>, live: boolean): SpritePaneState | undefined {
1020
+ const pane: SpritePaneState = {};
1021
+ const lists = {costumes: view.target.getCostumes?.(), sounds: view.target.getSounds?.()};
1022
+ for (const [kind, field] of [['costumes', 'costume'], ['sounds', 'sound']] as const) {
1023
+ const index = lists[kind]?.indexOf(view.assets.selected.get(kind) as never) ?? -1;
1024
+ if (index >= 0) pane[field] = index;
1025
+ }
1026
+ if (viewAdapter?.serialize) {
1027
+ const stored = view.snapshots?.get(0);
1028
+ // The tab on screen keeps its code area in the shared editor, which only a save reads.
1029
+ const showing = view === active && view.section === 0 && Boolean(slots.get(view.id)?.body.contains(content));
1030
+ try {
1031
+ const code = showing ? (live ? viewAdapter.serialize(describe(view), undefined) : undefined) :
1032
+ stored && viewAdapter.serialize(stored.view, stored.snapshot);
1033
+ if (code) pane.code = code;
1034
+ } catch { /* The code area is left as the tab opens by default. */ }
1035
+ }
1036
+ return Object.keys(pane).length ? pane : undefined;
1037
+ }
1038
+
1039
+ /** The asset selections and code snapshot a restored tab opens with. */
1040
+ function restorePane(id: string, target: Target, pane: SpritePaneState | undefined) {
1041
+ const selected = new Map<AssetKind, object>();
1042
+ const costume = pane?.costume === undefined ? undefined : target.getCostumes?.()[pane.costume];
1043
+ const sound = pane?.sound === undefined ? undefined : target.getSounds?.()[pane.sound];
1044
+ if (costume) selected.set('costumes', costume);
1045
+ if (sound) selected.set('sounds', sound);
1046
+ const assets = createAssetSelections(target, locale, {selected, layouts: new Map(), scroll: new Map()});
1047
+ let snapshots: View<Snapshot>['snapshots'];
1048
+ if (pane?.code && viewAdapter?.deserialize && pane.code !== null && typeof pane.code === 'object') {
1049
+ const view: SpriteTabView = {id, targetId: target.id, isStage: target.isStage, section: 0, groupId: '',
1050
+ active: false, groupActive: false};
1051
+ try {
1052
+ const snapshot = viewAdapter.deserialize(view, pane.code as Record<string, unknown>);
1053
+ if (snapshot !== undefined) snapshots = new Map([[0, {snapshot, view}]]);
1054
+ } catch { /* The code area opens as it does by default. */ }
1055
+ }
1056
+ return {assets, snapshots};
1057
+ }
1058
+
1059
+ /**
1060
+ * The current workspace as it is saved, or nothing while it cannot be described yet. `live` also reads the code
1061
+ * area on screen, which only a save of the project file does.
1062
+ */
1063
+ function captureLayout(live = false): WorkspaceLayout | undefined {
1003
1064
  const targets = originalTargets();
1004
1065
  if (!targets.length) return;
1005
1066
  const serialized = dockview.toJSON();
@@ -1008,8 +1069,9 @@ export function mountSpriteTabs<Snapshot>(root: HTMLElement, content: HTMLElemen
1008
1069
  if (!docked) return;
1009
1070
  const panels: Record<string, PanelReference> = Object.create(null);
1010
1071
  for (const [id, view] of views) {
1072
+ const pane = capturePane(view, live);
1011
1073
  panels[id] = {kind: 'sprite', name: targetName(view.target), stage: view.target.isStage, section: view.section,
1012
- number: view.number};
1074
+ number: view.number, ...(pane && {pane})};
1013
1075
  }
1014
1076
  if (dockview.getPanel(stagePanelId)) panels[stagePanelId] = {kind: 'stage'};
1015
1077
  const transient = new Set<string>();
@@ -1110,7 +1172,8 @@ export function mountSpriteTabs<Snapshot>(root: HTMLElement, content: HTMLElemen
1110
1172
  /** The tab arrangement and drawer state used to detect a change from the initial layout. */
1111
1173
  function layoutShape(layout: WorkspaceLayout) {
1112
1174
  type Node = WorkspaceLayout['grid']['root'];
1113
- const reference = (id: string) => layout.panels[id] ?? null;
1175
+ // What a tab shows inside its panes is not a change of the arrangement.
1176
+ const reference = (id: string) => layout.panels[id] ? {...layout.panels[id], pane: undefined} : null;
1114
1177
  const shape = (node: Node): unknown => Array.isArray(node.data) ? node.data.map(shape) :
1115
1178
  node.data.views.map(reference);
1116
1179
  return JSON.stringify([layout.grid.orientation, shape(layout.grid.root),
@@ -1154,7 +1217,7 @@ export function mountSpriteTabs<Snapshot>(root: HTMLElement, content: HTMLElemen
1154
1217
  function captureFileWorkspace(): WorkspaceLayout | undefined {
1155
1218
  // Until the opened project's layout is restored, the tabs on screen are not that project's.
1156
1219
  if (pendingRestore || !layoutSession) return fileLayout ? JSON.parse(fileLayout.layout) : undefined;
1157
- return captureLayout();
1220
+ return captureLayout(true);
1158
1221
  }
1159
1222
 
1160
1223
  /** Keep the layout the project opened with, so leaving it unchanged adds no record. */
@@ -1202,7 +1265,7 @@ export function mountSpriteTabs<Snapshot>(root: HTMLElement, content: HTMLElemen
1202
1265
  continue;
1203
1266
  }
1204
1267
  resolvedSprites.set(id, {id, target, section: reference.section, number: reference.number,
1205
- assets: createAssetSelections(target, locale)});
1268
+ ...restorePane(id, target, reference.pane)});
1206
1269
  panels[id] = {id, contentComponent: 'sprite', params: {icon: getIcon(target)}};
1207
1270
  } else if (reference.kind === 'stage') {
1208
1271
  if (id !== stagePanelId) return keepInitialLayout();
@@ -1450,6 +1513,8 @@ export function mountSpriteTabs<Snapshot>(root: HTMLElement, content: HTMLElemen
1450
1513
  for (const view of views.values()) disposeView(view);
1451
1514
  content.remove();
1452
1515
  dockview.dispose();
1516
+ for (const disconnect of openerConnections.values()) disconnect();
1517
+ openerConnections.clear();
1453
1518
  }
1454
1519
  };
1455
1520
  }
@@ -4,8 +4,17 @@ import type {DocumentPanelRequest} from './document-workspace.ts';
4
4
 
5
5
  type Grid = SerializedDockview['grid'];
6
6
  type Node = Grid['root'];
7
+ /** What a sprite tab showed inside its panes. Every field is optional, and a missing one keeps the default. */
8
+ export interface SpritePaneState {
9
+ /** The index of the costume or sound the tab had selected in that list. */
10
+ costume?: number;
11
+ sound?: number;
12
+ /** The code area as the host's tab adapter serialized it, such as its scroll position and zoom. */
13
+ code?: unknown;
14
+ }
15
+
7
16
  export type PanelReference =
8
- | {kind: 'sprite'; name: string; stage: boolean; section: number; number?: number}
17
+ | {kind: 'sprite'; name: string; stage: boolean; section: number; number?: number; pane?: SpritePaneState}
9
18
  | {kind: 'stage'}
10
19
  | ({kind: 'document'} & DocumentPanelRequest['reference']);
11
20
 
@@ -189,8 +198,9 @@ export function readWorkspaceLayout(raw: string, project?: string): WorkspaceLay
189
198
  typeof panel.section === 'number' && Number.isInteger(panel.section) && panel.section >= 0 && panel.section <= 4) {
190
199
  const number = panel.number;
191
200
  if (number !== undefined && (typeof number !== 'number' || !Number.isSafeInteger(number) || number < 2)) return;
201
+ const pane = readPaneState(panel.pane);
192
202
  panels[id] = {kind: 'sprite', name: panel.name, stage: panel.stage, section: panel.section,
193
- ...(typeof number === 'number' && {number})};
203
+ ...(typeof number === 'number' && {number}), ...(pane && {pane})};
194
204
  } else if (panel.kind === 'stage' && !hasStage) {
195
205
  hasStage = true;
196
206
  panels[id] = {kind: 'stage'};
@@ -212,6 +222,19 @@ export function readWorkspaceLayout(raw: string, project?: string): WorkspaceLay
212
222
  ...(popouts.length && {popouts})};
213
223
  }
214
224
 
225
+ const assetIndex = (value: unknown): value is number =>
226
+ typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 && value <= 100000;
227
+
228
+ /** Keep only the fields of a pane state that have the right shape. The code state is checked by the host. */
229
+ function readPaneState(input: unknown): SpritePaneState | undefined {
230
+ if (!record(input)) return;
231
+ const pane: SpritePaneState = {};
232
+ if (assetIndex(input.costume)) pane.costume = input.costume;
233
+ if (assetIndex(input.sound)) pane.sound = input.sound;
234
+ if (record(input.code)) pane.code = input.code;
235
+ return Object.keys(pane).length ? pane : undefined;
236
+ }
237
+
215
238
  function readStageDrawer(input: unknown): StageDrawerLayout | undefined {
216
239
  if (!record(input) || typeof input.open !== 'boolean' || typeof input.selected !== 'boolean') return;
217
240
  const {position, width, pinned} = input;