@kubohiroya/turbowarp-plus-editor-project-folder 0.14.0 → 0.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2 @@
1
+ import type { Extension } from '@codemirror/state';
2
+ export declare const textMinimap: (label: string) => Extension;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-plus-editor-project-folder",
3
- "version": "0.14.0",
3
+ "version": "0.15.1",
4
4
  "description": "Read and save expanded Scratch project folders in TurboWarp Plus Editor",
5
5
  "type": "module",
6
6
  "license": "MPL-2.0",
@@ -0,0 +1,59 @@
1
+ type Session = {id: string};
2
+
3
+ export async function connectExternalFileEditor(browser: Window, filename: string, extension: string, limit: number) {
4
+ // The existing companion serves its authenticated API on the same loopback origin as the Editor.
5
+ if (!['127.0.0.1', 'localhost', '[::1]'].includes(browser.location.hostname) || browser.location.protocol !== 'http:') return null;
6
+ const prefix = '/__twpe_yaml';
7
+ let config;
8
+ try {
9
+ const response = await browser.fetch(`${prefix}/config`, {credentials: 'same-origin', cache: 'no-store'});
10
+ if (!response.ok) return null;
11
+ config = await response.json();
12
+ } catch {return null;}
13
+ if (config?.available !== true || typeof config.token !== 'string' || config.editor !== 'VSCode') return null;
14
+ const format = extension === 'json' ? 'json' : ['yaml', 'yml'].includes(extension) ? 'yaml' : 'text';
15
+ if (!(Array.isArray(config.formats) ? config.formats : ['yaml', 'json']).includes(format)) return null;
16
+ const maxBytes = Math.min(limit, Number.isFinite(config.maxSourceBytes) && config.maxSourceBytes > 0 ? config.maxSourceBytes : limit);
17
+ let session: Session | undefined;
18
+ let closed = false;
19
+ const request = async (path: string, method = 'GET', body?: unknown) => {
20
+ const response = await browser.fetch(`${prefix}${path}`, {
21
+ method, credentials: 'same-origin', cache: 'no-store',
22
+ headers: {'X-TWPE-Yaml-Token': config.token, ...(body ? {'Content-Type': 'application/json'} : {})},
23
+ ...(body ? {body: JSON.stringify(body)} : {})
24
+ });
25
+ if (!response.ok) throw new Error('External editor request failed.');
26
+ return response.json();
27
+ };
28
+ const checkSource = (source: unknown): string => {
29
+ if (typeof source !== 'string' || new TextEncoder().encode(source).byteLength > maxBytes ||
30
+ /[\u0000-\u0008\u000b\u000e-\u001f\u007f]/u.test(source)) throw new Error('Invalid external text.');
31
+ return source;
32
+ };
33
+ const endSession = (id: string) => {void request(`/sessions/${id}`, 'DELETE').catch(() => {});};
34
+ const end = () => {
35
+ if (session) endSession(session.id);
36
+ session = undefined;
37
+ };
38
+ return {
39
+ get active() {return Boolean(session);},
40
+ async open(source: string) {
41
+ if (closed) return;
42
+ if (session) {
43
+ await request(`/sessions/${session.id}`, 'POST');
44
+ return;
45
+ }
46
+ const created = await request('/sessions', 'POST', {source: checkSource(source), sourceName: filename, format});
47
+ if (!/^[a-f0-9]{32}$/u.test(created?.id)) throw new Error('Invalid external editor session.');
48
+ if (closed) {endSession(created.id); return;}
49
+ session = {id: created.id};
50
+ },
51
+ async read() {
52
+ if (closed || !session) throw new Error('No external editor session.');
53
+ const saved = await request(`/sessions/${session.id}`);
54
+ return checkSource(saved.source);
55
+ },
56
+ end,
57
+ close() {closed = true; end();}
58
+ };
59
+ }
@@ -10,10 +10,12 @@ import {yaml} from '@codemirror/lang-yaml';
10
10
  import {HighlightStyle, StreamLanguage, syntaxHighlighting} from '@codemirror/language';
11
11
  import {shell} from '@codemirror/legacy-modes/mode/shell';
12
12
  import {MergeView} from '@codemirror/merge';
13
- import {EditorState} from '@codemirror/state';
13
+ import {Compartment, EditorState} from '@codemirror/state';
14
14
  import {drawSelection, EditorView, highlightActiveLine, highlightSpecialChars, keymap, lineNumbers} from '@codemirror/view';
