@kubohiroya/turbowarp-plus-editor-workbench 0.18.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -26,6 +26,11 @@ export interface WorkspaceLayoutSession {
26
26
  readonly exact: boolean;
27
27
  /** Whether the project has a saved layout, or a change was written in this session. */
28
28
  readonly saved: boolean;
29
+ /**
30
+ * When the saved layout was last changed, in milliseconds since the epoch. Missing for records written before
31
+ * it was kept, which count as older than any layout saved in a project file.
32
+ */
33
+ readonly savedAt?: number;
29
34
  /** Save the layout. The project's own record is updated, so it never adds a record per change. */
30
35
  write(layout: string, signature: string): Promise<void>;
31
36
  }
@@ -142,6 +142,7 @@ export function createWorkspaceLayoutStore({ indexedDB: factory = globalThis.ind
142
142
  const found = await find(opened, identity, signature);
143
143
  let id = found?.id;
144
144
  let written = false;
145
+ let savedAt = found?.savedAt;
145
146
  if (id !== undefined)
146
147
  await enqueue(() => touch(opened, id, now()));
147
148
  const fields = identityFields(identity);
@@ -149,13 +150,15 @@ export function createWorkspaceLayoutStore({ indexedDB: factory = globalThis.ind
149
150
  layout: found?.layout,
150
151
  exact: Boolean(found) && identity.kind !== 'anonymous',
151
152
  get saved() { return id !== undefined || written; },
153
+ get savedAt() { return savedAt; },
152
154
  write(layout, nextSignature) {
153
155
  if (bytes(layout) > maxBytes)
154
156
  return Promise.resolve();
155
157
  written = true;
158
+ const time = savedAt = now();
156
159
  return enqueue(async () => {
157
160
  id = await save(opened, { ...fields, ...(id !== undefined && { id }), signature: nextSignature, layout,
158
- lastUsedAt: now() }, limit);
161
+ lastUsedAt: time, savedAt: time }, limit);
159
162
  });
160
163
  }
161
164
  };
@@ -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.0",
3
+ "version": "0.19.0",
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",
@@ -72,6 +72,10 @@
72
72
  "types": "./dist/project-messages.d.ts",
73
73
  "default": "./dist/project-messages.js"
74
74
  },
