@kubohiroya/turbowarp-plus-editor-workbench 0.4.2 → 0.6.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
@@ -71,6 +71,29 @@ aiAgents.openSettings({locale, returnFocus: trigger});
71
71
  - ダイアログ(`role="dialog"`、`aria-modal`)は React を使わない DOM で、`openAgentSettingsDialog` で開ける。開くと最初の欄に移り、Tab はダイアログの中を回る。Escape かキャンセルで保存せずに閉じ、`returnFocus`、なければ開く前の要素に戻る。
72
72
  - 設定は `localStorage` の `twPlusAiAgents` に `{"version": 1, "services": [...]}` で保存する。各サービスの `target` は `kind: "url"`。ほかの `kind` は後の段階のためにあけてあり、いまは読み飛ばす。ない・壊れた・誤ったデータは、項目ごとに既定に戻す。
73
73
 
74
+ ## Dockview のレイアウトの保存
75
+
76
+ ホストが `workspaceLayout` を渡すと、`useSpriteTabs` と `mountSpriteTabs` は作品ごとの Dockview のレイアウトを IndexedDB に保存する。分割、各タブのスプライトと区分、ステージとドキュメントのタブ、編集中のタブ、別ウィンドウにあったタブを、次にその作品を開いたときに再現する。
77
+
78
+ ```js
79
+ workspaceLayout: {
80
+ // 読み込んだ作品のファイルやフォルダーのハンドル、またはデスクトップ版のキー。無ければ名前で見分ける。
81
+ identify: () => ({kind: 'file', name: handle.name, handle}),
82
+ isProjectLoading: () => loading,
83
+ subscribeProject: listener => subscribe(listener)
84
+ }
85
+ ```
86
+
87
+ - 作品は、ファイルやフォルダー(`kind: 'file' | 'directory'`)なら `FileSystemHandle.isSameEntry()` で、デスクトップ版(`kind: 'desktop'`)なら `key` で、どちらも無ければ名前とスプライトの組み合わせ(`kind: 'anonymous'`)で見分ける。ハンドルかキーで見つかった作品は、スプライト名を変えてもタブを再現し、無くなったスプライトのタブだけを外す。名前で見分けた作品は、スプライトが変わっていれば既定のレイアウトで開く。
88
+ - 作品を読み込むたびに、その作品のレイアウトを再現する。作品ごとの記録は、何度変更しても 1 件にとどめる。
89
+ - 開いたときのレイアウトから変わるまでは記録を作らない。大きさと選択中のタブの違いだけでは変わったとみなさない。
90
+ - 最後に使ったのが新しい順に 100 件を残す。開いただけでも使ったとみなす。古い記録は新しい記録を作るときに消す。256 KB を超えるレイアウトは保存しない。
91
+ - タブの位置(上/左)は全作品で共通の設定にする。
92
+ - IndexedDB が使えないときは既定のレイアウトで開き、何も保存しない。
93
+ - IndexedDB の応答は非同期なので、保存と再現は変更より後に終わる。`controller.layoutSettled()` は、読み込んだ作品のレイアウトの再現、タブの位置の読み込み、すべての変更の書き込みが終わると解決する。同じ状態を作業領域の要素の `data-workspace-layout`(`"pending"` または `"settled"`)にも示すので、ブラウザーテストは記録が現れるまでデータベースを読み直すのではなく、この属性を待つ。
94
+ - すべてのレイアウトを消すには、ブラウザーの開発者ツールで `twPlusWorkspaceLayout` データベースを削除する(Chrome では Application の IndexedDB)。コンソールで `indexedDB.deleteDatabase('twPlusWorkspaceLayout')` を実行してもよい。
95
+ - 以前の版は `localStorage`(`twPlusDockviewLayout` と `twPlusDockviewLayout.tabs`)に 1 件だけ保存していた。これらのキーは移さずに消す。
96
+
74
97
  ## 検証
75
98
 
76
99
  `npm test` で配分・縦横比・設定の読み書きを、`npm run test:browser` で独立した試験用ホストを検証する。試験用ホストを手動で開くには、このディレクトリで `npm install` と `python3 -m http.server` を実行し、`/example/` を表示する。
