@kubohiroya/turbowarp-plus-editor-project-folder 0.8.0 → 0.9.1

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,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 {canMoveExplorerEntry, copyExplorerFile, createExplorerDirectory, deleteExplorerEntry, ExplorerFileError,
10
+ explorerNameAvailable, moveExplorerEntry, parentPath, renameExplorerEntry, resolveExplorerDirectory} from './explorer-files.js';
11
+ import {actionCss, actionMessages, ExplorerFileDialog, ExplorerMenu} from './explorer-menu.js';
12
+ import type {FileAction, 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. It is only read. */
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 Node = {name: string; path: string; kind: 'file' | 'directory' | 'error'; message?: string};
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.
@@ -113,6 +143,7 @@ const failure = (error: unknown, message: Message) =>
113
143
  message.denied : message.failed;
114
144
 
115
145
  const prefix = 'twpf-explorer';
146
+ const entryDragType = 'application/x-twpf-explorer-entry';
116
147
  // Colors come from the host's text color, so the tree follows light and dark themes.
117
148
  const css = `.${prefix}{font:inherit;color:inherit}
118
149
  .${prefix}-item{display:flex;align-items:center;gap:.4em;width:100%;box-sizing:border-box;margin:0;border:0;border-radius:3px;
@@ -125,7 +156,13 @@ padding-block:.15em;padding-inline-end:.4em;background:none;color:inherit;font:i
125
156
  .${prefix}-icon img{width:20px;height:20px;object-fit:contain;border-radius:2px;
126
157
  background:repeating-conic-gradient(rgba(128,128,128,.22) 0 25%,transparent 0 50%) 0 0/8px 8px}
127
158
  .${prefix}-icon img[hidden]{display:none}
159
+ .${prefix}-filename{display:inline-flex;min-width:0}
128
160
  .${prefix}-name{overflow:hidden;text-overflow:ellipsis}
161
+ .${prefix}-item[data-staged] .${prefix}-filename{font-weight:700}
162
+ .${prefix}-item[data-revision="committed"] .${prefix}-filename{color:#174b9d;color:light-dark(#174b9d,#91c1ff)}
163
+ .${prefix}-item[data-revision="pushed"] .${prefix}-filename{color:#67369a;color:light-dark(#67369a,#dfafff)}
164
+ .${prefix}-item[data-revision="merged"] .${prefix}-filename{color:#17603e;color:light-dark(#17603e,#85e3ad)}
165
+ .${prefix}-unsaved{flex:none}
129
166
  .${prefix}-mark{flex:none;font-size:.85em;padding:0 .3em;border:1px solid currentColor;border-radius:3px;opacity:.85}
130
167
  .${prefix}-description{overflow:hidden;text-overflow:ellipsis;opacity:.7;font-size:.9em}
131
168
  .${prefix}-status{opacity:.7;font-style:italic;padding-block:.15em}
@@ -218,11 +255,26 @@ function Icon({kind, path, readFile}: {kind: IconKind; path: string; readFile?:
218
255
  );
219
256
  }
220
257
 
221
- function Explorer({directory, locale, descriptions, marks, onOpen, label}: ProjectFolderExplorerProps) {
258
+ function Explorer({directory, locale, descriptions, marks, fileStatuses, unsavedPaths, refreshKey,
259
+ onOpen, label, mutate, git, isCurrent}: ProjectFolderExplorerProps) {
222
260
  const message = messagesFor(locale);
261
+ const actions = actionMessages(locale);
223
262
  const [handles] = React.useState(() => new Map<string, FileSystemDirectoryHandle>([[rootId, directory]]));
224
263
  const [files] = React.useState(() => new Map<string, FileSystemFileHandle>());
264
+ const [loadedFolders] = React.useState(() => new Set<string>());
225
265
  const [rootLoaded, setRootLoaded] = React.useState(false);
266
+ const [drag, setDrag] = React.useState<string | null>(null);
267
+ const [move, setMove] = React.useState<{entry: ExplorerEntry; destinations: ReadonlySet<string>}>();
268
+ const [menu, setMenu] = React.useState<{entry: ExplorerEntry; anchor: MenuAnchor}>();
269
+ const [dialog, setDialog] = React.useState<{entry: ExplorerEntry; anchor: MenuAnchor; action: FileAction}>();
270
+ const [feedback, setFeedback] = React.useState('');
271
+ const [working, setWorking] = React.useState(false);
272
+ const running = React.useRef(false);
273
+ const mounted = React.useRef(true);
274
+ React.useEffect(() => {
275
+ mounted.current = true;
276
+ return () => {mounted.current = false;};
277
+ }, []);
226
278
  const collator = React.useMemo(() => new Intl.Collator(locale, {numeric: true, sensitivity: 'base'}), [locale]);
227
279
 
228
280
  const directoryAt = async (id: string) => {
@@ -242,7 +294,7 @@ function Explorer({directory, locale, descriptions, marks, onOpen, label}: Proje
242
294
  }
243
295
  return handle.getFile();
244
296
  };
245
- const tree = useTree<Node>({
297
+ const tree = useTree<ExplorerNode>({
246
298
  rootItemId: rootId,
247
299
  initialState: {expandedItems: [], selectedItems: [], focusedItem: null},
248
300
  getItemName: item => item.getItemData()?.name ?? '',
@@ -271,14 +323,15 @@ function Explorer({directory, locale, descriptions, marks, onOpen, label}: Proje
271
323
  try {
272
324
  const handle = await directoryAt(id);
273
325
  const base = id === rootId ? '' : `${id}/`;
274
- const nodes: Node[] = [];
326
+ const nodes: ExplorerNode[] = [];
275
327
  for await (const entry of (handle as IterableDirectory).values()) {
276
- if (entry.kind === 'directory' && entry.name === '.git') continue;
328
+ if (entry.name.toLowerCase() === '.git') continue;
277
329
  const path = base + entry.name;
278
330
  if (entry.kind === 'directory') handles.set(path, entry as FileSystemDirectoryHandle);
279
331
  else files.set(path, entry as FileSystemFileHandle);
280
332
  nodes.push({name: entry.name, path, kind: entry.kind});
281
333
  }
334
+ loadedFolders.add(id);
282
335
  nodes.sort((a, b) => (a.kind === 'directory' ? 0 : 1) - (b.kind === 'directory' ? 0 : 1) ||
283
336
  collator.compare(a.name, b.name) || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
284
337
  return nodes.map(data => ({id: data.path, data}));
@@ -295,25 +348,246 @@ function Explorer({directory, locale, descriptions, marks, onOpen, label}: Proje
295
348
  tree.setMounted(true);
296
349
  return () => tree.setMounted(false);
297
350
  }, [tree]);
351
+ const lastRefresh = React.useRef(refreshKey);
352
+ React.useEffect(() => {
353
+ if (lastRefresh.current === refreshKey) return;
354
+ lastRefresh.current = refreshKey;
355
+ void Promise.all([...loadedFolders].map(id => tree.getItemInstance(id).invalidateChildrenIds(true)));
356
+ }, [tree, loadedFolders, refreshKey]);
298
357
 
299
- const renderItem = (item: ItemInstance<Node>) => {
358
+ const errorText = (error: unknown) => {
359
+ if (error instanceof ExplorerFileError) return actions[error.code];
360
+ if (error instanceof DOMException && ['NotAllowedError', 'SecurityError'].includes(error.name)) return actions.denied;
361
+ if (error instanceof FolderError && error.code === 'conflict') return actions.conflict;
362
+ return actions.failed;
363
+ };
364
+ const run = async (operation: () => Promise<string | void>) => {
365
+ if (running.current) return;
366
+ running.current = true;
367
+ setWorking(true);
368
+ setFeedback('');
369
+ try {
370
+ const result = await operation();
371
+ if (mounted.current) setFeedback(result ?? '');
372
+ } catch (error) {
373
+ if (mounted.current) setFeedback(errorText(error));
374
+ } finally {
375
+ running.current = false;
376
+ if (mounted.current) setWorking(false);
377
+ }
378
+ };
379
+ const write = (path: string, operation: (parent: FileSystemDirectoryHandle, guard: () => void) => Promise<void>) =>
380
+ mutate!(async guard => {
381
+ const permission = (directory as FileSystemDirectoryHandle & {
382
+ requestPermission?(options: {mode: 'readwrite'}): Promise<PermissionState>;
383
+ }).requestPermission;
384
+ if (permission && await permission.call(directory, {mode: 'readwrite'}) !== 'granted') {
385
+ throw new DOMException('Write permission denied', 'NotAllowedError');
386
+ }
387
+ guard();
388
+ const parent = await resolveExplorerDirectory(directory, path);
389
+ guard();
390
+ await operation(parent, guard);
391
+ });
392
+ const reread = async (path: string, expand = false) => {
393
+ if (!mounted.current) return;
394
+ const parent = path ? tree.getItemInstance(path) : tree.getRootItem();
395
+ if (expand && path && !parent.isExpanded()) parent.expand();
396
+ await parent.invalidateChildrenIds(true);
397
+ };
398
+ const forget = (path: string) => {
399
+ const cache = tree.getDataRef() as React.MutableRefObject<{childrenIds: Record<string, string[]>}>;
400
+ for (const id of handles.keys()) {
401
+ if (id !== path && !id.startsWith(`${path}/`)) continue;
402
+ delete cache.current.childrenIds[id];
403
+ loadedFolders.delete(id);
404
+ handles.delete(id);
405
+ }
406
+ for (const id of files.keys()) if (id === path || id.startsWith(`${path}/`)) files.delete(id);
407
+ };
408
+ const dropPath = (target: EventTarget) =>
409
+ (target as Element).closest('[data-drop-directory]')?.getAttribute('data-drop-directory') ?? '';
410
+ const moveDropPath = (target: EventTarget) => {
411
+ const row = (target as Element).closest<HTMLButtonElement>(`.${prefix}-item`);
412
+ const path = row ? row.getAttribute('data-move-directory') : '';
413
+ return path !== null && move?.destinations.has(path) ? path : null;
414
+ };
415
+ const startMove = (event: React.DragEvent<HTMLButtonElement>, entry: ExplorerEntry) => {
416
+ if (running.current || dialog) {
417
+ event.preventDefault();
418
+ return;
419
+ }
420
+ event.stopPropagation();
421
+ setMenu(undefined);
422
+ setDrag(null);
423
+ event.dataTransfer.effectAllowed = 'move';
424
+ event.dataTransfer.setData(entryDragType, entry.path);
425
+ const row = event.currentTarget;
426
+ const document = row.ownerDocument;
427
+ const image = document.createElement('div');
428
+ image.className = `${prefix}-drag-image`;
429
+ const icon = row.querySelector(`.${prefix}-icon`);
430
+ if (icon) image.appendChild(icon.cloneNode(true));
431
+ const name = document.createElement('span');
432
+ name.className = `${prefix}-name`;
433
+ name.textContent = entry.name;
434
+ image.appendChild(name);
435
+ document.body.appendChild(image);
436
+ event.dataTransfer.setDragImage(image, -12, -12);
437
+ document.defaultView?.requestAnimationFrame(() => image.remove());
438
+
439
+ setMove({entry, destinations: new Set()});
440
+ const candidates = ['', ...tree.getItems().filter(item => item.isFolder()).map(item => item.getId())];
441
+ void Promise.all(candidates.filter(path => canMoveExplorerEntry(entry.path, path)).map(async path => {
442
+ try {
443
+ return await explorerNameAvailable(await directoryAt(path || rootId), entry.name) ? path : null;
444
+ } catch {
445
+ return null;
446
+ }
447
+ })).then(paths => {
448
+ if (mounted.current) setMove(current => current?.entry === entry ?
449
+ {entry, destinations: new Set(paths.filter(path => path !== null))} : current);
450
+ });
451
+ };
452
+ const endMove = () => {
453
+ setMove(undefined);
454
+ setDrag(null);
455
+ };
456
+ const dropMove = (event: React.DragEvent<HTMLDivElement>, entry: ExplorerEntry) => {
457
+ event.preventDefault();
458
+ event.stopPropagation();
459
+ const path = moveDropPath(event.target);
460
+ endMove();
461
+ if (path === null || event.dataTransfer.getData(entryDragType) !== entry.path) return;
462
+ void run(async () => {
463
+ let moved = false;
464
+ try {
465
+ await write(path, (destination, guard) => moveExplorerEntry(directory, entry, destination, path, guard));
466
+ moved = true;
467
+ } finally {
468
+ if (mounted.current) forget(entry.path);
469
+ await reread(parentPath(entry.path));
470
+ await reread(path, moved);
471
+ await git?.refresh();
472
+ }
473
+ });
474
+ };
475
+ const acceptsFiles = (event: React.DragEvent) => Boolean(mutate && event.dataTransfer.types.includes('Files'));
476
+ const drop = (event: React.DragEvent<HTMLDivElement>) => {
477
+ if (move && event.dataTransfer.types.includes(entryDragType)) return dropMove(event, move.entry);
478
+ if (!acceptsFiles(event)) return;
479
+ event.preventDefault();
480
+ event.stopPropagation();
481
+ setDrag(null);
482
+ const path = dropPath(event.target);
483
+ const items = Array.from(event.dataTransfer.items);
484
+ const problems: string[] = [];
485
+ const dropped = items.length ? items.flatMap(item => {
486
+ if (item.kind !== 'file') return [];
487
+ const entry = item.webkitGetAsEntry?.();
488
+ if (entry?.isDirectory) {
489
+ problems.push(`${entry.name} — ${actions.filesOnly}`);
490
+ return [];
491
+ }
492
+ const file = item.getAsFile();
493
+ return file ? [file] : [];
494
+ }) : Array.from(event.dataTransfer.files);
495
+ void run(async () => {
496
+ if (!dropped.length) return problems.join('\n') || actions.filesOnly;
497
+ try {
498
+ await write(path, async (parent, guard) => {
499
+ for (const file of dropped) {
500
+ guard();
501
+ try {await copyExplorerFile(parent, file, guard);}
502
+ catch (error) {problems.push(`${actions.copyFailed} ${file.name} — ${errorText(error)}`);}
503
+ }
504
+ });
505
+ } finally {
506
+ await reread(path, true);
507
+ await git?.refresh();
508
+ }
509
+ return problems.join('\n');
510
+ });
511
+ };
512
+ const closeMenu = (restoreFocus: boolean) => {
513
+ setMenu(undefined);
514
+ if (restoreFocus && menu?.anchor.row.isConnected) menu.anchor.row.focus({preventScroll: true});
515
+ };
516
+ const showMenu = (event: React.MouseEvent<HTMLButtonElement> | React.KeyboardEvent<HTMLButtonElement>, entry: ExplorerEntry) => {
517
+ if (running.current || (!mutate && !git)) return;
518
+ event.preventDefault();
519
+ event.stopPropagation();
520
+ const row = event.currentTarget;
521
+ const rect = row.getBoundingClientRect();
522
+ const pointer = 'clientX' in event && (event.clientX || event.clientY);
523
+ setMenu({entry, anchor: {row, x: pointer ? event.clientX : rect.left, y: pointer ? event.clientY : rect.bottom}});
524
+ };
525
+ const submitFileAction = (name: string) => {
526
+ if (!dialog) return;
527
+ const {entry, action} = dialog;
528
+ setDialog(undefined);
529
+ if (action === 'rename' && entry.name === name) return;
530
+ void run(async () => {
531
+ const parent = action === 'createFolder' ? entry.path : parentPath(entry.path);
532
+ let changed = false;
533
+ try {
534
+ await write(parent, (handle, guard) => {
535
+ if (action === 'createFolder') return createExplorerDirectory(handle, name, guard);
536
+ if (action === 'rename') return renameExplorerEntry(handle, entry, name, guard);
537
+ return deleteExplorerEntry(handle, entry, guard);
538
+ });
539
+ changed = true;
540
+ } finally {
541
+ if (mounted.current && action !== 'createFolder') forget(entry.path);
542
+ await reread(parent, action === 'createFolder' && changed);
543
+ await git?.refresh();
544
+ }
545
+ });
546
+ };
547
+ const renderItem = (item: ItemInstance<ExplorerNode>) => {
300
548
  const data = item.getItemData();
549
+ const entry: ExplorerEntry | undefined = data?.path && data.kind !== 'error' ?
550
+ {path: data.path, name: data.name, kind: data.kind} : undefined;
551
+ const itemProps = item.getProps();
301
552
  const level = item.getItemMeta().level;
302
553
  const folder = item.isFolder();
303
554
  const expanded = folder && item.isExpanded();
304
- const mark = data && data.kind !== 'error' ? marks?.get(data.path) : undefined;
555
+ const status = data?.kind === 'file' ? fileStatuses?.get(data.path) : undefined;
556
+ const unsaved = data?.kind === 'file' && unsavedPaths?.has(data.path);
557
+ const mark = status?.change ?? (data && data.kind !== 'error' ? marks?.get(data.path) : undefined);
305
558
  const markLabel = mark ? message.marks[mark] : '';
306
559
  const description = data && data.kind !== 'error' ? descriptions?.get(data.path) : undefined;
307
560
  const icon = !data || data.kind === 'error' ? undefined :
308
561
  folder ? (expanded ? 'folder-open' : 'folder') : iconFor(data.name);
309
- const accessibleName = [item.getItemName(), markLabel, description].filter(Boolean).join(message.separator);
562
+ const accessibleName = [item.getItemName(), unsaved && message.unsaved, status?.staged && message.staged,
563
+ status?.revision && message.revisions[status.revision], markLabel, description].filter(Boolean).join(message.separator);
564
+ const moveDestination = entry?.kind === 'directory' && move?.destinations.has(entry.path);
565
+ const moveActive = moveDestination && drag === entry.path;
310
566
  const rows = [
311
- <button {...item.getProps()} key={item.getId()} type="button" aria-label={accessibleName}
567
+ <button {...itemProps} key={item.getId()} type="button" aria-label={accessibleName}
312
568
  className={`${prefix}-item${data?.kind === 'error' ? ` ${prefix}-error` : ''}`} style={indent(level)}
313
- data-path={data?.path}>
569
+ data-path={data?.path} data-staged={status?.staged ? '' : undefined} data-revision={status?.revision}
570
+ title={unsaved || status?.staged || status?.revision ? accessibleName : undefined}
571
+ data-drop-directory={entry?.kind === 'directory' ? entry.path : entry ? parentPath(entry.path) : undefined}
572
+ data-drop-active={entry?.kind === 'directory' && drag === entry.path ? '' : undefined}
573
+ data-move-directory={entry?.kind === 'directory' ? entry.path : undefined}
574
+ data-move-unavailable={move && !moveDestination ? '' : undefined}
575
+ data-move-active={moveActive ? '' : undefined}
576
+ draggable={entry && mutate ? !working : undefined}
577
+ onDragStart={entry && mutate ? event => startMove(event, entry) : undefined}
578
+ onDragEnd={entry && mutate ? endMove : undefined}
579
+ aria-haspopup={entry && (mutate || git) ? 'menu' : undefined}
580
+ onContextMenu={entry ? event => showMenu(event, entry) : undefined}
581
+ onKeyDown={entry ? event => {
582
+ if ((mutate || git) && (event.key === 'ContextMenu' || (event.shiftKey && event.key === 'F10'))) showMenu(event, entry);
583
+ else itemProps.onKeyDown?.(event);
584
+ } : itemProps.onKeyDown}>
314
585
  <span className={`${prefix}-caret`} aria-hidden="true">{folder ? (expanded ? '▾' : '▸') : ''}</span>
315
586
  {icon ? <Icon kind={icon} path={data!.path} readFile={icon === 'image' ? readFile : undefined} /> : null}
316
- <span className={`${prefix}-name`}>{item.getItemName()}</span>
587
+ <span className={`${prefix}-filename`}>
588
+ <span className={`${prefix}-name`}>{item.getItemName()}</span>
589
+ {unsaved ? <span className={`${prefix}-unsaved`} aria-hidden="true">*</span> : null}
590
+ </span>
317
591
  {markLabel ? <span className={`${prefix}-mark`} aria-hidden="true">{markLabel}</span> : null}
318
592
  {description ? <span className={`${prefix}-description`} aria-hidden="true">{description}</span> : null}
319
593
  </button>
@@ -326,14 +600,54 @@ function Explorer({directory, locale, descriptions, marks, onOpen, label}: Proje
326
600
  };
327
601
  const items = tree.getItems();
328
602
  return (
329
- <div className={prefix}>
330
- <style>{css}</style>
603
+ <div className={`${prefix}${mutate ? ` ${prefix}-drop` : ''}`}
604
+ data-drop-active={drag === '' ? '' : undefined} onDrop={drop}
605
+ onDragOver={event => {
606
+ if (move && event.dataTransfer.types.includes(entryDragType)) {
607
+ const path = running.current ? null : moveDropPath(event.target);
608
+ event.stopPropagation();
609
+ if (path !== null) event.preventDefault();
610
+ event.dataTransfer.dropEffect = path === null ? 'none' : 'move';
611
+ setDrag(path);
612
+ return;
613
+ }
614
+ if (!acceptsFiles(event)) return;
615
+ event.preventDefault();
616
+ event.stopPropagation();
617
+ event.dataTransfer.dropEffect = running.current ? 'none' : 'copy';
618
+ if (!running.current) setDrag(dropPath(event.target));
619
+ }}
620
+ onDragLeave={event => {
621
+ if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setDrag(null);
622
+ }}>
623
+ <style>{css + actionCss}</style>
331
624
  <div {...tree.getContainerProps(label ?? message.label)}>
332
625
  {items.map(renderItem)}
333
626
  </div>
334
627
  {items.length ? null : (
335
628
  <div className={`${prefix}-status`} role="status">{rootLoaded ? message.empty : message.loading}</div>
336
629
  )}
630
+ {working || feedback ? <div className={`${prefix}-feedback`} role={feedback ? 'alert' : 'status'}>
631
+ {feedback || actions.working}
632
+ </div> : null}
633
+ {menu ? <ExplorerMenu anchor={menu.anchor} label={actions.actions} close={closeMenu} actions={[
634
+ ...(mutate && menu.entry.kind === 'directory' ? [
635
+ {label: actions.createFolder, run: () => {closeMenu(false); setDialog({...menu, action: 'createFolder'});}}
636
+ ] : []),
637
+ ...(mutate ? [
638
+ {label: actions.rename, run: () => {closeMenu(false); setDialog({...menu, action: 'rename'});}},
639
+ {label: actions.delete, run: () => {closeMenu(false); setDialog({...menu, action: 'delete'});}}
640
+ ] : []),
641
+ ...(git ? (['stage', 'unstage'] as const).map(kind => ({label: actions[kind], run: () => {
642
+ closeMenu(true);
643
+ void run(async () => {
644
+ const result = await git.change(kind, menu.entry, isCurrent ?? (() => mounted.current));
645
+ if (!result.done) return result.error ?? actions.conflict;
646
+ });
647
+ }})) : [])
648
+ ]} /> : null}
649
+ {dialog ? <ExplorerFileDialog anchor={dialog.anchor} name={dialog.entry.name} folder={dialog.entry.kind === 'directory'}
650
+ action={dialog.action} message={actions} close={() => setDialog(undefined)} submit={submitFileAction} /> : null}
337
651
  </div>
338
652
  );
339
653
  }
@@ -346,7 +660,7 @@ const keyFor = (directory: FileSystemDirectoryHandle) => {
346
660
  };
347
661
 
348
662
  /**
349
- * A read-only tree of a folder for the Editor's side panel, built on Headless Tree. Folders load when expanded, folders
663
+ * A tree of a folder for the Editor's side panel, built on Headless Tree. Folders load when expanded, folders
350
664
  * sort before files, and `.git` is hidden. Keyboard: arrow keys, Home and End move and expand; Enter or Space opens a
351
665
  * file. Needs React 16.14–18 from the host.
352
666
  */
@@ -358,12 +672,26 @@ export function ProjectFolderExplorer(props: ProjectFolderExplorerProps) {
358
672
  /** Follows marks for the files under `directory`, by path relative to it. Returns the function that stops it. */
359
673
  export type FollowMarks = (directory: FileSystemDirectoryHandle,
360
674
  update: (marks: ReadonlyMap<string, ExplorerMark>) => void) => () => void;
361
- type FolderViewProps = {vm: object; locale?: string; marks?: FollowMarks};
675
+ export type FollowFileStatuses = (directory: FileSystemDirectoryHandle,
676
+ update: (statuses: ReadonlyMap<string, ExplorerFileStatus>) => void) => () => void;
677
+ type FolderViewProps = {
678
+ vm: object;
679
+ locale?: string;
680
+ marks?: FollowMarks;
681
+ fileStatuses?: FollowFileStatuses;
682
+ git?: FollowExplorerGit;
683
+ /** Opens a transient file tab in the host workspace. */
684
+ openFile?(request: FilePreviewRequest): boolean;
685
+ /** Reads the latest committed version of a file, when the host has access to a Git repository. */
686
+ readBaseline?: ReadFileBaseline;
687
+ };
688
+ export type {FileBaseline, FilePreviewRequest, ReadFileBaseline} from './file-preview.js';
362
689
 
363
690
  const readJson = async (directory: FileSystemDirectoryHandle, name: string): Promise<Json> =>
364
691
  JSON.parse(await (await (await directory.getFileHandle(name)).getFile()).text());
365
692
 
366
- function FolderView({vm, locale, marks: followMarks}: FolderViewProps) {
693
+ function FolderView({vm, locale = 'en', marks: followMarks, fileStatuses: followStatuses, git: followGit,
694
+ openFile, readBaseline}: FolderViewProps) {
367
695
  const message = messagesFor(locale);
368
696
  const [{folder, directory, version}, setFollowed] = React.useState<{
369
697
  folder?: FollowedFolder; directory: FileSystemDirectoryHandle | null; version: number;
@@ -382,11 +710,38 @@ function FolderView({vm, locale, marks: followMarks}: FolderViewProps) {
382
710
  return () => {current = false;};
383
711
  }, [directory, version, locale]);
384
712
  const [marks, setMarks] = React.useState<ReadonlyMap<string, ExplorerMark>>();
713
+ const [unavailable, setUnavailable] = React.useState<FileSystemDirectoryHandle>();
385
714
  React.useEffect(() => {
386
715
  setMarks(undefined);
387
716
  if (!directory || !followMarks) return;
388
717
  return followMarks(directory, setMarks);
389
718
  }, [directory, followMarks]);
719
+ const [statuses, setStatuses] = React.useState<{directory: FileSystemDirectoryHandle; paths: ReadonlyMap<string, ExplorerFileStatus>}>();
720
+ React.useEffect(() => {
721
+ if (!directory || !followStatuses) return;
722
+ return followStatuses(directory, paths => setStatuses({directory, paths}));
723
+ }, [directory, followStatuses]);
724
+ const [unsaved, setUnsaved] = React.useState<{directory: FileSystemDirectoryHandle; paths: ReadonlySet<string>}>();
725
+ React.useEffect(() => {
726
+ if (!folder || !directory) return;
727
+ const update = () => {
728
+ const paths = folder.unsavedPaths();
729
+ if (paths) setUnsaved({directory, paths});
730
+ };
731
+ let timer: ReturnType<typeof setTimeout>;
732
+ const schedule = () => {
733
+ clearTimeout(timer);
734
+ timer = setTimeout(update, 100);
735
+ };
736
+ update();
737
+ const stop = folder.subscribeEdits(schedule);
738
+ return () => {stop(); clearTimeout(timer);};
739
+ }, [folder, directory, version]);
740
+ const [git, setGit] = React.useState<{directory: FileSystemDirectoryHandle; actions?: ExplorerGit}>();
741
+ React.useEffect(() => {
742
+ if (!directory || !followGit) return;
743
+ return followGit(directory, actions => setGit({directory, actions}));
744
+ }, [directory, followGit]);
390
745
  if (!folder) return null;
391
746
  if (!directory) {
392
747
  return <div className={`${prefix}-empty`}>
@@ -395,7 +750,18 @@ function FolderView({vm, locale, marks: followMarks}: FolderViewProps) {
395
750
  <button type="button" onClick={() => folder.open(locale ?? 'en')}>{message.open}</button>
396
751
  </div>;
397
752
  }
398
- return <ProjectFolderExplorer directory={directory} locale={locale} descriptions={descriptions} marks={marks}/>;
753
+ return <>
754
+ <ProjectFolderExplorer directory={directory} locale={locale} descriptions={descriptions} marks={marks}
755
+ refreshKey={version} fileStatuses={statuses?.directory === directory ? statuses.paths : undefined}
756
+ unsavedPaths={unsaved?.directory === directory ? unsaved.paths : undefined}
757
+ mutate={operation => folder.mutate(directory, operation)} isCurrent={() => folder.directory === directory}
758
+ git={git?.directory === directory ? git.actions : undefined}
759
+ onOpen={openFile && (entry => {
760
+ const request = createFilePreview(directory, `${keyFor(directory)}/${entry.path}`, entry, locale, readBaseline);
761
+ setUnavailable(openFile(request) ? undefined : directory);
762
+ })} />
763
+ {unavailable === directory && <p className={`${prefix}-status`} role="status">{message.unavailable}</p>}
764
+ </>;
399
765
  }
400
766
 
401
767
  /**
@@ -405,6 +771,6 @@ function FolderView({vm, locale, marks: followMarks}: FolderViewProps) {
405
771
  * Pass the same `marks` function across renders, or the marks are followed again.
406
772
  */
407
773
  export function renderProjectFolderExplorer(createElement: (component: any, props: any, ...children: any[]) => any,
408
- {vm, locale = 'en', marks}: FolderViewProps) {
409
- return createElement(FolderView, {vm, locale, marks});
774
+ {vm, locale = 'en', marks, fileStatuses, git, openFile, readBaseline}: FolderViewProps) {
775
+ return createElement(FolderView, {vm, locale, marks, fileStatuses, git, openFile, readBaseline});
410
776
  }