15
15
  import {tags} from '@lezer/highlight';
16
16
  import type {FileBaseline} from './file-preview.js';
17
+ import {textMinimap} from './text-minimap.js';
18
+ import {connectExternalFileEditor} from './external-file-editor.js';
17
19
 
18
20
  const decoder = new TextDecoder('utf-8', {fatal: true, ignoreBOM: true});
19
21
  const encoder = new TextEncoder();
@@ -54,18 +56,55 @@ const highlighting = syntaxHighlighting(HighlightStyle.define([
54
56
  ]));
55
57
 
56
58
  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
+ .twpf-text-shell{position:relative;height:100%;min-height:0}
60
+ .twpf-text-file{position:relative;display:flex;flex-direction:column;height:100%;min-height:0;font:inherit}
61
+ .twpf-text-file[inert]{opacity:.45}
62
+ .twpf-external-overlay{position:absolute;z-index:10;inset:0;display:flex;align-items:center;justify-content:center;
63
+ background:rgba(128,128,128,.16);padding:1rem;box-sizing:border-box}
64
+ .twpf-external-overlay[hidden]{display:none}
65
+ .twpf-external-card{max-width:28rem;padding:1rem;border-radius:.5rem;background:var(--ui-primary,#fff);
66
+ color:var(--text-primary,inherit);box-shadow:0 3px 15px rgba(0,0,0,.2);font:inherit}
67
+ .twpf-external-card h3{margin:0 0 .7rem;font-size:1rem}
68
+ .twpf-external-card p{margin:0 0 1rem;font-size:.9rem}
69
+ .twpf-external-card div{display:flex;flex-wrap:wrap;gap:.5rem}
70
+ .twpf-external-card button{font:inherit;color:inherit;border:1px solid var(--ui-black-transparent,#888);
71
+ border-radius:.3rem;background:var(--ui-secondary,#eee);padding:.4rem .6rem;cursor:pointer}
72
+ .twpf-external-card button:disabled{opacity:.55;cursor:default}
73
+ .twpf-file-toolbar{position:absolute;z-index:5;top:.5rem;right:1.25rem;display:flex;flex-wrap:wrap;
74
+ justify-content:flex-end;gap:.4rem;max-width:calc(100% - 2rem)}
75
+ .twpf-text-file .twpf-file-toolbar>button{background:var(--ui-primary,#fff)}
76
+ .twpf-diff-toolbar{display:flex;align-items:center;flex-wrap:wrap;gap:.4rem;padding:.5rem .7rem;
59
77
  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
78
  .twpf-file-actions{display:flex;gap:.25rem}
79
+ .twpf-file-modes{display:inline-flex;overflow:hidden;border:1px solid var(--ui-black-transparent,rgba(128,128,128,.35));
80
+ border-radius:999px;background:var(--ui-secondary,rgba(128,128,128,.1))}
81
+ .twpf-text-file .twpf-file-modes>button{border:0;border-radius:0;background:transparent;white-space:nowrap}
82
+ .twpf-text-file .twpf-file-modes>button+button{border-inline-start:1px solid var(--ui-black-transparent,rgba(128,128,128,.35))}
83
+ .twpf-file-modes>button[aria-checked=true]{background:var(--motion-primary,#2468b7);color:#fff}
84
+ .twpf-file-modes>button:focus-visible{outline:2px solid var(--motion-primary,#2468b7);outline-offset:-3px}
62
85
  .twpf-text-file button{font:inherit;font-size:.85em;color:inherit;background:transparent;border:1px solid
63
86
  var(--ui-black-transparent,rgba(128,128,128,.45));border-radius:.3rem;padding:.25rem .55rem;cursor:pointer}
64
87
  .twpf-text-file button[aria-pressed=true]{background:var(--motion-primary,#2468b7);border-color:transparent;color:#fff}
65
88
  .twpf-text-file button:disabled{opacity:.55;cursor:default}
89
+ .twpf-text-file button:has(svg){display:inline-flex;align-items:center;justify-content:center;gap:.3rem}
90
+ .twpf-text-file button svg{width:1rem;height:1rem;flex:none}
66
91
  .twpf-file-status,.twpf-diff-status{margin:0;padding:.35rem .7rem;font-size:.82em}
92
+ .twpf-file-status{position:absolute;z-index:5;bottom:.5rem;left:.5rem;max-width:calc(100% - 10rem);
93
+ max-height:40%;overflow:auto;border-radius:.3rem;background:var(--ui-primary,#fff);box-shadow:0 1px 6px rgba(0,0,0,.18)}
94
+ .twpf-file-snackbar{position:absolute;z-index:6;bottom:1rem;left:50%;transform:translateX(-50%);
95
+ box-sizing:border-box;max-width:calc(100% - 2rem);margin:0;padding:.65rem 1rem;border-radius:.35rem;
96
+ background:#323232;color:#fff;font-size:.9em;box-shadow:0 2px 8px rgba(0,0,0,.3);pointer-events:none}
67
97
  .twpf-file-edit,.twpf-file-diff{flex:1;min-height:0}
98
+ .twpf-file-diff{padding-top:var(--twpf-toolbar-height,3.25rem)}
68
99
  .twpf-file-edit>.cm-editor{height:100%}
100
+ .twpf-text-file .cm-scroller{overflow:auto}
101
+ .twpf-text-minimap{position:absolute;z-index:4;right:1.25rem;bottom:1.25rem;width: min(7rem,25%);
102
+ height:min(10.5rem,35%);overflow:hidden;border:1px solid var(--ui-black-transparent,rgba(128,128,128,.4));
103
+ border-radius:.3rem;background:var(--ui-primary,#fff);opacity:.85;cursor:pointer;touch-action:none}
104
+ .twpf-text-minimap:focus-visible{outline:2px solid var(--motion-primary,#2468b7);outline-offset:2px}
105
+ .twpf-text-minimap canvas{display:block;width:100%;height:100%;pointer-events:none}
106
+ .twpf-text-minimap-viewport{position:absolute;left:0;right:0;box-sizing:border-box;min-height:2px;
107
+ border:1px solid var(--motion-primary,#2468b7);background:rgba(76,151,255,.2);pointer-events:none}
69
108
  .twpf-file-diff{display:flex;flex-direction:column}
70
109
  .twpf-text-file [hidden]{display:none}
71
110
  .twpf-diff-headings{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));font-size:.83em;
@@ -86,8 +125,17 @@ border-bottom:1px solid var(--ui-black-transparent,rgba(128,128,128,.25))}
86
125
 
87
126
  const messages = {
88
127
  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.',
128
+ text: 'Normal view', textHint: 'Edit the file content in this tab', diff: 'Diff view', diffHint: 'Compare with the latest commit',
129
+ viewMode: 'View mode', external: 'Edit in VSCode', importExternal: 'Finish and import edits',
130
+ externalTitle: 'Editing in VSCode', cancelExternal: 'Finish without importing',
131
+ externalUnavailable: 'Open the Editor through the local companion to edit this file in VSCode.',
132
+ externalOpening: 'Opening VSCode…', externalHint: 'Save in VSCode, then choose “Finish and import edits”. This tab stays locked until you finish.',
133
+ externalReading: 'Reading external edits…', externalImported: 'External edits imported. Save the file to keep them.',
134
+ externalFailed: 'External editing failed. Your edits are still here. Check the local companion and try again.',
135
+ externalReplace: 'This tab has also changed. Replace its current content with the file saved in VSCode?',
136
+ externalChanged: 'This tab changed while reading. Import the external edits again to compare.',
137
+ changes: 'Changes only', whole: 'Full file', refresh: 'Reload latest commit',
138
+ save: 'Save file', unsaved: 'Unsaved changes', saving: 'Saving…', saved: 'Saved.',
91
139
  conflict: 'The file changed outside this tab. Your edits are still here. Reopen the file to load the current version.',
92
140
  saveFailed: 'The file could not be saved.', tooLarge: 'The text file exceeds the 4 MiB limit.',
93
141
  close: 'Discard the unsaved edits to this file?', loading: 'Reading the latest commit…',
@@ -95,11 +143,20 @@ const messages = {
95
143
  readFailed: 'The committed version could not be read.', unsupported: 'The committed version is not a UTF-8 text file.',
96
144
  missing: 'This file is not in the latest commit.', unborn: 'This branch has no commits yet.',
97
145
  same: 'No differences.', formatting: 'The line endings or UTF-8 BOM differ.',
98
- before: 'Latest commit', after: 'Current content', collapsed: '$ unchanged lines'
146
+ before: 'Latest commit', after: 'Current content', collapsed: '$ unchanged lines', minimap: 'File minimap'
99
147
  },
100
148
  ja: {
101
- edit: '編集', diff: '差分', changes: '変更箇所のみ', whole: '全体', refresh: '最新コミットを読み直す',
102
- save: 'ファイルを保存', unsaved: '未保存の変更があります', saving: '保存中…', saved: 'ファイルを保存しました。',
149
+ text: '通常表示', textHint: 'この画面でファイルの内容を編集', diff: '差分表示', diffHint: '最新コミットと現在の内容を比較',
150
+ viewMode: '表示モード', external: 'VSCodeで編集', importExternal: '終了して取り込む',
151
+ externalTitle: 'VSCodeで編集中', cancelExternal: '取り込まずに終了',
152
+ externalUnavailable: 'VSCodeで編集するには、ローカル連携からEditorを開いてください。',
153
+ externalOpening: 'VSCodeを開いています…', externalHint: 'VSCodeで保存後、「終了して取り込む」を押してください。終了までこのタブの操作はできません。',
154
+ externalReading: '外部の編集内容を読み込んでいます…', externalImported: '外部編集を取り込みました。ファイルを保存してください。',
155
+ externalFailed: '外部編集を利用できませんでした。編集内容は保持しています。ローカル連携を確認して再試行してください。',
156
+ externalReplace: 'この画面にも変更があります。VSCodeで保存した内容で、この画面の内容を置き換えますか?',
157
+ externalChanged: '読み込み中にこの画面の内容が変わりました。もう一度取り込みを行ってください。',
158
+ changes: '変更箇所のみ', whole: '全体', refresh: '最新コミットを読み直す',
159
+ save: 'ファイルを保存', unsaved: '未保存の変更があります', saving: '保存中…', saved: '保存しました',
103
160
  conflict: 'ファイルがこのタブの外で変更されました。編集内容はタブに残っています。現在の内容を読むにはファイルを開き直してください。',
104
161
  saveFailed: 'ファイルを保存できませんでした。', tooLarge: 'テキストファイルの上限(4 MiB)を超えています。',
105
162
  close: 'このファイルの未保存の編集を破棄しますか?', loading: '最新コミットを読み込んでいます…',
@@ -107,7 +164,7 @@ const messages = {
107
164
  readFailed: 'コミット済みの内容を読み込めませんでした。', unsupported: 'コミット済みの内容は UTF-8 テキストとして表示できません。',
108
165
  missing: '最新コミットにこのファイルはありません。', unborn: 'このブランチにはまだコミットがありません。',
109
166
  same: '差分はありません。', formatting: '改行コードまたは UTF-8 BOM が異なります。',
110
- before: '最新コミット', after: '現在の内容', collapsed: '変更のない $ 行'
167
+ before: '最新コミット', after: '現在の内容', collapsed: '変更のない $ 行', minimap: 'ファイルのミニマップ'
111
168
  }
112
169
  };
113
170
 
@@ -128,28 +185,59 @@ export function mountTextFile(parent: HTMLElement, options: TextFileOptions) {
128
185
  const {ownerDocument: document} = parent;
129
186
  const browser = document.defaultView;
130
187
  const message = options.locale.toLowerCase().startsWith('ja') ? messages.ja : messages.en;
131
- const element = <Tag extends 'div' | 'span' | 'p'>(tag: Tag, className: string) => {
188
+ const element = <Tag extends 'div' | 'span' | 'p' | 'h3'>(tag: Tag, className: string) => {
132
189
  const node = document.createElement(tag);
133
190
  node.className = className;
134
191
  return node;
135
192
  };
136
- const button = (label: string, action: () => void) => {
193
+ const button = (label: string, action: () => void, icon?: string) => {
137
194
  const node = document.createElement('button');
138
195
  node.type = 'button';
139
196
  node.textContent = label;
197
+ if (icon) {
198
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
199
+ svg.setAttribute('viewBox', '0 0 24 24');
200
+ svg.setAttribute('fill', 'none');
201
+ svg.setAttribute('stroke', 'currentColor');
202
+ svg.setAttribute('stroke-width', '1.8');
203
+ svg.setAttribute('stroke-linecap', 'round');
204
+ svg.setAttribute('stroke-linejoin', 'round');
205
+ svg.setAttribute('aria-hidden', 'true');
206
+ svg.setAttribute('focusable', 'false');
207
+ const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
208
+ path.setAttribute('d', icon);
209
+ svg.append(path);
210
+ node.prepend(svg);
211
+ }
140
212
  node.addEventListener('click', action);
141
213
  return node;
142
214
  };
143
215
  const press = (node: HTMLButtonElement, active: boolean) => node.setAttribute('aria-pressed', String(active));
144
216
  const setStatus = (node: HTMLElement, text: string) => {node.textContent = text; node.hidden = !text;};
217
+ const shell = element('div', 'twpf-text-shell');
145
218
  const panel = element('div', 'twpf-text-file');
146
219
  const style = document.createElement('style');
147
220
  style.textContent = styles;
148
221
  const toolbar = element('div', 'twpf-file-toolbar');
149
- const path = element('span', 'twpf-file-path');
150
- path.textContent = path.title = options.path;
222
+ toolbar.setAttribute('role', 'group');
223
+ toolbar.setAttribute('aria-label', options.path);
151
224
  const status = element('p', 'twpf-file-status');
152
225
  status.setAttribute('role', 'status');
226
+ const snackbar = element('p', 'twpf-file-snackbar');
227
+ snackbar.setAttribute('role', 'status');
228
+ snackbar.setAttribute('aria-atomic', 'true');
229
+ snackbar.hidden = true;
230
+ let snackbarTimeout: number | undefined;
231
+ const hideSnackbar = () => {
232
+ browser?.clearTimeout(snackbarTimeout);
233
+ snackbarTimeout = undefined;
234
+ setStatus(snackbar, '');
235
+ };
236
+ const showSaved = () => {
237
+ hideSnackbar();
238
+ setStatus(snackbar, message.saved);
239
+ snackbarTimeout = browser?.setTimeout(hideSnackbar, 4000);
240
+ };
153
241
  const editPane = element('div', 'twpf-file-edit');
154
242
  const diffPane = element('div', 'twpf-file-diff');
155
243
  const diffToolbar = element('div', 'twpf-diff-toolbar');
@@ -175,31 +263,81 @@ export function mountTextFile(parent: HTMLElement, options: TextFileOptions) {
175
263
  let savedDoc = EditorState.create({doc: initial, extensions: mixed ? EditorState.lineSeparator.of('\n') : []}).doc;
176
264
  let merge: MergeView | undefined;
177
265
  let saving = false;
266
+ let externalBusy = false;
267
+ let externalLocked = false;
268
+ let externalEditor: Awaited<ReturnType<typeof connectExternalFileEditor>> = null;
269
+ let externalOriginal: string | undefined;
178
270
  let disposed = false;
179
271
  let comparison: boolean | undefined;
180
272
  let changesOnly = true;
181
273
  let readVersion = 0;
274
+ let baselineLoading = false;
182
275
  const collapseUnchanged = {margin: 0, minSize: 1};
183
- const edit = button(message.edit, () => showDiff(false));
184
- const diff = button(message.diff, () => showDiff(true));
185
- const saveButton = button(message.save, () => void save());
276
+ const text = button(message.text, () => showDiff(false), 'M14 3H5v18h14V8l-5-5v5h5M8 12h8M8 16h8');
277
+ text.title = message.textHint;
278
+ const diff = button(message.diff, () => showDiff(true), 'M4 3h16v18H4zM12 3v18M6.5 8h3M14.5 8h3M16 6.5v3');
279
+ diff.title = message.diffHint;
280
+ const saveButton = button(message.save, () => void save(), 'M4 3h13l4 4v14H3V3h1M7 3v6h10V3M7 21v-8h10v8');
281
+ const externalButton = button(message.external, () => void openExternal(), 'M14 3h7v7M21 3l-11 11M11 5H3v16h16v-8');
282
+ externalButton.disabled = true;
283
+ externalButton.title = message.externalUnavailable;
284
+ const overlay = element('div', 'twpf-external-overlay');
285
+ overlay.hidden = true;
286
+ overlay.setAttribute('role', 'dialog');
287
+ overlay.setAttribute('aria-label', message.externalTitle);
288
+ const externalCard = element('div', 'twpf-external-card');
289
+ const externalTitle = element('h3', '');
290
+ externalTitle.textContent = message.externalTitle;
291
+ const externalStatus = element('p', '');
292
+ externalStatus.setAttribute('role', 'status');
293
+ const importButton = button(message.importExternal, () => void importExternal());
294
+ const cancelExternal = button(message.cancelExternal, () => {
295
+ if (externalBusy || disposed) return;
296
+ externalEditor?.end();
297
+ setExternalLocked(false);
298
+ updateSaveState();
299
+ externalButton.focus();
300
+ });
301
+ const externalActions = element('div', '');
302
+ externalActions.append(importButton, cancelExternal);
303
+ externalCard.append(externalTitle, externalStatus, externalActions);
304
+ overlay.append(externalCard);
186
305
  const changes = button(message.changes, () => changeVisibility(true));
187
306
  const whole = button(message.whole, () => changeVisibility(false));
188
307
  const refresh = button(message.refresh, () => void loadBaseline());
189
- const modes = element('div', 'twpf-file-actions');
190
- modes.append(edit, diff);
191
- toolbar.append(path, modes, saveButton);
308
+ const modes = element('div', 'twpf-file-modes');
309
+ modes.setAttribute('role', 'radiogroup');
310
+ modes.setAttribute('aria-label', message.viewMode);
311
+ text.setAttribute('role', 'radio');
312
+ diff.setAttribute('role', 'radio');
313
+ modes.append(text, diff);
314
+ modes.addEventListener('keydown', event => {
315
+ if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return;
316
+ event.preventDefault();
317
+ event.stopPropagation();
318
+ const active = event.key === 'Home' ? false : event.key === 'End' ? true : !comparison;
319
+ showDiff(active);
320
+ (active ? diff : text).focus();
321
+ });
322
+ toolbar.append(modes, saveButton, externalButton);
192
323
  const ranges = element('div', 'twpf-file-actions');
193
324
  ranges.append(changes, whole);
194
325
  diffToolbar.append(ranges, refresh);
195
- panel.append(style, toolbar, status, editPane, diffPane);
196
- parent.append(panel);
326
+ panel.append(style, toolbar, status, snackbar, editPane, diffPane);
327
+ shell.append(panel, overlay);
328
+ parent.append(shell);
329
+ const toolbarObserver = browser && new browser.ResizeObserver(() => {
330
+ panel.style.setProperty('--twpf-toolbar-height', `calc(${toolbar.getBoundingClientRect().height}px + 1rem)`);
331
+ });
332
+ toolbarObserver?.observe(toolbar);
197
333
 
334
+ const editing = new Compartment();
198
335
  const view = new EditorView({
199
336
  parent: editPane, doc: savedDoc,
200
337
  extensions: [
201
- common, mixed ? EditorState.lineSeparator.of('\n') : [], history(), drawSelection(), highlightSpecialChars(),
202
- highlightActiveLine(), EditorView.contentAttributes.of({'aria-label': options.path}),
338
+ common, editing.of([]), mixed ? EditorState.lineSeparator.of('\n') : [], history(), drawSelection(), highlightSpecialChars(),
339
+ highlightActiveLine(), textMinimap(message.minimap),
340
+ EditorView.contentAttributes.of({'aria-label': options.path}),
203
341
  keymap.of([...defaultKeymap, ...historyKeymap]),
204
342
  EditorView.updateListener.of(update => {if (update.docChanged) updateSaveState(undefined, true);})
205
343
  ]
@@ -210,7 +348,10 @@ export function mountTextFile(parent: HTMLElement, options: TextFileOptions) {
210
348
  let wasDirty = false;
211
349
  function updateSaveState(text = saving ? message.saving : dirty() ? message.unsaved : '', contentChanged = false) {
212
350
  const isDirty = dirty();
213
- saveButton.disabled = saving || !isDirty;
351
+ saveButton.disabled = saving || externalBusy || externalLocked || !isDirty;
352
+ externalButton.disabled = saving || externalBusy || externalLocked || !externalEditor;
353
+ importButton.disabled = saving || externalBusy;
354
+ cancelExternal.disabled = externalBusy;
214
355
  setStatus(status, text);
215
356
  if (isDirty !== wasDirty || contentChanged && isDirty) {
216
357
  wasDirty = isDirty;
@@ -218,6 +359,89 @@ export function mountTextFile(parent: HTMLElement, options: TextFileOptions) {
218
359
  }
219
360
  }
220
361
 
362
+ function setExternalLocked(active: boolean) {
363
+ externalLocked = active;
364
+ if (active) {
365
+ for (const button of panel.querySelectorAll('button')) {
366
+ button.disabled = true;
367
+ }
368
+ } else {
369
+ text.disabled = diff.disabled = false;
370
+ changes.disabled = whole.disabled = baselineLoading || !merge;
371
+ refresh.disabled = baselineLoading || !options.readBaseline;
372
+ }
373
+ panel.inert = active;
374
+ overlay.hidden = !active;
375
+ view.dispatch({effects: editing.reconfigure(active ? [EditorState.readOnly.of(true), EditorView.editable.of(false)] : [])});
376
+ updateSaveState(status.textContent || '');
377
+ }
378
+
379
+ async function openExternal() {
380
+ if (!externalEditor || saving || externalBusy || disposed) return;
381
+ externalBusy = true;
382
+ setExternalLocked(true);
383
+ externalStatus.textContent = message.externalOpening;
384
+ updateSaveState(message.externalOpening);
385
+ const initial = serialize();
386
+ const reopening = externalEditor.active;
387
+ try {
388
+ await externalEditor.open(initial);
389
+ if (disposed) return;
390
+ if (!reopening) externalOriginal = initial;
391
+ externalStatus.textContent = message.externalHint;
392
+ updateSaveState(message.externalHint);
393
+ importButton.focus();
394
+ } catch {
395
+ if (!disposed) {
396
+ setExternalLocked(false);
397
+ updateSaveState(message.externalFailed);
398
+ }
399
+ } finally {
400
+ externalBusy = false;
401
+ if (!disposed) {
402
+ updateSaveState(status.textContent || '');
403
+ if (externalLocked) importButton.focus();
404
+ }
405
+ }
406
+ }
407
+
408
+ async function importExternal() {
409
+ if (!externalEditor?.active || saving || externalBusy || disposed) return;
410
+ externalBusy = true;
411
+ externalStatus.textContent = message.externalReading;
412
+ updateSaveState(message.externalReading);
413
+ const beforeRead = serialize();
414
+ try {
415
+ const source = await externalEditor.read();
416
+ if (disposed) return;
417
+ if (serialize() !== beforeRead) {
418
+ externalStatus.textContent = message.externalChanged;
419
+ return updateSaveState(message.externalChanged);
420
+ }
421
+ if (beforeRead !== externalOriginal && source !== beforeRead && !browser?.confirm(message.externalReplace)) {
422
+ externalStatus.textContent = message.externalHint;
423
+ return updateSaveState();
424
+ }
425
+ const imported = EditorState.create({doc: source.replace(/^\uFEFF/u, ''),
426
+ extensions: mixed ? EditorState.lineSeparator.of('\n') : []}).doc;
427
+ view.dispatch({changes: {from: 0, to: view.state.doc.length, insert: imported}});
428
+ externalOriginal = serialize();
429
+ externalEditor.end();
430
+ setExternalLocked(false);
431
+ showDiff(false);
432
+ updateSaveState(message.externalImported);
433
+ view.focus();
434
+ } catch {
435
+ if (!disposed) {
436
+ externalStatus.textContent = message.externalFailed;
437
+ updateSaveState(message.externalFailed);
438
+ }
439
+ } finally {
440
+ externalBusy = false;
441
+ if (!disposed) updateSaveState(status.textContent || '');
442
+ }
443
+ }
444
+
221
445
  async function unchanged(handle: FileSystemFileHandle) {
222
446
  try {
223
447
  const file = await handle.getFile();
@@ -229,14 +453,16 @@ export function mountTextFile(parent: HTMLElement, options: TextFileOptions) {
229
453
  }
230
454
 
231
455
  async function save() {
232
- if (saving || disposed || !dirty()) return;
456
+ if (saving || externalBusy || externalLocked || disposed || !dirty()) return;
233
457
  const doc = view.state.doc;
234
458
  const content = serialize();
235
459
  const bytes = encoder.encode(content);
236
460
  if (bytes.byteLength > options.limit) return updateSaveState(message.tooLarge);
461
+ hideSnackbar();
237
462
  saving = true;
238
463
  updateSaveState();
239
464
  let result = message.saveFailed;
465
+ let didSave = false;
240
466
  let writable: FileSystemWritableFileStream | undefined;
241
467
  try {
242
468
  const handle = await options.readHandle();
@@ -257,13 +483,17 @@ export function mountTextFile(parent: HTMLElement, options: TextFileOptions) {
257
483
  writable = undefined;
258
484
  saved = content;
259
485
  savedDoc = doc;
260
- result = dirty() ? message.unsaved : message.saved;
486
+ didSave = true;
487
+ result = dirty() ? message.unsaved : '';
261
488
  } catch (error) {
262
489
  if (['NotFoundError', 'TypeMismatchError'].includes((error as DOMException).name)) result = message.conflict;
263
490
  } finally {
264
491
  await writable?.abort().catch(() => {});
265
492
  saving = false;
266
- if (!disposed) updateSaveState(result);
493
+ if (!disposed) {
494
+ updateSaveState(result);
495
+ if (didSave) showSaved();
496
+ }
267
497
  }
268
498
  }
269
499
 
@@ -285,17 +515,21 @@ export function mountTextFile(parent: HTMLElement, options: TextFileOptions) {
285
515
  comparison = active;
286
516
  editPane.hidden = active;
287
517
  diffPane.hidden = !active;
288
- press(edit, !active);
289
- press(diff, active);
518
+ text.setAttribute('aria-checked', String(!active));
519
+ diff.setAttribute('aria-checked', String(active));
520
+ text.tabIndex = active ? -1 : 0;
521
+ diff.tabIndex = active ? 0 : -1;
290
522
  if (active) void loadBaseline();
291
523
  else {
292
524
  ++readVersion;
525
+ baselineLoading = false;
293
526
  destroyDiff();
294
527
  }
295
528
  }
296
529
 
297
530
  async function loadBaseline() {
298
531
  const version = ++readVersion;
532
+ baselineLoading = true;
299
533
  destroyDiff();
300
534
  headings.hidden = true;
301
535
  changes.disabled = whole.disabled = true;
@@ -323,7 +557,7 @@ export function mountTextFile(parent: HTMLElement, options: TextFileOptions) {
323
557
  diffConfig: {scanLimit: 500, timeout: 100}
324
558
  });
325
559
  headings.hidden = false;
326
- changes.disabled = whole.disabled = false;
560
+ changes.disabled = whole.disabled = externalLocked;
327
561
  changeVisibility(changesOnly);
328
562
  const notice = !base.head ? message.unborn : !base.bytes ? message.missing :
329
563
  merge.chunks.length ? '' : text === edited ? message.same : message.formatting;
@@ -331,12 +565,15 @@ export function mountTextFile(parent: HTMLElement, options: TextFileOptions) {
331
565
  } catch (error) {
332
566
  if (current()) setStatus(diffStatus, (error as {code?: string})?.code === 'large' ? message.tooLarge : message.readFailed);
333
567
  } finally {
334
- if (current()) refresh.disabled = !options.readBaseline;
568
+ if (current()) {
569
+ baselineLoading = false;
570
+ refresh.disabled = externalLocked || !options.readBaseline;
571
+ }
335
572
  }
336
573
  }
337
574
 
338
575
  const beforeUnload = (event: BeforeUnloadEvent) => {
339
- if (!dirty()) return;
576
+ if (!dirty() && !externalLocked) return;
340
577
  event.preventDefault();
341
578
  event.returnValue = '';
342
579
  };
@@ -351,19 +588,29 @@ export function mountTextFile(parent: HTMLElement, options: TextFileOptions) {
351
588
  browser?.addEventListener('beforeunload', beforeUnload);
352
589
  showDiff(false);
353
590
  updateSaveState();
591
+ if (browser) void connectExternalFileEditor(browser, options.path.split('/').pop()!, options.extension, options.limit)
592
+ .then(editor => {
593
+ if (disposed) {editor?.close(); return;}
594
+ externalEditor = editor;
595
+ if (editor) externalButton.title = message.external;
596
+ updateSaveState(status.textContent || '');
597
+ });
354
598
  return {
355
599
  save,
356
600
  isDirty: dirty,
357
601
  readUnsaved: () => !disposed && dirty() ? encoder.encode(serialize()) : undefined,
358
602
  requestClose() {
359
- if (!saving && (!dirty() || browser?.confirm(message.close))) options.close();
603
+ if (!saving && !externalLocked && (!dirty() || browser?.confirm(message.close))) options.close();
360
604
  },
361
605
  dispose() {
362
606
  disposed = true;
607
+ hideSnackbar();
608
+ toolbarObserver?.disconnect();
609
+ externalEditor?.close();
363
610
  browser?.removeEventListener('beforeunload', beforeUnload);
364
611
  destroyDiff();
365
612
  view.destroy();
366
- panel.remove();
613
+ shell.remove();
367
614
  }
368
615
  };
369
616
  }