package/README.md CHANGED
@@ -73,6 +73,29 @@ aiAgents.openSettings({locale, returnFocus: trigger});
73
73
  - The dialog (`role="dialog"`, `aria-modal`) is plain DOM, so it can be opened without React (`openAgentSettingsDialog`). It focuses its first field, keeps Tab inside, closes on Escape or Cancel without saving, and returns focus to `returnFocus` or to the element focused before.
74
74
  - The settings are saved in `localStorage` under `twPlusAiAgents` as `{"version": 1, "services": [...]}`. Each service has a `target` of `kind: "url"`; other kinds are left for later and ignored for now. Missing, broken or invalid data falls back entry by entry to the presets.
75
75
 
76
+ ## Saved Dockview layout
77
+
78
+ `useSpriteTabs` and `mountSpriteTabs` keep the Dockview workspace of each project in IndexedDB when the host passes `workspaceLayout`. The splits, the sprite and section of each tab, the stage and document tabs, the edited tab and the separate windows tabs were in come back the next time that project opens.
79
+
80
+ ```js
81
+ workspaceLayout: {
82
+ // The file or folder handle, or the desktop key, of the loaded project. Without one it is known by its name.
83
+ identify: () => ({kind: 'file', name: handle.name, handle}),
84
+ isProjectLoading: () => loading,
85
+ subscribeProject: listener => subscribe(listener)
86
+ }
87
+ ```
88
+
89
+ - A project is found by `FileSystemHandle.isSameEntry()` for a file or folder (`kind: 'file' | 'directory'`), by `key` for the desktop app (`kind: 'desktop'`), or by its name together with its sprites (`kind: 'anonymous'`). A project found by its handle or key keeps its tabs after its sprites are renamed; tabs of sprites it no longer has are left out. A project found by its name opens with the default layout when its sprites changed.
90
+ - Each load of a project reopens the layout of that project. A project keeps one record however often it changes.
91
+ - A record is made only once the layout differs from the one the project opened with. Sizes and the selected tab alone do not count.
92
+ - The 100 most recently used projects keep their layout; opening a project counts as using it. Older records are removed when a new one is made. A layout over 256 KB is not saved.
93
+ - The tab position (top or left) is one preference for every project.
94
+ - Without IndexedDB, projects open with the default layout and nothing is saved.
95
+ - Saving and restoring finish later than the change, because IndexedDB answers asynchronously. `controller.layoutSettled()` resolves once the loaded project's layout is restored, the tab position is read and every change is written. The workspace element carries the same state as `data-workspace-layout="pending"` or `"settled"`, so a browser test waits for that attribute instead of reading the database until the record appears.
96
+ - 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.
97
+ - Earlier versions kept a single layout in `localStorage` (`twPlusDockviewLayout` and `twPlusDockviewLayout.tabs`). Those keys are removed without being moved.
98
+
76
99
  ## Verification
77
100
 
78
101
  Run `npm test` to verify split sizing, aspect ratios, and settings persistence. Run `npm run test:browser` to test the standalone host. To open the test host manually, run `npm install` and `python3 -m http.server` in this directory, then open `/example/`.
