@kubohiroya/turbowarp-plus-editor-project-folder 0.7.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/src/explorer.tsx CHANGED
@@ -2,13 +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
+ import {followProjectFolder} from './folder-registry.js';
7
+ import type {ExplorerMutation, FollowedFolder} from './folder-registry.js';
6
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';
7
15
 
8
16
  export type ExplorerMark = 'added' | 'modified' | 'deleted' | 'untracked';
17
+ export type ExplorerFileStatus = {
18
+ change?: ExplorerMark;
19
+ staged?: boolean;
20
+ revision?: 'committed' | 'pushed' | 'merged';
21
+ };
9
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;
10
28
  export type ProjectFolderExplorerProps = {
11
- /** The folder to show: a project folder or a repository root. It is only read. */
29
+ /** The folder to show: a project folder or a repository root. */
12
30
  directory: FileSystemDirectoryHandle;
13
31
  /** 'ja…' shows Japanese text; anything else shows English. */
14
32
  locale?: string;
@@ -16,18 +34,30 @@ export type ProjectFolderExplorerProps = {
16
34
  descriptions?: ReadonlyMap<string, string>;
17
35
  /** Git status for an entry, by path relative to `directory`. */
18
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;
19
41
  /** Called when a file is opened with Enter, Space or a click. */
20
42
  onOpen?(entry: ExplorerEntry): void;
21
43
  /** The tree's accessible name. Defaults to "Project folder". */
22
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;
23
49
  };
24
50
 
25
51
  const messages = {
26
52
  en: {
27
53
  label: 'Project folder', loading: 'Loading…', empty: 'This folder is empty.',
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.',
28
56
  failed: 'This folder could not be read.', denied: 'Permission to read this folder was not granted.',
29
57
  separator: ', ',
30
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'},
31
61
  project: 'Project data', manifest: 'Folder manifest', extensions: 'Embedded extensions',
32
62
  assetsDirectory: 'Costume and sound files', extensionsDirectory: 'Extension files',
33
63
  costume: (sprite: string, name: string) => `${sprite} · costume ${name}`,
@@ -37,9 +67,13 @@ const messages = {
37
67
  },
38
68
  ja: {
39
69
  label: '作品フォルダ', loading: '読み込んでいます…', empty: 'このフォルダは空です。',
70
+ noFolder: 'プロジェクトフォルダを開くと、ここにファイルを表示します。', open: 'プロジェクトフォルダを開く…',
71
+ unavailable: 'このエディターのレイアウトではファイルをタブで開けません。',
40
72
  failed: 'このフォルダを読み込めません。', denied: 'このフォルダを読む許可がありません。',
41
73
  separator: '、',
42
74
  marks: {added: '追加', modified: '変更', deleted: '削除', untracked: '未追跡'},
75
+ unsaved: '未保存の変更あり', staged: 'ステージ済み',
76
+ revisions: {committed: 'コミット済み', pushed: 'プッシュ済み', merged: 'PR マージ済み'},
43
77
  project: '作品データ', manifest: '作品フォルダの目録', extensions: '埋め込み拡張の一覧',
44
78
  assetsDirectory: 'コスチュームと音のファイル', extensionsDirectory: '拡張のファイル',
45
79
  costume: (sprite: string, name: string) => `${sprite} のコスチューム ${name}`,
@@ -97,7 +131,7 @@ export function describeProjectFolder(project: Project, locale?: string, {manife
97
131
  return descriptions;
98
132
  }
99
133
 
100
- type Node = {name: string; path: string; kind: 'file' | 'directory' | 'error'; message?: string};
134
+ type ExplorerNode = {name: string; path: string; kind: 'file' | 'directory' | 'error'; message?: string};
101
135
  type Message = typeof messages.en;
102
136
  const rootId = '/';
103
137
  // '\0' cannot appear in a file name, so the error row never collides with a real entry.
@@ -121,10 +155,19 @@ padding-block:.15em;padding-inline-end:.4em;background:none;color:inherit;font:i
121
155
  .${prefix}-icon img{width:20px;height:20px;object-fit:contain;border-radius:2px;
122
156
  background:repeating-conic-gradient(rgba(128,128,128,.22) 0 25%,transparent 0 50%) 0 0/8px 8px}
123
157
  .${prefix}-icon img[hidden]{display:none}
158
+ .${prefix}-filename{display:inline-flex;min-width:0}
124
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}
125
165
  .${prefix}-mark{flex:none;font-size:.85em;padding:0 .3em;border:1px solid currentColor;border-radius:3px;opacity:.85}
126
166
  .${prefix}-description{overflow:hidden;text-overflow:ellipsis;opacity:.7;font-size:.9em}
127
- .${prefix}-status{opacity:.7;font-style:italic;padding-block:.15em}`;
167
+ .${prefix}-status{opacity:.7;font-style:italic;padding-block:.15em}
168
+ .${prefix}-empty{padding:.5em}
169
+ .${prefix}-empty p{margin:0 0 .6em}
170
+ .${prefix}-empty button{color:inherit;background:transparent;border:1px solid currentColor;border-radius:4px;padding:.2em .6em;font:inherit;cursor:pointer}`;
128
171
 
129
172
  const indent = (level: number) => ({paddingInlineStart: `${0.25 + level * 1.1}em`});
130
173
 
@@ -211,11 +254,25 @@ function Icon({kind, path, readFile}: {kind: IconKind; path: string; readFile?:
211
254
  );
212
255
  }
213
256
 
214
- function Explorer({directory, locale, descriptions, marks, onOpen, label}: ProjectFolderExplorerProps) {
257
+ function Explorer({directory, locale, descriptions, marks, fileStatuses, unsavedPaths, refreshKey,
258
+ onOpen, label, mutate, git, isCurrent}: ProjectFolderExplorerProps) {
215
259
  const message = messagesFor(locale);
260
+ const actions = actionMessages(locale);
216
261
  const [handles] = React.useState(() => new Map<string, FileSystemDirectoryHandle>([[rootId, directory]]));
217
262
  const [files] = React.useState(() => new Map<string, FileSystemFileHandle>());
263
+ const [loadedFolders] = React.useState(() => new Set<string>());
218
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
+ }, []);
219
276
  const collator = React.useMemo(() => new Intl.Collator(locale, {numeric: true, sensitivity: 'base'}), [locale]);
220
277
 
221
278
  const directoryAt = async (id: string) => {
@@ -235,7 +292,7 @@ function Explorer({directory, locale, descriptions, marks, onOpen, label}: Proje
235
292
  }
236
293
  return handle.getFile();
237
294
  };
238
- const tree = useTree<Node>({
295
+ const tree = useTree<ExplorerNode>({
239
296
  rootItemId: rootId,
240
297
  initialState: {expandedItems: [], selectedItems: [], focusedItem: null},
241
298
  getItemName: item => item.getItemData()?.name ?? '',
@@ -264,14 +321,15 @@ function Explorer({directory, locale, descriptions, marks, onOpen, label}: Proje
264
321
  try {
265
322
  const handle = await directoryAt(id);
266
323
  const base = id === rootId ? '' : `${id}/`;
267
- const nodes: Node[] = [];
324
+ const nodes: ExplorerNode[] = [];
268
325
  for await (const entry of (handle as IterableDirectory).values()) {
269
- if (entry.kind === 'directory' && entry.name === '.git') continue;
326
+ if (entry.name.toLowerCase() === '.git') continue;
270
327
  const path = base + entry.name;
271
328
  if (entry.kind === 'directory') handles.set(path, entry as FileSystemDirectoryHandle);
272
329
  else files.set(path, entry as FileSystemFileHandle);
273
330
  nodes.push({name: entry.name, path, kind: entry.kind});
274
331
  }
332
+ loadedFolders.add(id);
275
333
  nodes.sort((a, b) => (a.kind === 'directory' ? 0 : 1) - (b.kind === 'directory' ? 0 : 1) ||
276
334
  collator.compare(a.name, b.name) || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
277
335
  return nodes.map(data => ({id: data.path, data}));
@@ -288,25 +346,167 @@ function Explorer({directory, locale, descriptions, marks, onOpen, label}: Proje
288
346
  tree.setMounted(true);
289
347
  return () => tree.setMounted(false);
290
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]);
291
355
 
292
- const renderItem = (item: ItemInstance<Node>) => {
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>) => {
293
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();
294
479
  const level = item.getItemMeta().level;
295
480
  const folder = item.isFolder();
296
481
  const expanded = folder && item.isExpanded();
297
- const mark = data && data.kind !== 'error' ? marks?.get(data.path) : undefined;
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);
298
485
  const markLabel = mark ? message.marks[mark] : '';
299
486
  const description = data && data.kind !== 'error' ? descriptions?.get(data.path) : undefined;
300
487
  const icon = !data || data.kind === 'error' ? undefined :
301
488
  folder ? (expanded ? 'folder-open' : 'folder') : iconFor(data.name);
302
- const accessibleName = [item.getItemName(), markLabel, description].filter(Boolean).join(message.separator);
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);
303
491
  const rows = [
304
- <button {...item.getProps()} key={item.getId()} type="button" aria-label={accessibleName}
492
+ <button {...itemProps} key={item.getId()} type="button" aria-label={accessibleName}
305
493
  className={`${prefix}-item${data?.kind === 'error' ? ` ${prefix}-error` : ''}`} style={indent(level)}
306
- 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}>
307
504
  <span className={`${prefix}-caret`} aria-hidden="true">{folder ? (expanded ? '▾' : '▸') : ''}</span>
308
505
  {icon ? <Icon kind={icon} path={data!.path} readFile={icon === 'image' ? readFile : undefined} /> : null}
309
- <span className={`${prefix}-name`}>{item.getItemName()}</span>
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>
310
510
  {markLabel ? <span className={`${prefix}-mark`} aria-hidden="true">{markLabel}</span> : null}
311
511
  {description ? <span className={`${prefix}-description`} aria-hidden="true">{description}</span> : null}
312
512
  </button>
@@ -319,14 +519,43 @@ function Explorer({directory, locale, descriptions, marks, onOpen, label}: Proje
319
519
  };
320
520
  const items = tree.getItems();
321
521
  return (
322
- <div className={prefix}>
323
- <style>{css}</style>
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>
324
535
  <div {...tree.getContainerProps(label ?? message.label)}>
325
536
  {items.map(renderItem)}
326
537
  </div>
327
538
  {items.length ? null : (
328
539
  <div className={`${prefix}-status`} role="status">{rootLoaded ? message.empty : message.loading}</div>
329
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}
330
559
  </div>
331
560
  );
332
561
  }
@@ -347,3 +576,109 @@ export function ProjectFolderExplorer(props: ProjectFolderExplorerProps) {
347
576
  // A new directory starts a new tree, so cached entries and expanded folders never leak between folders.
348
577
  return <Explorer key={keyFor(props.directory)} {...props} />;
349
578
  }
579
+
580
+ /** Follows marks for the files under `directory`, by path relative to it. Returns the function that stops it. */
581
+ export type FollowMarks = (directory: FileSystemDirectoryHandle,
582
+ update: (marks: ReadonlyMap<string, ExplorerMark>) => void) => () => void;
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';
597
+
598
+ const readJson = async (directory: FileSystemDirectoryHandle, name: string): Promise<Json> =>
599
+ JSON.parse(await (await (await directory.getFileHandle(name)).getFile()).text());
600
+
601
+ function FolderView({vm, locale = 'en', marks: followMarks, fileStatuses: followStatuses, git: followGit,
602
+ openFile, readBaseline}: FolderViewProps) {
603
+ const message = messagesFor(locale);
604
+ const [{folder, directory, version}, setFollowed] = React.useState<{
605
+ folder?: FollowedFolder; directory: FileSystemDirectoryHandle | null; version: number;
606
+ }>({directory: null, version: 0});
607
+ React.useEffect(() => followProjectFolder(vm, (folder, directory) =>
608
+ setFollowed(previous => ({folder, directory, version: previous.version + 1}))), [vm]);
609
+ // The descriptions come from the folder's project file as last saved, read again after each save.
610
+ const [descriptions, setDescriptions] = React.useState<ReadonlyMap<string, string>>();
611
+ React.useEffect(() => {
612
+ let current = true;
613
+ setDescriptions(undefined);
614
+ if (!directory) return;
615
+ Promise.all([readJson(directory, projectFile), readJson(directory, manifestFile).catch(() => undefined)]).then(([project, manifest]) => {
616
+ if (current && isObject(project)) setDescriptions(describeProjectFolder(project as Project, locale, {manifest}));
617
+ }, () => {});
618
+ return () => {current = false;};
619
+ }, [directory, version, locale]);
620
+ const [marks, setMarks] = React.useState<ReadonlyMap<string, ExplorerMark>>();
621
+ const [unavailable, setUnavailable] = React.useState<FileSystemDirectoryHandle>();
622
+ React.useEffect(() => {
623
+ setMarks(undefined);
624
+ if (!directory || !followMarks) return;
625
+ return followMarks(directory, setMarks);
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]);
653
+ if (!folder) return null;
654
+ if (!directory) {
655
+ return <div className={`${prefix}-empty`}>
656
+ <style>{css}</style>
657
+ <p>{message.noFolder}</p>
658
+ <button type="button" onClick={() => folder.open(locale ?? 'en')}>{message.open}</button>
659
+ </div>;
660
+ }
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
+ </>;
673
+ }
674
+
675
+ /**
676
+ * Renders the explorer of the project folder open for `vm`, for a side panel of the host: its files with what each is
677
+ * for, and `marks` (such as the Git status) when given. It follows the folder as it opens, closes and saves; with no
678
+ * folder open it offers Open Project Folder…, and it renders nothing while no project folder is mounted for `vm`.
679
+ * Pass the same `marks` function across renders, or the marks are followed again.
680
+ */
681
+ export function renderProjectFolderExplorer(createElement: (component: any, props: any, ...children: any[]) => any,
682
+ {vm, locale = 'en', marks, fileStatuses, git, openFile, readBaseline}: FolderViewProps) {
683
+ return createElement(FolderView, {vm, locale, marks, fileStatuses, git, openFile, readBaseline});
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
+ }