75
+ "./project-screen-state": {
76
+ "types": "./dist/project-screen-state.d.ts",
77
+ "default": "./dist/project-screen-state.js"
78
+ },
75
79
  "./project-search": {
76
80
  "types": "./dist/project-search-box.d.ts",
77
81
  "default": "./dist/project-search-box.js"
@@ -33,6 +33,8 @@ interface DebuggerPanelOptions {
33
33
  export const dockedClass = 'tw-plus-debugger-docked';
34
34
  export const debuggerReference = Object.freeze({providerId: 'turbowarp-plus', documentId: 'debugger'});
35
35
  const buttonSelector = '.sa-debugger-container';
36
+ // The add-on shows its Continue button only while the project is paused.
37
+ const unpauseSelector = '.sa-debugger-unpause-container';
36
38
 
37
39
  /** The ladybug that marks debugging in the editor, as an image for the tab. */
38
40
  export const debuggerTabIcon = 'data:image/svg+xml,' + encodeURIComponent(
@@ -102,6 +104,21 @@ export function attachDebuggerPanel (debuggerInterface: DebuggerInterface, optio
102
104
  });
103
105
  observer.observe(element, {attributes: true, attributeFilter: ['style']});
104
106
 
107
+ // A pause (a breakpoint, the breakpoint block, or Step) makes the add-on show the debugger, but
108
+ // when the tab is already open behind another one nothing changes on screen. Bring it forward
109
+ // when the Continue button appears, so the person sees why the project stopped.
110
+ const isPausedShown = () => {
111
+ const unpause = element.querySelector<HTMLElement>(unpauseSelector);
112
+ return Boolean(unpause) && unpause.style.display !== 'none';
113
+ };
114
+ let pausedShown = isPausedShown();
115
+ const pauseObserver = new document.defaultView.MutationObserver(() => {
116
+ const shown = isPausedShown();
117
+ if (shown && !pausedShown && close) dock();
118
+ pausedShown = shown;
119
+ });
120
+ pauseObserver.observe(element, {attributes: true, attributeFilter: ['style'], subtree: true, childList: true});
121
+
105
122
  // Opening an already open debugger leaves its style as it is, so the tab is brought forward here.
106
123
  const handleButton = (event: Event) => {
107
124
  if (close && (event.target as Element | null)?.closest?.(buttonSelector)) dock();
@@ -122,6 +139,7 @@ export function attachDebuggerPanel (debuggerInterface: DebuggerInterface, optio
122
139
  return {
123
140
  dispose () {
124
141
  observer.disconnect();
142
+ pauseObserver.disconnect();
125
143
  document.removeEventListener('click', handleButton);
126
144
  element.removeEventListener('pointerdown', handlePointerDown, {capture: true});
127
145
  close?.();
@@ -0,0 +1,228 @@
1
+ /**
2
+ * Keeps the screen of a project inside its SB3, so the project opens the way it was when it was saved: the drawer
3
+ * view, the tabs with the files and panes they showed, and whatever else a part of the editor registers.
4
+ *
5
+ * The state is a ZIP entry next to `project.json`. Scratch and TurboWarp ignore entries they do not know, so the
6
+ * file stays compatible, and saving it in another editor only drops the entry. Each part of the editor registers a
7
+ * slice under its own key; this module only carries the slices and hands each one back after a project loads.
8
+ */
9
+
10
+ /** The ZIP entry that holds the screen state. */
11
+ export const screenStateEntry = 'tw-plus/workspace.json';
12
+ /** The largest screen state that is read or written, in bytes. */
13
+ export const screenStateMaxBytes = 512 * 1024;
14
+
15
+ export interface SavedScreenState {
16
+ version: 1;
17
+ /** When the project was saved, in milliseconds since the epoch. */
18
+ savedAt: number;
19
+ slices: Record<string, unknown>;
20
+ }
21
+
22
+ export interface ScreenStateSlice {
23
+ /** The value written for this slice, or nothing to leave it out. Called synchronously while saving. */
24
+ capture(): unknown;
25
+ /**
26
+ * Called once for each loaded project that carries this slice, after the VM finished loading it, or when the
27
+ * slice is registered after that. The value comes from a file, so check its shape before using it.
28
+ */
29
+ apply?(value: unknown, savedAt: number): void;
30
+ }
31
+
32
+ interface ZipEntry {
33
+ async(type: 'string'): Promise<string>;
34
+ _data?: {uncompressedSize?: number};
35
+ }
36
+ interface ReadableZip {
37
+ file(name: string): ZipEntry | null;
38
+ }
39
+ interface WritableZip {
40
+ file(name: string, data: string, options?: {createFolders?: boolean}): unknown;
41
+ remove(name: string): unknown;
42
+ }
43
+ /** The JSZip constructor the host already bundles, such as `@turbowarp/jszip`. */
44
+ export interface ScreenStateZip {
45
+ loadAsync(bytes: ArrayBuffer | Uint8Array): Promise<ReadableZip>;
46
+ }
47
+
48
+ export interface ScreenStateVM {
49
+ loadProject(input: unknown, ...args: unknown[]): Promise<unknown>;
50
+ _saveProjectZip(...args: unknown[]): WritableZip;
51
+ saveProjectSb3DontZip?(...args: unknown[]): Record<string, Uint8Array>;
52
+ }
53
+
54
+ export interface ProjectScreenStateOptions {
55
+ Zip: ScreenStateZip;
56
+ /** Whether saving writes the screen state. Reading stays on, so files saved earlier still open as they were. */
57
+ save?: boolean;
58
+ now?(): number;
59
+ }
60
+
61
+ export interface ProjectScreenState {
62
+ /** Add a slice. Returns a function that removes it. */
63
+ register(key: string, slice: ScreenStateSlice): () => void;
64
+ /** The state read from the project loaded last, once that load finished. */
65
+ whenLoaded(): Promise<SavedScreenState | undefined>;
66
+ /** The state a save would write now. */
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;
78
+ /** Put the VM methods back. Hooks installed later on the same methods must be removed first. */
79
+ dispose(): void;
80
+ }
81
+
82
+ const encoder = new TextEncoder();
83
+ const record = (value: unknown): value is Record<string, unknown> =>
84
+ value !== null && typeof value === 'object' && !Array.isArray(value);
85
+ const validKey = (key: unknown): key is string => typeof key === 'string' && /^[a-z][a-zA-Z0-9-]{0,63}$/.test(key);
86
+
87
+ /** Read the screen state from the text of the ZIP entry, or nothing if it is not one. */
88
+ export function parseScreenState(text: string): SavedScreenState | undefined {
89
+ if (text.length > screenStateMaxBytes) return;
90
+ let input: unknown;
91
+ try { input = JSON.parse(text); } catch { return; }
92
+ if (!record(input) || input.version !== 1 || !record(input.slices)) return;
93
+ const savedAt = input.savedAt;
94
+ if (typeof savedAt !== 'number' || !Number.isFinite(savedAt) || savedAt < 0) return;
95
+ // A plain object is safe: a valid key never starts with an underscore, so `__proto__` is never assigned.
96
+ const slices: Record<string, unknown> = {};
97
+ for (const [key, value] of Object.entries(input.slices)) if (validKey(key) && value !== undefined) slices[key] = value;
98
+ return {version: 1, savedAt, slices};
99
+ }
100
+
101
+ const bytesOf = (input: unknown): ArrayBuffer | Uint8Array | undefined => {
102
+ if (input instanceof ArrayBuffer) return input;
103
+ if (ArrayBuffer.isView(input)) return new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
104
+ };
105
+
106
+ /** Read the screen state from a project as the VM receives it. A project without one, or not a ZIP, has none. */
107
+ export async function readScreenState(input: unknown, Zip: ScreenStateZip): Promise<SavedScreenState | undefined> {
108
+ const bytes = bytesOf(input);
109
+ if (!bytes || bytes.byteLength < 4) return;
110
+ const head = new Uint8Array(bytes instanceof ArrayBuffer ? bytes : bytes.buffer, bytes instanceof ArrayBuffer ? 0 :
111
+ bytes.byteOffset, 2);
112
+ if (head[0] !== 0x50 || head[1] !== 0x4b) return;
113
+ try {
114
+ const entry = (await Zip.loadAsync(bytes)).file(screenStateEntry);
115
+ if (!entry) return;
116
+ // The size from the central directory, so a crafted entry is never inflated to find out.
117
+ const size = entry._data?.uncompressedSize;
118
+ if (typeof size === 'number' && size > screenStateMaxBytes) return;
119
+ return parseScreenState(await entry.async('string'));
120
+ } catch {
121
+ // The VM reports a broken file itself; the project only opens with its default screen.
122
+ }
123
+ }
124
+
125
+ /**
126
+ * Wrap the VM's load and save methods. Install it after the extension loader's bridge, so this entry is written
127
+ * last and an entry carried over from the loaded file never stays.
128
+ */
129
+ export function installProjectScreenState(vm: ScreenStateVM, {Zip, save = true, now = Date.now}: ProjectScreenStateOptions):
130
+ ProjectScreenState {
131
+ const slices = new Map<string, ScreenStateSlice>();
132
+ const original = {
133
+ loadProject: vm.loadProject,
134
+ _saveProjectZip: vm._saveProjectZip,
135
+ saveProjectSb3DontZip: vm.saveProjectSb3DontZip
136
+ };
137
+ let generation = 0;
138
+ let loaded: Promise<SavedScreenState | undefined> = Promise.resolve(undefined);
139
+ let current: SavedScreenState | undefined;
140
+ /** Slices already given the current project's state, so registering again does not apply it twice. */
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;
144
+
145
+ const apply = (slice: ScreenStateSlice, key: string) => {
146
+ if (!current || applied.has(slice) || !Object.hasOwn(current.slices, key)) return;
147
+ applied.add(slice);
148
+ try {
149
+ slice.apply?.(current.slices[key], current.savedAt);
150
+ } catch { /* One slice that cannot use its value leaves the others. */ }
151
+ };
152
+
153
+ function capture(): SavedScreenState | undefined {
154
+ const captured: Record<string, unknown> = {};
155
+ for (const [key, slice] of slices) {
156
+ try {
157
+ const value = slice.capture();
158
+ if (value !== undefined) captured[key] = value;
159
+ } catch { /* A slice that cannot be described is left out. */ }
160
+ }
161
+ if (!Object.keys(captured).length) return;
162
+ return {version: 1, savedAt: now(), slices: captured};
163
+ }
164
+
165
+ const serialized = () => {
166
+ const state = save ? capture() : undefined;
167
+ if (!state) return;
168
+ const text = JSON.stringify(state);
169
+ return encoder.encode(text).length > screenStateMaxBytes ? undefined : text;
170
+ };
171
+
172
+ vm.loadProject = function(input, ...args) {
173
+ const mine = ++generation;
174
+ current = undefined;
175
+ applied = new Set();
176
+ // Read in parallel with the VM, which keeps its own copy of the bytes.
177
+ const reading = prepared ? Promise.resolve(prepared.state) : readScreenState(input, Zip);
178
+ prepared = undefined;
179
+ const result = original.loadProject.call(this, input, ...args);
180
+ const done = result.then(() => reading, () => undefined).then(state => {
181
+ if (mine !== generation) return;
182
+ current = state;
183
+ for (const [key, slice] of slices) apply(slice, key);
184
+ return state;
185
+ });
186
+ loaded = done;
187
+ return result;
188
+ };
189
+ vm._saveProjectZip = function(...args) {
190
+ const zip = original._saveProjectZip.apply(this, args);
191
+ const text = serialized();
192
+ if (text === undefined) zip.remove(screenStateEntry);
193
+ else zip.file(screenStateEntry, text, {createFolders: false});
194
+ return zip;
195
+ };
196
+ if (original.saveProjectSb3DontZip) {
197
+ vm.saveProjectSb3DontZip = function(...args) {
198
+ const files = {...original.saveProjectSb3DontZip!.apply(this, args)};
199
+ delete files[screenStateEntry];
200
+ const text = serialized();
201
+ if (text !== undefined) files[screenStateEntry] = encoder.encode(text);
202
+ return files;
203
+ };
204
+ }
205
+
206
+ return {
207
+ register(key, slice) {
208
+ if (!validKey(key)) throw new TypeError(`Invalid screen state key: ${key}`);
209
+ if (slices.has(key)) throw new Error(`The screen state key is already registered: ${key}`);
210
+ slices.set(key, slice);
211
+ apply(slice, key);
212
+ return () => {
213
+ if (slices.get(key) === slice) slices.delete(key);
214
+ };
215
+ },
216
+ whenLoaded: () => loaded,
217
+ capture,
218
+ serialize: serialized,
219
+ prepareLoad(text) {
220
+ prepared = {state: text === undefined ? undefined : parseScreenState(text)};
221
+ },
222
+ dispose() {
223
+ vm.loadProject = original.loadProject;
224
+ vm._saveProjectZip = original._saveProjectZip;
225
+ if (original.saveProjectSb3DontZip) vm.saveProjectSb3DontZip = original.saveProjectSb3DontZip;
226
+ }
227
+ };
228
+ }
@@ -15,9 +15,10 @@ import type {DocumentPanelRequest} from './document-workspace.ts';
15
15
  import {projectFolderIconPath} from './drawer-views.ts';
16
16
  import {dockPopoutGroups, positionOnScreen, readWorkspaceLayout, workspaceWithoutTransientPanels}
17
17
  from './workspace-layout.ts';
18
- import type {PanelReference, SavedPopout, WorkspaceLayout} from './workspace-layout.ts';
18
+ import type {PanelReference, SavedPopout, SpritePaneState, WorkspaceLayout} from './workspace-layout.ts';
19
19
  import {createWorkspaceLayoutStore} from './workspace-layout-store.ts';
20
20
  import type {WorkspaceLayoutSession, WorkspaceLayoutStore, WorkspaceProjectIdentity} from './workspace-layout-store.ts';
21
+ import type {ProjectScreenState, SavedScreenState} from './project-screen-state.ts';
21
22
  import type {SpriteVariableEdit, SpriteVariableEditError} from '@kubohiroya/turbowarp-plus-editor-project-model/sprite-variable-edit';
22
23
  import {SpriteMessagePane} from '@kubohiroya/turbowarp-plus-editor-sprite-panes/sprite-message-pane';
23
24
  import type {MessageRenameError} from '@kubohiroya/turbowarp-plus-editor-sprite-panes/sprite-message-pane';
@@ -45,6 +46,7 @@ interface Target {
45
46
  isStage: boolean;
46
47
  getName(): string;
47
48
  getCostumes?(): {assetId?: string}[];
49
+ getSounds?(): object[];
48
50
  getCurrentCostume?(): {asset?: CostumeAsset} | undefined;
49
51
  }
50
52
 
@@ -73,6 +75,13 @@ export interface SpriteTabAdapter<Snapshot = unknown> {
73
75
  renderInactive(container: HTMLElement, view: SpriteTabView, snapshot: Snapshot | undefined): void | (() => void);
74
76
  restore(view: SpriteTabView, snapshot: Snapshot | undefined): void;
75
77
  dispose?(view: SpriteTabView, snapshot: Snapshot): void;
78
+ /**
79
+ * Describe a snapshot of the code area as a small JSON object for the saved workspace, such as its scroll
80
+ * position and zoom. Without a snapshot, describe the mounted surface as it is now, without changing it.
81
+ */
82
+ serialize?(view: SpriteTabView, snapshot: Snapshot | undefined): Record<string, unknown> | undefined;
83
+ /** Turn a value `serialize` wrote back into a snapshot. The value comes from a file, so check its shape. */
84
+ deserialize?(view: SpriteTabView, value: Record<string, unknown>): Snapshot | undefined;
76
85
  }
77
86
 
78
87
  /** Optional bridge used by a native asset editor to restore and report its selection. */
@@ -162,6 +171,11 @@ interface TabOptions<Snapshot = unknown> {
162
171
  identify?(): WorkspaceProjectIdentity | undefined;
163
172
  isProjectLoading?(): boolean;
164
173
  subscribeProject?(listener: () => void): (() => void) | undefined;
174
+ /**
175
+ * The screen state kept in the project file. Saving writes the workspace into it, and opening uses the one
176
+ * in the file when it is newer than the layout this browser kept for the project.
177
+ */
178
+ screenState?: ProjectScreenState;
165
179
  };
166
180
  stagePane?: DockviewStagePane;
167
181
  variables?: boolean;
@@ -302,6 +316,8 @@ export function mountSpriteTabs<Snapshot>(root: HTMLElement, content: HTMLElemen
302
316
  const layoutStore = persistence ? persistence.store ?? createWorkspaceLayoutStore() : undefined;
303
317
  /** Where the layout of the loaded project is saved, once that project is identified. */
304
318
  let layoutSession: WorkspaceLayoutSession | undefined;
319
+ /** The workspace kept in the loaded project file, as the text the store keeps, and when the file was saved. */
320
+ let fileLayout: {layout: string; savedAt: number} | undefined;
305
321
  /** Counts project loads, so a lookup that ends after another project opened is dropped. */
306
322
  let projectGeneration = 0;
307
323
  let openingGeneration: number | undefined;
@@ -990,8 +1006,52 @@ export function mountSpriteTabs<Snapshot>(root: HTMLElement, content: HTMLElemen
990
1006
  scheduleSave();
991
1007
  }
992
1008
 
993
- /** The current workspace as it is saved, or nothing while it cannot be described yet. */
994
- function captureLayout(): WorkspaceLayout | undefined {
1009
+ /** The selected costume and sound of a tab, and its code area, as the workspace saves them. */
1010
+ function capturePane(view: View<Snapshot>, live: boolean): SpritePaneState | undefined {
1011
+ const pane: SpritePaneState = {};
1012
+ const lists = {costumes: view.target.getCostumes?.(), sounds: view.target.getSounds?.()};
1013
+ for (const [kind, field] of [['costumes', 'costume'], ['sounds', 'sound']] as const) {
1014
+ const index = lists[kind]?.indexOf(view.assets.selected.get(kind) as never) ?? -1;
1015
+ if (index >= 0) pane[field] = index;
1016
+ }
1017
+ if (viewAdapter?.serialize) {
1018
+ const stored = view.snapshots?.get(0);
1019
+ // The tab on screen keeps its code area in the shared editor, which only a save reads.
1020
+ const showing = view === active && view.section === 0 && Boolean(slots.get(view.id)?.body.contains(content));
1021
+ try {
1022
+ const code = showing ? (live ? viewAdapter.serialize(describe(view), undefined) : undefined) :
1023
+ stored && viewAdapter.serialize(stored.view, stored.snapshot);
1024
+ if (code) pane.code = code;
1025
+ } catch { /* The code area is left as the tab opens by default. */ }
1026
+ }
1027
+ return Object.keys(pane).length ? pane : undefined;
1028
+ }
1029
+
1030
+ /** The asset selections and code snapshot a restored tab opens with. */
1031
+ function restorePane(id: string, target: Target, pane: SpritePaneState | undefined) {
1032
+ const selected = new Map<AssetKind, object>();
1033
+ const costume = pane?.costume === undefined ? undefined : target.getCostumes?.()[pane.costume];
1034
+ const sound = pane?.sound === undefined ? undefined : target.getSounds?.()[pane.sound];
1035
+ if (costume) selected.set('costumes', costume);
1036
+ if (sound) selected.set('sounds', sound);
1037
+ const assets = createAssetSelections(target, locale, {selected, layouts: new Map(), scroll: new Map()});
1038
+ let snapshots: View<Snapshot>['snapshots'];
1039
+ if (pane?.code && viewAdapter?.deserialize && pane.code !== null && typeof pane.code === 'object') {
1040
+ const view: SpriteTabView = {id, targetId: target.id, isStage: target.isStage, section: 0, groupId: '',
1041
+ active: false, groupActive: false};
1042
+ try {
1043
+ const snapshot = viewAdapter.deserialize(view, pane.code as Record<string, unknown>);
1044
+ if (snapshot !== undefined) snapshots = new Map([[0, {snapshot, view}]]);
1045
+ } catch { /* The code area opens as it does by default. */ }
1046
+ }
1047
+ return {assets, snapshots};
1048
+ }
1049
+
1050
+ /**
1051
+ * The current workspace as it is saved, or nothing while it cannot be described yet. `live` also reads the code
1052
+ * area on screen, which only a save of the project file does.
1053
+ */
1054
+ function captureLayout(live = false): WorkspaceLayout | undefined {
995
1055
  const targets = originalTargets();
996
1056
  if (!targets.length) return;
997
1057
  const serialized = dockview.toJSON();
@@ -1000,8 +1060,9 @@ export function mountSpriteTabs<Snapshot>(root: HTMLElement, content: HTMLElemen
1000
1060
  if (!docked) return;
1001
1061
  const panels: Record<string, PanelReference> = Object.create(null);
1002
1062
  for (const [id, view] of views) {
1063
+ const pane = capturePane(view, live);
1003
1064
  panels[id] = {kind: 'sprite', name: targetName(view.target), stage: view.target.isStage, section: view.section,
1004
- number: view.number};
1065
+ number: view.number, ...(pane && {pane})};
1005
1066
  }
1006
1067
  if (dockview.getPanel(stagePanelId)) panels[stagePanelId] = {kind: 'stage'};
1007
1068
  const transient = new Set<string>();
@@ -1102,7 +1163,8 @@ export function mountSpriteTabs<Snapshot>(root: HTMLElement, content: HTMLElemen
1102
1163
  /** The tab arrangement and drawer state used to detect a change from the initial layout. */
1103
1164
  function layoutShape(layout: WorkspaceLayout) {
1104
1165
  type Node = WorkspaceLayout['grid']['root'];
1105
- const reference = (id: string) => layout.panels[id] ?? null;
1166
+ // What a tab shows inside its panes is not a change of the arrangement.
1167
+ const reference = (id: string) => layout.panels[id] ? {...layout.panels[id], pane: undefined} : null;
1106
1168
  const shape = (node: Node): unknown => Array.isArray(node.data) ? node.data.map(shape) :
1107
1169
  node.data.views.map(reference);
1108
1170
  return JSON.stringify([layout.grid.orientation, shape(layout.grid.root),
@@ -1121,9 +1183,12 @@ export function mountSpriteTabs<Snapshot>(root: HTMLElement, content: HTMLElemen
1121
1183
  function openLayoutSession(signature: string) {
1122
1184
  if (!layoutStore || openingGeneration === projectGeneration) return;
1123
1185
  const generation = openingGeneration = projectGeneration;
1124
- layoutStore.open(identifyProject(), signature).then(session => {
1186
+ const fileState = persistence && persistence.screenState ?
1187
+ persistence.screenState.whenLoaded().catch(() => undefined) : Promise.resolve(undefined);
1188
+ Promise.all([layoutStore.open(identifyProject(), signature), fileState]).then(([session, state]) => {
1125
1189
  if (disposed || generation !== projectGeneration) return;
1126
1190
  layoutSession = session;
1191
+ fileLayout = fileWorkspace(state);
1127
1192
  scheduleRestore();
1128
1193
  }, () => {
1129
1194
  // Without IndexedDB, the project opens with the default layout and nothing is saved.
@@ -1131,6 +1196,21 @@ export function mountSpriteTabs<Snapshot>(root: HTMLElement, content: HTMLElemen
1131
1196
  });
1132
1197
  }
1133
1198
 
1199
+ /** The workspace slice of a project file's screen state, if it has one in a supported shape. */
1200
+ function fileWorkspace(state: SavedScreenState | undefined) {
1201
+ const value = state?.slices.workspace;
1202
+ if (value === null || typeof value !== 'object') return;
1203
+ const layout = JSON.stringify(value);
1204
+ return readWorkspaceLayout(layout) ? {layout, savedAt: state!.savedAt} : undefined;
1205
+ }
1206
+
1207
+ /** The workspace a save writes into the project file. */
1208
+ function captureFileWorkspace(): WorkspaceLayout | undefined {
1209
+ // Until the opened project's layout is restored, the tabs on screen are not that project's.
1210
+ if (pendingRestore || !layoutSession) return fileLayout ? JSON.parse(fileLayout.layout) : undefined;
1211
+ return captureLayout(true);
1212
+ }
1213
+
1134
1214
  /** Keep the layout the project opened with, so leaving it unchanged adds no record. */
1135
1215
  function keepInitialLayout() {
1136
1216
  const layout = captureLayout();
@@ -1153,9 +1233,13 @@ export function mountSpriteTabs<Snapshot>(root: HTMLElement, content: HTMLElemen
1153
1233
  return;
1154
1234
  }
1155
1235
  reopenable.clear();
1156
- // A project found by its file, folder or desktop key keeps its tabs even after its sprites were renamed.
1157
- const exact = layoutSession.exact;
1158
- const raw = layoutSession.layout;
1236
+ // The layout saved in the project file wins when the file is newer than the layout kept in this browser.
1237
+ // It belongs to this very project, so like a project found by its file, folder or desktop key, its tabs are
1238
+ // kept even after its sprites were renamed.
1239
+ const fromFile = Boolean(fileLayout && (layoutSession.layout === undefined ||
1240
+ fileLayout.savedAt > (layoutSession.savedAt ?? 0)));
1241
+ const exact = fromFile || layoutSession.exact;
1242
+ const raw = fromFile ? fileLayout!.layout : layoutSession.layout;
1159
1243
  const stored = raw ? readWorkspaceLayout(raw, exact ? undefined : signature) : undefined;
1160
1244
  if (!stored) return keepInitialLayout();
1161
1245
  const resolvedSprites = new Map<string, View<Snapshot>>();
@@ -1172,7 +1256,7 @@ export function mountSpriteTabs<Snapshot>(root: HTMLElement, content: HTMLElemen
1172
1256
  continue;
1173
1257
  }
1174
1258
  resolvedSprites.set(id, {id, target, section: reference.section, number: reference.number,
1175
- assets: createAssetSelections(target, locale)});
1259
+ ...restorePane(id, target, reference.pane)});
1176
1260
  panels[id] = {id, contentComponent: 'sprite', params: {icon: getIcon(target)}};
1177
1261
  } else if (reference.kind === 'stage') {
1178
1262
  if (id !== stagePanelId) return keepInitialLayout();
@@ -1246,6 +1330,7 @@ export function mountSpriteTabs<Snapshot>(root: HTMLElement, content: HTMLElemen
1246
1330
  if (loading && !projectLoading) {
1247
1331
  projectGeneration++;
1248
1332
  layoutSession = undefined;
1333
+ fileLayout = undefined;
1249
1334
  initialShape = undefined;
1250
1335
  pendingRestore = true;
1251
1336
  drawerEditedDuringRestore = false;
@@ -1367,6 +1452,9 @@ export function mountSpriteTabs<Snapshot>(root: HTMLElement, content: HTMLElemen
1367
1452
  if (!disposed && !thumbnailChosen && hidden) setThumbnailHidden(true, false);
1368
1453
  }, () => undefined);
1369
1454
  if (persistence) window.addEventListener('pagehide', flushLayout);
1455
+ const unregisterScreenState = persistence ? persistence.screenState?.register('workspace', {
1456
+ capture: captureFileWorkspace
1457
+ }) : undefined;
1370
1458
  updateLayoutState();
1371
1459
  root.addEventListener('click', guardDocumentClose, true);
1372
1460
  root.addEventListener('keydown', guardDocumentClose, true);
@@ -1393,6 +1481,7 @@ export function mountSpriteTabs<Snapshot>(root: HTMLElement, content: HTMLElemen
1393
1481
  window.cancelAnimationFrame(restoreFrame);
1394
1482
  window.clearTimeout(restoreTimeout);
1395
1483
  if (persistence) window.removeEventListener('pagehide', flushLayout);
1484
+ unregisterScreenState?.();
1396
1485
  if (unsubscribeDocuments) unsubscribeDocuments();
1397
1486
  unsubscribeFixedProjectTab?.();
1398
1487
  if (unsubscribeProject) unsubscribeProject();
@@ -1,7 +1,9 @@
1
1
  import {createLayout, createSplitter, splitAxis} from './index.ts';
2
2
  import {createTargetList} from './targets.ts';
3
3
  import type {DrawerView, DrawerViews} from './drawer-views.ts';
4
- import {availableDrawerViews, createDrawerViewBar, drawerLabel, drawerPinIcon, hasDrawerBar, readDrawerView, writeDrawerView} from './drawer-views.ts';
4
+ import {availableDrawerViews, createDrawerViewBar, drawerLabel, drawerPinIcon, drawerViewIds, hasDrawerBar, readDrawerView, writeDrawerView} from './drawer-views.ts';
5
+ import type {DrawerViewId} from './drawer-views.ts';
6
+ import type {ProjectScreenState} from './project-screen-state.ts';
5
7
  import {attachStageDrawerDrag} from './stage-drawer-drag.ts';
6
8
  import type {StageDrawerLayout, StageDrawerPosition} from './workspace-layout.ts';
7
9
 
@@ -25,7 +27,7 @@ type DrawerPanel = (props: {
25
27
  }) => import('react').ReactNode;
26
28
 
27
29
  export function createStandardLayout(React, {styles, targetStyles, context, LayoutMenu, DrawerPanel = undefined as DrawerPanel | undefined}) {
28
- const {createElement: element, useContext, useLayoutEffect, useRef, useState} = React;
30
+ const {createElement: element, useContext, useEffect, useLayoutEffect, useRef, useState} = React;
29
31
  const SplitLayout = createLayout(React);
30
32
  const Splitter = createSplitter(React);
31
33
  const targets = createTargetList(React, targetStyles);
@@ -37,7 +39,8 @@ export function createStandardLayout(React, {styles, targetStyles, context, Layo
37
39
  enabled, splitter, windowLayout, stageActionEnabled, stageDrawer = false,
38
40
  onPaletteModeChange, windowTools, Container, render, drawerViews = undefined as DrawerViews | undefined,
39
41
  stageDrawerLayout = undefined as StageDrawerLayout | undefined,
40
- updateStageDrawer = undefined as ((patch: Partial<StageDrawerLayout>) => void) | undefined, ...props
42
+ updateStageDrawer = undefined as ((patch: Partial<StageDrawerLayout>) => void) | undefined,
43
+ screenState = undefined as ProjectScreenState | undefined, ...props
41
44
  }) {
42
45
  const [showUndock, setShowUndock] = useState(false);
43
46
  const [targetsPinned, setTargetsPinned] = useState(true);
@@ -57,6 +60,20 @@ export function createStandardLayout(React, {styles, targetStyles, context, Layo
57
60
  setPreferredDrawerView(view);
58
61
  writeDrawerView(props.storage, props.storageKey, view);
59
62
  }, [props.storage, props.storageKey]);
63
+ // The project file keeps the selected view, and a project opens with the view it was saved with.
64
+ const drawerViewRef = useRef(preferredDrawerView);
65
+ drawerViewRef.current = preferredDrawerView;
66
+ const selectDrawerViewRef = useRef(selectDrawerView);
67
+ selectDrawerViewRef.current = selectDrawerView;
68
+ useEffect(() => screenState?.register('drawer', {
69
+ capture: () => ({version: 1, view: drawerViewRef.current}),
70
+ apply(value) {
71
+ const view = (value as {version?: unknown; view?: unknown} | null)?.view;
72
+ if ((value as {version?: unknown})?.version === 1 && drawerViewIds.includes(view as DrawerViewId)) {
73
+ selectDrawerViewRef.current(view as DrawerViewId);
74
+ }
75
+ }
76
+ }), [screenState]);
60
77
  const body = useRef(null);
61
78
  const plusLayout = enabled && !props.fullscreen;
62
79
  const reportDrawerSelection = drawerViews?.onSelectionChange;