@kubohiroya/turbowarp-plus-editor-project-folder 0.8.0 → 0.9.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/dist/THIRD_PARTY_NOTICES.md +716 -0
- package/dist/create-folder.d.ts +8 -0
- package/dist/explorer-files.d.ts +15 -0
- package/dist/explorer-menu.d.ts +49 -0
- package/dist/explorer.d.ts +33 -3
- package/dist/explorer.js +1882 -694
- package/dist/file-preview.d.ts +24 -0
- package/dist/folder-registry.d.ts +4 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +1019 -555
- package/dist/session.d.ts +6 -0
- package/dist/shared-JdaDvk2R.js +588 -0
- package/dist/shared-kI7qYraF.js +30130 -0
- package/dist/text-file-editor.d.ts +17 -0
- package/package.json +16 -1
- package/src/create-folder.ts +99 -0
- package/src/explorer-files.ts +167 -0
- package/src/explorer-menu.tsx +125 -0
- package/src/explorer.tsx +295 -21
- package/src/file-preview.ts +134 -0
- package/src/folder-registry.ts +5 -0
- package/src/index.ts +27 -2
- package/src/session.ts +77 -12
- package/src/source.ts +16 -8
- package/src/text-file-editor.ts +356 -0
- package/vite.config.ts +2 -0
- package/dist/shared-DlmcdO1_.js +0 -458
package/src/explorer.tsx
CHANGED
|
@@ -2,15 +2,31 @@ import * as React from 'react';
|
|
|
2
2
|
import {asyncDataLoaderFeature, hotkeysCoreFeature, selectionFeature} from '@headless-tree/core';
|
|
3
3
|
import type {ItemInstance} from '@headless-tree/core';
|
|
4
4
|
import {useTree} from '@headless-tree/react/react17';
|
|
5
|
-
import {isObject, manifestFile, projectFile} from './source.js';
|
|
5
|
+
import {FolderError, isObject, manifestFile, projectFile} from './source.js';
|
|
6
6
|
import {followProjectFolder} from './folder-registry.js';
|
|
7
|
-
import type {FollowedFolder} from './folder-registry.js';
|
|
7
|
+
import type {ExplorerMutation, FollowedFolder} from './folder-registry.js';
|
|
8
8
|
import type {Json, Project} from './source.js';
|
|
9
|
+
import {copyExplorerFile, deleteExplorerEntry, ExplorerFileError, parentPath, renameExplorerEntry,
|
|
10
|
+
resolveExplorerDirectory} from './explorer-files.js';
|
|
11
|
+
import {actionCss, actionMessages, ExplorerFileDialog, ExplorerMenu} from './explorer-menu.js';
|
|
12
|
+
import type {MenuAnchor} from './explorer-menu.js';
|
|
13
|
+
import {createFilePreview} from './file-preview.js';
|
|
14
|
+
import type {FilePreviewRequest, ReadFileBaseline} from './file-preview.js';
|
|
9
15
|
|
|
10
16
|
export type ExplorerMark = 'added' | 'modified' | 'deleted' | 'untracked';
|
|
17
|
+
export type ExplorerFileStatus = {
|
|
18
|
+
change?: ExplorerMark;
|
|
19
|
+
staged?: boolean;
|
|
20
|
+
revision?: 'committed' | 'pushed' | 'merged';
|
|
21
|
+
};
|
|
11
22
|
export type ExplorerEntry = {path: string; name: string; kind: 'file' | 'directory'};
|
|
23
|
+
export type ExplorerGit = {
|
|
24
|
+
change(kind: 'stage' | 'unstage', entry: ExplorerEntry, isCurrent: () => boolean): Promise<{done: boolean; error?: string}>;
|
|
25
|
+
refresh(): Promise<void>;
|
|
26
|
+
};
|
|
27
|
+
export type FollowExplorerGit = (directory: FileSystemDirectoryHandle, update: (git?: ExplorerGit) => void) => () => void;
|
|
12
28
|
export type ProjectFolderExplorerProps = {
|
|
13
|
-
/** The folder to show: a project folder or a repository root.
|
|
29
|
+
/** The folder to show: a project folder or a repository root. */
|
|
14
30
|
directory: FileSystemDirectoryHandle;
|
|
15
31
|
/** 'ja…' shows Japanese text; anything else shows English. */
|
|
16
32
|
locale?: string;
|
|
@@ -18,19 +34,30 @@ export type ProjectFolderExplorerProps = {
|
|
|
18
34
|
descriptions?: ReadonlyMap<string, string>;
|
|
19
35
|
/** Git status for an entry, by path relative to `directory`. */
|
|
20
36
|
marks?: ReadonlyMap<string, ExplorerMark>;
|
|
37
|
+
fileStatuses?: ReadonlyMap<string, ExplorerFileStatus>;
|
|
38
|
+
unsavedPaths?: ReadonlySet<string>;
|
|
39
|
+
/** Changes after the folder contents have been saved or reloaded. */
|
|
40
|
+
refreshKey?: number;
|
|
21
41
|
/** Called when a file is opened with Enter, Space or a click. */
|
|
22
42
|
onOpen?(entry: ExplorerEntry): void;
|
|
23
43
|
/** The tree's accessible name. Defaults to "Project folder". */
|
|
24
44
|
label?: string;
|
|
45
|
+
/** Runs an explorer write in the host's active folder session. Without this, the tree is read-only. */
|
|
46
|
+
mutate?(operation: ExplorerMutation): Promise<void>;
|
|
47
|
+
git?: ExplorerGit;
|
|
48
|
+
isCurrent?(): boolean;
|
|
25
49
|
};
|
|
26
50
|
|
|
27
51
|
const messages = {
|
|
28
52
|
en: {
|
|
29
53
|
label: 'Project folder', loading: 'Loading…', empty: 'This folder is empty.',
|
|
30
54
|
noFolder: 'Open a project folder to show its files here.', open: 'Open Project Folder…',
|
|
55
|
+
unavailable: 'File tabs are unavailable in this editor layout.',
|
|
31
56
|
failed: 'This folder could not be read.', denied: 'Permission to read this folder was not granted.',
|
|
32
57
|
separator: ', ',
|
|
33
58
|
marks: {added: 'Added', modified: 'Modified', deleted: 'Deleted', untracked: 'Untracked'},
|
|
59
|
+
unsaved: 'Unsaved changes', staged: 'Staged',
|
|
60
|
+
revisions: {committed: 'Committed', pushed: 'Pushed', merged: 'Pull request merged'},
|
|
34
61
|
project: 'Project data', manifest: 'Folder manifest', extensions: 'Embedded extensions',
|
|
35
62
|
assetsDirectory: 'Costume and sound files', extensionsDirectory: 'Extension files',
|
|
36
63
|
costume: (sprite: string, name: string) => `${sprite} · costume ${name}`,
|
|
@@ -41,9 +68,12 @@ const messages = {
|
|
|
41
68
|
ja: {
|
|
42
69
|
label: '作品フォルダ', loading: '読み込んでいます…', empty: 'このフォルダは空です。',
|
|
43
70
|
noFolder: 'プロジェクトフォルダを開くと、ここにファイルを表示します。', open: 'プロジェクトフォルダを開く…',
|
|
71
|
+
unavailable: 'このエディターのレイアウトではファイルをタブで開けません。',
|
|
44
72
|
failed: 'このフォルダを読み込めません。', denied: 'このフォルダを読む許可がありません。',
|
|
45
73
|
separator: '、',
|
|
46
74
|
marks: {added: '追加', modified: '変更', deleted: '削除', untracked: '未追跡'},
|
|
75
|
+
unsaved: '未保存の変更あり', staged: 'ステージ済み',
|
|
76
|
+
revisions: {committed: 'コミット済み', pushed: 'プッシュ済み', merged: 'PR マージ済み'},
|
|
47
77
|
project: '作品データ', manifest: '作品フォルダの目録', extensions: '埋め込み拡張の一覧',
|
|
48
78
|
assetsDirectory: 'コスチュームと音のファイル', extensionsDirectory: '拡張のファイル',
|
|
49
79
|
costume: (sprite: string, name: string) => `${sprite} のコスチューム ${name}`,
|
|
@@ -101,7 +131,7 @@ export function describeProjectFolder(project: Project, locale?: string, {manife
|
|
|
101
131
|
return descriptions;
|
|
102
132
|
}
|
|
103
133
|
|
|
104
|
-
type
|
|
134
|
+
type ExplorerNode = {name: string; path: string; kind: 'file' | 'directory' | 'error'; message?: string};
|
|
105
135
|
type Message = typeof messages.en;
|
|
106
136
|
const rootId = '/';
|
|
107
137
|
// '\0' cannot appear in a file name, so the error row never collides with a real entry.
|
|
@@ -125,7 +155,13 @@ padding-block:.15em;padding-inline-end:.4em;background:none;color:inherit;font:i
|
|
|
125
155
|
.${prefix}-icon img{width:20px;height:20px;object-fit:contain;border-radius:2px;
|
|
126
156
|
background:repeating-conic-gradient(rgba(128,128,128,.22) 0 25%,transparent 0 50%) 0 0/8px 8px}
|
|
127
157
|
.${prefix}-icon img[hidden]{display:none}
|
|
158
|
+
.${prefix}-filename{display:inline-flex;min-width:0}
|
|
128
159
|
.${prefix}-name{overflow:hidden;text-overflow:ellipsis}
|
|
160
|
+
.${prefix}-item[data-staged] .${prefix}-filename{font-weight:700}
|
|
161
|
+
.${prefix}-item[data-revision="committed"] .${prefix}-filename{color:#174b9d;color:light-dark(#174b9d,#91c1ff)}
|
|
162
|
+
.${prefix}-item[data-revision="pushed"] .${prefix}-filename{color:#67369a;color:light-dark(#67369a,#dfafff)}
|
|
163
|
+
.${prefix}-item[data-revision="merged"] .${prefix}-filename{color:#17603e;color:light-dark(#17603e,#85e3ad)}
|
|
164
|
+
.${prefix}-unsaved{flex:none}
|
|
129
165
|
.${prefix}-mark{flex:none;font-size:.85em;padding:0 .3em;border:1px solid currentColor;border-radius:3px;opacity:.85}
|
|
130
166
|
.${prefix}-description{overflow:hidden;text-overflow:ellipsis;opacity:.7;font-size:.9em}
|
|
131
167
|
.${prefix}-status{opacity:.7;font-style:italic;padding-block:.15em}
|
|
@@ -218,11 +254,25 @@ function Icon({kind, path, readFile}: {kind: IconKind; path: string; readFile?:
|
|
|
218
254
|
);
|
|
219
255
|
}
|
|
220
256
|
|
|
221
|
-
function Explorer({directory, locale, descriptions, marks,
|
|
257
|
+
function Explorer({directory, locale, descriptions, marks, fileStatuses, unsavedPaths, refreshKey,
|
|
258
|
+
onOpen, label, mutate, git, isCurrent}: ProjectFolderExplorerProps) {
|
|
222
259
|
const message = messagesFor(locale);
|
|
260
|
+
const actions = actionMessages(locale);
|
|
223
261
|
const [handles] = React.useState(() => new Map<string, FileSystemDirectoryHandle>([[rootId, directory]]));
|
|
224
262
|
const [files] = React.useState(() => new Map<string, FileSystemFileHandle>());
|
|
263
|
+
const [loadedFolders] = React.useState(() => new Set<string>());
|
|
225
264
|
const [rootLoaded, setRootLoaded] = React.useState(false);
|
|
265
|
+
const [drag, setDrag] = React.useState<string | null>(null);
|
|
266
|
+
const [menu, setMenu] = React.useState<{entry: ExplorerEntry; anchor: MenuAnchor}>();
|
|
267
|
+
const [dialog, setDialog] = React.useState<{entry: ExplorerEntry; anchor: MenuAnchor; rename: boolean}>();
|
|
268
|
+
const [feedback, setFeedback] = React.useState('');
|
|
269
|
+
const [working, setWorking] = React.useState(false);
|
|
270
|
+
const running = React.useRef(false);
|
|
271
|
+
const mounted = React.useRef(true);
|
|
272
|
+
React.useEffect(() => {
|
|
273
|
+
mounted.current = true;
|
|
274
|
+
return () => {mounted.current = false;};
|
|
275
|
+
}, []);
|
|
226
276
|
const collator = React.useMemo(() => new Intl.Collator(locale, {numeric: true, sensitivity: 'base'}), [locale]);
|
|
227
277
|
|
|
228
278
|
const directoryAt = async (id: string) => {
|
|
@@ -242,7 +292,7 @@ function Explorer({directory, locale, descriptions, marks, onOpen, label}: Proje
|
|
|
242
292
|
}
|
|
243
293
|
return handle.getFile();
|
|
244
294
|
};
|
|
245
|
-
const tree = useTree<
|
|
295
|
+
const tree = useTree<ExplorerNode>({
|
|
246
296
|
rootItemId: rootId,
|
|
247
297
|
initialState: {expandedItems: [], selectedItems: [], focusedItem: null},
|
|
248
298
|
getItemName: item => item.getItemData()?.name ?? '',
|
|
@@ -271,14 +321,15 @@ function Explorer({directory, locale, descriptions, marks, onOpen, label}: Proje
|
|
|
271
321
|
try {
|
|
272
322
|
const handle = await directoryAt(id);
|
|
273
323
|
const base = id === rootId ? '' : `${id}/`;
|
|
274
|
-
const nodes:
|
|
324
|
+
const nodes: ExplorerNode[] = [];
|
|
275
325
|
for await (const entry of (handle as IterableDirectory).values()) {
|
|
276
|
-
if (entry.
|
|
326
|
+
if (entry.name.toLowerCase() === '.git') continue;
|
|
277
327
|
const path = base + entry.name;
|
|
278
328
|
if (entry.kind === 'directory') handles.set(path, entry as FileSystemDirectoryHandle);
|
|
279
329
|
else files.set(path, entry as FileSystemFileHandle);
|
|
280
330
|
nodes.push({name: entry.name, path, kind: entry.kind});
|
|
281
331
|
}
|
|
332
|
+
loadedFolders.add(id);
|
|
282
333
|
nodes.sort((a, b) => (a.kind === 'directory' ? 0 : 1) - (b.kind === 'directory' ? 0 : 1) ||
|
|
283
334
|
collator.compare(a.name, b.name) || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
284
335
|
return nodes.map(data => ({id: data.path, data}));
|
|
@@ -295,25 +346,167 @@ function Explorer({directory, locale, descriptions, marks, onOpen, label}: Proje
|
|
|
295
346
|
tree.setMounted(true);
|
|
296
347
|
return () => tree.setMounted(false);
|
|
297
348
|
}, [tree]);
|
|
349
|
+
const lastRefresh = React.useRef(refreshKey);
|
|
350
|
+
React.useEffect(() => {
|
|
351
|
+
if (lastRefresh.current === refreshKey) return;
|
|
352
|
+
lastRefresh.current = refreshKey;
|
|
353
|
+
void Promise.all([...loadedFolders].map(id => tree.getItemInstance(id).invalidateChildrenIds(true)));
|
|
354
|
+
}, [tree, loadedFolders, refreshKey]);
|
|
298
355
|
|
|
299
|
-
const
|
|
356
|
+
const errorText = (error: unknown) => {
|
|
357
|
+
if (error instanceof ExplorerFileError) return actions[error.code];
|
|
358
|
+
if (error instanceof DOMException && ['NotAllowedError', 'SecurityError'].includes(error.name)) return actions.denied;
|
|
359
|
+
if (error instanceof FolderError && error.code === 'conflict') return actions.conflict;
|
|
360
|
+
return actions.failed;
|
|
361
|
+
};
|
|
362
|
+
const run = async (operation: () => Promise<string | void>) => {
|
|
363
|
+
if (running.current) return;
|
|
364
|
+
running.current = true;
|
|
365
|
+
setWorking(true);
|
|
366
|
+
setFeedback('');
|
|
367
|
+
try {
|
|
368
|
+
const result = await operation();
|
|
369
|
+
if (mounted.current) setFeedback(result ?? '');
|
|
370
|
+
} catch (error) {
|
|
371
|
+
if (mounted.current) setFeedback(errorText(error));
|
|
372
|
+
} finally {
|
|
373
|
+
running.current = false;
|
|
374
|
+
if (mounted.current) setWorking(false);
|
|
375
|
+
}
|
|
376
|
+
};
|
|
377
|
+
const write = (path: string, operation: (parent: FileSystemDirectoryHandle, guard: () => void) => Promise<void>) =>
|
|
378
|
+
mutate!(async guard => {
|
|
379
|
+
const permission = (directory as FileSystemDirectoryHandle & {
|
|
380
|
+
requestPermission?(options: {mode: 'readwrite'}): Promise<PermissionState>;
|
|
381
|
+
}).requestPermission;
|
|
382
|
+
if (permission && await permission.call(directory, {mode: 'readwrite'}) !== 'granted') {
|
|
383
|
+
throw new DOMException('Write permission denied', 'NotAllowedError');
|
|
384
|
+
}
|
|
385
|
+
guard();
|
|
386
|
+
const parent = await resolveExplorerDirectory(directory, path);
|
|
387
|
+
guard();
|
|
388
|
+
await operation(parent, guard);
|
|
389
|
+
});
|
|
390
|
+
const reread = async (path: string, expand = false) => {
|
|
391
|
+
if (!mounted.current) return;
|
|
392
|
+
const parent = path ? tree.getItemInstance(path) : tree.getRootItem();
|
|
393
|
+
if (expand && path && !parent.isExpanded()) parent.expand();
|
|
394
|
+
await parent.invalidateChildrenIds(true);
|
|
395
|
+
};
|
|
396
|
+
const forget = (path: string) => {
|
|
397
|
+
const cache = tree.getDataRef() as React.MutableRefObject<{childrenIds: Record<string, string[]>}>;
|
|
398
|
+
for (const id of handles.keys()) {
|
|
399
|
+
if (id !== path && !id.startsWith(`${path}/`)) continue;
|
|
400
|
+
delete cache.current.childrenIds[id];
|
|
401
|
+
loadedFolders.delete(id);
|
|
402
|
+
handles.delete(id);
|
|
403
|
+
}
|
|
404
|
+
for (const id of files.keys()) if (id === path || id.startsWith(`${path}/`)) files.delete(id);
|
|
405
|
+
};
|
|
406
|
+
const dropPath = (target: EventTarget) =>
|
|
407
|
+
(target as Element).closest('[data-drop-directory]')?.getAttribute('data-drop-directory') ?? '';
|
|
408
|
+
const acceptsFiles = (event: React.DragEvent) => Boolean(mutate && event.dataTransfer.types.includes('Files'));
|
|
409
|
+
const drop = (event: React.DragEvent<HTMLDivElement>) => {
|
|
410
|
+
if (!acceptsFiles(event)) return;
|
|
411
|
+
event.preventDefault();
|
|
412
|
+
event.stopPropagation();
|
|
413
|
+
setDrag(null);
|
|
414
|
+
const path = dropPath(event.target);
|
|
415
|
+
const items = Array.from(event.dataTransfer.items);
|
|
416
|
+
const problems: string[] = [];
|
|
417
|
+
const dropped = items.length ? items.flatMap(item => {
|
|
418
|
+
if (item.kind !== 'file') return [];
|
|
419
|
+
const entry = item.webkitGetAsEntry?.();
|
|
420
|
+
if (entry?.isDirectory) {
|
|
421
|
+
problems.push(`${entry.name} — ${actions.filesOnly}`);
|
|
422
|
+
return [];
|
|
423
|
+
}
|
|
424
|
+
const file = item.getAsFile();
|
|
425
|
+
return file ? [file] : [];
|
|
426
|
+
}) : Array.from(event.dataTransfer.files);
|
|
427
|
+
void run(async () => {
|
|
428
|
+
if (!dropped.length) return problems.join('\n') || actions.filesOnly;
|
|
429
|
+
try {
|
|
430
|
+
await write(path, async (parent, guard) => {
|
|
431
|
+
for (const file of dropped) {
|
|
432
|
+
guard();
|
|
433
|
+
try {await copyExplorerFile(parent, file, guard);}
|
|
434
|
+
catch (error) {problems.push(`${actions.copyFailed} ${file.name} — ${errorText(error)}`);}
|
|
435
|
+
}
|
|
436
|
+
});
|
|
437
|
+
} finally {
|
|
438
|
+
await reread(path, true);
|
|
439
|
+
await git?.refresh();
|
|
440
|
+
}
|
|
441
|
+
return problems.join('\n');
|
|
442
|
+
});
|
|
443
|
+
};
|
|
444
|
+
const closeMenu = (restoreFocus: boolean) => {
|
|
445
|
+
setMenu(undefined);
|
|
446
|
+
if (restoreFocus && menu?.anchor.row.isConnected) menu.anchor.row.focus({preventScroll: true});
|
|
447
|
+
};
|
|
448
|
+
const showMenu = (event: React.MouseEvent<HTMLButtonElement> | React.KeyboardEvent<HTMLButtonElement>, entry: ExplorerEntry) => {
|
|
449
|
+
if (running.current || (!mutate && !git)) return;
|
|
450
|
+
event.preventDefault();
|
|
451
|
+
event.stopPropagation();
|
|
452
|
+
const row = event.currentTarget;
|
|
453
|
+
const rect = row.getBoundingClientRect();
|
|
454
|
+
const pointer = 'clientX' in event && (event.clientX || event.clientY);
|
|
455
|
+
setMenu({entry, anchor: {row, x: pointer ? event.clientX : rect.left, y: pointer ? event.clientY : rect.bottom}});
|
|
456
|
+
};
|
|
457
|
+
const submitFileAction = (name: string) => {
|
|
458
|
+
if (!dialog) return;
|
|
459
|
+
const {entry, rename} = dialog;
|
|
460
|
+
setDialog(undefined);
|
|
461
|
+
if (rename && entry.name === name) return;
|
|
462
|
+
void run(async () => {
|
|
463
|
+
const parent = parentPath(entry.path);
|
|
464
|
+
try {
|
|
465
|
+
await write(parent, (handle, guard) => rename ? renameExplorerEntry(handle, entry, name, guard) :
|
|
466
|
+
deleteExplorerEntry(handle, entry, guard));
|
|
467
|
+
} finally {
|
|
468
|
+
if (mounted.current) forget(entry.path);
|
|
469
|
+
await reread(parent);
|
|
470
|
+
await git?.refresh();
|
|
471
|
+
}
|
|
472
|
+
});
|
|
473
|
+
};
|
|
474
|
+
const renderItem = (item: ItemInstance<ExplorerNode>) => {
|
|
300
475
|
const data = item.getItemData();
|
|
476
|
+
const entry: ExplorerEntry | undefined = data?.path && data.kind !== 'error' ?
|
|
477
|
+
{path: data.path, name: data.name, kind: data.kind} : undefined;
|
|
478
|
+
const itemProps = item.getProps();
|
|
301
479
|
const level = item.getItemMeta().level;
|
|
302
480
|
const folder = item.isFolder();
|
|
303
481
|
const expanded = folder && item.isExpanded();
|
|
304
|
-
const
|
|
482
|
+
const status = data?.kind === 'file' ? fileStatuses?.get(data.path) : undefined;
|
|
483
|
+
const unsaved = data?.kind === 'file' && unsavedPaths?.has(data.path);
|
|
484
|
+
const mark = status?.change ?? (data && data.kind !== 'error' ? marks?.get(data.path) : undefined);
|
|
305
485
|
const markLabel = mark ? message.marks[mark] : '';
|
|
306
486
|
const description = data && data.kind !== 'error' ? descriptions?.get(data.path) : undefined;
|
|
307
487
|
const icon = !data || data.kind === 'error' ? undefined :
|
|
308
488
|
folder ? (expanded ? 'folder-open' : 'folder') : iconFor(data.name);
|
|
309
|
-
const accessibleName = [item.getItemName(),
|
|
489
|
+
const accessibleName = [item.getItemName(), unsaved && message.unsaved, status?.staged && message.staged,
|
|
490
|
+
status?.revision && message.revisions[status.revision], markLabel, description].filter(Boolean).join(message.separator);
|
|
310
491
|
const rows = [
|
|
311
|
-
<button {...
|
|
492
|
+
<button {...itemProps} key={item.getId()} type="button" aria-label={accessibleName}
|
|
312
493
|
className={`${prefix}-item${data?.kind === 'error' ? ` ${prefix}-error` : ''}`} style={indent(level)}
|
|
313
|
-
data-path={data?.path}
|
|
494
|
+
data-path={data?.path} data-staged={status?.staged ? '' : undefined} data-revision={status?.revision}
|
|
495
|
+
title={unsaved || status?.staged || status?.revision ? accessibleName : undefined}
|
|
496
|
+
data-drop-directory={entry?.kind === 'directory' ? entry.path : entry ? parentPath(entry.path) : undefined}
|
|
497
|
+
data-drop-active={entry?.kind === 'directory' && drag === entry.path ? '' : undefined}
|
|
498
|
+
aria-haspopup={entry && (mutate || git) ? 'menu' : undefined}
|
|
499
|
+
onContextMenu={entry ? event => showMenu(event, entry) : undefined}
|
|
500
|
+
onKeyDown={entry ? event => {
|
|
501
|
+
if ((mutate || git) && (event.key === 'ContextMenu' || (event.shiftKey && event.key === 'F10'))) showMenu(event, entry);
|
|
502
|
+
else itemProps.onKeyDown?.(event);
|
|
503
|
+
} : itemProps.onKeyDown}>
|
|
314
504
|
<span className={`${prefix}-caret`} aria-hidden="true">{folder ? (expanded ? '▾' : '▸') : ''}</span>
|
|
315
505
|
{icon ? <Icon kind={icon} path={data!.path} readFile={icon === 'image' ? readFile : undefined} /> : null}
|
|
316
|
-
<span className={`${prefix}-
|
|
506
|
+
<span className={`${prefix}-filename`}>
|
|
507
|
+
<span className={`${prefix}-name`}>{item.getItemName()}</span>
|
|
508
|
+
{unsaved ? <span className={`${prefix}-unsaved`} aria-hidden="true">*</span> : null}
|
|
509
|
+
</span>
|
|
317
510
|
{markLabel ? <span className={`${prefix}-mark`} aria-hidden="true">{markLabel}</span> : null}
|
|
318
511
|
{description ? <span className={`${prefix}-description`} aria-hidden="true">{description}</span> : null}
|
|
319
512
|
</button>
|
|
@@ -326,14 +519,43 @@ function Explorer({directory, locale, descriptions, marks, onOpen, label}: Proje
|
|
|
326
519
|
};
|
|
327
520
|
const items = tree.getItems();
|
|
328
521
|
return (
|
|
329
|
-
<div className={prefix}
|
|
330
|
-
|
|
522
|
+
<div className={`${prefix}${mutate ? ` ${prefix}-drop` : ''}`}
|
|
523
|
+
data-drop-active={drag === '' ? '' : undefined} onDrop={drop}
|
|
524
|
+
onDragOver={event => {
|
|
525
|
+
if (!acceptsFiles(event)) return;
|
|
526
|
+
event.preventDefault();
|
|
527
|
+
event.stopPropagation();
|
|
528
|
+
event.dataTransfer.dropEffect = running.current ? 'none' : 'copy';
|
|
529
|
+
if (!running.current) setDrag(dropPath(event.target));
|
|
530
|
+
}}
|
|
531
|
+
onDragLeave={event => {
|
|
532
|
+
if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setDrag(null);
|
|
533
|
+
}}>
|
|
534
|
+
<style>{css + actionCss}</style>
|
|
331
535
|
<div {...tree.getContainerProps(label ?? message.label)}>
|
|
332
536
|
{items.map(renderItem)}
|
|
333
537
|
</div>
|
|
334
538
|
{items.length ? null : (
|
|
335
539
|
<div className={`${prefix}-status`} role="status">{rootLoaded ? message.empty : message.loading}</div>
|
|
336
540
|
)}
|
|
541
|
+
{working || feedback ? <div className={`${prefix}-feedback`} role={feedback ? 'alert' : 'status'}>
|
|
542
|
+
{feedback || actions.working}
|
|
543
|
+
</div> : null}
|
|
544
|
+
{menu ? <ExplorerMenu anchor={menu.anchor} label={actions.actions} close={closeMenu} actions={[
|
|
545
|
+
...(mutate ? [
|
|
546
|
+
{label: actions.rename, run: () => {closeMenu(false); setDialog({...menu, rename: true});}},
|
|
547
|
+
{label: actions.delete, run: () => {closeMenu(false); setDialog({...menu, rename: false});}}
|
|
548
|
+
] : []),
|
|
549
|
+
...(git ? (['stage', 'unstage'] as const).map(kind => ({label: actions[kind], run: () => {
|
|
550
|
+
closeMenu(true);
|
|
551
|
+
void run(async () => {
|
|
552
|
+
const result = await git.change(kind, menu.entry, isCurrent ?? (() => mounted.current));
|
|
553
|
+
if (!result.done) return result.error ?? actions.conflict;
|
|
554
|
+
});
|
|
555
|
+
}})) : [])
|
|
556
|
+
]} /> : null}
|
|
557
|
+
{dialog ? <ExplorerFileDialog anchor={dialog.anchor} name={dialog.entry.name} folder={dialog.entry.kind === 'directory'}
|
|
558
|
+
rename={dialog.rename} message={actions} close={() => setDialog(undefined)} submit={submitFileAction} /> : null}
|
|
337
559
|
</div>
|
|
338
560
|
);
|
|
339
561
|
}
|
|
@@ -358,12 +580,26 @@ export function ProjectFolderExplorer(props: ProjectFolderExplorerProps) {
|
|
|
358
580
|
/** Follows marks for the files under `directory`, by path relative to it. Returns the function that stops it. */
|
|
359
581
|
export type FollowMarks = (directory: FileSystemDirectoryHandle,
|
|
360
582
|
update: (marks: ReadonlyMap<string, ExplorerMark>) => void) => () => void;
|
|
361
|
-
type
|
|
583
|
+
export type FollowFileStatuses = (directory: FileSystemDirectoryHandle,
|
|
584
|
+
update: (statuses: ReadonlyMap<string, ExplorerFileStatus>) => void) => () => void;
|
|
585
|
+
type FolderViewProps = {
|
|
586
|
+
vm: object;
|
|
587
|
+
locale?: string;
|
|
588
|
+
marks?: FollowMarks;
|
|
589
|
+
fileStatuses?: FollowFileStatuses;
|
|
590
|
+
git?: FollowExplorerGit;
|
|
591
|
+
/** Opens a transient file tab in the host workspace. */
|
|
592
|
+
openFile?(request: FilePreviewRequest): boolean;
|
|
593
|
+
/** Reads the latest committed version of a file, when the host has access to a Git repository. */
|
|
594
|
+
readBaseline?: ReadFileBaseline;
|
|
595
|
+
};
|
|
596
|
+
export type {FileBaseline, FilePreviewRequest, ReadFileBaseline} from './file-preview.js';
|
|
362
597
|
|
|
363
598
|
const readJson = async (directory: FileSystemDirectoryHandle, name: string): Promise<Json> =>
|
|
364
599
|
JSON.parse(await (await (await directory.getFileHandle(name)).getFile()).text());
|
|
365
600
|
|
|
366
|
-
function FolderView({vm, locale, marks: followMarks
|
|
601
|
+
function FolderView({vm, locale = 'en', marks: followMarks, fileStatuses: followStatuses, git: followGit,
|
|
602
|
+
openFile, readBaseline}: FolderViewProps) {
|
|
367
603
|
const message = messagesFor(locale);
|
|
368
604
|
const [{folder, directory, version}, setFollowed] = React.useState<{
|
|
369
605
|
folder?: FollowedFolder; directory: FileSystemDirectoryHandle | null; version: number;
|
|
@@ -382,11 +618,38 @@ function FolderView({vm, locale, marks: followMarks}: FolderViewProps) {
|
|
|
382
618
|
return () => {current = false;};
|
|
383
619
|
}, [directory, version, locale]);
|
|
384
620
|
const [marks, setMarks] = React.useState<ReadonlyMap<string, ExplorerMark>>();
|
|
621
|
+
const [unavailable, setUnavailable] = React.useState<FileSystemDirectoryHandle>();
|
|
385
622
|
React.useEffect(() => {
|
|
386
623
|
setMarks(undefined);
|
|
387
624
|
if (!directory || !followMarks) return;
|
|
388
625
|
return followMarks(directory, setMarks);
|
|
389
626
|
}, [directory, followMarks]);
|
|
627
|
+
const [statuses, setStatuses] = React.useState<{directory: FileSystemDirectoryHandle; paths: ReadonlyMap<string, ExplorerFileStatus>}>();
|
|
628
|
+
React.useEffect(() => {
|
|
629
|
+
if (!directory || !followStatuses) return;
|
|
630
|
+
return followStatuses(directory, paths => setStatuses({directory, paths}));
|
|
631
|
+
}, [directory, followStatuses]);
|
|
632
|
+
const [unsaved, setUnsaved] = React.useState<{directory: FileSystemDirectoryHandle; paths: ReadonlySet<string>}>();
|
|
633
|
+
React.useEffect(() => {
|
|
634
|
+
if (!folder || !directory) return;
|
|
635
|
+
const update = () => {
|
|
636
|
+
const paths = folder.unsavedPaths();
|
|
637
|
+
if (paths) setUnsaved({directory, paths});
|
|
638
|
+
};
|
|
639
|
+
let timer: ReturnType<typeof setTimeout>;
|
|
640
|
+
const schedule = () => {
|
|
641
|
+
clearTimeout(timer);
|
|
642
|
+
timer = setTimeout(update, 100);
|
|
643
|
+
};
|
|
644
|
+
update();
|
|
645
|
+
const stop = folder.subscribeEdits(schedule);
|
|
646
|
+
return () => {stop(); clearTimeout(timer);};
|
|
647
|
+
}, [folder, directory, version]);
|
|
648
|
+
const [git, setGit] = React.useState<{directory: FileSystemDirectoryHandle; actions?: ExplorerGit}>();
|
|
649
|
+
React.useEffect(() => {
|
|
650
|
+
if (!directory || !followGit) return;
|
|
651
|
+
return followGit(directory, actions => setGit({directory, actions}));
|
|
652
|
+
}, [directory, followGit]);
|
|
390
653
|
if (!folder) return null;
|
|
391
654
|
if (!directory) {
|
|
392
655
|
return <div className={`${prefix}-empty`}>
|
|
@@ -395,7 +658,18 @@ function FolderView({vm, locale, marks: followMarks}: FolderViewProps) {
|
|
|
395
658
|
<button type="button" onClick={() => folder.open(locale ?? 'en')}>{message.open}</button>
|
|
396
659
|
</div>;
|
|
397
660
|
}
|
|
398
|
-
return
|
|
661
|
+
return <>
|
|
662
|
+
<ProjectFolderExplorer directory={directory} locale={locale} descriptions={descriptions} marks={marks}
|
|
663
|
+
refreshKey={version} fileStatuses={statuses?.directory === directory ? statuses.paths : undefined}
|
|
664
|
+
unsavedPaths={unsaved?.directory === directory ? unsaved.paths : undefined}
|
|
665
|
+
mutate={operation => folder.mutate(directory, operation)} isCurrent={() => folder.directory === directory}
|
|
666
|
+
git={git?.directory === directory ? git.actions : undefined}
|
|
667
|
+
onOpen={openFile && (entry => {
|
|
668
|
+
const request = createFilePreview(directory, `${keyFor(directory)}/${entry.path}`, entry, locale, readBaseline);
|
|
669
|
+
setUnavailable(openFile(request) ? undefined : directory);
|
|
670
|
+
})} />
|
|
671
|
+
{unavailable === directory && <p className={`${prefix}-status`} role="status">{message.unavailable}</p>}
|
|
672
|
+
</>;
|
|
399
673
|
}
|
|
400
674
|
|
|
401
675
|
/**
|
|
@@ -405,6 +679,6 @@ function FolderView({vm, locale, marks: followMarks}: FolderViewProps) {
|
|
|
405
679
|
* Pass the same `marks` function across renders, or the marks are followed again.
|
|
406
680
|
*/
|
|
407
681
|
export function renderProjectFolderExplorer(createElement: (component: any, props: any, ...children: any[]) => any,
|
|
408
|
-
{vm, locale = 'en', marks}: FolderViewProps) {
|
|
409
|
-
return createElement(FolderView, {vm, locale, marks});
|
|
682
|
+
{vm, locale = 'en', marks, fileStatuses, git, openFile, readBaseline}: FolderViewProps) {
|
|
683
|
+
return createElement(FolderView, {vm, locale, marks, fileStatuses, git, openFile, readBaseline});
|
|
410
684
|
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
export interface FilePreviewRequest {
|
|
2
|
+
reference: {providerId: string; documentId: string};
|
|
3
|
+
filename: string;
|
|
4
|
+
title: string;
|
|
5
|
+
transient: true;
|
|
6
|
+
mount(element: HTMLElement, close: () => void): {requestClose(): void; dispose(): void};
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export type FileBaseline = {branch: string | undefined; head: string | null; bytes: Uint8Array | null};
|
|
10
|
+
export type ReadFileBaseline = (directory: FileSystemDirectoryHandle, path: string, limit: number) =>
|
|
11
|
+
Promise<FileBaseline | null>;
|
|
12
|
+
|
|
13
|
+
const mimeTypes = new Map(Object.entries({
|
|
14
|
+
apng: 'image/apng', avif: 'image/avif', bmp: 'image/bmp', gif: 'image/gif', ico: 'image/x-icon',
|
|
15
|
+
jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png', svg: 'image/svg+xml', webp: 'image/webp',
|
|
16
|
+
aac: 'audio/aac', aif: 'audio/aiff', aiff: 'audio/aiff', flac: 'audio/flac', m4a: 'audio/mp4',
|
|
17
|
+
mp3: 'audio/mpeg', oga: 'audio/ogg', ogg: 'audio/ogg', opus: 'audio/ogg', wav: 'audio/wav',
|
|
18
|
+
m4v: 'video/mp4', mov: 'video/quicktime', mp4: 'video/mp4', ogv: 'video/ogg', webm: 'video/webm'
|
|
19
|
+
}));
|
|
20
|
+
export const textLimit = 4 * 1024 * 1024;
|
|
21
|
+
|
|
22
|
+
const styles = `
|
|
23
|
+
.twpf-preview{box-sizing:border-box;height:100%;overflow:auto;padding:1rem;color:var(--text-primary,inherit);
|
|
24
|
+
background:var(--ui-primary,transparent)}
|
|
25
|
+
.twpf-preview:has(.twpf-text-file){padding:0;overflow:hidden}
|
|
26
|
+
.twpf-preview img,.twpf-preview video{display:block;max-width:100%;max-height:100%;margin:auto;object-fit:contain}
|
|
27
|
+
.twpf-preview audio{width:min(100%,32rem)}
|
|
28
|
+
`;
|
|
29
|
+
|
|
30
|
+
const messages = {
|
|
31
|
+
en: {
|
|
32
|
+
loading: 'Loading file…', failed: 'This file could not be read.',
|
|
33
|
+
unsupported: 'This file cannot be previewed.', mediaError: 'This media could not be opened.',
|
|
34
|
+
large: 'This text file is too large to open (4 MiB limit).'
|
|
35
|
+
},
|
|
36
|
+
ja: {
|
|
37
|
+
loading: 'ファイルを読み込んでいます…', failed: 'このファイルを読み込めません。',
|
|
38
|
+
unsupported: 'このファイルはプレビューできません。', mediaError: 'このメディアを開けません。',
|
|
39
|
+
large: 'このテキストファイルは開けるサイズの上限(4 MiB)を超えています。'
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
async function fileAt(directory: FileSystemDirectoryHandle, path: string): Promise<FileSystemFileHandle> {
|
|
44
|
+
const parts = path.split('/');
|
|
45
|
+
const name = parts.pop()!;
|
|
46
|
+
for (const part of parts) directory = await directory.getDirectoryHandle(part);
|
|
47
|
+
return directory.getFileHandle(name);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function createFilePreview(directory: FileSystemDirectoryHandle, documentId: string,
|
|
51
|
+
{name, path}: {name: string; path: string}, locale: string, readBaseline?: ReadFileBaseline): FilePreviewRequest {
|
|
52
|
+
return {
|
|
53
|
+
reference: {providerId: 'turbowarp-plus-project-folder', documentId},
|
|
54
|
+
filename: name,
|
|
55
|
+
title: name,
|
|
56
|
+
transient: true,
|
|
57
|
+
mount(element, close) {
|
|
58
|
+
const message = locale.toLowerCase().startsWith('ja') ? messages.ja : messages.en;
|
|
59
|
+
const {ownerDocument: document} = element;
|
|
60
|
+
const panel = document.createElement('div');
|
|
61
|
+
panel.className = 'twpf-preview';
|
|
62
|
+
const style = document.createElement('style');
|
|
63
|
+
style.textContent = styles;
|
|
64
|
+
const status = document.createElement('p');
|
|
65
|
+
status.setAttribute('role', 'status');
|
|
66
|
+
status.textContent = message.loading;
|
|
67
|
+
panel.append(style, status);
|
|
68
|
+
element.append(panel);
|
|
69
|
+
let disposed = false;
|
|
70
|
+
let url: string | undefined;
|
|
71
|
+
let media: HTMLMediaElement | undefined;
|
|
72
|
+
let textSession: ReturnType<FilePreviewRequest['mount']> | undefined;
|
|
73
|
+
const readHandle = () => fileAt(directory, path);
|
|
74
|
+
|
|
75
|
+
const show = (node: HTMLElement) => status.replaceWith(node);
|
|
76
|
+
const load = async () => {
|
|
77
|
+
const file = await (await readHandle()).getFile();
|
|
78
|
+
if (disposed) return;
|
|
79
|
+
const extension = name.includes('.') ? name.split('.').pop()!.toLowerCase() : '';
|
|
80
|
+
const mime = mimeTypes.get(extension) ?? file.type;
|
|
81
|
+
const kind = mime.split('/')[0];
|
|
82
|
+
if (kind === 'image' || kind === 'audio' || kind === 'video') {
|
|
83
|
+
url = URL.createObjectURL(mime === file.type ? file : file.slice(0, file.size, mime));
|
|
84
|
+
const view = document.createElement(kind === 'image' ? 'img' : kind);
|
|
85
|
+
view.addEventListener('error', () => {
|
|
86
|
+
status.textContent = message.mediaError;
|
|
87
|
+
view.replaceWith(status);
|
|
88
|
+
}, {once: true});
|
|
89
|
+
if (view.tagName === 'IMG') {
|
|
90
|
+
// An SVG loaded through an img cannot run scripts in the editor.
|
|
91
|
+
(view as HTMLImageElement).alt = name;
|
|
92
|
+
} else {
|
|
93
|
+
media = view as HTMLMediaElement;
|
|
94
|
+
media.controls = true;
|
|
95
|
+
media.preload = 'metadata';
|
|
96
|
+
media.setAttribute('aria-label', name);
|
|
97
|
+
}
|
|
98
|
+
view.src = url;
|
|
99
|
+
show(view);
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
if (file.size > textLimit) {
|
|
103
|
+
status.textContent = message.large;
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
const [bytes, {decodeText, mountTextFile}] = await Promise.all([
|
|
107
|
+
file.arrayBuffer(), import('./text-file-editor.js')
|
|
108
|
+
]);
|
|
109
|
+
if (disposed) return;
|
|
110
|
+
const content = decodeText(bytes);
|
|
111
|
+
if (content === null) {
|
|
112
|
+
status.textContent = message.unsupported;
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
textSession = mountTextFile(panel, {
|
|
116
|
+
path, extension, content, locale, limit: textLimit, readHandle, close,
|
|
117
|
+
readBaseline: readBaseline && (() => readBaseline(directory, path, textLimit))
|
|
118
|
+
});
|
|
119
|
+
status.remove();
|
|
120
|
+
};
|
|
121
|
+
void load().catch(() => {if (!disposed) status.textContent = message.failed;});
|
|
122
|
+
return {
|
|
123
|
+
requestClose() {if (textSession) textSession.requestClose(); else close();},
|
|
124
|
+
dispose() {
|
|
125
|
+
disposed = true;
|
|
126
|
+
textSession?.dispose();
|
|
127
|
+
media?.pause();
|
|
128
|
+
if (url) URL.revokeObjectURL(url);
|
|
129
|
+
panel.remove();
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
}
|
package/src/folder-registry.ts
CHANGED
|
@@ -1,9 +1,14 @@
|
|
|
1
1
|
/** The project folder mounted for a VM, as a view of the folder follows it. */
|
|
2
|
+
export type ExplorerMutation = (guard: () => void) => Promise<void>;
|
|
3
|
+
|
|
2
4
|
export interface FollowedFolder {
|
|
3
5
|
readonly directory: FileSystemDirectoryHandle | null;
|
|
4
6
|
subscribe(listener: () => void): () => void;
|
|
7
|
+
subscribeEdits(listener: () => void): () => void;
|
|
8
|
+
unsavedPaths(): ReadonlySet<string> | null;
|
|
5
9
|
/** Asks for a folder and opens it, as the File menu's Open Project Folder… does. */
|
|
6
10
|
open(locale: string): void;
|
|
11
|
+
mutate(directory: FileSystemDirectoryHandle, operation: ExplorerMutation): Promise<void>;
|
|
7
12
|
}
|
|
8
13
|
const folders = new WeakMap<object, FollowedFolder>();
|
|
9
14
|
// Views rendered before the folder is mounted, or after it is disposed, wait for the VM's folder here.
|