@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.
package/README.ja.md CHANGED
@@ -95,6 +95,24 @@ workspaceLayout: {
95
95
  - すべてのレイアウトを消すには、ブラウザーの開発者ツールで `twPlusWorkspaceLayout` データベースを削除する(Chrome では Application の IndexedDB)。コンソールで `indexedDB.deleteDatabase('twPlusWorkspaceLayout')` を実行してもよい。
96
96
  - 以前の版は `localStorage`(`twPlusDockviewLayout` と `twPlusDockviewLayout.tabs`)に 1 件だけ保存していた。これらのキーは移さずに消す。
97
97
 
98
+ ## SB3 に保存する画面状態
99
+
100
+ `/project-screen-state` の `installProjectScreenState(vm, {Zip})` は、作品の画面を SB3 の中に保存する。どのブラウザーで開いても、保存したときの画面で作品が開く。ホストは同梱している JSZip のコンストラクター(`@turbowarp/jszip`)を渡し、拡張ローダーの橋より後に組み込む。
101
+
102
+ ```js
103
+ const screenState = installProjectScreenState(vm, {Zip: JSZip, save: flags.saveWorkspace});
104
+ <StandardLayout {...props} screenState={screenState} />
105
+ useSpriteTabs({...props, workspaceLayout: {...workspaceLayout, screenState}});
106
+ ```
107
+
108
+ - 保存すると、`project.json` の隣に ZIP エントリ `tw-plus/workspace.json`(`{"version": 1, "savedAt": <ms>, "slices": {...}}`)を加える。Scratch と TurboWarp はこのエントリを無視するので、ファイルの互換性は変わらない。別のエディターで保存し直すと、エントリが消えるだけである。`project.json` は変えない。
109
+ - エディターの各部分は、自分のキーで `register(key, {capture, apply})` によりスライスを登録する。`capture` は保存中に同期で呼ばれる。`apply` は、そのスライスを含む作品を VM が読み込み終えたあとに作品ごとに1回呼ばれる。読み込み後に登録したスライスには、登録したときに呼ばれる。キーは `^[a-z][a-zA-Z0-9-]{0,63}$` に合うものとする。
110
+ - このパッケージは `drawer`(左側ドロワーで選んだ表示)と `workspace`([Dockview のレイアウトの保存](#dockview-のレイアウトの保存) の作業領域)を登録する。ファイルの作業領域は、このブラウザーがその作品について保存したレイアウトより新しいとき、またはブラウザーに記録がないときに使う。ファイルの保存後にレイアウトを変え、保存せずに開き直した場合は、ブラウザーの記録が使われる。
111
+ - 各スプライトのタブは、選んでいたコスチュームと音も、一覧での位置で保存する。ホストのタブアダプターが `serialize(view, snapshot)` と `deserialize(view, value)` を持つときは、スクロール位置やズームなどのコードエリアも保存する。画面に出ているタブについては、`serialize` をスナップショットなしで呼ぶので、コードエリアを変えずに読む。画面に出ているタブを読むのは作品ファイルの保存時だけなので、ブラウザーが保存するレイアウトには、ほかのタブのコードエリアだけが入る。
112
+ - SB3 として保存しない作品は、同じ状態を別の場所に保存する。`serialize()` は保存時に ZIP エントリへ書くテキストを返す。`prepareLoad(text)` を呼ぶと、次の `loadProject` は入力を読まずにこのテキストを使う。作品フォルダーは、これを `.tw-plus/workspace.json` として書く。
113
+ - `save: false` では、保存時にエントリを書かず、読み込んだファイルから引き継いだエントリも取り除く。読み込みは有効のままなので、以前に保存したファイルは保存時の画面で開く。
114
+ - 512 KiB を超えるエントリ、別の版のもの、形の合わないものは無視し、作品は通常の画面で開く。
115
+
98
116
  ## メニュー・作品のダイアログ・ステージの操作・バックパックの窓
99
117
 
100
118
  turbowarp-plus-editor の `packages/editor-ui` と `packages/editor-backpack` から移したもの。
package/README.md CHANGED
@@ -97,6 +97,24 @@ workspaceLayout: {
97
97
  - To forget every layout, delete the `twPlusWorkspaceLayout` database from the browser's developer tools (in Chrome: Application, then IndexedDB), or run `indexedDB.deleteDatabase('twPlusWorkspaceLayout')` in the console.
98
98
  - Earlier versions kept a single layout in `localStorage` (`twPlusDockviewLayout` and `twPlusDockviewLayout.tabs`). Those keys are removed without being moved.
99
99
 
100
+ ## Screen state in the SB3
101
+
102
+ `installProjectScreenState(vm, {Zip})` from `/project-screen-state` keeps the screen of a project inside its SB3, so the project opens the way it was when it was saved, in any browser. The host passes the JSZip constructor it already bundles (`@turbowarp/jszip`), and installs it after the extension loader's bridge.
103
+
104
+ ```js
105
+ const screenState = installProjectScreenState(vm, {Zip: JSZip, save: flags.saveWorkspace});
106
+ <StandardLayout {...props} screenState={screenState} />
107
+ useSpriteTabs({...props, workspaceLayout: {...workspaceLayout, screenState}});
108
+ ```
109
+
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
+ - 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
+ - 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`.
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.
116
+ - Entries larger than 512 KiB, of another version or of another shape are ignored, and the project opens with its usual screen.
117
+
100
118
  ## Menus, project dialogs, stage controls and the backpack window
101
119
 
102
120
  These moved here from `packages/editor-ui` and `packages/editor-backpack` in turbowarp-plus-editor.
@@ -17,6 +17,8 @@ import { getDocumentWorkspace } from "./document-workspace.js";
17
17
  export const dockedClass = 'tw-plus-debugger-docked';
18
18
  export const debuggerReference = Object.freeze({ providerId: 'turbowarp-plus', documentId: 'debugger' });
19
19
  const buttonSelector = '.sa-debugger-container';
20
+ // The add-on shows its Continue button only while the project is paused.
21
+ const unpauseSelector = '.sa-debugger-unpause-container';
20
22
  /** The ladybug that marks debugging in the editor, as an image for the tab. */
21
23
  export const debuggerTabIcon = 'data:image/svg+xml,' + encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><text x="8" y="13" font-size="13" ' +
22
24
  'text-anchor="middle">\u{1F41E}</text></svg>');
@@ -86,6 +88,21 @@ export function attachDebuggerPanel(debuggerInterface, options) {
86
88
  }
87
89
  });
88
90
  observer.observe(element, { attributes: true, attributeFilter: ['style'] });
91
+ // A pause (a breakpoint, the breakpoint block, or Step) makes the add-on show the debugger, but
92
+ // when the tab is already open behind another one nothing changes on screen. Bring it forward
93
+ // when the Continue button appears, so the person sees why the project stopped.
94
+ const isPausedShown = () => {
95
+ const unpause = element.querySelector(unpauseSelector);
96
+ return Boolean(unpause) && unpause.style.display !== 'none';
97
+ };
98
+ let pausedShown = isPausedShown();
99
+ const pauseObserver = new document.defaultView.MutationObserver(() => {
100
+ const shown = isPausedShown();
101
+ if (shown && !pausedShown && close)
102
+ dock();
103
+ pausedShown = shown;
104
+ });
105
+ pauseObserver.observe(element, { attributes: true, attributeFilter: ['style'], subtree: true, childList: true });
89
106
  // Opening an already open debugger leaves its style as it is, so the tab is brought forward here.
90
107
  const handleButton = (event) => {
91
108
  if (close && event.target?.closest?.(buttonSelector))
@@ -106,6 +123,7 @@ export function attachDebuggerPanel(debuggerInterface, options) {
106
123
  return {
107
124
  dispose() {
108
125
  observer.disconnect();
126
+ pauseObserver.disconnect();
109
127
  document.removeEventListener('click', handleButton);
110
128
  element.removeEventListener('pointerdown', handlePointerDown, { capture: true });
111
129
  close?.();
@@ -0,0 +1,87 @@
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
+ /** The ZIP entry that holds the screen state. */
10
+ export declare const screenStateEntry = "tw-plus/workspace.json";
11
+ /** The largest screen state that is read or written, in bytes. */
12
+ export declare const screenStateMaxBytes: number;
13
+ export interface SavedScreenState {
14
+ version: 1;
15
+ /** When the project was saved, in milliseconds since the epoch. */
16
+ savedAt: number;
17
+ slices: Record<string, unknown>;
18
+ }
19
+ export interface ScreenStateSlice {
20
+ /** The value written for this slice, or nothing to leave it out. Called synchronously while saving. */
21
+ capture(): unknown;
22
+ /**
23
+ * Called once for each loaded project that carries this slice, after the VM finished loading it, or when the
24
+ * slice is registered after that. The value comes from a file, so check its shape before using it.
25
+ */
26
+ apply?(value: unknown, savedAt: number): void;
27
+ }
28
+ interface ZipEntry {
29
+ async(type: 'string'): Promise<string>;
30
+ _data?: {
31
+ uncompressedSize?: number;
32
+ };
33
+ }
34
+ interface ReadableZip {
35
+ file(name: string): ZipEntry | null;
36
+ }
37
+ interface WritableZip {
38
+ file(name: string, data: string, options?: {
39
+ createFolders?: boolean;
40
+ }): 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
+ export interface ScreenStateVM {
48
+ loadProject(input: unknown, ...args: unknown[]): Promise<unknown>;
49
+ _saveProjectZip(...args: unknown[]): WritableZip;
50
+ saveProjectSb3DontZip?(...args: unknown[]): Record<string, Uint8Array>;
51
+ }
52
+ export interface ProjectScreenStateOptions {
53
+ Zip: ScreenStateZip;
54
+ /** Whether saving writes the screen state. Reading stays on, so files saved earlier still open as they were. */
55
+ save?: boolean;
56
+ now?(): number;
57
+ }
58
+ export interface ProjectScreenState {
59
+ /** Add a slice. Returns a function that removes it. */
60
+ register(key: string, slice: ScreenStateSlice): () => void;
61
+ /** The state read from the project loaded last, once that load finished. */
62
+ whenLoaded(): Promise<SavedScreenState | undefined>;
63
+ /** The state a save would write now. */
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;
75
+ /** Put the VM methods back. Hooks installed later on the same methods must be removed first. */
76
+ dispose(): void;
77
+ }
78
+ /** Read the screen state from the text of the ZIP entry, or nothing if it is not one. */
79
+ export declare function parseScreenState(text: string): SavedScreenState | undefined;
80
+ /** Read the screen state from a project as the VM receives it. A project without one, or not a ZIP, has none. */
81
+ export declare function readScreenState(input: unknown, Zip: ScreenStateZip): Promise<SavedScreenState | undefined>;
82
+ /**
83
+ * Wrap the VM's load and save methods. Install it after the extension loader's bridge, so this entry is written
84
+ * last and an entry carried over from the loaded file never stays.
85
+ */
86
+ export declare function installProjectScreenState(vm: ScreenStateVM, { Zip, save, now }: ProjectScreenStateOptions): ProjectScreenState;
87
+ export {};
@@ -0,0 +1,180 @@
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
+ /** The ZIP entry that holds the screen state. */
10
+ export const screenStateEntry = 'tw-plus/workspace.json';
11
+ /** The largest screen state that is read or written, in bytes. */
12
+ export const screenStateMaxBytes = 512 * 1024;
13
+ const encoder = new TextEncoder();
14
+ const record = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
15
+ const validKey = (key) => typeof key === 'string' && /^[a-z][a-zA-Z0-9-]{0,63}$/.test(key);
16
+ /** Read the screen state from the text of the ZIP entry, or nothing if it is not one. */
17
+ export function parseScreenState(text) {
18
+ if (text.length > screenStateMaxBytes)
19
+ return;
20
+ let input;
21
+ try {
22
+ input = JSON.parse(text);
23
+ }
24
+ catch {
25
+ return;
26
+ }
27
+ if (!record(input) || input.version !== 1 || !record(input.slices))
28
+ return;
29
+ const savedAt = input.savedAt;
30
+ if (typeof savedAt !== 'number' || !Number.isFinite(savedAt) || savedAt < 0)
31
+ return;
32
+ // A plain object is safe: a valid key never starts with an underscore, so `__proto__` is never assigned.
33
+ const slices = {};
34
+ for (const [key, value] of Object.entries(input.slices))
35
+ if (validKey(key) && value !== undefined)
36
+ slices[key] = value;
37
+ return { version: 1, savedAt, slices };
38
+ }
39
+ const bytesOf = (input) => {
40
+ if (input instanceof ArrayBuffer)
41
+ return input;
42
+ if (ArrayBuffer.isView(input))
43
+ return new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
44
+ };
45
+ /** Read the screen state from a project as the VM receives it. A project without one, or not a ZIP, has none. */
46
+ export async function readScreenState(input, Zip) {
47
+ const bytes = bytesOf(input);
48
+ if (!bytes || bytes.byteLength < 4)
49
+ return;
50
+ const head = new Uint8Array(bytes instanceof ArrayBuffer ? bytes : bytes.buffer, bytes instanceof ArrayBuffer ? 0 :
51
+ bytes.byteOffset, 2);
52
+ if (head[0] !== 0x50 || head[1] !== 0x4b)
53
+ return;
54
+ try {
55
+ const entry = (await Zip.loadAsync(bytes)).file(screenStateEntry);
56
+ if (!entry)
57
+ return;
58
+ // The size from the central directory, so a crafted entry is never inflated to find out.
59
+ const size = entry._data?.uncompressedSize;
60
+ if (typeof size === 'number' && size > screenStateMaxBytes)
61
+ return;
62
+ return parseScreenState(await entry.async('string'));
63
+ }
64
+ catch {
65
+ // The VM reports a broken file itself; the project only opens with its default screen.
66
+ }
67
+ }
68
+ /**
69
+ * Wrap the VM's load and save methods. Install it after the extension loader's bridge, so this entry is written
70
+ * last and an entry carried over from the loaded file never stays.
71
+ */
72
+ export function installProjectScreenState(vm, { Zip, save = true, now = Date.now }) {
73
+ const slices = new Map();
74
+ const original = {
75
+ loadProject: vm.loadProject,
76
+ _saveProjectZip: vm._saveProjectZip,
77
+ saveProjectSb3DontZip: vm.saveProjectSb3DontZip
78
+ };
79
+ let generation = 0;
80
+ let loaded = Promise.resolve(undefined);
81
+ let current;
82
+ /** Slices already given the current project's state, so registering again does not apply it twice. */
83
+ let applied = new Set();
84
+ /** The state the next load uses instead of its input, set by `prepareLoad`. */
85
+ let prepared;
86
+ const apply = (slice, key) => {
87
+ if (!current || applied.has(slice) || !Object.hasOwn(current.slices, key))
88
+ return;
89
+ applied.add(slice);
90
+ try {
91
+ slice.apply?.(current.slices[key], current.savedAt);
92
+ }
93
+ catch { /* One slice that cannot use its value leaves the others. */ }
94
+ };
95
+ function capture() {
96
+ const captured = {};
97
+ for (const [key, slice] of slices) {
98
+ try {
99
+ const value = slice.capture();
100
+ if (value !== undefined)
101
+ captured[key] = value;
102
+ }
103
+ catch { /* A slice that cannot be described is left out. */ }
104
+ }
105
+ if (!Object.keys(captured).length)
106
+ return;
107
+ return { version: 1, savedAt: now(), slices: captured };
108
+ }
109
+ const serialized = () => {
110
+ const state = save ? capture() : undefined;
111
+ if (!state)
112
+ return;
113
+ const text = JSON.stringify(state);
114
+ return encoder.encode(text).length > screenStateMaxBytes ? undefined : text;
115
+ };
116
+ vm.loadProject = function (input, ...args) {
117
+ const mine = ++generation;
118
+ current = undefined;
119
+ applied = new Set();
120
+ // Read in parallel with the VM, which keeps its own copy of the bytes.
121
+ const reading = prepared ? Promise.resolve(prepared.state) : readScreenState(input, Zip);
122
+ prepared = undefined;
123
+ const result = original.loadProject.call(this, input, ...args);
124
+ const done = result.then(() => reading, () => undefined).then(state => {
125
+ if (mine !== generation)
126
+ return;
127
+ current = state;
128
+ for (const [key, slice] of slices)
129
+ apply(slice, key);
130
+ return state;
131
+ });
132
+ loaded = done;
133
+ return result;
134
+ };
135
+ vm._saveProjectZip = function (...args) {
136
+ const zip = original._saveProjectZip.apply(this, args);
137
+ const text = serialized();
138
+ if (text === undefined)
139
+ zip.remove(screenStateEntry);
140
+ else
141
+ zip.file(screenStateEntry, text, { createFolders: false });
142
+ return zip;
143
+ };
144
+ if (original.saveProjectSb3DontZip) {
145
+ vm.saveProjectSb3DontZip = function (...args) {
146
+ const files = { ...original.saveProjectSb3DontZip.apply(this, args) };
147
+ delete files[screenStateEntry];
148
+ const text = serialized();
149
+ if (text !== undefined)
150
+ files[screenStateEntry] = encoder.encode(text);
151
+ return files;
152
+ };
153
+ }
154
+ return {
155
+ register(key, slice) {
156
+ if (!validKey(key))
157
+ throw new TypeError(`Invalid screen state key: ${key}`);
158
+ if (slices.has(key))
159
+ throw new Error(`The screen state key is already registered: ${key}`);
160
+ slices.set(key, slice);
161
+ apply(slice, key);
162
+ return () => {
163
+ if (slices.get(key) === slice)
164
+ slices.delete(key);
165
+ };
166
+ },
167
+ whenLoaded: () => loaded,
168
+ capture,
169
+ serialize: serialized,
170
+ prepareLoad(text) {
171
+ prepared = { state: text === undefined ? undefined : parseScreenState(text) };
172
+ },
173
+ dispose() {
174
+ vm.loadProject = original.loadProject;
175
+ vm._saveProjectZip = original._saveProjectZip;
176
+ if (original.saveProjectSb3DontZip)
177
+ vm.saveProjectSb3DontZip = original.saveProjectSb3DontZip;
178
+ }
179
+ };
180
+ }
@@ -5,6 +5,7 @@ import type { SpritePropertiesPanelProps } from '@kubohiroya/turbowarp-plus-edit
5
5
  import type { SpriteSearchResult } from '@kubohiroya/turbowarp-plus-editor-sprite-panes/sprite-editor-toolbar';
6
6
  import type { DockviewStagePane } from './dockview-stage.ts';
7
7
  import type { WorkspaceLayoutStore, WorkspaceProjectIdentity } from './workspace-layout-store.ts';
8
+ import type { ProjectScreenState } from './project-screen-state.ts';
8
9
  import type { SpriteVariableEdit, SpriteVariableEditError } from '@kubohiroya/turbowarp-plus-editor-project-model/sprite-variable-edit';
9
10
  import type { MessageRenameError } from '@kubohiroya/turbowarp-plus-editor-sprite-panes/sprite-message-pane';
10
11
  import type { FunctionKind, FunctionPaneData, MountFunctionEditor, OpenScriptOptions, SpriteFunction, SpriteHatScript } from '@kubohiroya/turbowarp-plus-editor-sprite-panes/sprite-function-pane';
@@ -27,6 +28,7 @@ interface Target {
27
28
  getCostumes?(): {
28
29
  assetId?: string;
29
30
  }[];
31
+ getSounds?(): object[];
30
32
  getCurrentCostume?(): {
31
33
  asset?: CostumeAsset;
32
34
  } | undefined;
@@ -56,6 +58,13 @@ export interface SpriteTabAdapter<Snapshot = unknown> {
56
58
  renderInactive(container: HTMLElement, view: SpriteTabView, snapshot: Snapshot | undefined): void | (() => void);
57
59
  restore(view: SpriteTabView, snapshot: Snapshot | undefined): void;
58
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;
59
68
  }
60
69
  /** Optional bridge used by a native asset editor to restore and report its selection. */
61
70
  export interface SpriteAssetSelection {
@@ -89,6 +98,11 @@ interface TabOptions<Snapshot = unknown> {
89
98
  identify?(): WorkspaceProjectIdentity | undefined;
90
99
  isProjectLoading?(): boolean;
91
100
  subscribeProject?(listener: () => void): (() => void) | undefined;
101
+ /**
102
+ * The screen state kept in the project file. Saving writes the workspace into it, and opening uses the one
103
+ * in the file when it is newer than the layout this browser kept for the project.
104
+ */
105
+ screenState?: ProjectScreenState;
92
106
  };
93
107
  stagePane?: DockviewStagePane;
94
108
  variables?: boolean;
@@ -149,6 +149,8 @@ export function mountSpriteTabs(root, content, options) {
149
149
  const layoutStore = persistence ? persistence.store ?? createWorkspaceLayoutStore() : undefined;
150
150
  /** Where the layout of the loaded project is saved, once that project is identified. */
151
151
  let layoutSession;
152
+ /** The workspace kept in the loaded project file, as the text the store keeps, and when the file was saved. */
153
+ let fileLayout;
152
154
  /** Counts project loads, so a lookup that ends after another project opened is dropped. */
153
155
  let projectGeneration = 0;
154
156
  let openingGeneration;
@@ -879,8 +881,57 @@ export function mountSpriteTabs(root, content, options) {
879
881
  refreshSurfaces();
880
882
  scheduleSave();
881
883
  }
882
- /** The current workspace as it is saved, or nothing while it cannot be described yet. */
883
- function captureLayout() {
884
+ /** The selected costume and sound of a tab, and its code area, as the workspace saves them. */
885
+ function capturePane(view, live) {
886
+ const pane = {};
887
+ const lists = { costumes: view.target.getCostumes?.(), sounds: view.target.getSounds?.() };
888
+ for (const [kind, field] of [['costumes', 'costume'], ['sounds', 'sound']]) {
889
+ const index = lists[kind]?.indexOf(view.assets.selected.get(kind)) ?? -1;
890
+ if (index >= 0)
891
+ pane[field] = index;
892
+ }
893
+ if (viewAdapter?.serialize) {
894
+ const stored = view.snapshots?.get(0);
895
+ // The tab on screen keeps its code area in the shared editor, which only a save reads.
896
+ const showing = view === active && view.section === 0 && Boolean(slots.get(view.id)?.body.contains(content));
897
+ try {
898
+ const code = showing ? (live ? viewAdapter.serialize(describe(view), undefined) : undefined) :
899
+ stored && viewAdapter.serialize(stored.view, stored.snapshot);
900
+ if (code)
901
+ pane.code = code;
902
+ }
903
+ catch { /* The code area is left as the tab opens by default. */ }
904
+ }
905
+ return Object.keys(pane).length ? pane : undefined;
906
+ }
907
+ /** The asset selections and code snapshot a restored tab opens with. */
908
+ function restorePane(id, target, pane) {
909
+ const selected = new Map();
910
+ const costume = pane?.costume === undefined ? undefined : target.getCostumes?.()[pane.costume];
911
+ const sound = pane?.sound === undefined ? undefined : target.getSounds?.()[pane.sound];
912
+ if (costume)
913
+ selected.set('costumes', costume);
914
+ if (sound)
915
+ selected.set('sounds', sound);
916
+ const assets = createAssetSelections(target, locale, { selected, layouts: new Map(), scroll: new Map() });
917
+ let snapshots;
918
+ if (pane?.code && viewAdapter?.deserialize && pane.code !== null && typeof pane.code === 'object') {
919
+ const view = { id, targetId: target.id, isStage: target.isStage, section: 0, groupId: '',
920
+ active: false, groupActive: false };
921
+ try {
922
+ const snapshot = viewAdapter.deserialize(view, pane.code);
923
+ if (snapshot !== undefined)
924
+ snapshots = new Map([[0, { snapshot, view }]]);
925
+ }
926
+ catch { /* The code area opens as it does by default. */ }
927
+ }
928
+ return { assets, snapshots };
929
+ }
930
+ /**
931
+ * The current workspace as it is saved, or nothing while it cannot be described yet. `live` also reads the code
932
+ * area on screen, which only a save of the project file does.
933
+ */
934
+ function captureLayout(live = false) {
884
935
  const targets = originalTargets();
885
936
  if (!targets.length)
886
937
  return;
@@ -892,8 +943,9 @@ export function mountSpriteTabs(root, content, options) {
892
943
  return;
893
944
  const panels = Object.create(null);
894
945
  for (const [id, view] of views) {
946
+ const pane = capturePane(view, live);
895
947
  panels[id] = { kind: 'sprite', name: targetName(view.target), stage: view.target.isStage, section: view.section,
896
- number: view.number };
948
+ number: view.number, ...(pane && { pane }) };
897
949
  }
898
950
  if (dockview.getPanel(stagePanelId))
899
951
  panels[stagePanelId] = { kind: 'stage' };
@@ -1000,7 +1052,8 @@ export function mountSpriteTabs(root, content, options) {
1000
1052
  }
1001
1053
  /** The tab arrangement and drawer state used to detect a change from the initial layout. */
1002
1054
  function layoutShape(layout) {
1003
- const reference = (id) => layout.panels[id] ?? null;
1055
+ // What a tab shows inside its panes is not a change of the arrangement.
1056
+ const reference = (id) => layout.panels[id] ? { ...layout.panels[id], pane: undefined } : null;
1004
1057
  const shape = (node) => Array.isArray(node.data) ? node.data.map(shape) :
1005
1058
  node.data.views.map(reference);
1006
1059
  return JSON.stringify([layout.grid.orientation, shape(layout.grid.root),
@@ -1020,10 +1073,13 @@ export function mountSpriteTabs(root, content, options) {
1020
1073
  if (!layoutStore || openingGeneration === projectGeneration)
1021
1074
  return;
1022
1075
  const generation = openingGeneration = projectGeneration;
1023
- layoutStore.open(identifyProject(), signature).then(session => {
1076
+ const fileState = persistence && persistence.screenState ?
1077
+ persistence.screenState.whenLoaded().catch(() => undefined) : Promise.resolve(undefined);
1078
+ Promise.all([layoutStore.open(identifyProject(), signature), fileState]).then(([session, state]) => {
1024
1079
  if (disposed || generation !== projectGeneration)
1025
1080
  return;
1026
1081
  layoutSession = session;
1082
+ fileLayout = fileWorkspace(state);
1027
1083
  scheduleRestore();
1028
1084
  }, () => {
1029
1085
  // Without IndexedDB, the project opens with the default layout and nothing is saved.
@@ -1031,6 +1087,21 @@ export function mountSpriteTabs(root, content, options) {
1031
1087
  finishRestore();
1032
1088
  });
1033
1089
  }
1090
+ /** The workspace slice of a project file's screen state, if it has one in a supported shape. */
1091
+ function fileWorkspace(state) {
1092
+ const value = state?.slices.workspace;
1093
+ if (value === null || typeof value !== 'object')
1094
+ return;
1095
+ const layout = JSON.stringify(value);
1096
+ return readWorkspaceLayout(layout) ? { layout, savedAt: state.savedAt } : undefined;
1097
+ }
1098
+ /** The workspace a save writes into the project file. */
1099
+ function captureFileWorkspace() {
1100
+ // Until the opened project's layout is restored, the tabs on screen are not that project's.
1101
+ if (pendingRestore || !layoutSession)
1102
+ return fileLayout ? JSON.parse(fileLayout.layout) : undefined;
1103
+ return captureLayout(true);
1104
+ }
1034
1105
  /** Keep the layout the project opened with, so leaving it unchanged adds no record. */
1035
1106
  function keepInitialLayout() {
1036
1107
  const layout = captureLayout();
@@ -1055,9 +1126,13 @@ export function mountSpriteTabs(root, content, options) {
1055
1126
  return;
1056
1127
  }
1057
1128
  reopenable.clear();
1058
- // A project found by its file, folder or desktop key keeps its tabs even after its sprites were renamed.
1059
- const exact = layoutSession.exact;
1060
- const raw = layoutSession.layout;
1129
+ // The layout saved in the project file wins when the file is newer than the layout kept in this browser.
1130
+ // It belongs to this very project, so like a project found by its file, folder or desktop key, its tabs are
1131
+ // kept even after its sprites were renamed.
1132
+ const fromFile = Boolean(fileLayout && (layoutSession.layout === undefined ||
1133
+ fileLayout.savedAt > (layoutSession.savedAt ?? 0)));
1134
+ const exact = fromFile || layoutSession.exact;
1135
+ const raw = fromFile ? fileLayout.layout : layoutSession.layout;
1061
1136
  const stored = raw ? readWorkspaceLayout(raw, exact ? undefined : signature) : undefined;
1062
1137
  if (!stored)
1063
1138
  return keepInitialLayout();
@@ -1077,7 +1152,7 @@ export function mountSpriteTabs(root, content, options) {
1077
1152
  continue;
1078
1153
  }
1079
1154
  resolvedSprites.set(id, { id, target, section: reference.section, number: reference.number,
1080
- assets: createAssetSelections(target, locale) });
1155
+ ...restorePane(id, target, reference.pane) });
1081
1156
  panels[id] = { id, contentComponent: 'sprite', params: { icon: getIcon(target) } };
1082
1157
  }
1083
1158
  else if (reference.kind === 'stage') {
@@ -1164,6 +1239,7 @@ export function mountSpriteTabs(root, content, options) {
1164
1239
  if (loading && !projectLoading) {
1165
1240
  projectGeneration++;
1166
1241
  layoutSession = undefined;
1242
+ fileLayout = undefined;
1167
1243
  initialShape = undefined;
1168
1244
  pendingRestore = true;
1169
1245
  drawerEditedDuringRestore = false;
@@ -1300,6 +1376,9 @@ export function mountSpriteTabs(root, content, options) {
1300
1376
  }, () => undefined);
1301
1377
  if (persistence)
1302
1378
  window.addEventListener('pagehide', flushLayout);
1379
+ const unregisterScreenState = persistence ? persistence.screenState?.register('workspace', {
1380
+ capture: captureFileWorkspace
1381
+ }) : undefined;
1303
1382
  updateLayoutState();
1304
1383
  root.addEventListener('click', guardDocumentClose, true);
1305
1384
  root.addEventListener('keydown', guardDocumentClose, true);
@@ -1329,6 +1408,7 @@ export function mountSpriteTabs(root, content, options) {
1329
1408
  window.clearTimeout(restoreTimeout);
1330
1409
  if (persistence)
1331
1410
  window.removeEventListener('pagehide', flushLayout);
1411
+ unregisterScreenState?.();
1332
1412
  if (unsubscribeDocuments)
1333
1413
  unsubscribeDocuments();
1334
1414
  unsubscribeFixedProjectTab?.();
@@ -1,4 +1,5 @@
1
1
  import type { DrawerView, DrawerViews } from './drawer-views.ts';
2
+ import type { ProjectScreenState } from './project-screen-state.ts';
2
3
  import type { StageDrawerLayout } from './workspace-layout.ts';
3
4
  export type { DrawerMenu, DrawerMenuRenderProps, DrawerRenderProps, DrawerView, DrawerViewId, DrawerViews, HostDrawerViewId } from './drawer-views.ts';
4
5
  type DrawerPanel = (props: {
@@ -16,7 +17,7 @@ export declare function createStandardLayout(React: any, { styles, targetStyles,
16
17
  LayoutMenu: any;
17
18
  DrawerPanel?: DrawerPanel;
18
19
  }): {
19
- StandardLayout: ({ enabled, splitter, windowLayout, stageActionEnabled, stageDrawer, onPaletteModeChange, windowTools, Container, render, drawerViews, stageDrawerLayout, updateStageDrawer, ...props }: {
20
+ StandardLayout: ({ enabled, splitter, windowLayout, stageActionEnabled, stageDrawer, onPaletteModeChange, windowTools, Container, render, drawerViews, stageDrawerLayout, updateStageDrawer, screenState, ...props }: {
20
21
  [x: string]: any;
21
22
  enabled: any;
22
23
  splitter: any;
@@ -30,6 +31,7 @@ export declare function createStandardLayout(React: any, { styles, targetStyles,
30
31
  drawerViews?: DrawerViews;
31
32
  stageDrawerLayout?: StageDrawerLayout;
32
33
  updateStageDrawer?: (patch: Partial<StageDrawerLayout>) => void;
34
+ screenState?: ProjectScreenState;
33
35
  }) => any;
34
36
  EdgeDrawer: ({ edge, label, pinned, onOpenChange, portalContent, holdOpenSelector, focusPanelRef, closePanelRef, focusBoundary, showTrigger, movableStage, available, keepOpenOnBlur, stageDrawerLayout, updateStageDrawer, children }: {
35
37
  edge: any;
@@ -1,6 +1,6 @@
1
1
  import { createLayout, createSplitter, splitAxis } from "./index.js";
2
2
  import { createTargetList } from "./targets.js";
3
- import { availableDrawerViews, createDrawerViewBar, drawerLabel, drawerPinIcon, hasDrawerBar, readDrawerView, writeDrawerView } from "./drawer-views.js";
3
+ import { availableDrawerViews, createDrawerViewBar, drawerLabel, drawerPinIcon, drawerViewIds, hasDrawerBar, readDrawerView, writeDrawerView } from "./drawer-views.js";
4
4
  import { attachStageDrawerDrag } from "./stage-drawer-drag.js";
5
5
  const isJapanese = locale => /^ja(?:-|$)/i.test(locale);
6
6
  const singleColumnTargetWidth = 108;
@@ -9,14 +9,14 @@ const drawerViewWidth = 300;
9
9
  const minimumDrawerViewWidth = 160;
10
10
  const minimumStandardEditor = 380;
11
11
  export function createStandardLayout(React, { styles, targetStyles, context, LayoutMenu, DrawerPanel = undefined }) {
12
- const { createElement: element, useContext, useLayoutEffect, useRef, useState } = React;
12
+ const { createElement: element, useContext, useEffect, useLayoutEffect, useRef, useState } = React;
13
13
  const SplitLayout = createLayout(React);
14
14
  const Splitter = createSplitter(React);
15
15
  const targets = createTargetList(React, targetStyles);
16
16
  const DrawerViewBar = createDrawerViewBar(React, styles);
17
17
  const targetSearch = React.createContext('');
18
18
  const targetTools = React.createContext(null);
19
- function StandardLayout({ enabled, splitter, windowLayout, stageActionEnabled, stageDrawer = false, onPaletteModeChange, windowTools, Container, render, drawerViews = undefined, stageDrawerLayout = undefined, updateStageDrawer = undefined, ...props }) {
19
+ function StandardLayout({ enabled, splitter, windowLayout, stageActionEnabled, stageDrawer = false, onPaletteModeChange, windowTools, Container, render, drawerViews = undefined, stageDrawerLayout = undefined, updateStageDrawer = undefined, screenState = undefined, ...props }) {
20
20
  const [showUndock, setShowUndock] = useState(false);
21
21
  const [targetsPinned, setTargetsPinned] = useState(true);
22
22
  const [showStage, setShowStage] = useState(true);
@@ -35,6 +35,20 @@ export function createStandardLayout(React, { styles, targetStyles, context, Lay
35
35
  setPreferredDrawerView(view);
36
36
  writeDrawerView(props.storage, props.storageKey, view);
37
37
  }, [props.storage, props.storageKey]);
38
+ // The project file keeps the selected view, and a project opens with the view it was saved with.
39
+ const drawerViewRef = useRef(preferredDrawerView);
40
+ drawerViewRef.current = preferredDrawerView;
41
+ const selectDrawerViewRef = useRef(selectDrawerView);
42
+ selectDrawerViewRef.current = selectDrawerView;
43
+ useEffect(() => screenState?.register('drawer', {
44
+ capture: () => ({ version: 1, view: drawerViewRef.current }),
45
+ apply(value) {
46
+ const view = value?.view;
47
+ if (value?.version === 1 && drawerViewIds.includes(view)) {
48
+ selectDrawerViewRef.current(view);
49
+ }
50
+ }
51
+ }), [screenState]);
38
52
  const body = useRef(null);
39
53
  const plusLayout = enabled && !props.fullscreen;
40
54
  const reportDrawerSelection = drawerViews?.onSelectionChange;