@kubohiroya/turbowarp-plus-editor-workbench 0.4.2 → 0.5.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 +22 -0
- package/README.md +22 -0
- package/dist/sprite-tabs.d.ts +9 -3
- package/dist/sprite-tabs.js +140 -42
- package/dist/workspace-layout-store.d.ts +51 -0
- package/dist/workspace-layout-store.js +177 -0
- package/dist/workspace-layout.d.ts +5 -2
- package/dist/workspace-layout.js +8 -4
- package/package.json +3 -2
- package/src/sprite-tabs.ts +140 -32
- package/src/workspace-layout-store.ts +221 -0
- package/src/workspace-layout.ts +9 -5
package/README.ja.md
CHANGED
|
@@ -71,6 +71,28 @@ 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
|
+
- すべてのレイアウトを消すには、ブラウザーの開発者ツールで `twPlusWorkspaceLayout` データベースを削除する(Chrome では Application の IndexedDB)。コンソールで `indexedDB.deleteDatabase('twPlusWorkspaceLayout')` を実行してもよい。
|
|
94
|
+
- 以前の版は `localStorage`(`twPlusDockviewLayout` と `twPlusDockviewLayout.tabs`)に 1 件だけ保存していた。これらのキーは移さずに消す。
|
|
95
|
+
|
|
74
96
|
## 検証
|
|
75
97
|
|
|
76
98
|
`npm test` で配分・縦横比・設定の読み書きを、`npm run test:browser` で独立した試験用ホストを検証する。試験用ホストを手動で開くには、このディレクトリで `npm install` と `python3 -m http.server` を実行し、`/example/` を表示する。
|
package/README.md
CHANGED
|
@@ -73,6 +73,28 @@ 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
|
+
- 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.
|
|
96
|
+
- Earlier versions kept a single layout in `localStorage` (`twPlusDockviewLayout` and `twPlusDockviewLayout.tabs`). Those keys are removed without being moved.
|
|
97
|
+
|
|
76
98
|
## Verification
|
|
77
99
|
|
|
78
100
|
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/`.
|
package/dist/sprite-tabs.d.ts
CHANGED
|
@@ -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
|
-
|
|
81
|
-
|
|
82
|
-
|
|
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
|
};
|
package/dist/sprite-tabs.js
CHANGED
|
@@ -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,7 +121,17 @@ 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.
|
|
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);
|
|
@@ -130,13 +142,9 @@ export function mountSpriteTabs(root, content, options) {
|
|
|
130
142
|
/** Panels that were in a separate window when the layout was saved, until the user reopens them. */
|
|
131
143
|
const reopenable = new Map();
|
|
132
144
|
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
|
|
134
|
-
const tabsKey = persistence ? persistence.key + '.tabs' : undefined;
|
|
145
|
+
// Whether tabs stand in a column at the left of each split. It is the user's preference for every project.
|
|
135
146
|
let verticalTabs = false;
|
|
136
|
-
|
|
137
|
-
verticalTabs = Boolean(tabsKey) && persistence.storage.getItem(tabsKey) === 'left';
|
|
138
|
-
}
|
|
139
|
-
catch { /* Storage can be unavailable. */ }
|
|
147
|
+
let tabsChosen = false;
|
|
140
148
|
const dockview = createDockview(root, {
|
|
141
149
|
theme: themeLight,
|
|
142
150
|
disableFloatingGroups: true,
|
|
@@ -339,17 +347,16 @@ export function mountSpriteTabs(root, content, options) {
|
|
|
339
347
|
});
|
|
340
348
|
return { ...menu, init() { } };
|
|
341
349
|
}
|
|
342
|
-
function setVerticalTabs(vertical) {
|
|
350
|
+
function setVerticalTabs(vertical, chosen = true) {
|
|
343
351
|
verticalTabs = vertical;
|
|
344
352
|
const position = vertical ? 'left' : 'top';
|
|
345
353
|
dockview.updateOptions({ defaultHeaderPosition: position });
|
|
346
354
|
for (const group of dockview.groups)
|
|
347
355
|
group.api.setHeaderPosition(position);
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
356
|
+
if (chosen) {
|
|
357
|
+
tabsChosen = true;
|
|
358
|
+
layoutStore?.writeTabsPosition(position).catch(() => undefined);
|
|
351
359
|
}
|
|
352
|
-
catch { /* Storage can be unavailable. */ }
|
|
353
360
|
refreshSurfaces();
|
|
354
361
|
}
|
|
355
362
|
const canRename = (target) => target.isOriginal && !target.isStage && Boolean(vm.renameSprite) && vm.runtime.targets.includes(target);
|
|
@@ -758,10 +765,10 @@ export function mountSpriteTabs(root, content, options) {
|
|
|
758
765
|
refreshSurfaces();
|
|
759
766
|
scheduleSave();
|
|
760
767
|
}
|
|
761
|
-
|
|
762
|
-
|
|
768
|
+
/** The current workspace as it is saved, or nothing while it cannot be described yet. */
|
|
769
|
+
function captureLayout() {
|
|
763
770
|
const targets = originalTargets();
|
|
764
|
-
if (!
|
|
771
|
+
if (!targets.length)
|
|
765
772
|
return;
|
|
766
773
|
const serialized = dockview.toJSON();
|
|
767
774
|
if (serialized.grid.width <= 0 || serialized.grid.height <= 0)
|
|
@@ -794,15 +801,23 @@ export function mountSpriteTabs(root, content, options) {
|
|
|
794
801
|
const popouts = [...new Set(reopenable.values())]
|
|
795
802
|
.map(popout => ({ ...popout, panels: popout.panels.filter(id => reopenable.get(id) === popout && views.has(id) && panels[id]?.kind === 'sprite') }))
|
|
796
803
|
.filter(popout => popout.panels.length);
|
|
797
|
-
|
|
804
|
+
return { version: 1, project: projectSignature(targets), ...saved,
|
|
798
805
|
editingView: active?.id, panels, ...(popouts.length && { popouts }) };
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
806
|
+
}
|
|
807
|
+
function writeLayout() {
|
|
808
|
+
saveFrame = undefined;
|
|
809
|
+
if (!persistence || !layoutSession || pendingRestore || syncing || persistence.isProjectLoading?.())
|
|
810
|
+
return;
|
|
811
|
+
const snapshot = captureLayout();
|
|
812
|
+
if (!snapshot)
|
|
813
|
+
return;
|
|
814
|
+
// Opening a project and leaving its tabs as they were is not worth a record that pushes out another project.
|
|
815
|
+
if (!layoutSession.saved && initialShape !== undefined && layoutShape(snapshot) === initialShape)
|
|
816
|
+
return;
|
|
817
|
+
layoutSession.write(JSON.stringify(snapshot), snapshot.project).catch(() => undefined);
|
|
803
818
|
}
|
|
804
819
|
function scheduleSave() {
|
|
805
|
-
if (persistence && !pendingRestore && saveFrame === undefined) {
|
|
820
|
+
if (persistence && layoutSession && !pendingRestore && saveFrame === undefined) {
|
|
806
821
|
saveFrame = window.requestAnimationFrame(writeLayout);
|
|
807
822
|
}
|
|
808
823
|
}
|
|
@@ -817,54 +832,113 @@ export function mountSpriteTabs(root, content, options) {
|
|
|
817
832
|
function finishRestore() {
|
|
818
833
|
pendingRestore = false;
|
|
819
834
|
window.clearTimeout(restoreTimeout);
|
|
835
|
+
restoreTimeout = undefined;
|
|
836
|
+
}
|
|
837
|
+
/** The panels and splits of a layout, without sizes or selection, to tell whether the user changed it. */
|
|
838
|
+
function layoutShape(layout) {
|
|
839
|
+
const reference = (id) => layout.panels[id] ?? null;
|
|
840
|
+
const shape = (node) => Array.isArray(node.data) ? node.data.map(shape) :
|
|
841
|
+
node.data.views.map(reference);
|
|
842
|
+
return JSON.stringify([layout.grid.orientation, shape(layout.grid.root),
|
|
843
|
+
(layout.popouts ?? []).map(popout => popout.panels.map(reference))]);
|
|
844
|
+
}
|
|
845
|
+
function identifyProject() {
|
|
846
|
+
try {
|
|
847
|
+
const identity = persistence && persistence.identify?.();
|
|
848
|
+
if (identity)
|
|
849
|
+
return identity;
|
|
850
|
+
}
|
|
851
|
+
catch { /* The project is still known by its name and sprites. */ }
|
|
852
|
+
return { kind: 'anonymous', name: '' };
|
|
853
|
+
}
|
|
854
|
+
/** Find where the loaded project keeps its layout. It runs once for each project load. */
|
|
855
|
+
function openLayoutSession(signature) {
|
|
856
|
+
if (!layoutStore || openingGeneration === projectGeneration)
|
|
857
|
+
return;
|
|
858
|
+
const generation = openingGeneration = projectGeneration;
|
|
859
|
+
layoutStore.open(identifyProject(), signature).then(session => {
|
|
860
|
+
if (disposed || generation !== projectGeneration)
|
|
861
|
+
return;
|
|
862
|
+
layoutSession = session;
|
|
863
|
+
scheduleRestore();
|
|
864
|
+
}, () => {
|
|
865
|
+
// Without IndexedDB, the project opens with the default layout and nothing is saved.
|
|
866
|
+
if (!disposed && generation === projectGeneration)
|
|
867
|
+
finishRestore();
|
|
868
|
+
});
|
|
869
|
+
}
|
|
870
|
+
/** Keep the layout the project opened with, so leaving it unchanged adds no record. */
|
|
871
|
+
function keepInitialLayout() {
|
|
872
|
+
const layout = captureLayout();
|
|
873
|
+
initialShape = layout && layoutShape(layout);
|
|
874
|
+
finishRestore();
|
|
820
875
|
}
|
|
821
876
|
function restoreLayout() {
|
|
822
877
|
restoreFrame = undefined;
|
|
823
|
-
if (!
|
|
878
|
+
if (!persistence || persistence.isProjectLoading?.())
|
|
824
879
|
return;
|
|
825
880
|
const targets = originalTargets();
|
|
826
881
|
if (!targets.length || !vm.editingTarget)
|
|
827
882
|
return;
|
|
883
|
+
const signature = projectSignature(targets);
|
|
884
|
+
if (!layoutSession)
|
|
885
|
+
return openLayoutSession(signature);
|
|
886
|
+
if (!pendingRestore)
|
|
887
|
+
return;
|
|
828
888
|
reopenable.clear();
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
stored = readWorkspaceLayout(raw, projectSignature(targets));
|
|
834
|
-
}
|
|
835
|
-
catch { /* Storage can be unavailable. */ }
|
|
889
|
+
// A project found by its file, folder or desktop key keeps its tabs even after its sprites were renamed.
|
|
890
|
+
const exact = layoutSession.exact;
|
|
891
|
+
const raw = layoutSession.layout;
|
|
892
|
+
const stored = raw ? readWorkspaceLayout(raw, exact ? undefined : signature) : undefined;
|
|
836
893
|
if (!stored)
|
|
837
|
-
return
|
|
894
|
+
return keepInitialLayout();
|
|
838
895
|
const resolvedSprites = new Map();
|
|
839
896
|
const resolvedDocuments = new Map();
|
|
840
897
|
const panels = Object.create(null);
|
|
898
|
+
const dropped = new Set();
|
|
841
899
|
for (const [id, reference] of Object.entries(stored.panels)) {
|
|
842
900
|
if (reference.kind === 'sprite') {
|
|
843
901
|
const target = targets.find(item => item.isStage === reference.stage && targetName(item) === reference.name);
|
|
844
|
-
if (
|
|
845
|
-
return
|
|
902
|
+
if (id === stagePanelId)
|
|
903
|
+
return keepInitialLayout();
|
|
904
|
+
if (!target || !sectionAvailable(reference.section)) {
|
|
905
|
+
if (!exact)
|
|
906
|
+
return keepInitialLayout();
|
|
907
|
+
dropped.add(id);
|
|
908
|
+
continue;
|
|
909
|
+
}
|
|
846
910
|
resolvedSprites.set(id, { id, target, section: reference.section, number: reference.number,
|
|
847
911
|
assets: createAssetSelections(target, locale) });
|
|
848
912
|
panels[id] = { id, contentComponent: 'sprite', params: { icon: getIcon(target) } };
|
|
849
913
|
}
|
|
850
914
|
else if (reference.kind === 'stage') {
|
|
851
|
-
if (
|
|
852
|
-
return
|
|
915
|
+
if (id !== stagePanelId)
|
|
916
|
+
return keepInitialLayout();
|
|
917
|
+
if (!stagePane) {
|
|
918
|
+
if (!exact)
|
|
919
|
+
return keepInitialLayout();
|
|
920
|
+
dropped.add(id);
|
|
921
|
+
continue;
|
|
922
|
+
}
|
|
853
923
|
panels[id] = { id, title: stagePane.title, contentComponent: stagePanelId, renderer: 'always' };
|
|
854
924
|
}
|
|
855
925
|
else {
|
|
856
926
|
if (id === stagePanelId)
|
|
857
|
-
return
|
|
927
|
+
return keepInitialLayout();
|
|
858
928
|
const request = documentWorkspace && documentWorkspace.resolve(reference);
|
|
859
929
|
if (!request) {
|
|
860
930
|
// The project can finish loading before the Blockly host publishes its document catalog.
|
|
861
|
-
restoreTimeout ??= window.setTimeout(
|
|
931
|
+
restoreTimeout ??= window.setTimeout(keepInitialLayout, 2000);
|
|
862
932
|
return;
|
|
863
933
|
}
|
|
864
934
|
resolvedDocuments.set(id, request);
|
|
865
935
|
panels[id] = { id, title: documentPanelTitle(request), contentComponent: documentComponent, renderer: 'always' };
|
|
866
936
|
}
|
|
867
937
|
}
|
|
938
|
+
const kept = workspaceWithoutTransientPanels(stored.grid, stored.activeGroup, dropped, stored.editingView);
|
|
939
|
+
if (!kept)
|
|
940
|
+
return keepInitialLayout();
|
|
941
|
+
const editingView = stored.editingView && !dropped.has(stored.editingView) ? stored.editingView : undefined;
|
|
868
942
|
assignTabNumbers(resolvedSprites.values(), new Set([...targets.map(baseTitle),
|
|
869
943
|
...Object.values(panels).map(panel => panel.title)]));
|
|
870
944
|
for (const [id, view] of resolvedSprites)
|
|
@@ -880,14 +954,14 @@ export function mountSpriteTabs(root, content, options) {
|
|
|
880
954
|
views.set(id, view);
|
|
881
955
|
for (const [id, request] of resolvedDocuments)
|
|
882
956
|
documents.set(id, { request });
|
|
883
|
-
dockview.fromJSON({ grid:
|
|
957
|
+
dockview.fromJSON({ grid: kept.grid, activeGroup: kept.activeGroup, panels });
|
|
884
958
|
for (const popout of stored.popouts ?? []) {
|
|
885
959
|
for (const id of popout.panels)
|
|
886
960
|
if (views.has(id))
|
|
887
961
|
reopenable.set(id, popout);
|
|
888
962
|
}
|
|
889
963
|
const selected = dockview.activePanel;
|
|
890
|
-
show(views.has(selected?.id) ? selected : dockview.getPanel(
|
|
964
|
+
show(views.has(selected?.id) ? selected : (editingView && dockview.getPanel(editingView)) ?? selected);
|
|
891
965
|
}
|
|
892
966
|
catch {
|
|
893
967
|
dockview.clear();
|
|
@@ -905,8 +979,26 @@ export function mountSpriteTabs(root, content, options) {
|
|
|
905
979
|
refresh();
|
|
906
980
|
}
|
|
907
981
|
function scheduleRestore() {
|
|
908
|
-
if (pendingRestore && restoreFrame === undefined)
|
|
982
|
+
if (persistence && (pendingRestore || !layoutSession) && restoreFrame === undefined) {
|
|
909
983
|
restoreFrame = window.requestAnimationFrame(restoreLayout);
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
/** Each loaded project has its own layout, so a new load reopens the tabs that project was left with. */
|
|
987
|
+
function projectChanged() {
|
|
988
|
+
const loading = Boolean(persistence && persistence.isProjectLoading?.());
|
|
989
|
+
if (loading && !projectLoading) {
|
|
990
|
+
projectGeneration++;
|
|
991
|
+
layoutSession = undefined;
|
|
992
|
+
initialShape = undefined;
|
|
993
|
+
pendingRestore = true;
|
|
994
|
+
if (saveFrame !== undefined)
|
|
995
|
+
window.cancelAnimationFrame(saveFrame);
|
|
996
|
+
saveFrame = undefined;
|
|
997
|
+
window.clearTimeout(restoreTimeout);
|
|
998
|
+
restoreTimeout = undefined;
|
|
999
|
+
}
|
|
1000
|
+
projectLoading = loading;
|
|
1001
|
+
scheduleRestore();
|
|
910
1002
|
}
|
|
911
1003
|
function refresh() {
|
|
912
1004
|
if (syncing)
|
|
@@ -994,7 +1086,12 @@ export function mountSpriteTabs(root, content, options) {
|
|
|
994
1086
|
});
|
|
995
1087
|
const disconnectDocuments = documentWorkspace && documentWorkspace.connect(openDocument);
|
|
996
1088
|
const unsubscribeDocuments = persistence && documentWorkspace && documentWorkspace.subscribe(scheduleRestore);
|
|
997
|
-
|
|
1089
|
+
projectLoading = Boolean(persistence && persistence.isProjectLoading?.());
|
|
1090
|
+
const unsubscribeProject = persistence && persistence.subscribeProject?.(projectChanged);
|
|
1091
|
+
layoutStore?.readTabsPosition().then(position => {
|
|
1092
|
+
if (!disposed && !tabsChosen && position === 'left')
|
|
1093
|
+
setVerticalTabs(true, false);
|
|
1094
|
+
}, () => undefined);
|
|
998
1095
|
if (persistence)
|
|
999
1096
|
window.addEventListener('pagehide', flushLayout);
|
|
1000
1097
|
root.addEventListener('click', guardDocumentClose, true);
|
|
@@ -1018,6 +1115,7 @@ export function mountSpriteTabs(root, content, options) {
|
|
|
1018
1115
|
views: () => [...views.values()].map(view => describe(view)),
|
|
1019
1116
|
dispose() {
|
|
1020
1117
|
flushLayout();
|
|
1118
|
+
disposed = true;
|
|
1021
1119
|
window.cancelAnimationFrame(restoreFrame);
|
|
1022
1120
|
window.clearTimeout(restoreTimeout);
|
|
1023
1121
|
if (persistence)
|
|
@@ -1142,7 +1240,7 @@ function SpriteTabs(props) {
|
|
|
1142
1240
|
resize: () => latest.current.resize(),
|
|
1143
1241
|
reopenLabel: props.reopenLabel,
|
|
1144
1242
|
multiView: props.multiView,
|
|
1145
|
-
|
|
1243
|
+
workspaceLayout: props.workspaceLayout,
|
|
1146
1244
|
stagePane: props.stagePane,
|
|
1147
1245
|
variables: hasVariables,
|
|
1148
1246
|
messages: hasMessages,
|
|
@@ -1164,7 +1262,7 @@ function SpriteTabs(props) {
|
|
|
1164
1262
|
instance.dispose();
|
|
1165
1263
|
};
|
|
1166
1264
|
}, [content, props.enabled, props.vm, props.reopenLabel, props.multiView, props.locale,
|
|
1167
|
-
props.viewAdapter, props.stagePane, props.
|
|
1265
|
+
props.viewAdapter, props.stagePane, props.workspaceLayout, props.renameLabels, props.popouts, props.className,
|
|
1168
1266
|
hasVariables, hasMessages, hasToolbar, hasAssetPreview]);
|
|
1169
1267
|
React.useLayoutEffect(() => {
|
|
1170
1268
|
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;
|
|
@@ -0,0 +1,177 @@
|
|
|
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
|
+
/** The database a person can delete from the browser's developer tools to forget every layout. */
|
|
9
|
+
export const workspaceLayoutDatabase = 'twPlusWorkspaceLayout';
|
|
10
|
+
export const workspaceLayoutLimit = 100;
|
|
11
|
+
export const workspaceLayoutMaxBytes = 256 * 1024;
|
|
12
|
+
const layoutsStore = 'layouts';
|
|
13
|
+
const preferencesStore = 'preferences';
|
|
14
|
+
const tabsPositionKey = 'tabsPosition';
|
|
15
|
+
const legacyKeys = ['twPlusDockviewLayout', 'twPlusDockviewLayout.tabs'];
|
|
16
|
+
const result = (request) => new Promise((resolve, reject) => {
|
|
17
|
+
request.onsuccess = () => resolve(request.result);
|
|
18
|
+
request.onerror = () => reject(request.error);
|
|
19
|
+
});
|
|
20
|
+
// Created with the transaction, before any request finishes, so the completion is never missed.
|
|
21
|
+
const completion = (transaction) => new Promise((resolve, reject) => {
|
|
22
|
+
transaction.oncomplete = () => resolve();
|
|
23
|
+
transaction.onerror = transaction.onabort = () => reject(transaction.error ?? new Error('The transaction was aborted.'));
|
|
24
|
+
});
|
|
25
|
+
function openDatabase(factory) {
|
|
26
|
+
const request = factory.open(workspaceLayoutDatabase, 1);
|
|
27
|
+
request.onupgradeneeded = () => {
|
|
28
|
+
const database = request.result;
|
|
29
|
+
const layouts = database.createObjectStore(layoutsStore, { keyPath: 'id', autoIncrement: true });
|
|
30
|
+
layouts.createIndex('name', 'name');
|
|
31
|
+
layouts.createIndex('desktopKey', 'desktopKey');
|
|
32
|
+
layouts.createIndex('lastUsedAt', 'lastUsedAt');
|
|
33
|
+
database.createObjectStore(preferencesStore);
|
|
34
|
+
};
|
|
35
|
+
return result(request);
|
|
36
|
+
}
|
|
37
|
+
const recent = (records) => records.sort((a, b) => b.lastUsedAt - a.lastUsedAt);
|
|
38
|
+
async function find(database, identity, signature) {
|
|
39
|
+
const transaction = database.transaction(layoutsStore, 'readonly');
|
|
40
|
+
const finished = completion(transaction);
|
|
41
|
+
const store = transaction.objectStore(layoutsStore);
|
|
42
|
+
const records = identity.kind === 'desktop' ?
|
|
43
|
+
await result(store.index('desktopKey').getAll(identity.key)) :
|
|
44
|
+
await result(store.index('name').getAll(identity.name));
|
|
45
|
+
await finished;
|
|
46
|
+
const candidates = recent(records.filter(record => record.kind === identity.kind));
|
|
47
|
+
if (identity.kind === 'desktop')
|
|
48
|
+
return candidates[0];
|
|
49
|
+
if (identity.kind === 'anonymous')
|
|
50
|
+
return candidates.find(record => record.signature === signature);
|
|
51
|
+
for (const record of candidates) {
|
|
52
|
+
try {
|
|
53
|
+
if (record.handle && await identity.handle.isSameEntry(record.handle))
|
|
54
|
+
return record;
|
|
55
|
+
}
|
|
56
|
+
catch { /* A handle from another browser profile or a removed file cannot be compared. */ }
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
async function touch(database, id, now) {
|
|
60
|
+
const transaction = database.transaction(layoutsStore, 'readwrite');
|
|
61
|
+
const finished = completion(transaction);
|
|
62
|
+
const store = transaction.objectStore(layoutsStore);
|
|
63
|
+
const record = await result(store.get(id));
|
|
64
|
+
if (record)
|
|
65
|
+
store.put({ ...record, lastUsedAt: now });
|
|
66
|
+
await finished;
|
|
67
|
+
}
|
|
68
|
+
async function save(database, record, limit) {
|
|
69
|
+
const transaction = database.transaction(layoutsStore, 'readwrite');
|
|
70
|
+
const finished = completion(transaction);
|
|
71
|
+
const store = transaction.objectStore(layoutsStore);
|
|
72
|
+
const id = await result(store.put(record));
|
|
73
|
+
if (record.id === undefined) {
|
|
74
|
+
// In the same transaction as the new record, so tabs saving at once never keep more than the limit.
|
|
75
|
+
let excess = await result(store.count()) - limit;
|
|
76
|
+
if (excess > 0) {
|
|
77
|
+
const cursor = store.index('lastUsedAt').openCursor();
|
|
78
|
+
await new Promise((resolve, reject) => {
|
|
79
|
+
cursor.onerror = () => reject(cursor.error);
|
|
80
|
+
cursor.onsuccess = () => {
|
|
81
|
+
const current = cursor.result;
|
|
82
|
+
if (!current || excess <= 0)
|
|
83
|
+
return resolve();
|
|
84
|
+
if (current.primaryKey !== id) {
|
|
85
|
+
current.delete();
|
|
86
|
+
excess--;
|
|
87
|
+
}
|
|
88
|
+
current.continue();
|
|
89
|
+
};
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
await finished;
|
|
94
|
+
return id;
|
|
95
|
+
}
|
|
96
|
+
function identityFields(identity) {
|
|
97
|
+
if (identity.kind === 'desktop')
|
|
98
|
+
return { kind: identity.kind, name: identity.name, desktopKey: identity.key };
|
|
99
|
+
if (identity.kind === 'anonymous')
|
|
100
|
+
return { kind: identity.kind, name: identity.name };
|
|
101
|
+
return { kind: identity.kind, name: identity.name, handle: identity.handle };
|
|
102
|
+
}
|
|
103
|
+
const defaultLegacyStorage = () => {
|
|
104
|
+
try {
|
|
105
|
+
return globalThis.localStorage ?? null;
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
export function createWorkspaceLayoutStore({ indexedDB: factory = globalThis.indexedDB, limit = workspaceLayoutLimit, maxBytes = workspaceLayoutMaxBytes, now = Date.now, legacyStorage = defaultLegacyStorage() } = {}) {
|
|
112
|
+
let database;
|
|
113
|
+
const connect = () => database ??= factory ? openDatabase(factory).then(opened => {
|
|
114
|
+
opened.onversionchange = () => {
|
|
115
|
+
opened.close();
|
|
116
|
+
database = undefined;
|
|
117
|
+
};
|
|
118
|
+
return opened;
|
|
119
|
+
}, error => {
|
|
120
|
+
database = undefined;
|
|
121
|
+
throw error;
|
|
122
|
+
}) : Promise.reject(new Error('IndexedDB is unavailable.'));
|
|
123
|
+
// Writes run one at a time, so a record is created once even when changes come quickly.
|
|
124
|
+
let queue = Promise.resolve();
|
|
125
|
+
const enqueue = (task) => {
|
|
126
|
+
const next = queue.then(task, task);
|
|
127
|
+
queue = next.catch(() => undefined);
|
|
128
|
+
return next;
|
|
129
|
+
};
|
|
130
|
+
for (const key of legacyKeys) {
|
|
131
|
+
try {
|
|
132
|
+
legacyStorage?.removeItem(key);
|
|
133
|
+
}
|
|
134
|
+
catch { /* Storage can be unavailable. */ }
|
|
135
|
+
}
|
|
136
|
+
const bytes = (text) => new TextEncoder().encode(text).length;
|
|
137
|
+
return {
|
|
138
|
+
async open(identity, signature) {
|
|
139
|
+
const opened = await connect();
|
|
140
|
+
const found = await find(opened, identity, signature);
|
|
141
|
+
let id = found?.id;
|
|
142
|
+
let written = false;
|
|
143
|
+
if (id !== undefined)
|
|
144
|
+
await enqueue(() => touch(opened, id, now()));
|
|
145
|
+
const fields = identityFields(identity);
|
|
146
|
+
return {
|
|
147
|
+
layout: found?.layout,
|
|
148
|
+
exact: Boolean(found) && identity.kind !== 'anonymous',
|
|
149
|
+
get saved() { return id !== undefined || written; },
|
|
150
|
+
write(layout, nextSignature) {
|
|
151
|
+
if (bytes(layout) > maxBytes)
|
|
152
|
+
return Promise.resolve();
|
|
153
|
+
written = true;
|
|
154
|
+
return enqueue(async () => {
|
|
155
|
+
id = await save(opened, { ...fields, ...(id !== undefined && { id }), signature: nextSignature, layout,
|
|
156
|
+
lastUsedAt: now() }, limit);
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
},
|
|
161
|
+
async readTabsPosition() {
|
|
162
|
+
const opened = await connect();
|
|
163
|
+
const transaction = opened.transaction(preferencesStore, 'readonly');
|
|
164
|
+
const value = await result(transaction.objectStore(preferencesStore).get(tabsPositionKey));
|
|
165
|
+
return value === 'left' || value === 'top' ? value : undefined;
|
|
166
|
+
},
|
|
167
|
+
writeTabsPosition(position) {
|
|
168
|
+
return enqueue(async () => {
|
|
169
|
+
const opened = await connect();
|
|
170
|
+
const transaction = opened.transaction(preferencesStore, 'readwrite');
|
|
171
|
+
const finished = completion(transaction);
|
|
172
|
+
transaction.objectStore(preferencesStore).put(position, tabsPositionKey);
|
|
173
|
+
await finished;
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
}
|
|
@@ -55,6 +55,9 @@ export declare function workspaceWithoutTransientPanels(grid: Grid, activeGroup:
|
|
|
55
55
|
grid: Grid;
|
|
56
56
|
activeGroup: string;
|
|
57
57
|
} | undefined;
|
|
58
|
-
/**
|
|
59
|
-
|
|
58
|
+
/**
|
|
59
|
+
* Rebuild only the supported docked grid and logical panel references from storage. Without `project`, a layout
|
|
60
|
+
* of any project is read; it is for a project already found by its file, folder or desktop key.
|
|
61
|
+
*/
|
|
62
|
+
export declare function readWorkspaceLayout(raw: string, project?: string): WorkspaceLayout | undefined;
|
|
60
63
|
export {};
|
package/dist/workspace-layout.js
CHANGED
|
@@ -98,9 +98,12 @@ const validId = (value) => typeof value === 'string' && value.length > 0 && valu
|
|
|
98
98
|
const coordinate = (value) => typeof value === 'number' && Number.isFinite(value) && Math.abs(value) <= 100000;
|
|
99
99
|
const size = (value) => typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 100000;
|
|
100
100
|
const record = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
101
|
-
/**
|
|
101
|
+
/**
|
|
102
|
+
* Rebuild only the supported docked grid and logical panel references from storage. Without `project`, a layout
|
|
103
|
+
* of any project is read; it is for a project already found by its file, folder or desktop key.
|
|
104
|
+
*/
|
|
102
105
|
export function readWorkspaceLayout(raw, project) {
|
|
103
|
-
if (raw.length >
|
|
106
|
+
if (raw.length > 256 * 1024)
|
|
104
107
|
return;
|
|
105
108
|
let input;
|
|
106
109
|
try {
|
|
@@ -109,7 +112,8 @@ export function readWorkspaceLayout(raw, project) {
|
|
|
109
112
|
catch {
|
|
110
113
|
return;
|
|
111
114
|
}
|
|
112
|
-
if (!record(input) || input.version !== 1 || input.project !==
|
|
115
|
+
if (!record(input) || input.version !== 1 || typeof input.project !== 'string' ||
|
|
116
|
+
(project !== undefined && input.project !== project) || !record(input.grid) ||
|
|
113
117
|
!record(input.panels) || !validId(input.activeGroup))
|
|
114
118
|
return;
|
|
115
119
|
const { width, height, orientation } = input.grid;
|
|
@@ -185,7 +189,7 @@ export function readWorkspaceLayout(raw, project) {
|
|
|
185
189
|
const popouts = readPopouts(input.popouts, panels);
|
|
186
190
|
if (!popouts)
|
|
187
191
|
return;
|
|
188
|
-
return { version: 1, project, grid: { root, width, height, orientation }, activeGroup: input.activeGroup,
|
|
192
|
+
return { version: 1, project: input.project, grid: { root, width, height, orientation }, activeGroup: input.activeGroup,
|
|
189
193
|
editingView: typeof editingView === 'string' ? editingView : undefined, panels,
|
|
190
194
|
...(popouts.length && { popouts }) };
|
|
191
195
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kubohiroya/turbowarp-plus-editor-workbench",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.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",
|
|
@@ -64,7 +64,8 @@
|
|
|
64
64
|
"typescript": "^6.0.3",
|
|
65
65
|
"jsdom": "26.1.0",
|
|
66
66
|
"@types/react": "18.3.31",
|
|
67
|
-
"@types/react-dom": "18.3.7"
|
|
67
|
+
"@types/react-dom": "18.3.7",
|
|
68
|
+
"fake-indexeddb": "6.2.6"
|
|
68
69
|
},
|
|
69
70
|
"repository": {
|
|
70
71
|
"type": "git",
|
package/src/sprite-tabs.ts
CHANGED
|
@@ -15,6 +15,8 @@ import type {DocumentPanelRequest} from './document-workspace.ts';
|
|
|
15
15
|
import {dockPopoutGroups, positionOnScreen, readWorkspaceLayout, workspaceWithoutTransientPanels}
|
|
16
16
|
from './workspace-layout.ts';
|
|
17
17
|
import type {PanelReference, SavedPopout, WorkspaceLayout} from './workspace-layout.ts';
|
|
18
|
+
import {createWorkspaceLayoutStore} from './workspace-layout-store.ts';
|
|
19
|
+
import type {WorkspaceLayoutSession, WorkspaceLayoutStore, WorkspaceProjectIdentity} from './workspace-layout-store.ts';
|
|
18
20
|
import type {SpriteVariableEdit, SpriteVariableEditError} from '@kubohiroya/turbowarp-plus-editor-project-model/sprite-variable-edit';
|
|
19
21
|
import {SpriteMessagePane} from '@kubohiroya/turbowarp-plus-editor-sprite-panes/sprite-message-pane';
|
|
20
22
|
import type {MessageRenameError} from '@kubohiroya/turbowarp-plus-editor-sprite-panes/sprite-message-pane';
|
|
@@ -22,6 +24,8 @@ import type {MessageUse, ProjectMessage, TargetMessages} from '@kubohiroya/turbo
|
|
|
22
24
|
import {createRenameMenuItem, spriteRenameLabel} from './target-tab-menu.ts';
|
|
23
25
|
|
|
24
26
|
export {getDocumentWorkspace} from './document-workspace.ts';
|
|
27
|
+
export {createWorkspaceLayoutStore, workspaceLayoutDatabase, workspaceLayoutLimit} from './workspace-layout-store.ts';
|
|
28
|
+
export type {WorkspaceLayoutStore, WorkspaceProjectIdentity} from './workspace-layout-store.ts';
|
|
25
29
|
export type {SpriteAssetKind, SpriteAssetPreviewItem} from '@kubohiroya/turbowarp-plus-editor-sprite-panes/sprite-asset-pane';
|
|
26
30
|
export {editSpriteVariable} from '@kubohiroya/turbowarp-plus-editor-project-model/sprite-variable-edit';
|
|
27
31
|
|
|
@@ -145,9 +149,12 @@ interface TabOptions<Snapshot = unknown> {
|
|
|
145
149
|
resize(): void;
|
|
146
150
|
reopenLabel: string;
|
|
147
151
|
multiView?: boolean;
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
152
|
+
/** Keep the workspace of each project and reopen it with the project. */
|
|
153
|
+
workspaceLayout?: {
|
|
154
|
+
/** IndexedDB by default. */
|
|
155
|
+
store?: WorkspaceLayoutStore;
|
|
156
|
+
/** The file, folder or desktop key the loaded project came from. Without one, it is known by its name. */
|
|
157
|
+
identify?(): WorkspaceProjectIdentity | undefined;
|
|
151
158
|
isProjectLoading?(): boolean;
|
|
152
159
|
subscribeProject?(listener: () => void): (() => void) | undefined;
|
|
153
160
|
};
|
|
@@ -266,7 +273,17 @@ export function mountSpriteTabs<Snapshot>(root: HTMLElement, content: HTMLElemen
|
|
|
266
273
|
let nextView = 0;
|
|
267
274
|
let renameDialog: HTMLDialogElement | undefined;
|
|
268
275
|
const text = options.renameLabels ?? renameLabels.en;
|
|
269
|
-
const persistence = multiView && options.
|
|
276
|
+
const persistence = multiView && options.workspaceLayout;
|
|
277
|
+
const layoutStore = persistence ? persistence.store ?? createWorkspaceLayoutStore() : undefined;
|
|
278
|
+
/** Where the layout of the loaded project is saved, once that project is identified. */
|
|
279
|
+
let layoutSession: WorkspaceLayoutSession | undefined;
|
|
280
|
+
/** Counts project loads, so a lookup that ends after another project opened is dropped. */
|
|
281
|
+
let projectGeneration = 0;
|
|
282
|
+
let openingGeneration: number | undefined;
|
|
283
|
+
let projectLoading = false;
|
|
284
|
+
/** The shape of the layout the project opened with, which is not worth a record of its own. */
|
|
285
|
+
let initialShape: string | undefined;
|
|
286
|
+
let disposed = false;
|
|
270
287
|
const window = document.defaultView;
|
|
271
288
|
const documentWorkspace = multiView && getDocumentWorkspace(vm);
|
|
272
289
|
let pendingRestore = Boolean(persistence);
|
|
@@ -277,10 +294,9 @@ export function mountSpriteTabs<Snapshot>(root: HTMLElement, content: HTMLElemen
|
|
|
277
294
|
/** Panels that were in a separate window when the layout was saved, until the user reopens them. */
|
|
278
295
|
const reopenable = new Map<string, SavedPopout>();
|
|
279
296
|
const originalTargets = () => vm.runtime.targets.filter(target => target.isOriginal);
|
|
280
|
-
// Whether tabs stand in a column at the left of each split. It is the user's preference
|
|
281
|
-
const tabsKey = persistence ? persistence.key + '.tabs' : undefined;
|
|
297
|
+
// Whether tabs stand in a column at the left of each split. It is the user's preference for every project.
|
|
282
298
|
let verticalTabs = false;
|
|
283
|
-
|
|
299
|
+
let tabsChosen = false;
|
|
284
300
|
|
|
285
301
|
const dockview = createDockview(root, {
|
|
286
302
|
theme: themeLight,
|
|
@@ -464,12 +480,15 @@ export function mountSpriteTabs<Snapshot>(root: HTMLElement, content: HTMLElemen
|
|
|
464
480
|
return {...menu, init() {}};
|
|
465
481
|
}
|
|
466
482
|
|
|
467
|
-
function setVerticalTabs(vertical: boolean) {
|
|
483
|
+
function setVerticalTabs(vertical: boolean, chosen = true) {
|
|
468
484
|
verticalTabs = vertical;
|
|
469
485
|
const position = vertical ? 'left' : 'top';
|
|
470
486
|
dockview.updateOptions({defaultHeaderPosition: position});
|
|
471
487
|
for (const group of dockview.groups) group.api.setHeaderPosition(position);
|
|
472
|
-
|
|
488
|
+
if (chosen) {
|
|
489
|
+
tabsChosen = true;
|
|
490
|
+
layoutStore?.writeTabsPosition(position).catch(() => undefined);
|
|
491
|
+
}
|
|
473
492
|
refreshSurfaces();
|
|
474
493
|
}
|
|
475
494
|
|
|
@@ -861,10 +880,10 @@ export function mountSpriteTabs<Snapshot>(root: HTMLElement, content: HTMLElemen
|
|
|
861
880
|
scheduleSave();
|
|
862
881
|
}
|
|
863
882
|
|
|
864
|
-
|
|
865
|
-
|
|
883
|
+
/** The current workspace as it is saved, or nothing while it cannot be described yet. */
|
|
884
|
+
function captureLayout(): WorkspaceLayout | undefined {
|
|
866
885
|
const targets = originalTargets();
|
|
867
|
-
if (!
|
|
886
|
+
if (!targets.length) return;
|
|
868
887
|
const serialized = dockview.toJSON();
|
|
869
888
|
if (serialized.grid.width <= 0 || serialized.grid.height <= 0) return;
|
|
870
889
|
const docked = dockPopoutGroups(serialized.grid, serialized.activeGroup, serialized.popoutGroups);
|
|
@@ -889,13 +908,22 @@ export function mountSpriteTabs<Snapshot>(root: HTMLElement, content: HTMLElemen
|
|
|
889
908
|
.map(popout => ({...popout, panels: popout.panels.filter(id =>
|
|
890
909
|
reopenable.get(id) === popout && views.has(id) && panels[id]?.kind === 'sprite')}))
|
|
891
910
|
.filter(popout => popout.panels.length);
|
|
892
|
-
|
|
911
|
+
return {version: 1, project: projectSignature(targets), ...saved,
|
|
893
912
|
editingView: active?.id, panels, ...(popouts.length && {popouts})};
|
|
894
|
-
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
function writeLayout() {
|
|
916
|
+
saveFrame = undefined;
|
|
917
|
+
if (!persistence || !layoutSession || pendingRestore || syncing || persistence.isProjectLoading?.()) return;
|
|
918
|
+
const snapshot = captureLayout();
|
|
919
|
+
if (!snapshot) return;
|
|
920
|
+
// Opening a project and leaving its tabs as they were is not worth a record that pushes out another project.
|
|
921
|
+
if (!layoutSession.saved && initialShape !== undefined && layoutShape(snapshot) === initialShape) return;
|
|
922
|
+
layoutSession.write(JSON.stringify(snapshot), snapshot.project).catch(() => undefined);
|
|
895
923
|
}
|
|
896
924
|
|
|
897
925
|
function scheduleSave() {
|
|
898
|
-
if (persistence && !pendingRestore && saveFrame === undefined) {
|
|
926
|
+
if (persistence && layoutSession && !pendingRestore && saveFrame === undefined) {
|
|
899
927
|
saveFrame = window.requestAnimationFrame(writeLayout);
|
|
900
928
|
}
|
|
901
929
|
}
|
|
@@ -910,45 +938,101 @@ export function mountSpriteTabs<Snapshot>(root: HTMLElement, content: HTMLElemen
|
|
|
910
938
|
function finishRestore() {
|
|
911
939
|
pendingRestore = false;
|
|
912
940
|
window.clearTimeout(restoreTimeout);
|
|
941
|
+
restoreTimeout = undefined;
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
/** The panels and splits of a layout, without sizes or selection, to tell whether the user changed it. */
|
|
945
|
+
function layoutShape(layout: WorkspaceLayout) {
|
|
946
|
+
type Node = WorkspaceLayout['grid']['root'];
|
|
947
|
+
const reference = (id: string) => layout.panels[id] ?? null;
|
|
948
|
+
const shape = (node: Node): unknown => Array.isArray(node.data) ? node.data.map(shape) :
|
|
949
|
+
node.data.views.map(reference);
|
|
950
|
+
return JSON.stringify([layout.grid.orientation, shape(layout.grid.root),
|
|
951
|
+
(layout.popouts ?? []).map(popout => popout.panels.map(reference))]);
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
function identifyProject(): WorkspaceProjectIdentity {
|
|
955
|
+
try {
|
|
956
|
+
const identity = persistence && persistence.identify?.();
|
|
957
|
+
if (identity) return identity;
|
|
958
|
+
} catch { /* The project is still known by its name and sprites. */ }
|
|
959
|
+
return {kind: 'anonymous', name: ''};
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
/** Find where the loaded project keeps its layout. It runs once for each project load. */
|
|
963
|
+
function openLayoutSession(signature: string) {
|
|
964
|
+
if (!layoutStore || openingGeneration === projectGeneration) return;
|
|
965
|
+
const generation = openingGeneration = projectGeneration;
|
|
966
|
+
layoutStore.open(identifyProject(), signature).then(session => {
|
|
967
|
+
if (disposed || generation !== projectGeneration) return;
|
|
968
|
+
layoutSession = session;
|
|
969
|
+
scheduleRestore();
|
|
970
|
+
}, () => {
|
|
971
|
+
// Without IndexedDB, the project opens with the default layout and nothing is saved.
|
|
972
|
+
if (!disposed && generation === projectGeneration) finishRestore();
|
|
973
|
+
});
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
/** Keep the layout the project opened with, so leaving it unchanged adds no record. */
|
|
977
|
+
function keepInitialLayout() {
|
|
978
|
+
const layout = captureLayout();
|
|
979
|
+
initialShape = layout && layoutShape(layout);
|
|
980
|
+
finishRestore();
|
|
913
981
|
}
|
|
914
982
|
|
|
915
983
|
function restoreLayout() {
|
|
916
984
|
restoreFrame = undefined;
|
|
917
|
-
if (!
|
|
985
|
+
if (!persistence || persistence.isProjectLoading?.()) return;
|
|
918
986
|
const targets = originalTargets();
|
|
919
987
|
if (!targets.length || !vm.editingTarget) return;
|
|
988
|
+
const signature = projectSignature(targets);
|
|
989
|
+
if (!layoutSession) return openLayoutSession(signature);
|
|
990
|
+
if (!pendingRestore) return;
|
|
920
991
|
reopenable.clear();
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
if (!stored) return finishRestore();
|
|
992
|
+
// A project found by its file, folder or desktop key keeps its tabs even after its sprites were renamed.
|
|
993
|
+
const exact = layoutSession.exact;
|
|
994
|
+
const raw = layoutSession.layout;
|
|
995
|
+
const stored = raw ? readWorkspaceLayout(raw, exact ? undefined : signature) : undefined;
|
|
996
|
+
if (!stored) return keepInitialLayout();
|
|
927
997
|
const resolvedSprites = new Map<string, View<Snapshot>>();
|
|
928
998
|
const resolvedDocuments = new Map<string, DocumentPanelRequest>();
|
|
929
999
|
const panels: SerializedDockview['panels'] = Object.create(null);
|
|
1000
|
+
const dropped = new Set<string>();
|
|
930
1001
|
for (const [id, reference] of Object.entries(stored.panels)) {
|
|
931
1002
|
if (reference.kind === 'sprite') {
|
|
932
1003
|
const target = targets.find(item => item.isStage === reference.stage && targetName(item) === reference.name);
|
|
933
|
-
if (
|
|
1004
|
+
if (id === stagePanelId) return keepInitialLayout();
|
|
1005
|
+
if (!target || !sectionAvailable(reference.section)) {
|
|
1006
|
+
if (!exact) return keepInitialLayout();
|
|
1007
|
+
dropped.add(id);
|
|
1008
|
+
continue;
|
|
1009
|
+
}
|
|
934
1010
|
resolvedSprites.set(id, {id, target, section: reference.section, number: reference.number,
|
|
935
1011
|
assets: createAssetSelections(target, locale)});
|
|
936
1012
|
panels[id] = {id, contentComponent: 'sprite', params: {icon: getIcon(target)}};
|
|
937
1013
|
} else if (reference.kind === 'stage') {
|
|
938
|
-
if (
|
|
1014
|
+
if (id !== stagePanelId) return keepInitialLayout();
|
|
1015
|
+
if (!stagePane) {
|
|
1016
|
+
if (!exact) return keepInitialLayout();
|
|
1017
|
+
dropped.add(id);
|
|
1018
|
+
continue;
|
|
1019
|
+
}
|
|
939
1020
|
panels[id] = {id, title: stagePane.title, contentComponent: stagePanelId, renderer: 'always'};
|
|
940
1021
|
} else {
|
|
941
|
-
if (id === stagePanelId) return
|
|
1022
|
+
if (id === stagePanelId) return keepInitialLayout();
|
|
942
1023
|
const request = documentWorkspace && documentWorkspace.resolve(reference);
|
|
943
1024
|
if (!request) {
|
|
944
1025
|
// The project can finish loading before the Blockly host publishes its document catalog.
|
|
945
|
-
restoreTimeout ??= window.setTimeout(
|
|
1026
|
+
restoreTimeout ??= window.setTimeout(keepInitialLayout, 2000);
|
|
946
1027
|
return;
|
|
947
1028
|
}
|
|
948
1029
|
resolvedDocuments.set(id, request);
|
|
949
1030
|
panels[id] = {id, title: documentPanelTitle(request), contentComponent: documentComponent, renderer: 'always'};
|
|
950
1031
|
}
|
|
951
1032
|
}
|
|
1033
|
+
const kept = workspaceWithoutTransientPanels(stored.grid, stored.activeGroup, dropped, stored.editingView);
|
|
1034
|
+
if (!kept) return keepInitialLayout();
|
|
1035
|
+
const editingView = stored.editingView && !dropped.has(stored.editingView) ? stored.editingView : undefined;
|
|
952
1036
|
assignTabNumbers(resolvedSprites.values(), new Set([...targets.map(baseTitle),
|
|
953
1037
|
...Object.values(panels).map(panel => panel.title)]));
|
|
954
1038
|
for (const [id, view] of resolvedSprites) panels[id].title = tabTitle(view);
|
|
@@ -961,12 +1045,12 @@ export function mountSpriteTabs<Snapshot>(root: HTMLElement, content: HTMLElemen
|
|
|
961
1045
|
closed = new WeakSet(targets.filter(target => !represented.has(target)));
|
|
962
1046
|
for (const [id, view] of resolvedSprites) views.set(id, view);
|
|
963
1047
|
for (const [id, request] of resolvedDocuments) documents.set(id, {request});
|
|
964
|
-
dockview.fromJSON({grid:
|
|
1048
|
+
dockview.fromJSON({grid: kept.grid, activeGroup: kept.activeGroup, panels});
|
|
965
1049
|
for (const popout of stored.popouts ?? []) {
|
|
966
1050
|
for (const id of popout.panels) if (views.has(id)) reopenable.set(id, popout);
|
|
967
1051
|
}
|
|
968
1052
|
const selected = dockview.activePanel;
|
|
969
|
-
show(views.has(selected?.id) ? selected : dockview.getPanel(
|
|
1053
|
+
show(views.has(selected?.id) ? selected : (editingView && dockview.getPanel(editingView)) ?? selected);
|
|
970
1054
|
} catch {
|
|
971
1055
|
dockview.clear();
|
|
972
1056
|
for (const view of views.values()) disposeView(view);
|
|
@@ -981,7 +1065,26 @@ export function mountSpriteTabs<Snapshot>(root: HTMLElement, content: HTMLElemen
|
|
|
981
1065
|
}
|
|
982
1066
|
|
|
983
1067
|
function scheduleRestore() {
|
|
984
|
-
if (pendingRestore && restoreFrame === undefined)
|
|
1068
|
+
if (persistence && (pendingRestore || !layoutSession) && restoreFrame === undefined) {
|
|
1069
|
+
restoreFrame = window.requestAnimationFrame(restoreLayout);
|
|
1070
|
+
}
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
/** Each loaded project has its own layout, so a new load reopens the tabs that project was left with. */
|
|
1074
|
+
function projectChanged() {
|
|
1075
|
+
const loading = Boolean(persistence && persistence.isProjectLoading?.());
|
|
1076
|
+
if (loading && !projectLoading) {
|
|
1077
|
+
projectGeneration++;
|
|
1078
|
+
layoutSession = undefined;
|
|
1079
|
+
initialShape = undefined;
|
|
1080
|
+
pendingRestore = true;
|
|
1081
|
+
if (saveFrame !== undefined) window.cancelAnimationFrame(saveFrame);
|
|
1082
|
+
saveFrame = undefined;
|
|
1083
|
+
window.clearTimeout(restoreTimeout);
|
|
1084
|
+
restoreTimeout = undefined;
|
|
1085
|
+
}
|
|
1086
|
+
projectLoading = loading;
|
|
1087
|
+
scheduleRestore();
|
|
985
1088
|
}
|
|
986
1089
|
|
|
987
1090
|
function refresh() {
|
|
@@ -1060,7 +1163,11 @@ export function mountSpriteTabs<Snapshot>(root: HTMLElement, content: HTMLElemen
|
|
|
1060
1163
|
});
|
|
1061
1164
|
const disconnectDocuments = documentWorkspace && documentWorkspace.connect(openDocument);
|
|
1062
1165
|
const unsubscribeDocuments = persistence && documentWorkspace && documentWorkspace.subscribe(scheduleRestore);
|
|
1063
|
-
|
|
1166
|
+
projectLoading = Boolean(persistence && persistence.isProjectLoading?.());
|
|
1167
|
+
const unsubscribeProject = persistence && persistence.subscribeProject?.(projectChanged);
|
|
1168
|
+
layoutStore?.readTabsPosition().then(position => {
|
|
1169
|
+
if (!disposed && !tabsChosen && position === 'left') setVerticalTabs(true, false);
|
|
1170
|
+
}, () => undefined);
|
|
1064
1171
|
if (persistence) window.addEventListener('pagehide', flushLayout);
|
|
1065
1172
|
root.addEventListener('click', guardDocumentClose, true);
|
|
1066
1173
|
root.addEventListener('keydown', guardDocumentClose, true);
|
|
@@ -1082,6 +1189,7 @@ export function mountSpriteTabs<Snapshot>(root: HTMLElement, content: HTMLElemen
|
|
|
1082
1189
|
views: () => [...views.values()].map(view => describe(view)),
|
|
1083
1190
|
dispose() {
|
|
1084
1191
|
flushLayout();
|
|
1192
|
+
disposed = true;
|
|
1085
1193
|
window.cancelAnimationFrame(restoreFrame);
|
|
1086
1194
|
window.clearTimeout(restoreTimeout);
|
|
1087
1195
|
if (persistence) window.removeEventListener('pagehide', flushLayout);
|
|
@@ -1237,7 +1345,7 @@ function SpriteTabs<Snapshot>(props: SpriteTabsProps<Snapshot>) {
|
|
|
1237
1345
|
resize: () => latest.current.resize(),
|
|
1238
1346
|
reopenLabel: props.reopenLabel,
|
|
1239
1347
|
multiView: props.multiView,
|
|
1240
|
-
|
|
1348
|
+
workspaceLayout: props.workspaceLayout,
|
|
1241
1349
|
stagePane: props.stagePane,
|
|
1242
1350
|
variables: hasVariables,
|
|
1243
1351
|
messages: hasMessages,
|
|
@@ -1258,7 +1366,7 @@ function SpriteTabs<Snapshot>(props: SpriteTabsProps<Snapshot>) {
|
|
|
1258
1366
|
instance.dispose();
|
|
1259
1367
|
};
|
|
1260
1368
|
}, [content, props.enabled, props.vm, props.reopenLabel, props.multiView, props.locale,
|
|
1261
|
-
props.viewAdapter, props.stagePane, props.
|
|
1369
|
+
props.viewAdapter, props.stagePane, props.workspaceLayout, props.renameLabels, props.popouts, props.className,
|
|
1262
1370
|
hasVariables, hasMessages, hasToolbar, hasAssetPreview]);
|
|
1263
1371
|
React.useLayoutEffect(() => {
|
|
1264
1372
|
controller.current?.syncActiveSection(props.activeSection);
|
|
@@ -0,0 +1,221 @@
|
|
|
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
|
+
|
|
9
|
+
export type WorkspaceProjectIdentity =
|
|
10
|
+
| {kind: 'file' | 'directory'; name: string; handle: FileSystemHandle}
|
|
11
|
+
| {kind: 'desktop'; name: string; key: string}
|
|
12
|
+
| {kind: 'anonymous'; name: string};
|
|
13
|
+
|
|
14
|
+
export type TabsPosition = 'top' | 'left';
|
|
15
|
+
|
|
16
|
+
/** The saved workspace of one opened project, and where its next changes are written. */
|
|
17
|
+
export interface WorkspaceLayoutSession {
|
|
18
|
+
/** The saved layout, if this project has one. */
|
|
19
|
+
readonly layout: string | undefined;
|
|
20
|
+
/** Whether the project was found by its file, folder or desktop key, not only by its name and sprites. */
|
|
21
|
+
readonly exact: boolean;
|
|
22
|
+
/** Whether the project has a saved layout, or a change was written in this session. */
|
|
23
|
+
readonly saved: boolean;
|
|
24
|
+
/** Save the layout. The project's own record is updated, so it never adds a record per change. */
|
|
25
|
+
write(layout: string, signature: string): Promise<void>;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface WorkspaceLayoutStore {
|
|
29
|
+
open(identity: WorkspaceProjectIdentity, signature: string): Promise<WorkspaceLayoutSession>;
|
|
30
|
+
readTabsPosition(): Promise<TabsPosition | undefined>;
|
|
31
|
+
writeTabsPosition(position: TabsPosition): Promise<void>;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface WorkspaceLayoutStoreOptions {
|
|
35
|
+
indexedDB?: IDBFactory;
|
|
36
|
+
/** How many projects keep their layout. The least recently used ones are removed past it. */
|
|
37
|
+
limit?: number;
|
|
38
|
+
/** The largest layout that is saved, in bytes. */
|
|
39
|
+
maxBytes?: number;
|
|
40
|
+
now?(): number;
|
|
41
|
+
/** Where earlier versions kept a single layout. It is cleared once, without moving it. */
|
|
42
|
+
legacyStorage?: Pick<Storage, 'removeItem'> | null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** The database a person can delete from the browser's developer tools to forget every layout. */
|
|
46
|
+
export const workspaceLayoutDatabase = 'twPlusWorkspaceLayout';
|
|
47
|
+
export const workspaceLayoutLimit = 100;
|
|
48
|
+
export const workspaceLayoutMaxBytes = 256 * 1024;
|
|
49
|
+
|
|
50
|
+
const layoutsStore = 'layouts';
|
|
51
|
+
const preferencesStore = 'preferences';
|
|
52
|
+
const tabsPositionKey = 'tabsPosition';
|
|
53
|
+
const legacyKeys = ['twPlusDockviewLayout', 'twPlusDockviewLayout.tabs'];
|
|
54
|
+
|
|
55
|
+
interface LayoutRecord {
|
|
56
|
+
id?: number;
|
|
57
|
+
kind: WorkspaceProjectIdentity['kind'];
|
|
58
|
+
name: string;
|
|
59
|
+
handle?: FileSystemHandle;
|
|
60
|
+
desktopKey?: string;
|
|
61
|
+
signature: string;
|
|
62
|
+
layout: string;
|
|
63
|
+
lastUsedAt: number;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const result = <T>(request: IDBRequest<T>) => new Promise<T>((resolve, reject) => {
|
|
67
|
+
request.onsuccess = () => resolve(request.result);
|
|
68
|
+
request.onerror = () => reject(request.error);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
// Created with the transaction, before any request finishes, so the completion is never missed.
|
|
72
|
+
const completion = (transaction: IDBTransaction) => new Promise<void>((resolve, reject) => {
|
|
73
|
+
transaction.oncomplete = () => resolve();
|
|
74
|
+
transaction.onerror = transaction.onabort = () => reject(transaction.error ?? new Error('The transaction was aborted.'));
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
function openDatabase(factory: IDBFactory) {
|
|
78
|
+
const request = factory.open(workspaceLayoutDatabase, 1);
|
|
79
|
+
request.onupgradeneeded = () => {
|
|
80
|
+
const database = request.result;
|
|
81
|
+
const layouts = database.createObjectStore(layoutsStore, {keyPath: 'id', autoIncrement: true});
|
|
82
|
+
layouts.createIndex('name', 'name');
|
|
83
|
+
layouts.createIndex('desktopKey', 'desktopKey');
|
|
84
|
+
layouts.createIndex('lastUsedAt', 'lastUsedAt');
|
|
85
|
+
database.createObjectStore(preferencesStore);
|
|
86
|
+
};
|
|
87
|
+
return result(request);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const recent = (records: LayoutRecord[]) => records.sort((a, b) => b.lastUsedAt - a.lastUsedAt);
|
|
91
|
+
|
|
92
|
+
async function find(database: IDBDatabase, identity: WorkspaceProjectIdentity, signature: string) {
|
|
93
|
+
const transaction = database.transaction(layoutsStore, 'readonly');
|
|
94
|
+
const finished = completion(transaction);
|
|
95
|
+
const store = transaction.objectStore(layoutsStore);
|
|
96
|
+
const records = identity.kind === 'desktop' ?
|
|
97
|
+
await result(store.index('desktopKey').getAll(identity.key)) as LayoutRecord[] :
|
|
98
|
+
await result(store.index('name').getAll(identity.name)) as LayoutRecord[];
|
|
99
|
+
await finished;
|
|
100
|
+
const candidates = recent(records.filter(record => record.kind === identity.kind));
|
|
101
|
+
if (identity.kind === 'desktop') return candidates[0];
|
|
102
|
+
if (identity.kind === 'anonymous') return candidates.find(record => record.signature === signature);
|
|
103
|
+
for (const record of candidates) {
|
|
104
|
+
try {
|
|
105
|
+
if (record.handle && await identity.handle.isSameEntry(record.handle)) return record;
|
|
106
|
+
} catch { /* A handle from another browser profile or a removed file cannot be compared. */ }
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async function touch(database: IDBDatabase, id: number, now: number) {
|
|
111
|
+
const transaction = database.transaction(layoutsStore, 'readwrite');
|
|
112
|
+
const finished = completion(transaction);
|
|
113
|
+
const store = transaction.objectStore(layoutsStore);
|
|
114
|
+
const record = await result(store.get(id)) as LayoutRecord | undefined;
|
|
115
|
+
if (record) store.put({...record, lastUsedAt: now});
|
|
116
|
+
await finished;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async function save(database: IDBDatabase, record: LayoutRecord, limit: number) {
|
|
120
|
+
const transaction = database.transaction(layoutsStore, 'readwrite');
|
|
121
|
+
const finished = completion(transaction);
|
|
122
|
+
const store = transaction.objectStore(layoutsStore);
|
|
123
|
+
const id = await result(store.put(record)) as number;
|
|
124
|
+
if (record.id === undefined) {
|
|
125
|
+
// In the same transaction as the new record, so tabs saving at once never keep more than the limit.
|
|
126
|
+
let excess = await result(store.count()) - limit;
|
|
127
|
+
if (excess > 0) {
|
|
128
|
+
const cursor = store.index('lastUsedAt').openCursor();
|
|
129
|
+
await new Promise<void>((resolve, reject) => {
|
|
130
|
+
cursor.onerror = () => reject(cursor.error);
|
|
131
|
+
cursor.onsuccess = () => {
|
|
132
|
+
const current = cursor.result;
|
|
133
|
+
if (!current || excess <= 0) return resolve();
|
|
134
|
+
if (current.primaryKey !== id) {
|
|
135
|
+
current.delete();
|
|
136
|
+
excess--;
|
|
137
|
+
}
|
|
138
|
+
current.continue();
|
|
139
|
+
};
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
await finished;
|
|
144
|
+
return id;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function identityFields(identity: WorkspaceProjectIdentity): Pick<LayoutRecord, 'kind' | 'name' | 'handle' | 'desktopKey'> {
|
|
148
|
+
if (identity.kind === 'desktop') return {kind: identity.kind, name: identity.name, desktopKey: identity.key};
|
|
149
|
+
if (identity.kind === 'anonymous') return {kind: identity.kind, name: identity.name};
|
|
150
|
+
return {kind: identity.kind, name: identity.name, handle: identity.handle};
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const defaultLegacyStorage = () => {
|
|
154
|
+
try { return globalThis.localStorage ?? null; } catch { return null; }
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
export function createWorkspaceLayoutStore({indexedDB: factory = globalThis.indexedDB, limit = workspaceLayoutLimit,
|
|
158
|
+
maxBytes = workspaceLayoutMaxBytes, now = Date.now, legacyStorage = defaultLegacyStorage()}: WorkspaceLayoutStoreOptions = {}):
|
|
159
|
+
WorkspaceLayoutStore {
|
|
160
|
+
let database: Promise<IDBDatabase> | undefined;
|
|
161
|
+
const connect = () => database ??= factory ? openDatabase(factory).then(opened => {
|
|
162
|
+
opened.onversionchange = () => {
|
|
163
|
+
opened.close();
|
|
164
|
+
database = undefined;
|
|
165
|
+
};
|
|
166
|
+
return opened;
|
|
167
|
+
}, error => {
|
|
168
|
+
database = undefined;
|
|
169
|
+
throw error;
|
|
170
|
+
}) : Promise.reject(new Error('IndexedDB is unavailable.'));
|
|
171
|
+
// Writes run one at a time, so a record is created once even when changes come quickly.
|
|
172
|
+
let queue: Promise<unknown> = Promise.resolve();
|
|
173
|
+
const enqueue = <T>(task: () => Promise<T>) => {
|
|
174
|
+
const next = queue.then(task, task);
|
|
175
|
+
queue = next.catch(() => undefined);
|
|
176
|
+
return next;
|
|
177
|
+
};
|
|
178
|
+
for (const key of legacyKeys) {
|
|
179
|
+
try { legacyStorage?.removeItem(key); } catch { /* Storage can be unavailable. */ }
|
|
180
|
+
}
|
|
181
|
+
const bytes = (text: string) => new TextEncoder().encode(text).length;
|
|
182
|
+
|
|
183
|
+
return {
|
|
184
|
+
async open(identity, signature) {
|
|
185
|
+
const opened = await connect();
|
|
186
|
+
const found = await find(opened, identity, signature);
|
|
187
|
+
let id = found?.id;
|
|
188
|
+
let written = false;
|
|
189
|
+
if (id !== undefined) await enqueue(() => touch(opened, id!, now()));
|
|
190
|
+
const fields = identityFields(identity);
|
|
191
|
+
return {
|
|
192
|
+
layout: found?.layout,
|
|
193
|
+
exact: Boolean(found) && identity.kind !== 'anonymous',
|
|
194
|
+
get saved() { return id !== undefined || written; },
|
|
195
|
+
write(layout, nextSignature) {
|
|
196
|
+
if (bytes(layout) > maxBytes) return Promise.resolve();
|
|
197
|
+
written = true;
|
|
198
|
+
return enqueue(async () => {
|
|
199
|
+
id = await save(opened, {...fields, ...(id !== undefined && {id}), signature: nextSignature, layout,
|
|
200
|
+
lastUsedAt: now()}, limit);
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
};
|
|
204
|
+
},
|
|
205
|
+
async readTabsPosition() {
|
|
206
|
+
const opened = await connect();
|
|
207
|
+
const transaction = opened.transaction(preferencesStore, 'readonly');
|
|
208
|
+
const value = await result(transaction.objectStore(preferencesStore).get(tabsPositionKey));
|
|
209
|
+
return value === 'left' || value === 'top' ? value : undefined;
|
|
210
|
+
},
|
|
211
|
+
writeTabsPosition(position) {
|
|
212
|
+
return enqueue(async () => {
|
|
213
|
+
const opened = await connect();
|
|
214
|
+
const transaction = opened.transaction(preferencesStore, 'readwrite');
|
|
215
|
+
const finished = completion(transaction);
|
|
216
|
+
transaction.objectStore(preferencesStore).put(position, tabsPositionKey);
|
|
217
|
+
await finished;
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
};
|
|
221
|
+
}
|
package/src/workspace-layout.ts
CHANGED
|
@@ -123,12 +123,16 @@ const size = (value: unknown): value is number =>
|
|
|
123
123
|
const record = (value: unknown): value is Record<string, unknown> =>
|
|
124
124
|
value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
125
125
|
|
|
126
|
-
/**
|
|
127
|
-
|
|
128
|
-
|
|
126
|
+
/**
|
|
127
|
+
* Rebuild only the supported docked grid and logical panel references from storage. Without `project`, a layout
|
|
128
|
+
* of any project is read; it is for a project already found by its file, folder or desktop key.
|
|
129
|
+
*/
|
|
130
|
+
export function readWorkspaceLayout(raw: string, project?: string): WorkspaceLayout | undefined {
|
|
131
|
+
if (raw.length > 256 * 1024) return;
|
|
129
132
|
let input: unknown;
|
|
130
133
|
try { input = JSON.parse(raw); } catch { return; }
|
|
131
|
-
if (!record(input) || input.version !== 1 || input.project !==
|
|
134
|
+
if (!record(input) || input.version !== 1 || typeof input.project !== 'string' ||
|
|
135
|
+
(project !== undefined && input.project !== project) || !record(input.grid) ||
|
|
132
136
|
!record(input.panels) || !validId(input.activeGroup)) return;
|
|
133
137
|
const {width, height, orientation} = input.grid;
|
|
134
138
|
if (!size(width) || !width || !size(height) || !height ||
|
|
@@ -187,7 +191,7 @@ export function readWorkspaceLayout(raw: string, project: string): WorkspaceLayo
|
|
|
187
191
|
if (editingView !== undefined && (!validId(editingView) || panels[editingView]?.kind !== 'sprite')) return;
|
|
188
192
|
const popouts = readPopouts(input.popouts, panels);
|
|
189
193
|
if (!popouts) return;
|
|
190
|
-
return {version: 1, project, grid: {root, width, height, orientation}, activeGroup: input.activeGroup,
|
|
194
|
+
return {version: 1, project: input.project, grid: {root, width, height, orientation}, activeGroup: input.activeGroup,
|
|
191
195
|
editingView: typeof editingView === 'string' ? editingView : undefined, panels,
|
|
192
196
|
...(popouts.length && {popouts})};
|
|
193
197
|
}
|