@kubohiroya/turbowarp-plus-editor-project-folder 0.9.2 → 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/dist/index.js CHANGED
@@ -343,6 +343,12 @@ var readerFor = (storage) => {
343
343
  storageReaders.set(storage, reader);
344
344
  return reader;
345
345
  };
346
+ var encodeJson = (value) => new TextEncoder().encode(`${JSON.stringify(value, null, 2)}\n`);
347
+ function saveManifest(source, added, removed) {
348
+ const value = JSON.parse(new TextDecoder().decode(source.files.get(manifestFile)));
349
+ const entries = value.archiveEntries.filter((name) => !removed.includes(name));
350
+ return encodeJson(_objectSpread2(_objectSpread2({}, value), {}, { archiveEntries: [...entries, ...added] }));
351
+ }
346
352
  function createFolderSession(vm, host) {
347
353
  let current = null;
348
354
  const listeners = /* @__PURE__ */ new Set();
@@ -565,6 +571,29 @@ function createFolderSession(vm, host) {
565
571
  }
566
572
  return paths;
567
573
  },
574
+ /** The bytes the next save would write, null for a deletion, or undefined when no preview is available. */
575
+ readUnsavedFile(path) {
576
+ if (!current || busy) return;
577
+ try {
578
+ const { result, extensionSave, added, removed } = planSave(current, snapshot());
579
+ if (path === "project.source.json" && result) return encodeJson(extensionSave.project);
580
+ if (path === "embedded-extensions.json" && extensionSave.manifestChanged) return encodeJson(extensionSave.embedded);
581
+ if (path === "sb3-source.json" && (added.length || removed.length)) return saveManifest(current.source, added.map(([name]) => name), removed);
582
+ if (path.startsWith("assets/")) {
583
+ var _added$find, _assetData;
584
+ const name = path.slice(7);
585
+ if (removed.includes(name)) return null;
586
+ const kind = (_added$find = added.find(([asset]) => asset === name)) === null || _added$find === void 0 ? void 0 : _added$find[1];
587
+ if (kind) return (_assetData = assetData(name, kind)) !== null && _assetData !== void 0 ? _assetData : void 0;
588
+ }
589
+ if (path.startsWith("extensions/")) {
590
+ const name = path.slice(11);
591
+ return extensionSave.removed.includes(name) ? null : extensionSave.writes.get(name);
592
+ }
593
+ } catch (error) {
594
+ if (!(error instanceof FolderError)) throw error;
595
+ }
596
+ },
568
597
  get canSave() {
569
598
  return current !== null;
570
599
  },
@@ -765,13 +794,7 @@ function createFolderSession(vm, host) {
765
794
  sourceRemoved: []
766
795
  };
767
796
  }
