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

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
@@ -3,6 +3,7 @@ import {asyncDataLoaderFeature, hotkeysCoreFeature, selectionFeature} from '@hea
3
3
  import type {ItemInstance} from '@headless-tree/core';
4
4
  import {useTree} from '@headless-tree/react/react17';
5
5
  import {FolderError, isObject, manifestFile, projectFile} from './source.js';
6
+ import {projectFolderOverwriteWarning} from './create-folder.js';
6
7
  import {followProjectFolder} from './folder-registry.js';
7
8
  import type {ExplorerMutation, FollowedFolder} from './folder-registry.js';
8
9
  import type {Json, Project} from './source.js';
@@ -38,6 +39,8 @@ export type ProjectFolderExplorerProps = {
38
39
  unsavedPaths?: ReadonlySet<string>;
39
40
  /** Changes after the folder contents have been saved or reloaded. */
40
41
  refreshKey?: number;
42
+ /** Case-insensitive search by file name or relative path. */
43
+ query?: string;
41
44
  /** Called when a file is opened with Enter, Space or a click. */
42
45
  onOpen?(entry: ExplorerEntry): void;
43
46
  /** The tree's accessible name. Defaults to "Project folder". */
@@ -50,13 +53,16 @@ export type ProjectFolderExplorerProps = {
50
53
 
51
54
  const messages = {
52
55
  en: {
53
- label: 'Project folder', loading: 'Loading…', empty: 'This folder is empty.',
56
+ label: 'Project folder', loading: 'Loading…', empty: 'This folder is empty.', noMatches: 'No matching files.',
57
+ results: 'Matching files',
54
58
  noFolder: 'Open a project folder to show its files here.', open: 'Open Project Folder…',
59
+ create: 'Create Project Folder', creating: 'Creating project folder…',
60
+ createFailed: 'Could not create the project folder.',
55
61
  unavailable: 'File tabs are unavailable in this editor layout.',
56
62
  failed: 'This folder could not be read.', denied: 'Permission to read this folder was not granted.',
57
63
  separator: ', ',
58
- marks: {added: 'Added', modified: 'Modified', deleted: 'Deleted', untracked: 'Untracked'},
59
- unsaved: 'Unsaved changes', staged: 'Staged',
64
+ marks: {added: 'New file', modified: 'Saved, not committed', deleted: 'Deleted', untracked: 'Untracked'},
65
+ unsaved: 'Unsaved changes', staged: 'Added to Git index',
60
66
  revisions: {committed: 'Committed', pushed: 'Pushed', merged: 'Pull request merged'},
61
67
  project: 'Project data', manifest: 'Folder manifest', extensions: 'Embedded extensions',
62
68
  assetsDirectory: 'Costume and sound files', extensionsDirectory: 'Extension files',
@@ -66,13 +72,16 @@ const messages = {
66
72
  stageSound: (name: string) => `Stage · sound ${name}`
67
73
  },
68
74
  ja: {
69
- label: '作品フォルダ', loading: '読み込んでいます…', empty: 'このフォルダは空です。',
75
+ label: '作品フォルダ', loading: '読み込んでいます…', empty: 'このフォルダは空です。', noMatches: '該当するファイルはありません。',
76
+ results: '検索結果',
70
77
  noFolder: 'プロジェクトフォルダを開くと、ここにファイルを表示します。', open: 'プロジェクトフォルダを開く…',
78
+ create: 'プロジェクトフォルダを作成', creating: 'プロジェクトフォルダを作成しています…',
79
+ createFailed: 'プロジェクトフォルダを作成できませんでした。',
71
80
  unavailable: 'このエディターのレイアウトではファイルをタブで開けません。',
72
81
  failed: 'このフォルダを読み込めません。', denied: 'このフォルダを読む許可がありません。',
73
82
  separator: '、',
74
- marks: {added: '追加', modified: '変更', deleted: '削除', untracked: '未追跡'},
75
- unsaved: '未保存の変更あり', staged: 'ステージ済み',
83
+ marks: {added: '新しいファイル', modified: '保存済・未コミットの変更', deleted: '削除', untracked: '未追跡'},
84
+ unsaved: '未保存の変更あり', staged: 'Git のインデックスに追加済み',
76
85
  revisions: {committed: 'コミット済み', pushed: 'プッシュ済み', merged: 'PR マージ済み'},
77
86
  project: '作品データ', manifest: '作品フォルダの目録', extensions: '埋め込み拡張の一覧',
78
87
  assetsDirectory: 'コスチュームと音のファイル', extensionsDirectory: '拡張のファイル',
@@ -131,7 +140,7 @@ export function describeProjectFolder(project: Project, locale?: string, {manife
131
140
  return descriptions;
132
141
  }
133
142
 
134
- type ExplorerNode = {name: string; path: string; kind: 'file' | 'directory' | 'error'; message?: string};
143
+ type ExplorerNode = {name: string; path: string; kind: 'file' | 'directory' | 'error'; deleted?: boolean; message?: string};
135
144
  type Message = typeof messages.en;
136
145
  const rootId = '/';
137
146
  // '\0' cannot appear in a file name, so the error row never collides with a real entry.
@@ -146,8 +155,13 @@ const prefix = 'twpf-explorer';
146
155
  const entryDragType = 'application/x-twpf-explorer-entry';
147
156
  // Colors come from the host's text color, so the tree follows light and dark themes.
148
157
  const css = `.${prefix}{font:inherit;color:inherit}
149
- .${prefix}-item{display:flex;align-items:center;gap:.4em;width:100%;box-sizing:border-box;margin:0;border:0;border-radius:3px;
158
+ .${prefix}-item{display:grid;grid-template-columns:1em 20px minmax(0,1fr);align-items:center;gap:.2em .4em;
159
+ width:100%;box-sizing:border-box;margin:0;border:0;border-radius:3px;
150
160
  padding-block:.15em;padding-inline-end:.4em;background:none;color:inherit;font:inherit;text-align:start;cursor:pointer;white-space:nowrap}
161
+ .${prefix}-search-result{display:block;width:100%;text-align:start;color:inherit;font:inherit;background:transparent;
162
+ border:0;border-radius:3px;padding:.35em .5em;overflow-wrap:anywhere;cursor:pointer}
163
+ .${prefix}-search-result:hover{background:rgba(128,128,128,.12)}
164
+ .${prefix}-search-result:focus-visible{outline:2px solid currentColor;outline-offset:-2px}
151
165
  .${prefix}-item:hover{background:rgba(128,128,128,.12)}
152
166
  .${prefix}-item[aria-selected="true"]{background:rgba(128,128,128,.24)}
153
167
  .${prefix}-item:focus-visible{outline:2px solid currentColor;outline-offset:-2px}
@@ -156,15 +170,20 @@ padding-block:.15em;padding-inline-end:.4em;background:none;color:inherit;font:i
156
170
  .${prefix}-icon img{width:20px;height:20px;object-fit:contain;border-radius:2px;
157
171
  background:repeating-conic-gradient(rgba(128,128,128,.22) 0 25%,transparent 0 50%) 0 0/8px 8px}
158
172
  .${prefix}-icon img[hidden]{display:none}
173
+ .${prefix}-label{grid-column:3;display:flex;align-items:center;gap:.4em;min-width:0}
159
174
  .${prefix}-filename{display:inline-flex;min-width:0}
160
175
  .${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}
166
- .${prefix}-mark{flex:none;font-size:.85em;padding:0 .3em;border:1px solid currentColor;border-radius:3px;opacity:.85}
167
- .${prefix}-description{overflow:hidden;text-overflow:ellipsis;opacity:.7;font-size:.9em}
176
+ .${prefix}-marker{flex:none;white-space:pre}
177
+ .${prefix}-item[data-staged] .${prefix}-name, .${prefix}-search-result[data-staged] .${prefix}-name,
178
+ .${prefix}-name[data-git-change="modified"], .${prefix}-name[data-git-change="added"]{font-weight:700}
179
+ .${prefix}-name[data-revision="committed"]{color:#174b9d;color:light-dark(#174b9d,#91c1ff)}
180
+ .${prefix}-name[data-revision="pushed"]{color:#67369a;color:light-dark(#67369a,#dfafff)}
181
+ .${prefix}-name[data-revision="merged"]{color:#17603e;color:light-dark(#17603e,#85e3ad)}
182
+ .${prefix}-name[data-git-change="deleted"]{text-decoration:line-through}
183
+ .${prefix}-item[aria-disabled="true"], .${prefix}-search-result:disabled{cursor:default}
184
+ .${prefix}-description{grid-column:3;min-width:0;padding:.2em .4em;border-radius:3px;background:rgba(128,128,128,.12);
185
+ color:inherit;color:color-mix(in srgb,currentColor 78%,transparent);font-size:.75em;line-height:1.4;
186
+ white-space:normal;overflow-wrap:anywhere}
168
187
  .${prefix}-status{opacity:.7;font-style:italic;padding-block:.15em}
169
188
  .${prefix}-empty{padding:.5em}
170
189
  .${prefix}-empty p{margin:0 0 .6em}
@@ -255,6 +274,100 @@ function Icon({kind, path, readFile}: {kind: IconKind; path: string; readFile?:
255
274
  );
256
275
  }
257
276
 
277
+ function FileStatusMarkers({unsaved, change}: {unsaved?: boolean; change?: ExplorerMark}) {
278
+ return <>
279
+ {unsaved && <span className={`${prefix}-marker`} data-tw-plus-unsaved-marker aria-hidden="true">{' *'}</span>}
280
+ {change === 'untracked' && <span className={`${prefix}-marker`} aria-hidden="true">{' ✨'}</span>}
281
+ </>;
282
+ }
283
+
284
+ function fileStatusLabels(message: ReturnType<typeof messagesFor>, unsaved: boolean | undefined,
285
+ status: ExplorerFileStatus | undefined, change: ExplorerMark | undefined) {
286
+ return [unsaved && message.unsaved, status?.staged && message.staged,
287
+ status?.revision && message.revisions[status.revision], change && message.marks[change]];
288
+ }
289
+
290
+ function deletedPaths(fileStatuses: ProjectFolderExplorerProps['fileStatuses'], marks: ProjectFolderExplorerProps['marks']) {
291
+ const paths = new Set<string>();
292
+ for (const [path, mark] of marks ?? []) if (mark === 'deleted') paths.add(path);
293
+ for (const [path, status] of fileStatuses ?? []) {
294
+ if (status.change === 'deleted') paths.add(path);
295
+ else paths.delete(path);
296
+ }
297
+ return paths;
298
+ }
299
+
300
+ function deletedChildren(paths: ReadonlySet<string>) {
301
+ const folders = new Map<string, Map<string, ExplorerNode>>();
302
+ for (const path of paths) {
303
+ const parts = path.split('/');
304
+ let parent = rootId;
305
+ for (const [index, name] of parts.entries()) {
306
+ const child = parent === rootId ? name : parent + '/' + name;
307
+ const kind = index === parts.length - 1 ? 'file' : 'directory';
308
+ let children = folders.get(parent);
309
+ if (!children) folders.set(parent, children = new Map());
310
+ children.set(child, {name, path: child, kind, deleted: true});
311
+ parent = child;
312
+ }
313
+ }
314
+ return folders;
315
+ }
316
+
317
+ function FileSearch({directory, query, locale, refreshKey, marks, fileStatuses, unsavedPaths, onOpen}:
318
+ ProjectFolderExplorerProps & {query: string}) {
319
+ const message = messagesFor(locale);
320
+ const [index, setIndex] = React.useState<{files: ExplorerEntry[]; failed: boolean}>();
321
+ React.useEffect(() => {
322
+ let current = true;
323
+ setIndex(undefined);
324
+ const files: ExplorerEntry[] = [];
325
+ let failed = false;
326
+ const walk = async (folder: FileSystemDirectoryHandle, base: string) => {
327
+ try {
328
+ for await (const entry of (folder as IterableDirectory).values()) {
329
+ if (!current) return;
330
+ if (entry.name.toLowerCase() === '.git') continue;
331
+ const path = base + entry.name;
332
+ if (entry.kind === 'directory') await walk(entry as FileSystemDirectoryHandle, path + '/');
333
+ else files.push({path, name: entry.name, kind: 'file'});
334
+ }
335
+ } catch {
336
+ failed = true;
337
+ }
338
+ };
339
+ void walk(directory, '').then(() => {
340
+ if (current) setIndex({files, failed});
341
+ });
342
+ return () => {current = false;};
343
+ }, [directory, refreshKey]);
344
+
345
+ const paths = deletedPaths(fileStatuses, marks);
346
+ const files = new Map(index?.files.map(entry => [entry.path, entry]));
347
+ for (const path of paths) {
348
+ if (!files.has(path)) files.set(path, {name: path.split('/').pop()!, path, kind: 'file'});
349
+ }
350
+ const matches = [...files.values()].filter(entry => entry.path.toLowerCase().includes(query))
351
+ .sort((a, b) => a.path.localeCompare(b.path, locale, {numeric: true}));
352
+ return <div className={prefix} role="group" aria-label={message.results}>
353
+ {matches?.map(entry => {
354
+ const unsaved = unsavedPaths?.has(entry.path);
355
+ const status = fileStatuses?.get(entry.path);
356
+ const change = status?.change ?? marks?.get(entry.path);
357
+ const accessibleName = [entry.path, ...fileStatusLabels(message, unsaved, status, change)]
358
+ .filter(Boolean).join(message.separator);
359
+ return <button key={entry.path} type="button" className={`${prefix}-search-result`}
360
+ aria-label={accessibleName} title={accessibleName} data-staged={status?.staged ? '' : undefined}
361
+ data-revision={status?.revision} disabled={paths.has(entry.path)} onClick={() => onOpen?.(entry)}>
362
+ <span className={`${prefix}-name`} data-git-change={change} data-revision={status?.revision}>{entry.path}</span>
363
+ <FileStatusMarkers unsaved={unsaved} change={change}/>
364
+ </button>;
365
+ })}
366
+ {!index ? <p role="status">{message.loading}</p> : index.failed ? <p role="status">{message.failed}</p> :
367
+ !matches?.length && <p role="status">{message.noMatches}</p>}
368
+ </div>;
369
+ }
370
+
258
371
  function Explorer({directory, locale, descriptions, marks, fileStatuses, unsavedPaths, refreshKey,
259
372
  onOpen, label, mutate, git, isCurrent}: ProjectFolderExplorerProps) {
260
373
  const message = messagesFor(locale);
@@ -294,6 +407,10 @@ function Explorer({directory, locale, descriptions, marks, fileStatuses, unsaved
294
407
  }
295
408
  return handle.getFile();
296
409
  };
410
+ const deleted = React.useMemo(() => deletedChildren(deletedPaths(fileStatuses, marks)), [fileStatuses, marks]);
411
+ const compareNodes = (a: ExplorerNode, b: ExplorerNode) =>
412
+ (a.kind === 'directory' ? 0 : 1) - (b.kind === 'directory' ? 0 : 1) ||
413
+ collator.compare(a.name, b.name) || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
297
414
  const tree = useTree<ExplorerNode>({
298
415
  rootItemId: rootId,
299
416
  initialState: {expandedItems: [], selectedItems: [], focusedItem: null},
@@ -302,7 +419,7 @@ function Explorer({directory, locale, descriptions, marks, fileStatuses, unsaved
302
419
  createLoadingItemData: () => ({name: '', path: '', kind: 'file'}),
303
420
  onPrimaryAction: item => {
304
421
  const data = item.getItemData();
305
- if (data?.kind === 'file') onOpen?.({path: data.path, name: data.name, kind: 'file'});
422
+ if (data?.kind === 'file' && !data.deleted && (fileStatuses?.get(data.path)?.change ?? marks?.get(data.path)) !== 'deleted') onOpen?.({path: data.path, name: data.name, kind: 'file'});
306
423
  },
307
424
  onLoadedChildren: id => {if (id === rootId) setRootLoaded(true);},
308
425
  dataLoader: {
@@ -320,24 +437,25 @@ function Explorer({directory, locale, descriptions, marks, fileStatuses, unsaved
320
437
  }
321
438
  },
322
439
  getChildrenWithData: async id => {
440
+ const base = id === rootId ? '' : `${id}/`;
441
+ const missingChildren = deleted.get(id);
442
+ const nodes = new Map(missingChildren);
323
443
  try {
324
444
  const handle = await directoryAt(id);
325
- const base = id === rootId ? '' : `${id}/`;
326
- const nodes: ExplorerNode[] = [];
327
445
  for await (const entry of (handle as IterableDirectory).values()) {
328
446
  if (entry.name.toLowerCase() === '.git') continue;
329
447
  const path = base + entry.name;
330
448
  if (entry.kind === 'directory') handles.set(path, entry as FileSystemDirectoryHandle);
331
449
  else files.set(path, entry as FileSystemFileHandle);
332
- nodes.push({name: entry.name, path, kind: entry.kind});
450
+ nodes.set(path, {name: entry.name, path, kind: entry.kind});
333
451
  }
334
- loadedFolders.add(id);
335
- nodes.sort((a, b) => (a.kind === 'directory' ? 0 : 1) - (b.kind === 'directory' ? 0 : 1) ||
336
- collator.compare(a.name, b.name) || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
337
- return nodes.map(data => ({id: data.path, data}));
338
452
  } catch (error) {
339
- return [{id: errorId(id), data: {name: failure(error, message), path: '', kind: 'error'}}];
453
+ if (!missingChildren || (error as DOMException).name !== 'NotFoundError') {
454
+ return [{id: errorId(id), data: {name: failure(error, message), path: '', kind: 'error'}}];
455
+ }
340
456
  }
457
+ loadedFolders.add(id);
458
+ return [...nodes.values()].sort(compareNodes).map(data => ({id: data.path, data}));
341
459
  }
342
460
  },
343
461
  features: [asyncDataLoaderFeature, selectionFeature, hotkeysCoreFeature]
@@ -348,12 +466,18 @@ function Explorer({directory, locale, descriptions, marks, fileStatuses, unsaved
348
466
  tree.setMounted(true);
349
467
  return () => tree.setMounted(false);
350
468
  }, [tree]);
351
- const lastRefresh = React.useRef(refreshKey);
469
+ const lastRefresh = React.useRef({refreshKey, deleted});
352
470
  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]);
471
+ const previous = lastRefresh.current;
472
+ lastRefresh.current = {refreshKey, deleted};
473
+ const affected = [...loadedFolders].filter(id => {
474
+ if (previous.refreshKey !== refreshKey) return true;
475
+ const before = previous.deleted.get(id);
476
+ const after = deleted.get(id);
477
+ return before?.size !== after?.size || [...after ?? []].some(([path, node]) => before?.get(path)?.kind !== node.kind);
478
+ });
479
+ void Promise.all(affected.map(id => tree.getItemInstance(id).invalidateChildrenIds(true)));
480
+ }, [tree, loadedFolders, refreshKey, deleted]);
357
481
 
358
482
  const errorText = (error: unknown) => {
359
483
  if (error instanceof ExplorerFileError) return actions[error.code];
@@ -546,28 +670,28 @@ function Explorer({directory, locale, descriptions, marks, fileStatuses, unsaved
546
670
  };
547
671
  const renderItem = (item: ItemInstance<ExplorerNode>) => {
548
672
  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
673
  const itemProps = item.getProps();
552
674
  const level = item.getItemMeta().level;
553
675
  const folder = item.isFolder();
554
676
  const expanded = folder && item.isExpanded();
555
677
  const status = data?.kind === 'file' ? fileStatuses?.get(data.path) : undefined;
556
678
  const unsaved = data?.kind === 'file' && unsavedPaths?.has(data.path);
557
- const mark = status?.change ?? (data && data.kind !== 'error' ? marks?.get(data.path) : undefined);
558
- const markLabel = mark ? message.marks[mark] : '';
679
+ const change = data?.deleted ? 'deleted' : status?.change ?? (data?.kind === 'file' ? marks?.get(data.path) : undefined);
680
+ const entry: ExplorerEntry | undefined = data?.path && data.kind !== 'error' && change !== 'deleted' ?
681
+ {path: data.path, name: data.name, kind: data.kind} : undefined;
559
682
  const description = data && data.kind !== 'error' ? descriptions?.get(data.path) : undefined;
560
683
  const icon = !data || data.kind === 'error' ? undefined :
561
684
  folder ? (expanded ? 'folder-open' : 'folder') : iconFor(data.name);
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);
685
+ const accessibleName = [item.getItemName(), ...fileStatusLabels(message, unsaved, status, change), description]
686
+ .filter(Boolean).join(message.separator);
564
687
  const moveDestination = entry?.kind === 'directory' && move?.destinations.has(entry.path);
565
688
  const moveActive = moveDestination && drag === entry.path;
566
689
  const rows = [
567
690
  <button {...itemProps} key={item.getId()} type="button" aria-label={accessibleName}
568
691
  className={`${prefix}-item${data?.kind === 'error' ? ` ${prefix}-error` : ''}`} style={indent(level)}
569
692
  data-path={data?.path} data-staged={status?.staged ? '' : undefined} data-revision={status?.revision}
570
- title={unsaved || status?.staged || status?.revision ? accessibleName : undefined}
693
+ aria-disabled={change === 'deleted' && !folder ? true : undefined}
694
+ title={accessibleName || undefined}
571
695
  data-drop-directory={entry?.kind === 'directory' ? entry.path : entry ? parentPath(entry.path) : undefined}
572
696
  data-drop-active={entry?.kind === 'directory' && drag === entry.path ? '' : undefined}
573
697
  data-move-directory={entry?.kind === 'directory' ? entry.path : undefined}
@@ -583,12 +707,13 @@ function Explorer({directory, locale, descriptions, marks, fileStatuses, unsaved
583
707
  else itemProps.onKeyDown?.(event);
584
708
  } : itemProps.onKeyDown}>
585
709
  <span className={`${prefix}-caret`} aria-hidden="true">{folder ? (expanded ? '▾' : '▸') : ''}</span>
586
- {icon ? <Icon kind={icon} path={data!.path} readFile={icon === 'image' ? readFile : undefined} /> : null}
587
- <span className={`${prefix}-filename`}>
588
- <span className={`${prefix}-name`}>{item.getItemName()}</span>
589
- {unsaved ? <span className={`${prefix}-unsaved`} aria-hidden="true">*</span> : null}
710
+ {icon ? <Icon kind={icon} path={data!.path} readFile={icon === 'image' && change !== 'deleted' ? readFile : undefined} /> : null}
711
+ <span className={`${prefix}-label`}>
712
+ <span className={`${prefix}-filename`}>
713
+ <span className={`${prefix}-name`} data-git-change={change} data-revision={status?.revision}>{item.getItemName()}</span>
714
+ <FileStatusMarkers unsaved={unsaved} change={change}/>
715
+ </span>
590
716
  </span>
591
- {markLabel ? <span className={`${prefix}-mark`} aria-hidden="true">{markLabel}</span> : null}
592
717
  {description ? <span className={`${prefix}-description`} aria-hidden="true">{description}</span> : null}
593
718
  </button>
594
719
  ];
@@ -666,7 +791,11 @@ const keyFor = (directory: FileSystemDirectoryHandle) => {
666
791
  */
667
792
  export function ProjectFolderExplorer(props: ProjectFolderExplorerProps) {
668
793
  // A new directory starts a new tree, so cached entries and expanded folders never leak between folders.
669
- return <Explorer key={keyFor(props.directory)} {...props} />;
794
+ const query = props.query?.trim().toLowerCase();
795
+ return <React.Fragment key={keyFor(props.directory)}>
796
+ <div hidden={Boolean(query)}><Explorer {...props} /></div>
797
+ {query && <FileSearch {...props} query={query} />}
798
+ </React.Fragment>;
670
799
  }
671
800
 
672
801
  /** Follows marks for the files under `directory`, by path relative to it. Returns the function that stops it. */
@@ -677,8 +806,13 @@ export type FollowFileStatuses = (directory: FileSystemDirectoryHandle,
677
806
  type FolderViewProps = {
678
807
  vm: object;
679
808
  locale?: string;
809
+ /** Saves the current project to a local folder. */
810
+ createFolder?(): Promise<unknown>;
680
811
  marks?: FollowMarks;
681
812
  fileStatuses?: FollowFileStatuses;
813
+ /** Reports unsaved text edits in open file tabs for the given folder. */
814
+ followFileEdits?(directory: FileSystemDirectoryHandle, update: (paths: readonly string[]) => void): () => void;
815
+ query?: string;
682
816
  git?: FollowExplorerGit;
683
817
  /** Opens a transient file tab in the host workspace. */
684
818
  openFile?(request: FilePreviewRequest): boolean;
@@ -691,8 +825,22 @@ const readJson = async (directory: FileSystemDirectoryHandle, name: string): Pro
691
825
  JSON.parse(await (await (await directory.getFileHandle(name)).getFile()).text());
692
826
 
693
827
  function FolderView({vm, locale = 'en', marks: followMarks, fileStatuses: followStatuses, git: followGit,
694
- openFile, readBaseline}: FolderViewProps) {
828
+ openFile, readBaseline, query, followFileEdits, createFolder}: FolderViewProps) {
695
829
  const message = messagesFor(locale);
830
+ const [creating, setCreating] = React.useState(false);
831
+ const [createError, setCreateError] = React.useState('');
832
+ const create = async () => {
833
+ if (!createFolder || creating) return;
834
+ setCreating(true);
835
+ setCreateError('');
836
+ try {
837
+ await createFolder();
838
+ } catch {
839
+ setCreateError(message.createFailed);
840
+ } finally {
841
+ setCreating(false);
842
+ }
843
+ };
696
844
  const [{folder, directory, version}, setFollowed] = React.useState<{
697
845
  folder?: FollowedFolder; directory: FileSystemDirectoryHandle | null; version: number;
698
846
  }>({directory: null, version: 0});
@@ -737,6 +885,11 @@ function FolderView({vm, locale = 'en', marks: followMarks, fileStatuses: follow
737
885
  const stop = folder.subscribeEdits(schedule);
738
886
  return () => {stop(); clearTimeout(timer);};
739
887
  }, [folder, directory, version]);
888
+ const [fileEdits, setFileEdits] = React.useState<{directory: FileSystemDirectoryHandle; paths: readonly string[]}>();
889
+ React.useEffect(() => {
890
+ if (!directory || !followFileEdits) return;
891
+ return followFileEdits(directory, paths => setFileEdits({directory, paths}));
892
+ }, [directory, followFileEdits]);
740
893
  const [git, setGit] = React.useState<{directory: FileSystemDirectoryHandle; actions?: ExplorerGit}>();
741
894
  React.useEffect(() => {
742
895
  if (!directory || !followGit) return;
@@ -746,14 +899,23 @@ function FolderView({vm, locale = 'en', marks: followMarks, fileStatuses: follow
746
899
  if (!directory) {
747
900
  return <div className={`${prefix}-empty`}>
748
901
  <style>{css}</style>
749
- <p>{message.noFolder}</p>
750
- <button type="button" onClick={() => folder.open(locale ?? 'en')}>{message.open}</button>
902
+ {createFolder ? <>
903
+ <p>{projectFolderOverwriteWarning(locale)}</p>
904
+ <button type="button" disabled={creating} onClick={() => void create()}>{message.create}</button>
905
+ {creating && <p role="status">{message.creating}</p>}
906
+ {createError && <p role="alert">{createError}</p>}
907
+ </> : <>
908
+ <p>{message.noFolder}</p>
909
+ <button type="button" onClick={() => folder.open(locale)}>{message.open}</button>
910
+ </>}
751
911
  </div>;
752
912
  }
913
+ const unsavedPaths = new Set(unsaved?.directory === directory ? unsaved.paths : undefined);
914
+ if (fileEdits?.directory === directory) for (const path of fileEdits.paths) unsavedPaths.add(path);
753
915
  return <>
754
916
  <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}
917
+ refreshKey={version} query={query} fileStatuses={statuses?.directory === directory ? statuses.paths : undefined}
918
+ unsavedPaths={unsavedPaths}
757
919
  mutate={operation => folder.mutate(directory, operation)} isCurrent={() => folder.directory === directory}
758
920
  git={git?.directory === directory ? git.actions : undefined}
759
921
  onOpen={openFile && (entry => {
@@ -767,10 +929,11 @@ function FolderView({vm, locale = 'en', marks: followMarks, fileStatuses: follow
767
929
  /**
768
930
  * Renders the explorer of the project folder open for `vm`, for a side panel of the host: its files with what each is
769
931
  * for, and `marks` (such as the Git status) when given. It follows the folder as it opens, closes and saves; with no
770
- * folder open it offers Open Project Folder…, and it renders nothing while no project folder is mounted for `vm`.
932
+ * folder open it offers to create one when the host supplies a command, or to open an existing one.
933
+ * It renders nothing while no project folder is mounted for `vm`.
771
934
  * Pass the same `marks` function across renders, or the marks are followed again.
772
935
  */
773
936
  export function renderProjectFolderExplorer(createElement: (component: any, props: any, ...children: any[]) => any,
774
- {vm, locale = 'en', marks, fileStatuses, git, openFile, readBaseline}: FolderViewProps) {
775
- return createElement(FolderView, {vm, locale, marks, fileStatuses, git, openFile, readBaseline});
937
+ props: FolderViewProps) {
938
+ return createElement(FolderView, props);
776
939
  }
@@ -1,9 +1,22 @@
1
+ interface FilePreviewSession {
2
+ requestClose(): void;
3
+ dispose(): void;
4
+ save?: () => Promise<void>;
5
+ readonly fileEdit?: {
6
+ directory: FileSystemDirectoryHandle;
7
+ path: string;
8
+ isDirty(): boolean;
9
+ readUnsaved(): Uint8Array | undefined;
10
+ save(): Promise<void>;
11
+ };
12
+ }
13
+
1
14
  export interface FilePreviewRequest {
2
15
  reference: {providerId: string; documentId: string};
3
16
  filename: string;
4
17
  title: string;
5
18
  transient: true;
6
- mount(element: HTMLElement, close: () => void): {requestClose(): void; dispose(): void};
19
+ mount(element: HTMLElement, close: () => void, onSaveAvailable?: () => void): FilePreviewSession;
7
20
  }
8
21
 
9
22
  export type FileBaseline = {branch: string | undefined; head: string | null; bytes: Uint8Array | null};
@@ -54,7 +67,7 @@ export function createFilePreview(directory: FileSystemDirectoryHandle, document
54
67
  filename: name,
55
68
  title: name,
56
69
  transient: true,
57
- mount(element, close) {
70
+ mount(element, close, onSaveAvailable) {
58
71
  const message = locale.toLowerCase().startsWith('ja') ? messages.ja : messages.en;
59
72
  const {ownerDocument: document} = element;
60
73
  const panel = document.createElement('div');
@@ -69,7 +82,7 @@ export function createFilePreview(directory: FileSystemDirectoryHandle, document
69
82
  let disposed = false;
70
83
  let url: string | undefined;
71
84
  let media: HTMLMediaElement | undefined;
72
- let textSession: ReturnType<FilePreviewRequest['mount']> | undefined;
85
+ let textSession: ReturnType<typeof import('./text-file-editor.js').mountTextFile> | undefined;
73
86
  const readHandle = () => fileAt(directory, path);
74
87
 
75
88
  const show = (node: HTMLElement) => status.replaceWith(node);
@@ -114,12 +127,17 @@ export function createFilePreview(directory: FileSystemDirectoryHandle, document
114
127
  }
115
128
  textSession = mountTextFile(panel, {
116
129
  path, extension, content, locale, limit: textLimit, readHandle, close,
117
- readBaseline: readBaseline && (() => readBaseline(directory, path, textLimit))
130
+ readBaseline: readBaseline && (() => readBaseline(directory, path, textLimit)),
131
+ hostSaveShortcut: Boolean(onSaveAvailable), onDirtyChange: onSaveAvailable
118
132
  });
119
133
  status.remove();
134
+ onSaveAvailable?.();
120
135
  };
121
136
  void load().catch(() => {if (!disposed) status.textContent = message.failed;});
122
137
  return {
138
+ get save() {return textSession?.save;},
139
+ get fileEdit() {return textSession && {directory, path, isDirty: textSession.isDirty,
140
+ readUnsaved: textSession.readUnsaved, save: textSession.save};},
123
141
  requestClose() {if (textSession) textSession.requestClose(); else close();},
124
142
  dispose() {
125
143
  disposed = true;
package/src/index.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import {FolderError} from './source.js';
2
2
  import {createFolderSession} from './session.js';
3
+ import {isProjectFolderEmpty} from './create-folder.js';
3
4
  import {registerFolder} from './folder-registry.js';
4
5
  import type {FolderHost, FolderVM, PickerWindow} from './session.js';
5
6
 
@@ -8,7 +9,7 @@ export type {ReloadTarget} from './block-reload.js';
8
9
  export {followProjectFolder} from './folder-registry.js';
9
10
  export type {FollowedFolder} from './folder-registry.js';
10
11
  export type {DeserializeBlocks} from './script-reload.js';
11
- export {createProjectFolder} from './create-folder.js';
12
+ export {createProjectFolder, projectFolderOverwriteWarning} from './create-folder.js';
12
13
 
13
14
  const messages = {
14
15
  en: {
@@ -261,16 +262,27 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
261
262
  return {
262
263
  openDirectory: (...args: Parameters<typeof session.openDirectory>) =>
263
264
  session.openDirectory(...args).finally(renderReload),
265
+ unsavedPaths: () => session.unsavedPaths(),
266
+ readUnsavedFile: (path: string) => session.readUnsavedFile(path),
267
+ subscribeEdits: (listener: () => void) => session.subscribeEdits(listener),
264
268
  save: () => session.save().finally(renderReload),
265
- createFromSnapshot({prepareFiles, directory, current = () => true}: {
269
+ createFromSnapshot({prepareFiles, collectEdits, directory, current = () => true}: {
266
270
  prepareFiles: () => Promise<ReadonlyMap<string, Uint8Array>>;
271
+ collectEdits?: () => Promise<void>;
267
272
  directory?: FileSystemDirectoryHandle;
268
273
  current?: () => boolean;
269
274
  }) {
275
+ const message = locale.startsWith('ja') ?
276
+ '指定されたフォルダは空ではありません。フォルダに保存されている内容が上書きされる場合があります。よろしいですか?' :
277
+ 'The selected folder is not empty. Contents in the folder may be overwritten. Continue?';
270
278
  return session.createFromSnapshot(async () => {
271
- if (directory) return directory;
272
279
  try {
273
- return await pickDirectory.call(view, {id: 'turbowarp-plus-project-folder', mode: 'readwrite'});
280
+ const selected = directory ?? await pickDirectory.call(view, {id: 'turbowarp-plus-project-folder', mode: 'readwrite'});
281
+ if (!current()) return null;
282
+ const overwrite = !await isProjectFolderEmpty(selected);
283
+ if (!current() || (overwrite && !view.confirm(message))) return null;
284
+ await collectEdits?.();
285
+ return current() ? {directory: selected, overwrite} : null;
274
286
  } catch (error) {
275
287
  if (error instanceof DOMException && error.name === 'AbortError') return null;
276
288
  throw error;