@@ -4,10 +4,13 @@ import type { NativeAssetPanelRenderer, NativeAssetSelector, SpriteAssetKind, Sp
4
4
  import type { SpritePropertiesPanelProps } from '@kubohiroya/turbowarp-plus-editor-sprite-panes/sprite-properties';
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
+ import type { WorkspaceLayoutStore, WorkspaceProjectIdentity } from './workspace-layout-store.ts';
7
8
  import type { SpriteVariableEdit, SpriteVariableEditError } from '@kubohiroya/turbowarp-plus-editor-project-model/sprite-variable-edit';
8
9
  import type { MessageRenameError } from '@kubohiroya/turbowarp-plus-editor-sprite-panes/sprite-message-pane';
9
10
  import type { MessageUse, ProjectMessage, TargetMessages } from '@kubohiroya/turbowarp-plus-editor-project-model/project-messages';
10
11
  export { getDocumentWorkspace } from './document-workspace.ts';
12
+ export { createWorkspaceLayoutStore, workspaceLayoutDatabase, workspaceLayoutLimit } from './workspace-layout-store.ts';
13
+ export type { WorkspaceLayoutStore, WorkspaceProjectIdentity } from './workspace-layout-store.ts';
11
14
  export type { SpriteAssetKind, SpriteAssetPreviewItem } from '@kubohiroya/turbowarp-plus-editor-sprite-panes/sprite-asset-pane';
12
15
  export { editSpriteVariable } from '@kubohiroya/turbowarp-plus-editor-project-model/sprite-variable-edit';
13
16
  export { useDockviewStage } from './dockview-stage.ts';
@@ -77,9 +80,12 @@ interface TabOptions<Snapshot = unknown> {
77
80
  resize(): void;
78
81
  reopenLabel: string;
79
82
  multiView?: boolean;
80
- layoutStorage?: {
81
- storage: Pick<Storage, 'getItem' | 'setItem'>;
82
- key: string;
83
+ /** Keep the workspace of each project and reopen it with the project. */
84
+ workspaceLayout?: {
85
+ /** IndexedDB by default. */
86
+ store?: WorkspaceLayoutStore;
87
+ /** The file, folder or desktop key the loaded project came from. Without one, it is known by its name. */
88
+ identify?(): WorkspaceProjectIdentity | undefined;
83
89
  isProjectLoading?(): boolean;
84
90
  subscribeProject?(listener: () => void): (() => void) | undefined;
85
91
  };
@@ -146,6 +152,7 @@ export declare function mountSpriteTabs<Snapshot>(root: HTMLElement, content: HT
146
152
  setViewSection: (id: string, section: number) => boolean;
147
153
  syncActiveSection: (section: number) => void;
148
154
  refreshSurfaces: () => void;
155
+ layoutSettled: () => Promise<any>;
149
156
  rename(id: string): void;
150
157
  selectAsset(id: string, kind: AssetKind, index: number): void;
151
158
  currentView: () => SpriteTabView;
@@ -201,6 +208,7 @@ export declare function useSpriteTabs<Snapshot>({ available, enabled, locale, ..
201
208
  setViewSection: (id: string, section: number) => boolean;
202
209
  syncActiveSection: (section: number) => void;
203
210
  refreshSurfaces: () => void;
211
+ layoutSettled: () => Promise<any>;
204
212
  rename(id: string): void;
205
213
  selectAsset(id: string, kind: AssetKind, index: number): void;
206
214
  currentView: () => SpriteTabView;
@@ -6,9 +6,11 @@ import { NativeAssetPanel, SpriteAssetPane } from '@kubohiroya/turbowarp-plus-ed
6
6
  import { SpriteEditorToolbar, spriteEditorSections } from '@kubohiroya/turbowarp-plus-editor-sprite-panes/sprite-editor-toolbar';
7
7
  import { documentPanelTitle, getDocumentWorkspace } from "./document-workspace.js";
8
8
  import { dockPopoutGroups, positionOnScreen, readWorkspaceLayout, workspaceWithoutTransientPanels } from "./workspace-layout.js";
9
+ import { createWorkspaceLayoutStore } from "./workspace-layout-store.js";
9
10
  import { SpriteMessagePane } from '@kubohiroya/turbowarp-plus-editor-sprite-panes/sprite-message-pane';
10
11
  import { createRenameMenuItem, spriteRenameLabel } from "./target-tab-menu.js";
11
12
  export { getDocumentWorkspace } from "./document-workspace.js";
13
+ export { createWorkspaceLayoutStore, workspaceLayoutDatabase, workspaceLayoutLimit } from "./workspace-layout-store.js";
12
14
  export { editSpriteVariable } from '@kubohiroya/turbowarp-plus-editor-project-model/sprite-variable-edit';
13
15
  export { useDockviewStage } from "./dockview-stage.js";
14
16
  export { SpriteTargetTabsContext, useTargetTabMenu } from "./target-tab-menu.js";
@@ -119,24 +121,36 @@ export function mountSpriteTabs(root, content, options) {
119
121
  let nextView = 0;
120
122
  let renameDialog;
121
123
  const text = options.renameLabels ?? renameLabels.en;
122
- const persistence = multiView && options.layoutStorage;
124
+ const persistence = multiView && options.workspaceLayout;
125
+ const layoutStore = persistence ? persistence.store ?? createWorkspaceLayoutStore() : undefined;
126
+ /** Where the layout of the loaded project is saved, once that project is identified. */
127
+ let layoutSession;
128
+ /** Counts project loads, so a lookup that ends after another project opened is dropped. */
129
+ let projectGeneration = 0;
130
+ let openingGeneration;
131
+ let projectLoading = false;
132
+ /** The shape of the layout the project opened with, which is not worth a record of its own. */
133
+ let initialShape;
134
+ let disposed = false;
123
135
  const window = document.defaultView;
124
136
  const documentWorkspace = multiView && getDocumentWorkspace(vm);
125
137
  let pendingRestore = Boolean(persistence);
126
138
  let restoreFrame;
127
139
  let restoreTimeout;
128
140
  let saveFrame;
141
+ /** Layout writes handed to the store that have not finished yet. */
142
+ let layoutWrites = 0;
143
+ /** Whether the tab position chosen for every project is still being read. */
144
+ let readingTabs = Boolean(layoutStore);
145
+ let lastWrite = Promise.resolve();
146
+ const settledWaiters = [];
129
147
  const openingGroups = new Set();
130
148
  /** Panels that were in a separate window when the layout was saved, until the user reopens them. */
131
149
  const reopenable = new Map();
132
150
  const originalTargets = () => vm.runtime.targets.filter(target => target.isOriginal);
133
- // Whether tabs stand in a column at the left of each split. It is the user's preference, kept apart from the layout.
134
- const tabsKey = persistence ? persistence.key + '.tabs' : undefined;
151
+ // Whether tabs stand in a column at the left of each split. It is the user's preference for every project.
135
152
  let verticalTabs = false;
136
- try {
137
- verticalTabs = Boolean(tabsKey) && persistence.storage.getItem(tabsKey) === 'left';
138
- }
139
- catch { /* Storage can be unavailable. */ }
153
+ let tabsChosen = false;
140
154
  const dockview = createDockview(root, {
141
155
  theme: themeLight,
142
156
  disableFloatingGroups: true,
@@ -339,17 +353,16 @@ export function mountSpriteTabs(root, content, options) {
339
353
  });
340
354
  return { ...menu, init() { } };
341
355
  }
342
- function setVerticalTabs(vertical) {
356
+ function setVerticalTabs(vertical, chosen = true) {
343
357
  verticalTabs = vertical;
344
358
  const position = vertical ? 'left' : 'top';
345
359
  dockview.updateOptions({ defaultHeaderPosition: position });
346
360
  for (const group of dockview.groups)
347
361
  group.api.setHeaderPosition(position);
348
- try {
349
- if (tabsKey)
350
- persistence.storage.setItem(tabsKey, position);
362
+ if (chosen) {
363
+ tabsChosen = true;
364
+ layoutStore?.writeTabsPosition(position).catch(() => undefined);
351
365
  }
352
- catch { /* Storage can be unavailable. */ }
353
366
  refreshSurfaces();
354
367
  }
355
368
  const canRename = (target) => target.isOriginal && !target.isStage && Boolean(vm.renameSprite) && vm.runtime.targets.includes(target);
@@ -758,10 +771,10 @@ export function mountSpriteTabs(root, content, options) {
758
771
  refreshSurfaces();
759
772
  scheduleSave();
760
773
  }
761
- function writeLayout() {
762
- saveFrame = undefined;
774
+ /** The current workspace as it is saved, or nothing while it cannot be described yet. */
775
+ function captureLayout() {
763
776
  const targets = originalTargets();
764
- if (!persistence || pendingRestore || syncing || !targets.length || persistence.isProjectLoading?.())
777
+ if (!targets.length)
765
778
  return;
766
779
  const serialized = dockview.toJSON();
767
780
  if (serialized.grid.width <= 0 || serialized.grid.height <= 0)
@@ -794,17 +807,69 @@ export function mountSpriteTabs(root, content, options) {
794
807
  const popouts = [...new Set(reopenable.values())]
795
808
  .map(popout => ({ ...popout, panels: popout.panels.filter(id => reopenable.get(id) === popout && views.has(id) && panels[id]?.kind === 'sprite') }))
796
809
  .filter(popout => popout.panels.length);
797
- const snapshot = { version: 1, project: projectSignature(targets), ...saved,
810
+ return { version: 1, project: projectSignature(targets), ...saved,
798
811
  editingView: active?.id, panels, ...(popouts.length && { popouts }) };
812
+ }
813
+ function writeLayout() {
814
+ saveFrame = undefined;
799
815
  try {
800
- persistence.storage.setItem(persistence.key, JSON.stringify(snapshot));
816
+ if (!persistence || !layoutSession || pendingRestore || syncing || persistence.isProjectLoading?.())
817
+ return;
818
+ const snapshot = captureLayout();
819
+ if (!snapshot)
820
+ return;
821
+ // Opening a project and leaving its tabs as they were is not worth a record that pushes out another project.
822
+ if (!layoutSession.saved && initialShape !== undefined && layoutShape(snapshot) === initialShape)
823
+ return;
824
+ layoutWrites++;
825
+ lastWrite = layoutSession.write(JSON.stringify(snapshot), snapshot.project).catch(() => undefined).finally(() => {
826
+ layoutWrites--;
827
+ updateLayoutState();
828
+ });
829
+ }
830
+ finally {
831
+ updateLayoutState();
801
832
  }
802
- catch { /* Storage can be unavailable. */ }
803
833
  }
804
834
  function scheduleSave() {
805
- if (persistence && !pendingRestore && saveFrame === undefined) {
835
+ if (persistence && layoutSession && !pendingRestore && saveFrame === undefined) {
806
836
  saveFrame = window.requestAnimationFrame(writeLayout);
837
+ updateLayoutState();
838
+ }
839
+ }
840
+ const layoutBusy = () => !disposed && (pendingRestore || readingTabs || saveFrame !== undefined || layoutWrites > 0);
841
+ /**
842
+ * Tell the host and its tests when the layout of the loaded project is restored and every change is saved.
843
+ * Dockview reports a layout change in a microtask after the change, so being idle is confirmed only after
844
+ * that report had its chance to schedule a save.
845
+ */
846
+ function updateLayoutState() {
847
+ if (!persistence)
848
+ return;
849
+ if (layoutBusy()) {
850
+ root.dataset.workspaceLayout = 'pending';
851
+ return;
852
+ }
853
+ queueMicrotask(() => {
854
+ if (layoutBusy())
855
+ return;
856
+ root.dataset.workspaceLayout = 'settled';
857
+ for (const resolve of settledWaiters.splice(0))
858
+ resolve();
859
+ });
860
+ }
861
+ /** Resolves once the loaded project's layout is restored and its changes are written to the store. */
862
+ function layoutSettled() {
863
+ if (!persistence)
864
+ return Promise.resolve();
865
+ if (saveFrame !== undefined) {
866
+ window.cancelAnimationFrame(saveFrame);
867
+ writeLayout();
807
868
  }
869
+ return new Promise(resolve => {
870
+ settledWaiters.push(resolve);
871
+ updateLayoutState();
872
+ }).then(() => lastWrite).then(() => undefined);
808
873
  }
809
874
  function flushLayout() {
810
875
  const pending = saveFrame !== undefined;
@@ -817,54 +882,114 @@ export function mountSpriteTabs(root, content, options) {
817
882
  function finishRestore() {
818
883
  pendingRestore = false;
819
884
  window.clearTimeout(restoreTimeout);
885
+ restoreTimeout = undefined;
886
+ updateLayoutState();
887
+ }
888
+ /** The panels and splits of a layout, without sizes or selection, to tell whether the user changed it. */
889
+ function layoutShape(layout) {
890
+ const reference = (id) => layout.panels[id] ?? null;
891
+ const shape = (node) => Array.isArray(node.data) ? node.data.map(shape) :
892
+ node.data.views.map(reference);
893
+ return JSON.stringify([layout.grid.orientation, shape(layout.grid.root),
894
+ (layout.popouts ?? []).map(popout => popout.panels.map(reference))]);
895
+ }
896
+ function identifyProject() {
897
+ try {
898
+ const identity = persistence && persistence.identify?.();
899
+ if (identity)
900
+ return identity;
901
+ }
902
+ catch { /* The project is still known by its name and sprites. */ }
903
+ return { kind: 'anonymous', name: '' };
904
+ }
905
+ /** Find where the loaded project keeps its layout. It runs once for each project load. */
906
+ function openLayoutSession(signature) {
907
+ if (!layoutStore || openingGeneration === projectGeneration)
908
+ return;
909
+ const generation = openingGeneration = projectGeneration;
910
+ layoutStore.open(identifyProject(), signature).then(session => {
911
+ if (disposed || generation !== projectGeneration)
912
+ return;
913
+ layoutSession = session;
914
+ scheduleRestore();
915
+ }, () => {
916
+ // Without IndexedDB, the project opens with the default layout and nothing is saved.
917
+ if (!disposed && generation === projectGeneration)
918
+ finishRestore();
919
+ });
920
+ }
921
+ /** Keep the layout the project opened with, so leaving it unchanged adds no record. */
922
+ function keepInitialLayout() {
923
+ const layout = captureLayout();
924
+ initialShape = layout && layoutShape(layout);
925
+ finishRestore();
820
926
  }
821
927
  function restoreLayout() {
822
928
  restoreFrame = undefined;
823
- if (!pendingRestore || !persistence || persistence.isProjectLoading?.())
929
+ if (!persistence || persistence.isProjectLoading?.())
824
930
  return;
825
931
  const targets = originalTargets();
826
932
  if (!targets.length || !vm.editingTarget)
827
933
  return;
934
+ const signature = projectSignature(targets);
935
+ if (!layoutSession)
936
+ return openLayoutSession(signature);
937
+ if (!pendingRestore)
938
+ return;
828
939
  reopenable.clear();
829
- let stored;
830
- try {
831
- const raw = persistence.storage.getItem(persistence.key);
832
- if (raw)
833
- stored = readWorkspaceLayout(raw, projectSignature(targets));
834
- }
835
- catch { /* Storage can be unavailable. */ }
940
+ // A project found by its file, folder or desktop key keeps its tabs even after its sprites were renamed.
941
+ const exact = layoutSession.exact;
942
+ const raw = layoutSession.layout;
943
+ const stored = raw ? readWorkspaceLayout(raw, exact ? undefined : signature) : undefined;
836
944
  if (!stored)
837
- return finishRestore();
945
+ return keepInitialLayout();
838
946
  const resolvedSprites = new Map();
839
947
  const resolvedDocuments = new Map();
840
948
  const panels = Object.create(null);
949
+ const dropped = new Set();
841
950
  for (const [id, reference] of Object.entries(stored.panels)) {
842
951
  if (reference.kind === 'sprite') {
843
952
  const target = targets.find(item => item.isStage === reference.stage && targetName(item) === reference.name);
844
- if (!target || id === stagePanelId || !sectionAvailable(reference.section))
845
- return finishRestore();
953
+ if (id === stagePanelId)
954
+ return keepInitialLayout();
955
+ if (!target || !sectionAvailable(reference.section)) {
956
+ if (!exact)
957
+ return keepInitialLayout();
958
+ dropped.add(id);
959
+ continue;
960
+ }
846
961
  resolvedSprites.set(id, { id, target, section: reference.section, number: reference.number,
847
962
  assets: createAssetSelections(target, locale) });
848
963
  panels[id] = { id, contentComponent: 'sprite', params: { icon: getIcon(target) } };
849
964
  }
850
965
  else if (reference.kind === 'stage') {
851
- if (!stagePane || id !== stagePanelId)
852
- return finishRestore();
966
+ if (id !== stagePanelId)
967
+ return keepInitialLayout();
968
+ if (!stagePane) {
969
+ if (!exact)
970
+ return keepInitialLayout();
971
+ dropped.add(id);
972
+ continue;
973
+ }
853
974
  panels[id] = { id, title: stagePane.title, contentComponent: stagePanelId, renderer: 'always' };
854
975
  }
855
976
  else {
856
977
  if (id === stagePanelId)
857
- return finishRestore();
978
+ return keepInitialLayout();
858
979
  const request = documentWorkspace && documentWorkspace.resolve(reference);
859
980
  if (!request) {
860
981
  // The project can finish loading before the Blockly host publishes its document catalog.
861
- restoreTimeout ??= window.setTimeout(finishRestore, 2000);
982
+ restoreTimeout ??= window.setTimeout(keepInitialLayout, 2000);
862
983
  return;
863
984
  }
864
985
  resolvedDocuments.set(id, request);
865
986
  panels[id] = { id, title: documentPanelTitle(request), contentComponent: documentComponent, renderer: 'always' };
866
987
  }
867
988
  }
989
+ const kept = workspaceWithoutTransientPanels(stored.grid, stored.activeGroup, dropped, stored.editingView);
990
+ if (!kept)
991
+ return keepInitialLayout();
992
+ const editingView = stored.editingView && !dropped.has(stored.editingView) ? stored.editingView : undefined;
868
993
  assignTabNumbers(resolvedSprites.values(), new Set([...targets.map(baseTitle),
869
994
  ...Object.values(panels).map(panel => panel.title)]));
870
995
  for (const [id, view] of resolvedSprites)
@@ -880,14 +1005,14 @@ export function mountSpriteTabs(root, content, options) {
880
1005
  views.set(id, view);
881
1006
  for (const [id, request] of resolvedDocuments)
882
1007
  documents.set(id, { request });
883
- dockview.fromJSON({ grid: stored.grid, activeGroup: stored.activeGroup, panels });
1008
+ dockview.fromJSON({ grid: kept.grid, activeGroup: kept.activeGroup, panels });
884
1009
  for (const popout of stored.popouts ?? []) {
885
1010
  for (const id of popout.panels)
886
1011
  if (views.has(id))
887
1012
  reopenable.set(id, popout);
888
1013
  }
889
1014
  const selected = dockview.activePanel;
890
- show(views.has(selected?.id) ? selected : dockview.getPanel(stored.editingView) ?? selected);
1015
+ show(views.has(selected?.id) ? selected : (editingView && dockview.getPanel(editingView)) ?? selected);
891
1016
  }
892
1017
  catch {
893
1018
  dockview.clear();
@@ -905,8 +1030,27 @@ export function mountSpriteTabs(root, content, options) {
905
1030
  refresh();
906
1031
  }
907
1032
  function scheduleRestore() {
908
- if (pendingRestore && restoreFrame === undefined)
1033
+ if (persistence && (pendingRestore || !layoutSession) && restoreFrame === undefined) {
909
1034
  restoreFrame = window.requestAnimationFrame(restoreLayout);
1035
+ }
1036
+ }
1037
+ /** Each loaded project has its own layout, so a new load reopens the tabs that project was left with. */
1038
+ function projectChanged() {
1039
+ const loading = Boolean(persistence && persistence.isProjectLoading?.());
1040
+ if (loading && !projectLoading) {
1041
+ projectGeneration++;
1042
+ layoutSession = undefined;
1043
+ initialShape = undefined;
1044
+ pendingRestore = true;
1045
+ if (saveFrame !== undefined)
1046
+ window.cancelAnimationFrame(saveFrame);
1047
+ saveFrame = undefined;
1048
+ window.clearTimeout(restoreTimeout);
1049
+ restoreTimeout = undefined;
1050
+ updateLayoutState();
1051
+ }
1052
+ projectLoading = loading;
1053
+ scheduleRestore();
910
1054
  }
911
1055
  function refresh() {
912
1056
  if (syncing)
@@ -994,16 +1138,25 @@ export function mountSpriteTabs(root, content, options) {
994
1138
  });
995
1139
  const disconnectDocuments = documentWorkspace && documentWorkspace.connect(openDocument);
996
1140
  const unsubscribeDocuments = persistence && documentWorkspace && documentWorkspace.subscribe(scheduleRestore);
997
- const unsubscribeProject = persistence && persistence.subscribeProject?.(scheduleRestore);
1141
+ projectLoading = Boolean(persistence && persistence.isProjectLoading?.());
1142
+ const unsubscribeProject = persistence && persistence.subscribeProject?.(projectChanged);
1143
+ layoutStore?.readTabsPosition().then(position => {
1144
+ if (!disposed && !tabsChosen && position === 'left')
1145
+ setVerticalTabs(true, false);
1146
+ }, () => undefined).finally(() => {
1147
+ readingTabs = false;
1148
+ updateLayoutState();
1149
+ });
998
1150
  if (persistence)
999
1151
  window.addEventListener('pagehide', flushLayout);
1152
+ updateLayoutState();
1000
1153
  root.addEventListener('click', guardDocumentClose, true);
1001
1154
  root.addEventListener('keydown', guardDocumentClose, true);
1002
1155
  vm.on('targetsUpdate', refresh);
1003
1156
  refresh();
1004
1157
  return {
1005
1158
  select, selectFromList, targetTabs, openStage, closeStage, split, closeSplit, activateView,
1006
- setViewSection, syncActiveSection, refreshSurfaces,
1159
+ setViewSection, syncActiveSection, refreshSurfaces, layoutSettled,
1007
1160
  rename(id) {
1008
1161
  const target = vm.runtime.targets.find(item => item.id === id);
1009
1162
  if (target)
@@ -1018,6 +1171,9 @@ export function mountSpriteTabs(root, content, options) {
1018
1171
  views: () => [...views.values()].map(view => describe(view)),
1019
1172
  dispose() {
1020
1173
  flushLayout();
1174
+ disposed = true;
1175
+ for (const resolve of settledWaiters.splice(0))
1176
+ resolve();
1021
1177
  window.cancelAnimationFrame(restoreFrame);
1022
1178
  window.clearTimeout(restoreTimeout);
1023
1179
  if (persistence)
@@ -1142,7 +1298,7 @@ function SpriteTabs(props) {
1142
1298
  resize: () => latest.current.resize(),
1143
1299
  reopenLabel: props.reopenLabel,
1144
1300
  multiView: props.multiView,
1145
- layoutStorage: props.layoutStorage,
1301
+ workspaceLayout: props.workspaceLayout,
1146
1302
  stagePane: props.stagePane,
1147
1303
  variables: hasVariables,
1148
1304
  messages: hasMessages,
@@ -1164,7 +1320,7 @@ function SpriteTabs(props) {
1164
1320
  instance.dispose();
1165
1321
  };
1166
1322
  }, [content, props.enabled, props.vm, props.reopenLabel, props.multiView, props.locale,
1167
- props.viewAdapter, props.stagePane, props.layoutStorage, props.renameLabels, props.popouts, props.className,
1323
+ props.viewAdapter, props.stagePane, props.workspaceLayout, props.renameLabels, props.popouts, props.className,
1168
1324
  hasVariables, hasMessages, hasToolbar, hasAssetPreview]);
1169
1325
  React.useLayoutEffect(() => {
1170
1326
  controller.current?.syncActiveSection(props.activeSection);
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Keeps the Dockview workspace of each project in IndexedDB, so a project opens with the tabs it was left with.
3
+ *
4
+ * A project is told apart by the file or folder handle it was opened from, by the key the desktop app gives the
5
+ * opened path, or, without either, by its name together with the shape of its sprites. Only the projects used most
6
+ * recently are kept, so layouts of projects nobody opens any more are removed without asking.
7
+ */
8
+ export type WorkspaceProjectIdentity = {
9
+ kind: 'file' | 'directory';
10
+ name: string;
11
+ handle: FileSystemHandle;
12
+ } | {
13
+ kind: 'desktop';
14
+ name: string;
15
+ key: string;
16
+ } | {
17
+ kind: 'anonymous';
18
+ name: string;
19
+ };
20
+ export type TabsPosition = 'top' | 'left';
21
+ /** The saved workspace of one opened project, and where its next changes are written. */
22
+ export interface WorkspaceLayoutSession {
23
+ /** The saved layout, if this project has one. */
24
+ readonly layout: string | undefined;
25
+ /** Whether the project was found by its file, folder or desktop key, not only by its name and sprites. */
26
+ readonly exact: boolean;
27
+ /** Whether the project has a saved layout, or a change was written in this session. */
28
+ readonly saved: boolean;
29
+ /** Save the layout. The project's own record is updated, so it never adds a record per change. */
30
+ write(layout: string, signature: string): Promise<void>;
31
+ }
32
+ export interface WorkspaceLayoutStore {
33
+ open(identity: WorkspaceProjectIdentity, signature: string): Promise<WorkspaceLayoutSession>;
34
+ readTabsPosition(): Promise<TabsPosition | undefined>;
35
+ writeTabsPosition(position: TabsPosition): Promise<void>;
36
+ }
37
+ export interface WorkspaceLayoutStoreOptions {
38
+ indexedDB?: IDBFactory;
39
+ /** How many projects keep their layout. The least recently used ones are removed past it. */
40
+ limit?: number;
41
+ /** The largest layout that is saved, in bytes. */
42
+ maxBytes?: number;
43
+ now?(): number;
44
+ /** Where earlier versions kept a single layout. It is cleared once, without moving it. */
45
+ legacyStorage?: Pick<Storage, 'removeItem'> | null;
46
+ }
47
+ /** The database a person can delete from the browser's developer tools to forget every layout. */
48
+ export declare const workspaceLayoutDatabase = "twPlusWorkspaceLayout";
49
+ export declare const workspaceLayoutLimit = 100;
50
+ export declare const workspaceLayoutMaxBytes: number;
51
+ export declare function createWorkspaceLayoutStore({ indexedDB: factory, limit, maxBytes, now, legacyStorage }?: WorkspaceLayoutStoreOptions): WorkspaceLayoutStore;