@kubohiroya/turbowarp-plus-editor-project-folder 0.12.0 → 0.14.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 +17 -2
- package/README.md +17 -2
- package/dist/browser-project-dialog.d.ts +20 -0
- package/dist/browser-projects.d.ts +47 -0
- package/dist/explorer-files.d.ts +5 -0
- package/dist/explorer.js +93 -32
- package/dist/index.d.ts +25 -2
- package/dist/index.js +704 -19
- package/dist/zip.d.ts +9 -0
- package/package.json +1 -1
- package/src/browser-project-dialog.ts +257 -0
- package/src/browser-projects.ts +211 -0
- package/src/explorer-files.ts +33 -1
- package/src/explorer.tsx +28 -14
- package/src/index.ts +75 -16
- package/src/zip.ts +103 -0
package/dist/zip.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Writes a folder as a ZIP archive without compression, so a project folder kept in the browser can be saved as one
|
|
3
|
+
* file. Entries use UTF-8 names. The archive holds at most 65535 entries and 4 GiB, which a project folder stays under.
|
|
4
|
+
*/
|
|
5
|
+
export declare function crc32(bytes: Uint8Array): number;
|
|
6
|
+
/** The files under `directory` as a ZIP. `exclude` receives paths relative to `directory`, such as `.git`. */
|
|
7
|
+
export declare function zipDirectory(directory: FileSystemDirectoryHandle, { exclude }?: {
|
|
8
|
+
exclude?: (path: string) => boolean;
|
|
9
|
+
}): Promise<Blob>;
|
package/package.json
CHANGED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
import type {BrowserProject, BrowserProjects} from './browser-projects.js';
|
|
2
|
+
import {zipDirectory} from './zip.js';
|
|
3
|
+
|
|
4
|
+
const messages = {
|
|
5
|
+
en: {
|
|
6
|
+
openTitle: 'Project Folders in This Browser', createTitle: 'New Project Folder in This Browser',
|
|
7
|
+
note: 'These folders are stored only in this browser. The browser may delete them when you clear site data or ' +
|
|
8
|
+
'do not use this site for a while. Export a ZIP or push to GitHub to keep a copy.',
|
|
9
|
+
usage: (used: string, quota: string) => `Using ${used} of ${quota}.`,
|
|
10
|
+
persisted: 'The browser keeps this storage until you clear it.',
|
|
11
|
+
empty: 'No project folders are stored in this browser yet.',
|
|
12
|
+
name: 'Name', create: 'Create', open: 'Open', exportZip: 'Export ZIP', remove: 'Delete…', close: 'Close',
|
|
13
|
+
updated: (date: string) => `Updated ${date}`,
|
|
14
|
+
confirmRemove: (title: string) => `Delete “${title}” from this browser? This cannot be undone. Export a ZIP first to keep a copy.`,
|
|
15
|
+
failed: 'The browser storage could not be used.'
|
|
16
|
+
},
|
|
17
|
+
ja: {
|
|
18
|
+
openTitle: 'ブラウザー内の作品フォルダ', createTitle: '新しい作品フォルダをブラウザー内に作る',
|
|
19
|
+
note: 'この作品フォルダは、このブラウザーの中にだけ保存されます。サイトのデータを消したときや、しばらくこのサイトを' +
|
|
20
|
+
'使わなかったときに、ブラウザーが消すことがあります。ZIP で書き出すか、GitHub に送って残してください。',
|
|
21
|
+
usage: (used: string, quota: string) => `${quota} のうち ${used} を使っています。`,
|
|
22
|
+
persisted: 'このブラウザーは、データを消すまでこの保存領域を残します。',
|
|
23
|
+
empty: 'このブラウザーには、まだ作品フォルダがありません。',
|
|
24
|
+
name: '名前', create: '作成', open: '開く', exportZip: 'ZIP で書き出す', remove: '削除…', close: '閉じる',
|
|
25
|
+
updated: (date: string) => `更新: ${date}`,
|
|
26
|
+
confirmRemove: (title: string) => `「${title}」をこのブラウザーから削除しますか?元に戻せません。残すには、先に ZIP で書き出してください。`,
|
|
27
|
+
failed: 'ブラウザーの保存領域を使えませんでした。'
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
const closeIcon = 'M4 4l8 8M12 4l-8 8';
|
|
32
|
+
|
|
33
|
+
function formatBytes(value: number, locale: string) {
|
|
34
|
+
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
|
|
35
|
+
let size = value;
|
|
36
|
+
let unit = 0;
|
|
37
|
+
while (size >= 1024 && unit < units.length - 1) {
|
|
38
|
+
size /= 1024;
|
|
39
|
+
unit++;
|
|
40
|
+
}
|
|
41
|
+
return `${new Intl.NumberFormat(locale, {maximumFractionDigits: unit ? 1 : 0}).format(size)} ${units[unit]}`;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** A file name for the exported ZIP that every OS accepts. */
|
|
45
|
+
export function zipFileName(title: string) {
|
|
46
|
+
const name = title.replace(/[\\/:*?"<>|\u0000-\u001f\u007f]/gu, '_').replace(/^[.\s]+|[.\s]+$/gu, '').slice(0, 120);
|
|
47
|
+
return `${name || 'project'}.zip`;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Saves the stored folder of `project` as a ZIP through the browser's download. */
|
|
51
|
+
export async function exportBrowserProject(document: Document, projects: BrowserProjects, project: BrowserProject) {
|
|
52
|
+
const root = await projects.root(project.id);
|
|
53
|
+
if (!root) throw new DOMException('The project folder was deleted', 'NotFoundError');
|
|
54
|
+
const blob = await projects.exclusive(project.id, () => zipDirectory(root));
|
|
55
|
+
const view = document.defaultView!;
|
|
56
|
+
const url = view.URL.createObjectURL(blob);
|
|
57
|
+
const link = document.createElement('a');
|
|
58
|
+
link.href = url;
|
|
59
|
+
link.download = zipFileName(project.title);
|
|
60
|
+
link.hidden = true;
|
|
61
|
+
document.body.append(link);
|
|
62
|
+
link.click();
|
|
63
|
+
link.remove();
|
|
64
|
+
// Give the download time to start before the URL goes away.
|
|
65
|
+
view.setTimeout(() => view.URL.revokeObjectURL(url), 60_000);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export type BrowserProjectChoice = {project: BrowserProject; directory: FileSystemDirectoryHandle};
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Shows the project folders kept in this browser. With `purpose: 'open'` the user picks one; with `'create'` the user
|
|
72
|
+
* names a new empty one. Resolves with the chosen folder, or `null` when the dialog closes without one.
|
|
73
|
+
*/
|
|
74
|
+
export function chooseBrowserProject({document, projects, locale = 'en', purpose, title = ''}: {
|
|
75
|
+
document: Document; projects: BrowserProjects; locale?: string; purpose: 'open' | 'create'; title?: string;
|
|
76
|
+
}): Promise<BrowserProjectChoice | null> {
|
|
77
|
+
const message = locale.startsWith('ja') ? messages.ja : messages.en;
|
|
78
|
+
const view = document.defaultView!;
|
|
79
|
+
const dialog = document.createElement('dialog');
|
|
80
|
+
dialog.dataset.browserProjects = purpose;
|
|
81
|
+
dialog.setAttribute('aria-labelledby', 'tw-plus-browser-projects-title');
|
|
82
|
+
Object.assign(dialog.style, {
|
|
83
|
+
width: 'min(34rem, calc(100vw - 2rem))', maxHeight: 'calc(100vh - 4rem)', padding: '1rem 1.25rem',
|
|
84
|
+
background: 'Canvas', color: 'CanvasText', border: '1px solid GrayText', borderRadius: '0.5rem',
|
|
85
|
+
fontFamily: 'inherit', fontSize: '0.875rem', boxSizing: 'border-box'
|
|
86
|
+
});
|
|
87
|
+
const header = document.createElement('header');
|
|
88
|
+
Object.assign(header.style, {display: 'flex', alignItems: 'center', gap: '0.5rem', marginBlockEnd: '0.5rem'});
|
|
89
|
+
const heading = document.createElement('h2');
|
|
90
|
+
heading.id = 'tw-plus-browser-projects-title';
|
|
91
|
+
heading.textContent = purpose === 'open' ? message.openTitle : message.createTitle;
|
|
92
|
+
Object.assign(heading.style, {flex: '1', margin: '0', fontSize: '1rem'});
|
|
93
|
+
const close = document.createElement('button');
|
|
94
|
+
close.type = 'button';
|
|
95
|
+
close.dataset.browserProjectsClose = '';
|
|
96
|
+
close.title = message.close;
|
|
97
|
+
close.setAttribute('aria-label', message.close);
|
|
98
|
+
Object.assign(close.style, {display: 'grid', placeItems: 'center', width: '2rem', height: '2rem', padding: '0',
|
|
99
|
+
background: 'transparent', color: 'inherit', border: '0', borderRadius: '0.25rem', cursor: 'pointer'});
|
|
100
|
+
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
|
|
101
|
+
svg.setAttribute('viewBox', '0 0 16 16');
|
|
102
|
+
svg.setAttribute('width', '16');
|
|
103
|
+
svg.setAttribute('height', '16');
|
|
104
|
+
svg.setAttribute('aria-hidden', 'true');
|
|
105
|
+
const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
|
|
106
|
+
path.setAttribute('d', closeIcon);
|
|
107
|
+
path.setAttribute('stroke', 'currentColor');
|
|
108
|
+
path.setAttribute('stroke-width', '1.5');
|
|
109
|
+
path.setAttribute('stroke-linecap', 'round');
|
|
110
|
+
svg.append(path);
|
|
111
|
+
close.append(svg);
|
|
112
|
+
header.append(heading, close);
|
|
113
|
+
const note = document.createElement('p');
|
|
114
|
+
note.textContent = message.note;
|
|
115
|
+
Object.assign(note.style, {margin: '0 0 0.25rem'});
|
|
116
|
+
const usage = document.createElement('p');
|
|
117
|
+
usage.dataset.browserProjectsUsage = '';
|
|
118
|
+
Object.assign(usage.style, {margin: '0 0 0.75rem', color: 'GrayText'});
|
|
119
|
+
const status = document.createElement('p');
|
|
120
|
+
status.setAttribute('role', 'alert');
|
|
121
|
+
status.hidden = true;
|
|
122
|
+
Object.assign(status.style, {margin: '0 0 0.75rem'});
|
|
123
|
+
dialog.append(header, note, usage, status);
|
|
124
|
+
|
|
125
|
+
let settled = false;
|
|
126
|
+
let resolveChoice: (choice: BrowserProjectChoice | null) => void;
|
|
127
|
+
const result = new Promise<BrowserProjectChoice | null>(resolve => {resolveChoice = resolve;});
|
|
128
|
+
const finish = (choice: BrowserProjectChoice | null) => {
|
|
129
|
+
if (settled) return;
|
|
130
|
+
settled = true;
|
|
131
|
+
if (dialog.open) dialog.close();
|
|
132
|
+
dialog.remove();
|
|
133
|
+
resolveChoice(choice);
|
|
134
|
+
};
|
|
135
|
+
const fail = (error: unknown) => {
|
|
136
|
+
status.hidden = false;
|
|
137
|
+
status.textContent = message.failed + (error instanceof Error && error.message ? ` (${error.message})` : '');
|
|
138
|
+
};
|
|
139
|
+
let busy = false;
|
|
140
|
+
const run = async (action: () => Promise<void>) => {
|
|
141
|
+
if (busy) return;
|
|
142
|
+
busy = true;
|
|
143
|
+
dialog.setAttribute('aria-busy', 'true');
|
|
144
|
+
try {
|
|
145
|
+
await action();
|
|
146
|
+
} catch (error) {
|
|
147
|
+
fail(error);
|
|
148
|
+
} finally {
|
|
149
|
+
busy = false;
|
|
150
|
+
dialog.removeAttribute('aria-busy');
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
close.addEventListener('click', () => finish(null));
|
|
154
|
+
dialog.addEventListener('cancel', event => {
|
|
155
|
+
event.preventDefault();
|
|
156
|
+
finish(null);
|
|
157
|
+
});
|
|
158
|
+
dialog.addEventListener('close', () => finish(null));
|
|
159
|
+
|
|
160
|
+
if (purpose === 'create') {
|
|
161
|
+
const form = document.createElement('form');
|
|
162
|
+
Object.assign(form.style, {display: 'flex', gap: '0.5rem', alignItems: 'end'});
|
|
163
|
+
const label = document.createElement('label');
|
|
164
|
+
Object.assign(label.style, {display: 'grid', gap: '0.25rem', flex: '1'});
|
|
165
|
+
const caption = document.createElement('span');
|
|
166
|
+
caption.textContent = message.name;
|
|
167
|
+
const input = document.createElement('input');
|
|
168
|
+
input.name = 'title';
|
|
169
|
+
input.required = true;
|
|
170
|
+
input.maxLength = 200;
|
|
171
|
+
input.value = title;
|
|
172
|
+
input.autocomplete = 'off';
|
|
173
|
+
label.append(caption, input);
|
|
174
|
+
const submit = document.createElement('button');
|
|
175
|
+
submit.type = 'submit';
|
|
176
|
+
submit.textContent = message.create;
|
|
177
|
+
form.append(label, submit);
|
|
178
|
+
form.addEventListener('submit', event => {
|
|
179
|
+
event.preventDefault();
|
|
180
|
+
const name = input.value.trim();
|
|
181
|
+
if (!name) return;
|
|
182
|
+
void run(async () => {
|
|
183
|
+
const created = await projects.create(name);
|
|
184
|
+
finish({project: {id: created.id, title: created.title, projectPath: created.projectPath,
|
|
185
|
+
createdAt: created.createdAt, updatedAt: created.updatedAt}, directory: created.directory});
|
|
186
|
+
});
|
|
187
|
+
});
|
|
188
|
+
dialog.append(form);
|
|
189
|
+
} else {
|
|
190
|
+
const list = document.createElement('ul');
|
|
191
|
+
list.dataset.browserProjectsList = '';
|
|
192
|
+
Object.assign(list.style, {listStyle: 'none', margin: '0', padding: '0', display: 'grid', gap: '0.5rem',
|
|
193
|
+
overflowY: 'auto', maxHeight: '50vh'});
|
|
194
|
+
const dateFormat = new Intl.DateTimeFormat(locale, {dateStyle: 'medium', timeStyle: 'short'});
|
|
195
|
+
const render = async () => {
|
|
196
|
+
const stored = await projects.list();
|
|
197
|
+
list.replaceChildren();
|
|
198
|
+
if (!stored.length) {
|
|
199
|
+
const empty = document.createElement('li');
|
|
200
|
+
empty.textContent = message.empty;
|
|
201
|
+
empty.style.color = 'GrayText';
|
|
202
|
+
list.append(empty);
|
|
203
|
+
}
|
|
204
|
+
for (const project of stored) {
|
|
205
|
+
const item = document.createElement('li');
|
|
206
|
+
item.dataset.browserProject = project.id;
|
|
207
|
+
Object.assign(item.style, {display: 'flex', alignItems: 'center', gap: '0.5rem', flexWrap: 'wrap',
|
|
208
|
+
padding: '0.5rem', border: '1px solid GrayText', borderRadius: '0.375rem'});
|
|
209
|
+
const text = document.createElement('div');
|
|
210
|
+
Object.assign(text.style, {flex: '1', minWidth: '10rem'});
|
|
211
|
+
const name = document.createElement('strong');
|
|
212
|
+
name.textContent = project.title;
|
|
213
|
+
const updated = document.createElement('div');
|
|
214
|
+
updated.textContent = message.updated(dateFormat.format(project.updatedAt));
|
|
215
|
+
updated.style.color = 'GrayText';
|
|
216
|
+
text.append(name, updated);
|
|
217
|
+
const button = (label: string, action: () => Promise<void>) => {
|
|
218
|
+
const element = document.createElement('button');
|
|
219
|
+
element.type = 'button';
|
|
220
|
+
element.textContent = label;
|
|
221
|
+
element.addEventListener('click', () => void run(action));
|
|
222
|
+
return element;
|
|
223
|
+
};
|
|
224
|
+
item.append(text,
|
|
225
|
+
button(message.open, async () => {
|
|
226
|
+
const directory = await projects.directory(project.id);
|
|
227
|
+
if (!directory) return render();
|
|
228
|
+
finish({project, directory});
|
|
229
|
+
}),
|
|
230
|
+
button(message.exportZip, () => exportBrowserProject(document, projects, project)),
|
|
231
|
+
button(message.remove, async () => {
|
|
232
|
+
if (!view.confirm(message.confirmRemove(project.title))) return;
|
|
233
|
+
await projects.remove(project.id);
|
|
234
|
+
await render();
|
|
235
|
+
await showUsage();
|
|
236
|
+
}));
|
|
237
|
+
list.append(item);
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
dialog.append(list);
|
|
241
|
+
void run(render);
|
|
242
|
+
}
|
|
243
|
+
const showUsage = async () => {
|
|
244
|
+
const state = await projects.storage().catch(() => null);
|
|
245
|
+
if (!state) return;
|
|
246
|
+
const parts = [];
|
|
247
|
+
if (state.usage !== undefined && state.quota) parts.push(message.usage(formatBytes(state.usage, locale), formatBytes(state.quota, locale)));
|
|
248
|
+
if (state.persisted) parts.push(message.persisted);
|
|
249
|
+
usage.textContent = parts.join(' ');
|
|
250
|
+
usage.hidden = !parts.length;
|
|
251
|
+
};
|
|
252
|
+
void showUsage();
|
|
253
|
+
document.body.append(dialog);
|
|
254
|
+
dialog.showModal();
|
|
255
|
+
(dialog.querySelector('input') ?? dialog.querySelector('[data-browser-projects-list] button') ?? close as HTMLElement)?.focus();
|
|
256
|
+
return result;
|
|
257
|
+
}
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Project folders kept in the browser's origin private file system (OPFS). They let browsers without the folder
|
|
3
|
+
* picker, such as Safari and Firefox, open and save project folders. The folders live only in this browser, so the
|
|
4
|
+
* browser may delete them; a user keeps a copy by exporting a ZIP or pushing to GitHub.
|
|
5
|
+
*
|
|
6
|
+
* Layout under the OPFS root:
|
|
7
|
+
* turbowarp-plus/projects/<id>/ the folder (a project folder, or a repository with the project inside)
|
|
8
|
+
* turbowarp-plus/project-info/<id>.json its title and times, kept outside the folder so Git never sees them
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
export interface BrowserProject {
|
|
12
|
+
id: string;
|
|
13
|
+
title: string;
|
|
14
|
+
/** The project folder inside the stored folder, such as `project` in a repository, or `''` for the folder itself. */
|
|
15
|
+
projectPath: string;
|
|
16
|
+
createdAt: number;
|
|
17
|
+
updatedAt: number;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface BrowserStorageState {
|
|
21
|
+
usage?: number;
|
|
22
|
+
quota?: number;
|
|
23
|
+
persisted: boolean;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface BrowserProjects {
|
|
27
|
+
list(): Promise<BrowserProject[]>;
|
|
28
|
+
create(title: string, options?: {projectPath?: string}): Promise<BrowserProject & {root: FileSystemDirectoryHandle;
|
|
29
|
+
directory: FileSystemDirectoryHandle}>;
|
|
30
|
+
/** The stored folder, or `null` when it was deleted. */
|
|
31
|
+
root(id: string): Promise<FileSystemDirectoryHandle | null>;
|
|
32
|
+
/** The project folder of the entry, `projectPath` inside its stored folder. */
|
|
33
|
+
directory(id: string): Promise<FileSystemDirectoryHandle | null>;
|
|
34
|
+
/** The entry that holds `handle`, or `null` when it is not in the browser's storage. */
|
|
35
|
+
find(handle: FileSystemHandle): Promise<BrowserProject | null>;
|
|
36
|
+
touch(id: string): Promise<void>;
|
|
37
|
+
rename(id: string, title: string): Promise<void>;
|
|
38
|
+
remove(id: string): Promise<void>;
|
|
39
|
+
storage(): Promise<BrowserStorageState>;
|
|
40
|
+
/** Asks the browser to keep the storage. The browser may still say no. */
|
|
41
|
+
persist(): Promise<boolean>;
|
|
42
|
+
/** Runs `run` while no other tab of this origin works on the same entry. */
|
|
43
|
+
exclusive<T>(id: string, run: () => Promise<T>): Promise<T>;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
type StorageWindow = Window & {
|
|
47
|
+
navigator: Navigator & {storage?: StorageManager & {getDirectory?(): Promise<FileSystemDirectoryHandle>}};
|
|
48
|
+
};
|
|
49
|
+
type IterableDirectory = FileSystemDirectoryHandle & {values(): AsyncIterable<FileSystemHandle>};
|
|
50
|
+
|
|
51
|
+
const base = 'turbowarp-plus';
|
|
52
|
+
const projectsDirectory = 'projects';
|
|
53
|
+
const infoDirectory = 'project-info';
|
|
54
|
+
const idPattern = /^[a-z0-9-]{1,64}$/u;
|
|
55
|
+
const pathPattern = /^(?:[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*)?$/u;
|
|
56
|
+
const maxTitle = 200;
|
|
57
|
+
const infoMaxBytes = 16 * 1024;
|
|
58
|
+
|
|
59
|
+
const missing = (error: unknown) => error instanceof DOMException && ['NotFoundError', 'TypeMismatchError'].includes(error.name);
|
|
60
|
+
|
|
61
|
+
function cleanTitle(title: string) {
|
|
62
|
+
const value = String(title).replace(/[\u0000-\u001f\u007f]/gu, ' ').trim().slice(0, maxTitle);
|
|
63
|
+
return value || 'Untitled';
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function parseInfo(id: string, text: string): BrowserProject | null {
|
|
67
|
+
try {
|
|
68
|
+
const value = JSON.parse(text);
|
|
69
|
+
if (!value || typeof value !== 'object' || typeof value.title !== 'string' ||
|
|
70
|
+
!Number.isFinite(value.createdAt) || !Number.isFinite(value.updatedAt)) return null;
|
|
71
|
+
const projectPath = typeof value.projectPath === 'string' && pathPattern.test(value.projectPath) &&
|
|
72
|
+
!value.projectPath.split('/').some((part: string) => part === '.' || part === '..') ? value.projectPath : '';
|
|
73
|
+
return {id, title: cleanTitle(value.title), projectPath, createdAt: value.createdAt, updatedAt: value.updatedAt};
|
|
74
|
+
} catch {
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function writeText(directory: FileSystemDirectoryHandle, name: string, text: string) {
|
|
80
|
+
const writable = await (await directory.getFileHandle(name, {create: true})).createWritable();
|
|
81
|
+
try {
|
|
82
|
+
await writable.write(new TextEncoder().encode(text));
|
|
83
|
+
await writable.close();
|
|
84
|
+
} catch (error) {
|
|
85
|
+
await writable.abort().catch(() => {});
|
|
86
|
+
throw error;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function resolvePath(root: FileSystemDirectoryHandle, path: string) {
|
|
91
|
+
let directory = root;
|
|
92
|
+
for (const part of path ? path.split('/') : []) directory = await directory.getDirectoryHandle(part);
|
|
93
|
+
return directory;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** The browser's project folders, or `null` when the browser has no origin private file system. */
|
|
97
|
+
export function openBrowserProjects(view: Window): BrowserProjects | null {
|
|
98
|
+
const navigator = (view as StorageWindow).navigator;
|
|
99
|
+
const storage = navigator?.storage;
|
|
100
|
+
if (typeof storage?.getDirectory !== 'function' || typeof view.crypto?.randomUUID !== 'function') return null;
|
|
101
|
+
const locks = navigator.locks;
|
|
102
|
+
let opened: Promise<{projects: FileSystemDirectoryHandle; info: FileSystemDirectoryHandle}> | undefined;
|
|
103
|
+
const folders = () => opened ??= (async () => {
|
|
104
|
+
const top = await (await storage.getDirectory!()).getDirectoryHandle(base, {create: true});
|
|
105
|
+
return {
|
|
106
|
+
projects: await top.getDirectoryHandle(projectsDirectory, {create: true}),
|
|
107
|
+
info: await top.getDirectoryHandle(infoDirectory, {create: true})
|
|
108
|
+
};
|
|
109
|
+
})().catch(error => {opened = undefined; throw error;});
|
|
110
|
+
const checkId = (id: string) => {
|
|
111
|
+
if (!idPattern.test(id)) throw new DOMException('Unknown browser project', 'NotFoundError');
|
|
112
|
+
};
|
|
113
|
+
const readInfo = async (id: string) => {
|
|
114
|
+
checkId(id);
|
|
115
|
+
try {
|
|
116
|
+
const file = await (await (await folders()).info.getFileHandle(`${id}.json`)).getFile();
|
|
117
|
+
return file.size > infoMaxBytes ? null : parseInfo(id, await file.text());
|
|
118
|
+
} catch (error) {
|
|
119
|
+
if (missing(error)) return null;
|
|
120
|
+
throw error;
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
const writeInfo = async (project: BrowserProject) => {
|
|
124
|
+
const {id, ...info} = project;
|
|
125
|
+
await writeText((await folders()).info, `${id}.json`, `${JSON.stringify(info, null, 2)}\n`);
|
|
126
|
+
};
|
|
127
|
+
const root = async (id: string) => {
|
|
128
|
+
checkId(id);
|
|
129
|
+
try {
|
|
130
|
+
return await (await folders()).projects.getDirectoryHandle(id);
|
|
131
|
+
} catch (error) {
|
|
132
|
+
if (missing(error)) return null;
|
|
133
|
+
throw error;
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
const exclusive = <T>(id: string, run: () => Promise<T>): Promise<T> => {
|
|
137
|
+
checkId(id);
|
|
138
|
+
return locks ? locks.request(`turbowarp-plus-browser-project:${id}`, run) as Promise<T> : run();
|
|
139
|
+
};
|
|
140
|
+
const projects: BrowserProjects = {
|
|
141
|
+
async list() {
|
|
142
|
+
const {info} = await folders();
|
|
143
|
+
const found: BrowserProject[] = [];
|
|
144
|
+
for await (const entry of (info as IterableDirectory).values()) {
|
|
145
|
+
const id = entry.kind === 'file' && entry.name.endsWith('.json') ? entry.name.slice(0, -5) : '';
|
|
146
|
+
if (!idPattern.test(id)) continue;
|
|
147
|
+
const project = await readInfo(id).catch(() => null);
|
|
148
|
+
if (project && await root(id).catch(() => null)) found.push(project);
|
|
149
|
+
}
|
|
150
|
+
return found.sort((a, b) => b.updatedAt - a.updatedAt || a.title.localeCompare(b.title));
|
|
151
|
+
},
|
|
152
|
+
async create(title, {projectPath = ''} = {}) {
|
|
153
|
+
if (!pathPattern.test(projectPath) || projectPath.split('/').some(part => part === '.' || part === '..')) {
|
|
154
|
+
throw new TypeError('Invalid project path');
|
|
155
|
+
}
|
|
156
|
+
const id = view.crypto.randomUUID().toLowerCase();
|
|
157
|
+
const now = Date.now();
|
|
158
|
+
const project = {id, title: cleanTitle(title), projectPath, createdAt: now, updatedAt: now};
|
|
159
|
+
const top = await (await folders()).projects.getDirectoryHandle(id, {create: true});
|
|
160
|
+
let directory = top;
|
|
161
|
+
for (const part of projectPath ? projectPath.split('/') : []) directory = await directory.getDirectoryHandle(part, {create: true});
|
|
162
|
+
await writeInfo(project);
|
|
163
|
+
// Best effort: the first folder is a good moment to ask, and the answer does not change what happens.
|
|
164
|
+
void projects.persist().catch(() => false);
|
|
165
|
+
return {...project, root: top, directory};
|
|
166
|
+
},
|
|
167
|
+
root,
|
|
168
|
+
async directory(id) {
|
|
169
|
+
const project = await readInfo(id);
|
|
170
|
+
const top = project && await root(id);
|
|
171
|
+
if (!top) return null;
|
|
172
|
+
try {
|
|
173
|
+
return await resolvePath(top, project.projectPath);
|
|
174
|
+
} catch (error) {
|
|
175
|
+
if (missing(error)) return null;
|
|
176
|
+
throw error;
|
|
177
|
+
}
|
|
178
|
+
},
|
|
179
|
+
async find(handle) {
|
|
180
|
+
const path = await (await folders()).projects.resolve(handle).catch(() => null);
|
|
181
|
+
return path?.length && idPattern.test(path[0]) ? readInfo(path[0]) : null;
|
|
182
|
+
},
|
|
183
|
+
async touch(id) {
|
|
184
|
+
const project = await readInfo(id);
|
|
185
|
+
if (project) await writeInfo({...project, updatedAt: Math.max(Date.now(), project.updatedAt)});
|
|
186
|
+
},
|
|
187
|
+
async rename(id, title) {
|
|
188
|
+
const project = await readInfo(id);
|
|
189
|
+
if (!project) throw new DOMException('Unknown browser project', 'NotFoundError');
|
|
190
|
+
await writeInfo({...project, title: cleanTitle(title), updatedAt: Math.max(Date.now(), project.updatedAt)});
|
|
191
|
+
},
|
|
192
|
+
remove: id => exclusive(id, async () => {
|
|
193
|
+
const {projects: stored, info} = await folders();
|
|
194
|
+
// The folder goes first, so an interrupted removal leaves no listed entry without its folder.
|
|
195
|
+
await stored.removeEntry(id, {recursive: true}).catch(error => {if (!missing(error)) throw error;});
|
|
196
|
+
await info.removeEntry(`${id}.json`).catch(error => {if (!missing(error)) throw error;});
|
|
197
|
+
}),
|
|
198
|
+
async storage() {
|
|
199
|
+
const [estimate, persisted] = await Promise.all([
|
|
200
|
+
storage.estimate?.().catch(() => undefined),
|
|
201
|
+
storage.persisted?.().catch(() => false) ?? false
|
|
202
|
+
]);
|
|
203
|
+
return {usage: estimate?.usage, quota: estimate?.quota, persisted: Boolean(persisted)};
|
|
204
|
+
},
|
|
205
|
+
async persist() {
|
|
206
|
+
return Boolean(await storage.persist?.());
|
|
207
|
+
},
|
|
208
|
+
exclusive
|
|
209
|
+
};
|
|
210
|
+
return projects;
|
|
211
|
+
}
|
package/src/explorer-files.ts
CHANGED
|
@@ -81,7 +81,39 @@ export async function copyExplorerFile(directory: FileSystemDirectoryHandle, fil
|
|
|
81
81
|
await writeNewFile(directory, file.name, file, guard);
|
|
82
82
|
}
|
|
83
83
|
|
|
84
|
-
|
|
84
|
+
/**
|
|
85
|
+
* Copy a folder dropped from outside, such as from Finder or File Explorer, into `parent` with everything in it.
|
|
86
|
+
* Entries the tree hides, such as `.git`, are left out. If any part fails, the partial copy is removed.
|
|
87
|
+
*/
|
|
88
|
+
export async function copyExplorerDirectory(parent: FileSystemDirectoryHandle, source: FileSystemDirectoryHandle,
|
|
89
|
+
guard: () => void) {
|
|
90
|
+
validateName(source.name);
|
|
91
|
+
await assertUnused(parent, source.name);
|
|
92
|
+
guard();
|
|
93
|
+
const destination = await parent.getDirectoryHandle(source.name, {create: true});
|
|
94
|
+
try {
|
|
95
|
+
await copyDirectoryContents(source as DirectoryEntries, destination, guard);
|
|
96
|
+
} catch (error) {
|
|
97
|
+
await removeIncompleteCopy(parent, source.name);
|
|
98
|
+
throw error;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async function copyDirectoryContents(source: DirectoryEntries, destination: FileSystemDirectoryHandle, guard: () => void) {
|
|
103
|
+
for await (const handle of source.values()) {
|
|
104
|
+
if (hiddenEntry(handle.name)) continue;
|
|
105
|
+
validateName(handle.name);
|
|
106
|
+
if (handle.kind === 'file') {
|
|
107
|
+
await writeNewFile(destination, handle.name, await (handle as FileSystemFileHandle).getFile(), guard);
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
guard();
|
|
111
|
+
const directory = await destination.getDirectoryHandle(handle.name, {create: true});
|
|
112
|
+
await copyDirectoryContents(handle as DirectoryEntries, directory, guard);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
type CopiedEntry ={verify(): Promise<void>; removeSource(): Promise<void>};
|
|
85
117
|
|
|
86
118
|
async function copyEntry(sourceParent: FileSystemDirectoryHandle, source: FileSystemHandle, parent: FileSystemDirectoryHandle,
|
|
87
119
|
name: string, guard: () => void): Promise<CopiedEntry> {
|
package/src/explorer.tsx
CHANGED
|
@@ -9,7 +9,7 @@ import {hiddenEntry, readExplorerState, subscribeExplorerState, writeExplorerSta
|
|
|
9
9
|
import type {ExplorerTreeState} from './explorer-state.js';
|
|
10
10
|
import type {ExplorerMutation, FollowedFolder} from './folder-registry.js';
|
|
11
11
|
import type {Json, Project} from './source.js';
|
|
12
|
-
import {canMoveExplorerEntry, copyExplorerFile, createExplorerDirectory, deleteExplorerEntry, ExplorerFileError,
|
|
12
|
+
import {canMoveExplorerEntry, copyExplorerDirectory, copyExplorerFile, createExplorerDirectory, deleteExplorerEntry, ExplorerFileError,
|
|
13
13
|
explorerNameAvailable, moveExplorerEntry, parentPath, renameExplorerEntry, resolveExplorerDirectory} from './explorer-files.js';
|
|
14
14
|
import {actionCss, actionMessages, ExplorerFileDialog, ExplorerMenu} from './explorer-menu.js';
|
|
15
15
|
import type {FileAction, MenuAnchor} from './explorer-menu.js';
|
|
@@ -630,24 +630,38 @@ function Explorer({directory, locale, descriptions, marks, fileStatuses, unsaved
|
|
|
630
630
|
const path = dropPath(event.target);
|
|
631
631
|
const items = Array.from(event.dataTransfer.items);
|
|
632
632
|
const problems: string[] = [];
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
633
|
+
// A folder's handle has to be asked for while the drop event runs; the items are emptied after it.
|
|
634
|
+
type Dropped = {name: string; file: File} | {name: string; folder: Promise<FileSystemHandle | null>};
|
|
635
|
+
const dropped: Dropped[] =
|
|
636
|
+
items.length ? items.flatMap((item): Dropped[] => {
|
|
637
|
+
if (item.kind !== 'file') return [];
|
|
638
|
+
const entry = item.webkitGetAsEntry?.();
|
|
639
|
+
if (entry?.isDirectory) {
|
|
640
|
+
const folder = (item as DataTransferItem & {
|
|
641
|
+
getAsFileSystemHandle?(): Promise<FileSystemHandle | null>;
|
|
642
|
+
}).getAsFileSystemHandle?.();
|
|
643
|
+
if (folder) return [{name: entry.name, folder}];
|
|
644
|
+
problems.push(`${entry.name} — ${actions.filesOnly}`);
|
|
645
|
+
return [];
|
|
646
|
+
}
|
|
647
|
+
const file = item.getAsFile();
|
|
648
|
+
return file ? [{name: file.name, file}] : [];
|
|
649
|
+
}) : Array.from(event.dataTransfer.files, file => ({name: file.name, file}));
|
|
643
650
|
void run(async () => {
|
|
644
651
|
if (!dropped.length) return problems.join('\n') || actions.filesOnly;
|
|
645
652
|
try {
|
|
646
653
|
await write(path, async (parent, guard) => {
|
|
647
|
-
for (const
|
|
654
|
+
for (const item of dropped) {
|
|
648
655
|
guard();
|
|
649
|
-
try {
|
|
650
|
-
|
|
656
|
+
try {
|
|
657
|
+
if ('file' in item) {
|
|
658
|
+
await copyExplorerFile(parent, item.file, guard);
|
|
659
|
+
continue;
|
|
660
|
+
}
|
|
661
|
+
const folder = await item.folder;
|
|
662
|
+
if (folder?.kind !== 'directory') throw new DOMException('Not a folder', 'NotFoundError');
|
|
663
|
+
await copyExplorerDirectory(parent, folder as FileSystemDirectoryHandle, guard);
|
|
664
|
+
} catch (error) {problems.push(`${actions.copyFailed} ${item.name} — ${errorText(error)}`);}
|
|
651
665
|
}
|
|
652
666
|
});
|
|
653
667
|
} finally {
|