768
- const encoder = new TextEncoder();
769
- let manifest = null;
770
- if (added.size || removed.length) {
771
- const value = JSON.parse(new TextDecoder().decode(source.files.get(manifestFile)));
772
- value.archiveEntries = [...value.archiveEntries.filter((name) => !removed.includes(name)), ...added.keys()];
773
- manifest = encoder.encode(`${JSON.stringify(value, null, 2)}\n`);
774
- }
797
+ const manifest = added.size || removed.length ? saveManifest(source, added.keys(), removed) : null;
775
798
  const root = {
776
799
  directory: source.directory,
777
800
  files: source.files,
@@ -833,8 +856,8 @@ function createFolderSession(vm, host) {
833
856
  for (const [name, data] of added) await write(assets, name, data);
834
857
  for (const [name, data] of extensionSave.writes) await write(extensions, name, data);
835
858
  if (manifest) await write(root, manifestFile, manifest);
836
- if (extensionSave.manifestChanged) await write(root, extensionsFile, encoder.encode(`${JSON.stringify(extensionSave.embedded, null, 2)}\n`));
837
- if (result) await write(root, projectFile, encoder.encode(`${JSON.stringify(extensionSave.project, null, 2)}\n`));
859
+ if (extensionSave.manifestChanged) await write(root, extensionsFile, encodeJson(extensionSave.embedded));
860
+ if (result) await write(root, projectFile, encodeJson(extensionSave.project));
838
861
  } catch (error) {
839
862
  for (const restore of undo.reverse()) await restore().catch(() => {});
840
863
  throw error;
@@ -1162,6 +1185,9 @@ function mountProjectFolder({ vm, document, host, locale = "en", autoReload = tr
1162
1185
  });
1163
1186
  return {
1164
1187
  openDirectory: (...args) => session.openDirectory(...args).finally(renderReload),
1188
+ unsavedPaths: () => session.unsavedPaths(),
1189
+ readUnsavedFile: (path) => session.readUnsavedFile(path),
1190
+ subscribeEdits: (listener) => session.subscribeEdits(listener),
1165
1191
  save: () => session.save().finally(renderReload),
1166
1192
  createFromSnapshot({ prepareFiles, collectEdits, directory, current = () => true }) {
1167
1193
  const message = locale.startsWith("ja") ? "指定されたフォルダは空ではありません。フォルダに保存されている内容が上書きされる場合があります。よろしいですか?" : "The selected folder is not empty. Contents in the folder may be overwritten. Continue?";
package/dist/session.d.ts CHANGED
@@ -94,6 +94,8 @@ export declare function createFolderSession(vm: FolderVM, host: FolderHost): {
94
94
  subscribeEdits(listener: () => void): () => void;
95
95
  /** Files affected by the pending save. A save in progress still owns its baseline. */
96
96
  unsavedPaths(): ReadonlySet<string> | null;
97
+ /** The bytes the next save would write, null for a deletion, or undefined when no preview is available. */
98
+ readUnsavedFile(path: string): Uint8Array | null | undefined;
97
99
  readonly canSave: boolean;
98
100
  readonly busy: boolean;
99
101
  readonly reloadState: ReloadState;
@@ -29959,15 +29959,22 @@ function mountTextFile(parent, options) {
29959
29959
  EditorView.contentAttributes.of({ "aria-label": options.path }),
29960
29960
  keymap.of([...defaultKeymap, ...historyKeymap]),
29961
29961
  EditorView.updateListener.of((update) => {
29962
- if (update.docChanged) updateSaveState();
29962
+ if (update.docChanged) updateSaveState(void 0, true);
29963
29963
  })
29964
29964
  ]
29965
29965
  });
29966
29966
  const dirty = () => !view.state.doc.eq(savedDoc);
29967
29967
  const serialize = () => bom + (newline === "\n" ? view.state.doc.toString() : view.state.doc.toString().replace(/\n/gu, newline));
29968
- function updateSaveState(text = saving ? message.saving : dirty() ? message.unsaved : "") {
29969
- saveButton.disabled = saving || !dirty();
29968
+ let wasDirty = false;
29969
+ function updateSaveState(text = saving ? message.saving : dirty() ? message.unsaved : "", contentChanged = false) {
29970
+ const isDirty = dirty();
29971
+ saveButton.disabled = saving || !isDirty;
29970
29972
  setStatus(status, text);
29973
+ if (isDirty !== wasDirty || contentChanged && isDirty) {
29974
+ var _options$onDirtyChang;
29975
+ wasDirty = isDirty;
29976
+ (_options$onDirtyChang = options.onDirtyChange) === null || _options$onDirtyChang === void 0 || _options$onDirtyChang.call(options);
29977
+ }
29971
29978
  }
29972
29979
  async function unchanged(handle) {
29973
29980
  try {
@@ -30107,6 +30114,7 @@ function mountTextFile(parent, options) {
30107
30114
  };
30108
30115
  panel.addEventListener("keydown", (event) => {
30109
30116
  if (!(event.metaKey || event.ctrlKey) || event.key.toLowerCase() !== "s") return;
30117
+ if (options.hostSaveShortcut && panel.ownerDocument === document) return;
30110
30118
  event.preventDefault();
30111
30119
  event.stopPropagation();
30112
30120
  save();
@@ -30115,6 +30123,9 @@ function mountTextFile(parent, options) {
30115
30123
  showDiff(false);
30116
30124
  updateSaveState();
30117
30125
  return {
30126
+ save,
30127
+ isDirty: dirty,
30128
+ readUnsaved: () => !disposed && dirty() ? encoder.encode(serialize()) : void 0,
30118
30129
  requestClose() {
30119
30130
  if (!saving && (!dirty() || (browser === null || browser === void 0 ? void 0 : browser.confirm(message.close)))) options.close();
30120
30131
  },
@@ -9,8 +9,13 @@ type TextFileOptions = {
9
9
  readHandle(): Promise<FileSystemFileHandle>;
10
10
  readBaseline?(): Promise<FileBaseline | null>;
11
11
  close(): void;
12
+ hostSaveShortcut?: boolean;
13
+ onDirtyChange?(): void;
12
14
  };
13
15
  export declare function mountTextFile(parent: HTMLElement, options: TextFileOptions): {
16
+ save: () => Promise<void>;
17
+ isDirty: () => boolean;
18
+ readUnsaved: () => Uint8Array<ArrayBuffer> | undefined;
14
19
  requestClose(): void;
15
20
  dispose(): void;
16
21
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-plus-editor-project-folder",
3
- "version": "0.9.2",
3
+ "version": "0.9.3",
4
4
  "description": "Read and save expanded Scratch project folders in TurboWarp Plus Editor",
5
5
  "type": "module",
6
6
  "license": "MPL-2.0",
@@ -5,7 +5,7 @@ export const actionMessages = (locale = 'en') => locale.toLowerCase().startsWith
5
5
  actions: 'ファイルとフォルダの操作', rename: '名前を変更…', renameTitle: '名前を変更', delete: '削除…', deleteTitle: '削除',
6
6
  createFolder: '新規フォルダを作成', folderName: 'フォルダ名', newName: '新しい名前', cancel: 'キャンセル',
7
7
  remove: (name: string, folder: boolean) => folder ? `「${name}」とその中身を削除しますか?` : `「${name}」を削除しますか?`,
8
- stage: 'Git にステージ', unstage: 'Git のステージを解除',
8
+ stage: '次のコミットに含める', unstage: '次のコミットから外す',
9
9
  working: '処理中…', copyFailed: 'コピーできませんでした', filesOnly: 'ファイルをドロップしてください。',
10
10
  invalidName: 'この名前は使用できません。', exists: '同じ名前のファイルまたはフォルダがあります。',
11
11
  invalidDestination: 'このフォルダには移動できません。',
package/src/explorer.tsx CHANGED
@@ -39,6 +39,8 @@ export type ProjectFolderExplorerProps = {
39
39
  unsavedPaths?: ReadonlySet<string>;
40
40
  /** Changes after the folder contents have been saved or reloaded. */
41
41
  refreshKey?: number;
42
+ /** Case-insensitive search by file name or relative path. */
43
+ query?: string;
42
44
  /** Called when a file is opened with Enter, Space or a click. */
43
45
  onOpen?(entry: ExplorerEntry): void;
44
46
  /** The tree's accessible name. Defaults to "Project folder". */
@@ -51,15 +53,16 @@ export type ProjectFolderExplorerProps = {
51
53
 
52
54
  const messages = {
53
55
  en: {
54
- 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',
55
58
  noFolder: 'Open a project folder to show its files here.', open: 'Open Project Folder…',
56
59
  create: 'Create Project Folder', creating: 'Creating project folder…',
57
60
  createFailed: 'Could not create the project folder.',
58
61
  unavailable: 'File tabs are unavailable in this editor layout.',
59
62
  failed: 'This folder could not be read.', denied: 'Permission to read this folder was not granted.',
60
63
  separator: ', ',
61
- marks: {added: 'Added', modified: 'Modified', deleted: 'Deleted', untracked: 'Untracked'},
62
- 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',
63
66
  revisions: {committed: 'Committed', pushed: 'Pushed', merged: 'Pull request merged'},
64
67
  project: 'Project data', manifest: 'Folder manifest', extensions: 'Embedded extensions',
65
68
  assetsDirectory: 'Costume and sound files', extensionsDirectory: 'Extension files',
@@ -69,15 +72,16 @@ const messages = {
69
72
  stageSound: (name: string) => `Stage · sound ${name}`
70
73
  },
71
74
  ja: {
72
- label: '作品フォルダ', loading: '読み込んでいます…', empty: 'このフォルダは空です。',
75
+ label: '作品フォルダ', loading: '読み込んでいます…', empty: 'このフォルダは空です。', noMatches: '該当するファイルはありません。',
76
+ results: '検索結果',
73
77
  noFolder: 'プロジェクトフォルダを開くと、ここにファイルを表示します。', open: 'プロジェクトフォルダを開く…',
74
78
  create: 'プロジェクトフォルダを作成', creating: 'プロジェクトフォルダを作成しています…',
75
79
  createFailed: 'プロジェクトフォルダを作成できませんでした。',
76
80
  unavailable: 'このエディターのレイアウトではファイルをタブで開けません。',
77
81
  failed: 'このフォルダを読み込めません。', denied: 'このフォルダを読む許可がありません。',
78
82
  separator: '、',
79
- marks: {added: '追加', modified: '変更', deleted: '削除', untracked: '未追跡'},
80
- unsaved: '未保存の変更あり', staged: 'ステージ済み',
83
+ marks: {added: '新しいファイル', modified: '保存済・未コミットの変更', deleted: '削除', untracked: '未追跡'},
84
+ unsaved: '未保存の変更あり', staged: 'Git のインデックスに追加済み',
81
85
  revisions: {committed: 'コミット済み', pushed: 'プッシュ済み', merged: 'PR マージ済み'},
82
86
  project: '作品データ', manifest: '作品フォルダの目録', extensions: '埋め込み拡張の一覧',
83
87
  assetsDirectory: 'コスチュームと音のファイル', extensionsDirectory: '拡張のファイル',
@@ -136,7 +140,7 @@ export function describeProjectFolder(project: Project, locale?: string, {manife
136
140
  return descriptions;
137
141
  }
138
142
 
139
- 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};
140
144
  type Message = typeof messages.en;
141
145
  const rootId = '/';
142
146
  // '\0' cannot appear in a file name, so the error row never collides with a real entry.
@@ -154,6 +158,10 @@ const css = `.${prefix}{font:inherit;color:inherit}
154
158
  .${prefix}-item{display:grid;grid-template-columns:1em 20px minmax(0,1fr);align-items:center;gap:.2em .4em;
155
159
  width:100%;box-sizing:border-box;margin:0;border:0;border-radius:3px;
156
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}
157
165
  .${prefix}-item:hover{background:rgba(128,128,128,.12)}
158
166
  .${prefix}-item[aria-selected="true"]{background:rgba(128,128,128,.24)}
159
167
  .${prefix}-item:focus-visible{outline:2px solid currentColor;outline-offset:-2px}
@@ -165,12 +173,14 @@ background:repeating-conic-gradient(rgba(128,128,128,.22) 0 25%,transparent 0 50
165
173
  .${prefix}-label{grid-column:3;display:flex;align-items:center;gap:.4em;min-width:0}
166
174
  .${prefix}-filename{display:inline-flex;min-width:0}
167
175
  .${prefix}-name{overflow:hidden;text-overflow:ellipsis}
168
- .${prefix}-item[data-staged] .${prefix}-filename{font-weight:700}
169
- .${prefix}-item[data-revision="committed"] .${prefix}-filename{color:#174b9d;color:light-dark(#174b9d,#91c1ff)}
170
- .${prefix}-item[data-revision="pushed"] .${prefix}-filename{color:#67369a;color:light-dark(#67369a,#dfafff)}
171
- .${prefix}-item[data-revision="merged"] .${prefix}-filename{color:#17603e;color:light-dark(#17603e,#85e3ad)}
172
- .${prefix}-unsaved{flex:none}
173
- .${prefix}-mark{flex:none;font-size:.85em;padding:0 .3em;border:1px solid currentColor;border-radius:3px;opacity:.85}
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}
174
184
  .${prefix}-description{grid-column:3;min-width:0;padding:.2em .4em;border-radius:3px;background:rgba(128,128,128,.12);
175
185
  color:inherit;color:color-mix(in srgb,currentColor 78%,transparent);font-size:.75em;line-height:1.4;
176
186
  white-space:normal;overflow-wrap:anywhere}
@@ -264,6 +274,100 @@ function Icon({kind, path, readFile}: {kind: IconKind; path: string; readFile?:
264
274
  );
265
275
  }
266
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
+
267
371
  function Explorer({directory, locale, descriptions, marks, fileStatuses, unsavedPaths, refreshKey,
268
372
  onOpen, label, mutate, git, isCurrent}: ProjectFolderExplorerProps) {
269
373
  const message = messagesFor(locale);
@@ -303,6 +407,10 @@ function Explorer({directory, locale, descriptions, marks, fileStatuses, unsaved
303
407
  }
304
408
  return handle.getFile();
305
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);
306
414
  const tree = useTree<ExplorerNode>({
307
415
  rootItemId: rootId,
308
416
  initialState: {expandedItems: [], selectedItems: [], focusedItem: null},
@@ -311,7 +419,7 @@ function Explorer({directory, locale, descriptions, marks, fileStatuses, unsaved
311
419
  createLoadingItemData: () => ({name: '', path: '', kind: 'file'}),
312
420
  onPrimaryAction: item => {
313
421
  const data = item.getItemData();
314
- 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'});
315
423
  },
316
424
  onLoadedChildren: id => {if (id === rootId) setRootLoaded(true);},
317
425
  dataLoader: {
@@ -329,24 +437,25 @@ function Explorer({directory, locale, descriptions, marks, fileStatuses, unsaved
329
437
  }
330
438
  },
331
439
  getChildrenWithData: async id => {
440
+ const base = id === rootId ? '' : `${id}/`;
441
+ const missingChildren = deleted.get(id);
442
+ const nodes = new Map(missingChildren);
332
443
  try {
333
444
  const handle = await directoryAt(id);
334
- const base = id === rootId ? '' : `${id}/`;
335
- const nodes: ExplorerNode[] = [];
336
445
  for await (const entry of (handle as IterableDirectory).values()) {
337
446
  if (entry.name.toLowerCase() === '.git') continue;
338
447
  const path = base + entry.name;
339
448
  if (entry.kind === 'directory') handles.set(path, entry as FileSystemDirectoryHandle);
340
449
  else files.set(path, entry as FileSystemFileHandle);
341
- nodes.push({name: entry.name, path, kind: entry.kind});
450
+ nodes.set(path, {name: entry.name, path, kind: entry.kind});
342
451
  }
343
- loadedFolders.add(id);
344
- nodes.sort((a, b) => (a.kind === 'directory' ? 0 : 1) - (b.kind === 'directory' ? 0 : 1) ||
345
- collator.compare(a.name, b.name) || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
346
- return nodes.map(data => ({id: data.path, data}));
347
452
  } catch (error) {
348
- 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
+ }
349
456
  }
457
+ loadedFolders.add(id);
458
+ return [...nodes.values()].sort(compareNodes).map(data => ({id: data.path, data}));
350
459
  }
351
460
  },
352
461
  features: [asyncDataLoaderFeature, selectionFeature, hotkeysCoreFeature]
@@ -357,12 +466,18 @@ function Explorer({directory, locale, descriptions, marks, fileStatuses, unsaved
357
466
  tree.setMounted(true);
358
467
  return () => tree.setMounted(false);
359
468
  }, [tree]);
360
- const lastRefresh = React.useRef(refreshKey);
469
+ const lastRefresh = React.useRef({refreshKey, deleted});
361
470
  React.useEffect(() => {
362
- if (lastRefresh.current === refreshKey) return;
363
- lastRefresh.current = refreshKey;
364
- void Promise.all([...loadedFolders].map(id => tree.getItemInstance(id).invalidateChildrenIds(true)));
365
- }, [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]);
366
481
 
367
482
  const errorText = (error: unknown) => {
368
483
  if (error instanceof ExplorerFileError) return actions[error.code];
@@ -555,27 +670,27 @@ function Explorer({directory, locale, descriptions, marks, fileStatuses, unsaved
555
670
  };
556
671
  const renderItem = (item: ItemInstance<ExplorerNode>) => {
557
672
  const data = item.getItemData();
558
- const entry: ExplorerEntry | undefined = data?.path && data.kind !== 'error' ?
559
- {path: data.path, name: data.name, kind: data.kind} : undefined;
560
673
  const itemProps = item.getProps();
561
674
  const level = item.getItemMeta().level;
562
675
  const folder = item.isFolder();
563
676
  const expanded = folder && item.isExpanded();
564
677
  const status = data?.kind === 'file' ? fileStatuses?.get(data.path) : undefined;
565
678
  const unsaved = data?.kind === 'file' && unsavedPaths?.has(data.path);
566
- const mark = status?.change ?? (data && data.kind !== 'error' ? marks?.get(data.path) : undefined);
567
- 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;
568
682
  const description = data && data.kind !== 'error' ? descriptions?.get(data.path) : undefined;
569
683
  const icon = !data || data.kind === 'error' ? undefined :
570
684
  folder ? (expanded ? 'folder-open' : 'folder') : iconFor(data.name);
571
- const accessibleName = [item.getItemName(), unsaved && message.unsaved, status?.staged && message.staged,
572
- 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);
573
687
  const moveDestination = entry?.kind === 'directory' && move?.destinations.has(entry.path);
574
688
  const moveActive = moveDestination && drag === entry.path;
575
689
  const rows = [
576
690
  <button {...itemProps} key={item.getId()} type="button" aria-label={accessibleName}
577
691
  className={`${prefix}-item${data?.kind === 'error' ? ` ${prefix}-error` : ''}`} style={indent(level)}
578
692
  data-path={data?.path} data-staged={status?.staged ? '' : undefined} data-revision={status?.revision}
693
+ aria-disabled={change === 'deleted' && !folder ? true : undefined}
579
694
  title={accessibleName || undefined}
580
695
  data-drop-directory={entry?.kind === 'directory' ? entry.path : entry ? parentPath(entry.path) : undefined}
581
696
  data-drop-active={entry?.kind === 'directory' && drag === entry.path ? '' : undefined}
@@ -592,13 +707,12 @@ function Explorer({directory, locale, descriptions, marks, fileStatuses, unsaved
592
707
  else itemProps.onKeyDown?.(event);
593
708
  } : itemProps.onKeyDown}>
594
709
  <span className={`${prefix}-caret`} aria-hidden="true">{folder ? (expanded ? '▾' : '▸') : ''}</span>
595
- {icon ? <Icon kind={icon} path={data!.path} readFile={icon === 'image' ? readFile : undefined} /> : null}
710
+ {icon ? <Icon kind={icon} path={data!.path} readFile={icon === 'image' && change !== 'deleted' ? readFile : undefined} /> : null}
596
711
  <span className={`${prefix}-label`}>
597
712
  <span className={`${prefix}-filename`}>
598
- <span className={`${prefix}-name`}>{item.getItemName()}</span>
599
- {unsaved ? <span className={`${prefix}-unsaved`} aria-hidden="true">*</span> : null}
713
+ <span className={`${prefix}-name`} data-git-change={change} data-revision={status?.revision}>{item.getItemName()}</span>
714
+ <FileStatusMarkers unsaved={unsaved} change={change}/>
600
715
  </span>
601
- {markLabel ? <span className={`${prefix}-mark`} aria-hidden="true">{markLabel}</span> : null}
602
716
  </span>
603
717
  {description ? <span className={`${prefix}-description`} aria-hidden="true">{description}</span> : null}
604
718
  </button>
@@ -677,7 +791,11 @@ const keyFor = (directory: FileSystemDirectoryHandle) => {
677
791
  */
678
792
  export function ProjectFolderExplorer(props: ProjectFolderExplorerProps) {
679
793
  // A new directory starts a new tree, so cached entries and expanded folders never leak between folders.
680
- 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>;
681
799
  }
682
800
 
683
801
  /** Follows marks for the files under `directory`, by path relative to it. Returns the function that stops it. */
@@ -692,6 +810,9 @@ type FolderViewProps = {
692
810
  createFolder?(): Promise<unknown>;
693
811
  marks?: FollowMarks;
694
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;
695
816
  git?: FollowExplorerGit;
696
817
  /** Opens a transient file tab in the host workspace. */
697
818
  openFile?(request: FilePreviewRequest): boolean;
@@ -704,7 +825,7 @@ const readJson = async (directory: FileSystemDirectoryHandle, name: string): Pro
704
825
  JSON.parse(await (await (await directory.getFileHandle(name)).getFile()).text());
705
826
 
706
827
  function FolderView({vm, locale = 'en', marks: followMarks, fileStatuses: followStatuses, git: followGit,
707
- openFile, readBaseline, createFolder}: FolderViewProps) {
828
+ openFile, readBaseline, query, followFileEdits, createFolder}: FolderViewProps) {
708
829
  const message = messagesFor(locale);
709
830
  const [creating, setCreating] = React.useState(false);
710
831
  const [createError, setCreateError] = React.useState('');
@@ -764,6 +885,11 @@ function FolderView({vm, locale = 'en', marks: followMarks, fileStatuses: follow
764
885
  const stop = folder.subscribeEdits(schedule);
765
886
  return () => {stop(); clearTimeout(timer);};
766
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]);
767
893
  const [git, setGit] = React.useState<{directory: FileSystemDirectoryHandle; actions?: ExplorerGit}>();
768
894
  React.useEffect(() => {
769
895
  if (!directory || !followGit) return;
@@ -784,10 +910,12 @@ function FolderView({vm, locale = 'en', marks: followMarks, fileStatuses: follow
784
910
  </>}
785
911
  </div>;
786
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);
787
915
  return <>
788
916
  <ProjectFolderExplorer directory={directory} locale={locale} descriptions={descriptions} marks={marks}
789
- refreshKey={version} fileStatuses={statuses?.directory === directory ? statuses.paths : undefined}
790
- unsavedPaths={unsaved?.directory === directory ? unsaved.paths : undefined}
917
+ refreshKey={version} query={query} fileStatuses={statuses?.directory === directory ? statuses.paths : undefined}
918
+ unsavedPaths={unsavedPaths}
791
919
  mutate={operation => folder.mutate(directory, operation)} isCurrent={() => folder.directory === directory}
792
920
  git={git?.directory === directory ? git.actions : undefined}
793
921
  onOpen={openFile && (entry => {
@@ -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
@@ -262,6 +262,9 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
262
262
  return {
263
263
  openDirectory: (...args: Parameters<typeof session.openDirectory>) =>
264
264
  session.openDirectory(...args).finally(renderReload),
265
+ unsavedPaths: () => session.unsavedPaths(),
266
+ readUnsavedFile: (path: string) => session.readUnsavedFile(path),
267
+ subscribeEdits: (listener: () => void) => session.subscribeEdits(listener),
265
268
  save: () => session.save().finally(renderReload),
266
269
  createFromSnapshot({prepareFiles, collectEdits, directory, current = () => true}: {
267
270
  prepareFiles: () => Promise<ReadonlyMap<string, Uint8Array>>;