@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.
@@ -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
+ }
@@ -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
- /** Rebuild only the supported docked grid and logical panel references from storage. */
127
- export function readWorkspaceLayout(raw: string, project: string): WorkspaceLayout | undefined {
128
- if (raw.length > 1024 * 1024) return;
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 !== project || !record(input.grid) ||
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
  }