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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts CHANGED
@@ -8,6 +8,7 @@ export type {ReloadTarget} from './block-reload.js';
8
8
  export {followProjectFolder} from './folder-registry.js';
9
9
  export type {FollowedFolder} from './folder-registry.js';
10
10
  export type {DeserializeBlocks} from './script-reload.js';
11
+ export {createProjectFolder} from './create-folder.js';
11
12
 
12
13
  const messages = {
13
14
  en: {
@@ -235,7 +236,12 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
235
236
  save(locale) {
236
237
  if (!session.busy) {
237
238
  const message = messageFor(locale);
238
- void session.save().then(({status, sourceRemoved}) => {
239
+ const directory = session.directory;
240
+ const save = () => {
241
+ if (session.directory !== directory) throw new FolderError('conflict');
242
+ return session.save();
243
+ };
244
+ void (host.saveWithLock?.(save) ?? save()).then(({status, sourceRemoved}) => {
239
245
  const detail = sourceRemoved.length ? ` ${message.sourceRemoved(sourceRemoved)}` : '';
240
246
  report(message[status] + detail);
241
247
  }, error => fail(locale, error)).finally(renderReload);
@@ -247,11 +253,30 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
247
253
  const unregister = registerFolder(vm, {
248
254
  get directory() {return session.directory;},
249
255
  subscribe: listener => session.subscribe(listener),
250
- open: locale => menu.open(locale)
256
+ subscribeEdits: listener => session.subscribeEdits(listener),
257
+ unsavedPaths: () => session.unsavedPaths(),
258
+ open: locale => menu.open(locale),
259
+ mutate: (directory, operation) => session.mutate(directory, operation).finally(renderReload)
251
260
  });
252
261
  return {
253
262
  openDirectory: (...args: Parameters<typeof session.openDirectory>) =>
254
263
  session.openDirectory(...args).finally(renderReload),
264
+ save: () => session.save().finally(renderReload),
265
+ createFromSnapshot({prepareFiles, directory, current = () => true}: {
266
+ prepareFiles: () => Promise<ReadonlyMap<string, Uint8Array>>;
267
+ directory?: FileSystemDirectoryHandle;
268
+ current?: () => boolean;
269
+ }) {
270
+ return session.createFromSnapshot(async () => {
271
+ if (directory) return directory;
272
+ try {
273
+ return await pickDirectory.call(view, {id: 'turbowarp-plus-project-folder', mode: 'readwrite'});
274
+ } catch (error) {
275
+ if (error instanceof DOMException && error.name === 'AbortError') return null;
276
+ throw error;
277
+ }
278
+ }, prepareFiles, current).finally(renderReload);
279
+ },
255
280
  /**
256
281
  * The folder the loaded project came from, or `null` once another project loaded or the folder was
257
282
  * detached. A host can tell projects apart by it, for example to keep the layout of each one.
package/src/session.ts CHANGED
@@ -5,6 +5,7 @@ import {applyBlockReload, planBlockReload} from './block-reload.js';
5
5
  import type {ReloadTarget} from './block-reload.js';
6
6
  import {applyScriptReload, planScriptReload} from './script-reload.js';
7
7
  import type {DeserializeBlocks, ScriptReloadTarget} from './script-reload.js';
8
+ import {createProjectFolder} from './create-folder.js';
8
9
 
9
10
  export interface FolderVM {
10
11
  runtime: {
@@ -44,6 +45,7 @@ export interface FolderHost {
44
45
  beforeLoad(): void;
45
46
  onOpened(title: string): void;
46
47
  onSaved(): void;
48
+ saveWithLock?<T>(save: () => Promise<T>): Promise<T>;
47
49
  blockReload?: {
48
50
  isRunning(): boolean;
49
51
  subscribe(listener: () => void): () => void;
@@ -149,7 +151,18 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
149
151
  }
150
152
  return null;
151
153
  };
152
- const changed = () => {revision++;};
154
+ const editListeners = new Set<() => void>();
155
+ const notifyEdits = () => {for (const listener of [...editListeners]) listener();};
156
+ const changed = () => {revision++; notifyEdits();};
157
+ const planSave = (session: Session, edited: Project) => {
158
+ const {source} = session;
159
+ const result = projectChanges(source.project, session.baseline, edited, identity(session, edited));
160
+ const extensionSave = planExtensionSave(source, result ?? source.project);
161
+ const needed = projectAssets(extensionSave.project);
162
+ const added = [...needed].filter(([name]) => !source.bytes.has(name));
163
+ const removed = [...source.bytes.keys()].filter(name => !needed.has(name));
164
+ return {result, extensionSave, added, removed};
165
+ };
153
166
  const loaded = () => setCurrent(null);
154
167
  vm.runtime.on('PROJECT_LOADED', loaded);
155
168
  vm.on('PROJECT_CHANGED', changed);
@@ -162,12 +175,16 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
162
175
  disposed = true;
163
176
  setCurrent(null);
164
177
  listeners.clear();
178
+ editListeners.clear();
165
179
  vm.runtime.off('PROJECT_LOADED', loaded);
166
180
  vm.off('PROJECT_CHANGED', changed);
167
181
  };
168
182
  const openFrom = async (
169
183
  getDirectory: () => Promise<FileSystemDirectoryHandle | null>,
170
- confirmReplace: () => boolean
184
+ confirmReplace: () => boolean,
185
+ prepare: (directory: FileSystemDirectoryHandle) => Promise<FolderSource | null> =
186
+ directory => readFolder(directory, vm.runtime.storage),
187
+ stillCurrent = () => true
171
188
  ): Promise<OpenResult> => {
172
189
  if (disposed || busy) return 'cancelled';
173
190
  busy = true;
@@ -176,8 +193,8 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
176
193
  const directory = await getDirectory();
177
194
  if (!directory || disposed) return 'cancelled';
178
195
  const storage = vm.runtime.storage;
179
- const source = await readFolder(directory, storage);
180
- if (disposed || vm.runtime.getTargetForStage() !== priorStage) return 'cancelled';
196
+ const source = await prepare(directory);
197
+ if (!source || disposed || !stillCurrent() || vm.runtime.getTargetForStage() !== priorStage) return 'cancelled';
181
198
  if (host.isProjectDirty() && !confirmReplace()) return 'cancelled';
182
199
  host.beforeLoad();
183
200
  setCurrent(null);
@@ -246,6 +263,28 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
246
263
  listeners.add(listener);
247
264
  return () => {listeners.delete(listener);};
248
265
  },
266
+ subscribeEdits(listener: () => void) {
267
+ editListeners.add(listener);
268
+ return () => {editListeners.delete(listener);};
269
+ },
270
+ /** Files affected by the pending save. A save in progress still owns its baseline. */
271
+ unsavedPaths(): ReadonlySet<string> | null {
272
+ if (busy) return null;
273
+ const paths = new Set<string>();
274
+ if (!current) return paths;
275
+ try {
276
+ const {result, extensionSave, added, removed} = planSave(current, snapshot());
277
+ if (result) paths.add(projectFile);
278
+ if (extensionSave.manifestChanged) paths.add(extensionsFile);
279
+ if (added.length || removed.length) paths.add(manifestFile);
280
+ for (const name of [...added.map(([name]) => name), ...removed]) paths.add(`assets/${name}`);
281
+ for (const name of [...extensionSave.writes.keys(), ...extensionSave.removed]) paths.add(`extensions/${name}`);
282
+ } catch (error) {
283
+ if (!(error instanceof FolderError)) throw error;
284
+ if (host.isProjectDirty()) paths.add(projectFile);
285
+ }
286
+ return paths;
287
+ },
249
288
  get canSave() {return current !== null;},
250
289
  get busy() {return busy;},
251
290
  get reloadState() {return reloadState();},
@@ -266,6 +305,19 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
266
305
  return typeof pending === 'object' && pending !== null ? pending.update.version : null;
267
306
  },
268
307
  get directory() {return current?.source.directory ?? null;},
308
+ async mutate(directory: FileSystemDirectoryHandle, operation: (guard: () => void) => Promise<void>) {
309
+ const session = current;
310
+ if (!session || busy || session.source.directory !== directory) throw new FolderError('conflict');
311
+ const guard = () => active(session);
312
+ guard();
313
+ busy = true;
314
+ try {
315
+ await operation(guard);
316
+ } finally {
317
+ busy = false;
318
+ if (current === session) notify();
319
+ }
320
+ },
269
321
  /**
270
322
  * Reads what to compare before unsaved edits are replaced. `editor` is `null` when the edits cannot be
271
323
  * written to the folder, and `disk` when the folder's project file cannot be read.
@@ -334,9 +386,11 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
334
386
  session.source.versions.set(projectFile, pending.update.version);
335
387
  session.pending = null;
336
388
  host.blockReload.onApplied(targets);
389
+ notify();
337
390
  return true;
338
391
  } finally {
339
392
  busy = false;
393
+ notifyEdits();
340
394
  }
341
395
  },
342
396
  /**
@@ -363,6 +417,20 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
363
417
  openDirectory(directory: FileSystemDirectoryHandle, confirmReplace: () => boolean): Promise<OpenResult> {
364
418
  return openFrom(() => Promise.resolve(directory), confirmReplace);
365
419
  },
420
+ createFromSnapshot(getDirectory: () => Promise<FileSystemDirectoryHandle | null>,
421
+ prepareFiles: () => Promise<ReadonlyMap<string, Uint8Array>>, isCurrent: () => boolean): Promise<OpenResult> {
422
+ const stage = vm.runtime.getTargetForStage();
423
+ let savedRevision: number | undefined;
424
+ const currentProject = () => !disposed && vm.runtime.getTargetForStage() === stage &&
425
+ (savedRevision === undefined || revision === savedRevision) && isCurrent();
426
+ return openFrom(getDirectory, currentProject, async directory => {
427
+ if (!currentProject()) return null;
428
+ savedRevision = revision;
429
+ const files = await prepareFiles();
430
+ if (!currentProject()) return null;
431
+ return createProjectFolder({directory, files, storage: vm.runtime.storage, current: currentProject});
432
+ }, currentProject);
433
+ },
366
434
  async save(): Promise<SaveResult> {
367
435
  if (!current || busy) throw new FolderError('conflict');
368
436
  const session = current;
@@ -372,15 +440,12 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
372
440
  const saveRevision = revision;
373
441
  const edited = snapshot();
374
442
  const ids = identify(edited);
375
- const result = projectChanges(session.source.project, session.baseline, edited, identity(session, edited));
443
+ const {result, extensionSave, added: newAssets, removed} = planSave(session, edited);
376
444
  await assertFolderUnchanged(session.source);
377
445
  active(session);
378
446
  const {source} = session;
379
- const extensionSave = planExtensionSave(source, result ?? source.project);
380
- const needed = projectAssets(extensionSave.project);
381
447
  const added = new Map<string, Uint8Array>();
382
- for (const [name, kind] of needed) {
383
- if (source.bytes.has(name)) continue;
448
+ for (const [name, kind] of newAssets) {
384
449
  const data = assetData(name, kind);
385
450
  if (!data) return unsupported(`The data of ${name} is not in the Editor`);
386
451
  const [id, format] = name.split('.');
@@ -388,7 +453,6 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
388
453
  if (asset.assetId !== id) return unsupported(`Asset hash mismatch: ${name}`);
389
454
  added.set(name, data);
390
455
  }
391
- const removed = [...source.bytes.keys()].filter(name => !needed.has(name));
392
456
  if (!result && !removed.length && !extensionSave.removed.length) {
393
457
  if (revision === saveRevision) host.onSaved();
394
458
  notify();
@@ -403,8 +467,8 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
403
467
  manifest = encoder.encode(`${JSON.stringify(value, null, 2)}\n`);
404
468
  }
405
469
  const root = {directory: source.directory, files: source.files, prefix: ''};
406
- const assets = {directory: await source.directory.getDirectoryHandle('assets'), files: source.bytes, prefix: 'assets/'};
407
- const extensions = {directory: await source.directory.getDirectoryHandle('extensions'),
470
+ const assets = {directory: await source.directory.getDirectoryHandle('assets', {create: true}), files: source.bytes, prefix: 'assets/'};
471
+ const extensions = {directory: await source.directory.getDirectoryHandle('extensions', {create: true}),
408
472
  files: source.extensionBytes, prefix: 'extensions/'};
409
473
  const undo: (() => Promise<void>)[] = [];
410
474
  const write = async ({directory, files, prefix}: SaveDirectory, name: string, data: Uint8Array) => {
@@ -489,6 +553,7 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
489
553
  return {status: 'saved', sourceRemoved: extensionSave.sourceRemoved};
490
554
  } finally {
491
555
  busy = false;
556
+ notifyEdits();
492
557
  }
493
558
  },
494
559
  dispose
package/src/source.ts CHANGED
@@ -67,12 +67,14 @@ export type FolderSource = FolderFiles & {
67
67
  embedded: ExtensionManifest;
68
68
  };
69
69
 
70
- const getFile = async (dir: FileSystemDirectoryHandle, name: string) => (await dir.getFileHandle(name)).getFile();
70
+ const getFile = async (dir: FileSystemDirectoryHandle | null, name: string) =>
71
+ dir ? (await dir.getFileHandle(name)).getFile() : unsupported(`Missing folder for ${name}`);
71
72
  export const fileVersion = (file: File) => `${file.size}:${file.lastModified}`;
72
73
  const fileBytes = async (file: File) => new Uint8Array(await file.arrayBuffer());
73
- const readBytes = async (dir: FileSystemDirectoryHandle, name: string) => fileBytes(await getFile(dir, name));
74
- const readNames = async (dir: FileSystemDirectoryHandle) => {
74
+ const readBytes = async (dir: FileSystemDirectoryHandle | null, name: string) => fileBytes(await getFile(dir, name));
75
+ const readNames = async (dir: FileSystemDirectoryHandle | null) => {
75
76
  const names = new Set<string>();
77
+ if (!dir) return names;
76
78
  // Directory iteration is available alongside the picker, but absent from older DOM typings.
77
79
  for await (const entry of (dir as FileSystemDirectoryHandle & {values(): AsyncIterable<FileSystemHandle>}).values()) {
78
80
  if (entry.kind !== 'file') return unsupported('Nested entries are outside the supported source format');
@@ -80,6 +82,11 @@ const readNames = async (dir: FileSystemDirectoryHandle) => {
80
82
  }
81
83
  return names;
82
84
  };
85
+ // Git does not retain empty asset or extension directories.
86
+ const readDirectory = (dir: FileSystemDirectoryHandle, name: string) => dir.getDirectoryHandle(name).catch(error => {
87
+ if (error instanceof DOMException && error.name === 'NotFoundError') return null;
88
+ throw error;
89
+ });
83
90
  const sameNames = (actual: Set<string>, expected: Iterable<string>) => {
84
91
  const expectedNames = new Set(expected);
85
92
  return actual.size === expectedNames.size && [...actual].every(name => expectedNames.has(name));
@@ -267,7 +274,7 @@ export function planExtensionSave(source: FolderSource, project: Project) {
267
274
 
268
275
  export async function readFolder(directory: FileSystemDirectoryHandle, storage: Storage): Promise<FolderSource> {
269
276
  const versions = new Map<string, string>();
270
- const readEntry = async (dir: FileSystemDirectoryHandle, name: string, prefix = '') => {
277
+ const readEntry = async (dir: FileSystemDirectoryHandle | null, name: string, prefix = '') => {
271
278
  const file = await getFile(dir, name);
272
279
  versions.set(prefix + name, fileVersion(file));
273
280
  return [name, await fileBytes(file)] as const;
@@ -291,7 +298,7 @@ export async function readFolder(directory: FileSystemDirectoryHandle, storage:
291
298
  return unsupported('Asset references and archiveEntries do not match');
292
299
  }
293
300
  expected.delete('project.json');
294
- const [assets, extensions] = await Promise.all([directory.getDirectoryHandle('assets'), directory.getDirectoryHandle('extensions')]);
301
+ const [assets, extensions] = await Promise.all([readDirectory(directory, 'assets'), readDirectory(directory, 'extensions')]);
295
302
  const scripts = extensionNames(extensionManifest.extensions);
296
303
  if (!sameNames(await readNames(assets), expected) || !sameNames(await readNames(extensions), scripts)) {
297
304
  return unsupported('Unexpected or missing source files');
@@ -325,7 +332,7 @@ export async function readFolderUpdate(source: FolderSource, previous: FolderUpd
325
332
  const {directory, versions} = source;
326
333
  try {
327
334
  const [assets, extensions, project] = await Promise.all([
328
- directory.getDirectoryHandle('assets'), directory.getDirectoryHandle('extensions'), getFile(directory, projectFile)
335
+ readDirectory(directory, 'assets'), readDirectory(directory, 'extensions'), getFile(directory, projectFile)
329
336
  ]);
330
337
  const [assetNames, extensionNames] = await Promise.all([readNames(assets), readNames(extensions)]);
331
338
  if (!sameNames(assetNames, source.bytes.keys()) || !sameNames(extensionNames, source.extensionBytes.keys())) return 'structure';
@@ -356,8 +363,9 @@ export async function readFolderUpdate(source: FolderSource, previous: FolderUpd
356
363
 
357
364
  export async function assertFolderUnchanged(source: FolderSource) {
358
365
  try {
359
- const assets = await source.directory.getDirectoryHandle('assets');
360
- const extensions = await source.directory.getDirectoryHandle('extensions');
366
+ const [assets, extensions] = await Promise.all([
367
+ readDirectory(source.directory, 'assets'), readDirectory(source.directory, 'extensions')
368
+ ]);
361
369
  if (!sameNames(await readNames(assets), source.bytes.keys()) ||
362
370
  !sameNames(await readNames(extensions), source.extensionBytes.keys())) throw new FolderError('conflict');
363
371
  for (const [directory, files] of [[source.directory, source.files], [assets, source.bytes], [extensions, source.extensionBytes]] as const) {
@@ -0,0 +1,356 @@
1
+ import {defaultKeymap, history, historyKeymap} from '@codemirror/commands';
2
+ import {css} from '@codemirror/lang-css';
3
+ import {html} from '@codemirror/lang-html';
4
+ import {javascript} from '@codemirror/lang-javascript';
5
+ import {json} from '@codemirror/lang-json';
6
+ import {markdown} from '@codemirror/lang-markdown';
7
+ import {python} from '@codemirror/lang-python';
8
+ import {xml} from '@codemirror/lang-xml';
9
+ import {yaml} from '@codemirror/lang-yaml';
10
+ import {HighlightStyle, StreamLanguage, syntaxHighlighting} from '@codemirror/language';
11
+ import {shell} from '@codemirror/legacy-modes/mode/shell';
12
+ import {MergeView} from '@codemirror/merge';
13
+ import {EditorState} from '@codemirror/state';
14
+ import {drawSelection, EditorView, highlightActiveLine, highlightSpecialChars, keymap, lineNumbers} from '@codemirror/view';
15
+ import {tags} from '@lezer/highlight';
16
+ import type {FileBaseline} from './file-preview.js';
17
+
18
+ const decoder = new TextDecoder('utf-8', {fatal: true, ignoreBOM: true});
19
+ const encoder = new TextEncoder();
20
+
21
+ export function decodeText(bytes: ArrayBuffer | Uint8Array): string | null {
22
+ try {
23
+ const content = decoder.decode(bytes as ArrayBuffer | Uint8Array<ArrayBuffer>);
24
+ return /[\u0000-\u0008\u000b\u000e-\u001f\u007f]/u.test(content) ? null : content;
25
+ } catch {
26
+ return null;
27
+ }
28
+ }
29
+
30
+ const languageFor = (extension: string) => {
31
+ switch (extension) {
32
+ case 'js': case 'mjs': case 'cjs': return javascript();
33
+ case 'jsx': return javascript({jsx: true});
34
+ case 'ts': case 'mts': case 'cts': return javascript({typescript: true});
35
+ case 'tsx': return javascript({typescript: true, jsx: true});
36
+ case 'json': case 'jsonc': return json();
37
+ case 'yaml': case 'yml': return yaml();
38
+ case 'md': case 'markdown': return markdown();
39
+ case 'html': case 'htm': return html();
40
+ case 'css': return css();
41
+ case 'xml': return xml();
42
+ case 'py': return python();
43
+ case 'sh': case 'bash': return StreamLanguage.define(shell);
44
+ default: return [];
45
+ }
46
+ };
47
+
48
+ const highlighting = syntaxHighlighting(HighlightStyle.define([
49
+ {tag: [tags.comment, tags.quote], class: 'twpf-syntax-comment'},
50
+ {tag: [tags.keyword, tags.bool, tags.null, tags.meta], class: 'twpf-syntax-keyword'},
51
+ {tag: [tags.string, tags.regexp], class: 'twpf-syntax-string'},
52
+ {tag: [tags.propertyName, tags.attributeName, tags.tagName, tags.heading], class: 'twpf-syntax-name'},
53
+ {tag: [tags.number, tags.atom, tags.literal], class: 'twpf-syntax-number'}
54
+ ]));
55
+
56
+ const styles = `
57
+ .twpf-text-file{display:flex;flex-direction:column;height:100%;min-height:0;font:inherit}
58
+ .twpf-file-toolbar,.twpf-diff-toolbar{display:flex;align-items:center;flex-wrap:wrap;gap:.4rem;padding:.5rem .7rem;
59
+ border-bottom:1px solid var(--ui-black-transparent,rgba(128,128,128,.25))}
60
+ .twpf-file-path{font-size:.83em;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;margin-inline-end:auto;min-width:0}
61
+ .twpf-file-actions{display:flex;gap:.25rem}
62
+ .twpf-text-file button{font:inherit;font-size:.85em;color:inherit;background:transparent;border:1px solid
63
+ var(--ui-black-transparent,rgba(128,128,128,.45));border-radius:.3rem;padding:.25rem .55rem;cursor:pointer}
64
+ .twpf-text-file button[aria-pressed=true]{background:var(--motion-primary,#2468b7);border-color:transparent;color:#fff}
65
+ .twpf-text-file button:disabled{opacity:.55;cursor:default}
66
+ .twpf-file-status,.twpf-diff-status{margin:0;padding:.35rem .7rem;font-size:.82em}
67
+ .twpf-file-edit,.twpf-file-diff{flex:1;min-height:0}
68
+ .twpf-file-edit>.cm-editor{height:100%}
69
+ .twpf-file-diff{display:flex;flex-direction:column}
70
+ .twpf-text-file [hidden]{display:none}
71
+ .twpf-diff-headings{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));font-size:.83em;
72
+ border-bottom:1px solid var(--ui-black-transparent,rgba(128,128,128,.25))}
73
+ .twpf-diff-headings span{padding:.4rem .7rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
74
+ .twpf-diff-content{flex:1;min-height:0;overflow:auto}
75
+ .twpf-diff-content .cm-mergeViewEditor+.cm-mergeViewEditor{border-inline-start:1px solid var(--ui-black-transparent,rgba(128,128,128,.25))}
76
+ .twpf-text-file .cm-content{font:.875rem/1.55 monospace}
77
+ .twpf-text-file .cm-gutters{background:transparent;color:inherit;border-color:rgba(128,128,128,.25);font:.78rem/1.74 monospace}
78
+ .twpf-text-file .cm-activeLine,.twpf-text-file .cm-activeLineGutter{background:rgba(128,128,128,.12)}
79
+ .twpf-text-file .cm-collapsedLines{color:inherit;background:rgba(128,128,128,.12);border-color:rgba(128,128,128,.24)}
80
+ .twpf-syntax-comment{color:light-dark(#586576,#a6b0bc)}
81
+ .twpf-syntax-keyword{color:light-dark(#80359b,#dda7ef)}
82
+ .twpf-syntax-string{color:light-dark(#1b6c45,#9ddaac)}
83
+ .twpf-syntax-name{color:light-dark(#145e97,#99cfff)}
84
+ .twpf-syntax-number{color:light-dark(#8d440e,#f0b28a)}
85
+ `;
86
+
87
+ const messages = {
88
+ en: {
89
+ edit: 'Edit', diff: 'Diff', changes: 'Changes only', whole: 'Full file', refresh: 'Reload latest commit',
90
+ save: 'Save file', unsaved: 'Unsaved changes', saving: 'Saving…', saved: 'File saved.',
91
+ conflict: 'The file changed outside this tab. Your edits are still here. Reopen the file to load the current version.',
92
+ saveFailed: 'The file could not be saved.', tooLarge: 'The text file exceeds the 4 MiB limit.',
93
+ close: 'Discard the unsaved edits to this file?', loading: 'Reading the latest commit…',
94
+ noGit: 'No accessible Git repository for this file. Select its repository in Local Git to compare.',
95
+ readFailed: 'The committed version could not be read.', unsupported: 'The committed version is not a UTF-8 text file.',
96
+ missing: 'This file is not in the latest commit.', unborn: 'This branch has no commits yet.',
97
+ same: 'No differences.', formatting: 'The line endings or UTF-8 BOM differ.',
98
+ before: 'Latest commit', after: 'Current content', collapsed: '$ unchanged lines'
99
+ },
100
+ ja: {
101
+ edit: '編集', diff: '差分', changes: '変更箇所のみ', whole: '全体', refresh: '最新コミットを読み直す',
102
+ save: 'ファイルを保存', unsaved: '未保存の変更があります', saving: '保存中…', saved: 'ファイルを保存しました。',
103
+ conflict: 'ファイルがこのタブの外で変更されました。編集内容はタブに残っています。現在の内容を読むにはファイルを開き直してください。',
104
+ saveFailed: 'ファイルを保存できませんでした。', tooLarge: 'テキストファイルの上限(4 MiB)を超えています。',
105
+ close: 'このファイルの未保存の編集を破棄しますか?', loading: '最新コミットを読み込んでいます…',
106
+ noGit: 'このファイルの Git リポジトリを参照できません。比較するにはローカル Git でリポジトリを選んでください。',
107
+ readFailed: 'コミット済みの内容を読み込めませんでした。', unsupported: 'コミット済みの内容は UTF-8 テキストとして表示できません。',
108
+ missing: '最新コミットにこのファイルはありません。', unborn: 'このブランチにはまだコミットがありません。',
109
+ same: '差分はありません。', formatting: '改行コードまたは UTF-8 BOM が異なります。',
110
+ before: '最新コミット', after: '現在の内容', collapsed: '変更のない $ 行'
111
+ }
112
+ };
113
+
114
+ type TextFileOptions = {
115
+ path: string;
116
+ extension: string;
117
+ content: string;
118
+ locale: string;
119
+ limit: number;
120
+ readHandle(): Promise<FileSystemFileHandle>;
121
+ readBaseline?(): Promise<FileBaseline | null>;
122
+ close(): void;
123
+ };
124
+
125
+ export function mountTextFile(parent: HTMLElement, options: TextFileOptions) {
126
+ const {ownerDocument: document} = parent;
127
+ const browser = document.defaultView;
128
+ const message = options.locale.toLowerCase().startsWith('ja') ? messages.ja : messages.en;
129
+ const element = <Tag extends 'div' | 'span' | 'p'>(tag: Tag, className: string) => {
130
+ const node = document.createElement(tag);
131
+ node.className = className;
132
+ return node;
133
+ };
134
+ const button = (label: string, action: () => void) => {
135
+ const node = document.createElement('button');
136
+ node.type = 'button';
137
+ node.textContent = label;
138
+ node.addEventListener('click', action);
139
+ return node;
140
+ };
141
+ const press = (node: HTMLButtonElement, active: boolean) => node.setAttribute('aria-pressed', String(active));
142
+ const setStatus = (node: HTMLElement, text: string) => {node.textContent = text; node.hidden = !text;};
143
+ const panel = element('div', 'twpf-text-file');
144
+ const style = document.createElement('style');
145
+ style.textContent = styles;
146
+ const toolbar = element('div', 'twpf-file-toolbar');
147
+ const path = element('span', 'twpf-file-path');
148
+ path.textContent = path.title = options.path;
149
+ const status = element('p', 'twpf-file-status');
150
+ status.setAttribute('role', 'status');
151
+ const editPane = element('div', 'twpf-file-edit');
152
+ const diffPane = element('div', 'twpf-file-diff');
153
+ const diffToolbar = element('div', 'twpf-diff-toolbar');
154
+ const headings = element('div', 'twpf-diff-headings');
155
+ const left = element('span', '');
156
+ const right = element('span', '');
157
+ right.textContent = message.after;
158
+ headings.append(left, right);
159
+ const diffStatus = element('p', 'twpf-diff-status');
160
+ diffStatus.setAttribute('role', 'status');
161
+ const diffContent = element('div', 'twpf-diff-content');
162
+ diffPane.append(diffToolbar, diffStatus, headings, diffContent);
163
+
164
+ let saved = options.content;
165
+ const bom = saved.startsWith('\uFEFF') ? '\uFEFF' : '';
166
+ const initial = saved.slice(bom.length);
167
+ const hasLF = initial.includes('\n');
168
+ const hasCR = initial.includes('\r');
169
+ const mixed = hasLF && hasCR && /(^|[^\r])\n|\r(?!\n)/u.test(initial);
170
+ // When LF and CRLF are mixed, keep CRs in existing lines and use LF for new lines.
171
+ const newline = hasCR && !mixed ? hasLF ? '\r\n' : '\r' : '\n';
172
+ const common = [lineNumbers(), languageFor(options.extension), highlighting];
173
+ let savedDoc = EditorState.create({doc: initial, extensions: mixed ? EditorState.lineSeparator.of('\n') : []}).doc;
174
+ let merge: MergeView | undefined;
175
+ let saving = false;
176
+ let disposed = false;
177
+ let comparison: boolean | undefined;
178
+ let changesOnly = true;
179
+ let readVersion = 0;
180
+ const collapseUnchanged = {margin: 0, minSize: 1};
181
+ const edit = button(message.edit, () => showDiff(false));
182
+ const diff = button(message.diff, () => showDiff(true));
183
+ const saveButton = button(message.save, () => void save());
184
+ const changes = button(message.changes, () => changeVisibility(true));
185
+ const whole = button(message.whole, () => changeVisibility(false));
186
+ const refresh = button(message.refresh, () => void loadBaseline());
187
+ const modes = element('div', 'twpf-file-actions');
188
+ modes.append(edit, diff);
189
+ toolbar.append(path, modes, saveButton);
190
+ const ranges = element('div', 'twpf-file-actions');
191
+ ranges.append(changes, whole);
192
+ diffToolbar.append(ranges, refresh);
193
+ panel.append(style, toolbar, status, editPane, diffPane);
194
+ parent.append(panel);
195
+
196
+ const view = new EditorView({
197
+ parent: editPane, doc: savedDoc,
198
+ extensions: [
199
+ common, mixed ? EditorState.lineSeparator.of('\n') : [], history(), drawSelection(), highlightSpecialChars(),
200
+ highlightActiveLine(), EditorView.contentAttributes.of({'aria-label': options.path}),
201
+ keymap.of([...defaultKeymap, ...historyKeymap]),
202
+ EditorView.updateListener.of(update => {if (update.docChanged) updateSaveState();})
203
+ ]
204
+ });
205
+ const dirty = () => !view.state.doc.eq(savedDoc);
206
+ const serialize = () => bom + (newline === '\n' ? view.state.doc.toString() : view.state.doc.toString().replace(/\n/gu, newline));
207
+
208
+ function updateSaveState(text = saving ? message.saving : dirty() ? message.unsaved : '') {
209
+ saveButton.disabled = saving || !dirty();
210
+ setStatus(status, text);
211
+ }
212
+
213
+ async function unchanged(handle: FileSystemFileHandle) {
214
+ try {
215
+ const file = await handle.getFile();
216
+ return file.size <= options.limit && decodeText(await file.arrayBuffer()) === saved;
217
+ } catch (error) {
218
+ if (['NotFoundError', 'TypeMismatchError'].includes((error as DOMException).name)) return false;
219
+ throw error;
220
+ }
221
+ }
222
+
223
+ async function save() {
224
+ if (saving || disposed || !dirty()) return;
225
+ const doc = view.state.doc;
226
+ const content = serialize();
227
+ const bytes = encoder.encode(content);
228
+ if (bytes.byteLength > options.limit) return updateSaveState(message.tooLarge);
229
+ saving = true;
230
+ updateSaveState();
231
+ let result = message.saveFailed;
232
+ let writable: FileSystemWritableFileStream | undefined;
233
+ try {
234
+ const handle = await options.readHandle();
235
+ if (!await unchanged(handle)) {
236
+ result = message.conflict;
237
+ return;
238
+ }
239
+ if (disposed) return;
240
+ writable = await handle.createWritable({mode: 'exclusive'} as FileSystemCreateWritableOptions);
241
+ await writable.write(bytes);
242
+ const current = await options.readHandle();
243
+ if (!await current.isSameEntry(handle) || !await unchanged(current)) {
244
+ result = message.conflict;
245
+ return;
246
+ }
247
+ if (disposed) return;
248
+ await writable.close();
249
+ writable = undefined;
250
+ saved = content;
251
+ savedDoc = doc;
252
+ result = dirty() ? message.unsaved : message.saved;
253
+ } catch (error) {
254
+ if (['NotFoundError', 'TypeMismatchError'].includes((error as DOMException).name)) result = message.conflict;
255
+ } finally {
256
+ await writable?.abort().catch(() => {});
257
+ saving = false;
258
+ if (!disposed) updateSaveState(result);
259
+ }
260
+ }
261
+
262
+ function destroyDiff() {
263
+ merge?.destroy();
264
+ merge = undefined;
265
+ }
266
+
267
+ function changeVisibility(onlyChanges: boolean) {
268
+ changesOnly = onlyChanges;
269
+ press(changes, onlyChanges);
270
+ press(whole, !onlyChanges);
271
+ merge?.reconfigure({collapseUnchanged: onlyChanges ? collapseUnchanged : undefined});
272
+ diffContent.hidden = !merge || (onlyChanges && merge.chunks.length === 0);
273
+ }
274
+
275
+ function showDiff(active: boolean) {
276
+ if (comparison === active) return;
277
+ comparison = active;
278
+ editPane.hidden = active;
279
+ diffPane.hidden = !active;
280
+ press(edit, !active);
281
+ press(diff, active);
282
+ if (active) void loadBaseline();
283
+ else {
284
+ ++readVersion;
285
+ destroyDiff();
286
+ }
287
+ }
288
+
289
+ async function loadBaseline() {
290
+ const version = ++readVersion;
291
+ destroyDiff();
292
+ headings.hidden = true;
293
+ changes.disabled = whole.disabled = true;
294
+ refresh.disabled = true;
295
+ changeVisibility(changesOnly);
296
+ setStatus(diffStatus, message.loading);
297
+ const current = () => !disposed && comparison && version === readVersion;
298
+ try {
299
+ const base = await options.readBaseline?.();
300
+ if (!current()) return;
301
+ if (!base) return setStatus(diffStatus, message.noGit);
302
+ const text = base.bytes ? decodeText(base.bytes) : '';
303
+ if (text === null) return setStatus(diffStatus, message.unsupported);
304
+ const edited = serialize();
305
+ if (encoder.encode(edited).byteLength > options.limit) return setStatus(diffStatus, message.tooLarge);
306
+ left.textContent = [message.before, base.branch, base.head?.slice(0, 8)].filter(Boolean).join(' · ');
307
+ left.title = base.head ?? left.textContent;
308
+ const readOnly = (label: string) => [common, EditorState.readOnly.of(true), EditorView.editable.of(false),
309
+ EditorView.contentAttributes.of({'aria-label': label, tabindex: '0'}),
310
+ EditorState.phrases.of({'$ unchanged lines': message.collapsed})];
311
+ merge = new MergeView({
312
+ parent: diffContent,
313
+ a: {doc: text.replace(/^\uFEFF/u, ''), extensions: readOnly(left.textContent)},
314
+ b: {doc: edited.replace(/^\uFEFF/u, ''), extensions: readOnly(message.after)},
315
+ diffConfig: {scanLimit: 500, timeout: 100}
316
+ });
317
+ headings.hidden = false;
318
+ changes.disabled = whole.disabled = false;
319
+ changeVisibility(changesOnly);
320
+ const notice = !base.head ? message.unborn : !base.bytes ? message.missing :
321
+ merge.chunks.length ? '' : text === edited ? message.same : message.formatting;
322
+ setStatus(diffStatus, notice);
323
+ } catch (error) {
324
+ if (current()) setStatus(diffStatus, (error as {code?: string})?.code === 'large' ? message.tooLarge : message.readFailed);
325
+ } finally {
326
+ if (current()) refresh.disabled = !options.readBaseline;
327
+ }
328
+ }
329
+
330
+ const beforeUnload = (event: BeforeUnloadEvent) => {
331
+ if (!dirty()) return;
332
+ event.preventDefault();
333
+ event.returnValue = '';
334
+ };
335
+ panel.addEventListener('keydown', event => {
336
+ if (!(event.metaKey || event.ctrlKey) || event.key.toLowerCase() !== 's') return;
337
+ event.preventDefault();
338
+ event.stopPropagation();
339
+ void save();
340
+ });
341
+ browser?.addEventListener('beforeunload', beforeUnload);
342
+ showDiff(false);
343
+ updateSaveState();
344
+ return {
345
+ requestClose() {
346
+ if (!saving && (!dirty() || browser?.confirm(message.close))) options.close();
347
+ },
348
+ dispose() {
349
+ disposed = true;
350
+ browser?.removeEventListener('beforeunload', beforeUnload);
351
+ destroyDiff();
352
+ view.destroy();
353
+ panel.remove();
354
+ }
355
+ };
356
+ }