@celljs/ta-workspace 0.0.0-stage → 4.6.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,471 @@
1
+ import type { TaFileContent } from '@celljs/ta-protocol';
2
+ import { Action, Glyph } from './common';
3
+ import { fileTabIcon } from './file-icon';
4
+ import { FilesChanged, Host, pi, useFilesChanged, useLoad } from './host';
5
+ import { t } from './i18n';
6
+ import { MarkdownPreview, MediaPreview } from './preview';
7
+ import { React } from './react';
8
+ import { GitUtil } from './util/git';
9
+ import { PreviewUtil } from './util/preview';
10
+ import { type KeptFile, WorkspaceUtil } from './util/workspace';
11
+ import { WorkspaceClient } from './workspace-client';
12
+
13
+ export interface OpenFile {
14
+ id: string;
15
+ kind: 'file' | 'diff';
16
+ title: string;
17
+ /** The path. */
18
+ detail: string;
19
+ /** The directory the path is in. */
20
+ cwd: string;
21
+ /** Shows it again: openEditor with an open id activates its tab. */
22
+ reopen(): void;
23
+ /** What opens it again when the page loads. */
24
+ kept: KeptFile;
25
+ }
26
+
27
+ const OPEN_FILES_KEY = 'open-files';
28
+
29
+ /** The tabs this package opened, for the view of open files; kept, so that they open again with the page. */
30
+ export namespace OpenFiles {
31
+ let files: OpenFile[] = [];
32
+ /** Until the tabs of before are open again, nothing is written over them. */
33
+ let restored = false;
34
+ const listeners = new Set<() => void>();
35
+
36
+ /** The tabs of before, behind the one shown (unless one of them was: ta shows it again). */
37
+ export async function restore(): Promise<void> {
38
+ let kept: unknown;
39
+ try {
40
+ kept = await pi.storage.get(OPEN_FILES_KEY);
41
+ } catch {
42
+ // The server cannot say: nothing opens again, and nothing is written over what it keeps.
43
+ return;
44
+ }
45
+ for (const file of WorkspaceUtil.keptFiles(kept)) {
46
+ if (file.kind === 'file') {
47
+ openFile(file.cwd, file.path, undefined, { preserveFocus: true });
48
+ } else {
49
+ openDiff(file.cwd, file.path, file.staged === true, { preserveFocus: true });
50
+ }
51
+ }
52
+ restored = true;
53
+ save();
54
+ }
55
+
56
+ function save(): void {
57
+ if (restored) {
58
+ pi.storage
59
+ .set(
60
+ OPEN_FILES_KEY,
61
+ files.map(file => file.kept),
62
+ )
63
+ .catch(() => undefined);
64
+ }
65
+ }
66
+
67
+ export function list(): OpenFile[] {
68
+ return files;
69
+ }
70
+
71
+ export function subscribe(listener: () => void): () => void {
72
+ listeners.add(listener);
73
+ return () => listeners.delete(listener);
74
+ }
75
+
76
+ export function add(file: OpenFile): void {
77
+ const known = files.some(other => other.id === file.id);
78
+ files = known ? files.map(other => (other.id === file.id ? file : other)) : [...files, file];
79
+ if (!known) {
80
+ save();
81
+ }
82
+ for (const listener of listeners) {
83
+ listener();
84
+ }
85
+ }
86
+
87
+ export function remove(id: string): void {
88
+ files = files.filter(file => file.id !== id);
89
+ save();
90
+ for (const listener of listeners) {
91
+ listener();
92
+ }
93
+ }
94
+ }
95
+
96
+ export function useOpenFiles(): OpenFile[] {
97
+ return React.useSyncExternalStore(OpenFiles.subscribe, OpenFiles.list);
98
+ }
99
+
100
+ /** Where a file opens: its line and the match to select there, columns from 1. */
101
+ export interface FileTarget {
102
+ line: number;
103
+ column?: number;
104
+ /** Lines to select, as those a link names (`#L10-L20`): to `endColumn` of this line, or to its end. */
105
+ endLine?: number;
106
+ endColumn?: number;
107
+ }
108
+
109
+ export interface OpenOptions {
110
+ /** Behind the tab shown (the tabs of before, when the page loads). */
111
+ preserveFocus?: boolean;
112
+ /** As a single click: the next preview takes its place, until it is pinned (a double click, an edit). */
113
+ preview?: boolean;
114
+ }
115
+
116
+ export function fileId(cwd: string, path: string): string {
117
+ return `ta-workspace:file:${cwd}:${path}`;
118
+ }
119
+
120
+ /** The line to go to in an open file: each request a new object, so that the same line is gone to again. */
121
+ const targets = new Map<string, { target: FileTarget }>();
122
+ const targetListeners = new Set<() => void>();
123
+
124
+ function useTarget(id: string): { target: FileTarget } | undefined {
125
+ return React.useSyncExternalStore(
126
+ listener => {
127
+ targetListeners.add(listener);
128
+ return () => targetListeners.delete(listener);
129
+ },
130
+ () => targets.get(id),
131
+ );
132
+ }
133
+
134
+ /** One component for each tab: opening a file again goes to its line without making its editor anew, so what the user typed stays. */
135
+ const renders = new Map<string, React.ComponentType>();
136
+
137
+ /** Opens a file of `cwd`, at a line (and a match) when given. */
138
+ export function openFile(cwd: string, path: string, target?: FileTarget, options: OpenOptions = {}): void {
139
+ const id = fileId(cwd, path);
140
+ const name = WorkspaceUtil.basename(path);
141
+ if (target) {
142
+ targets.set(id, { target });
143
+ for (const listener of targetListeners) {
144
+ listener();
145
+ }
146
+ }
147
+ OpenFiles.add({ id, kind: 'file', title: name, detail: path, cwd, reopen: () => openFile(cwd, path), kept: { kind: 'file', cwd, path } });
148
+ pi.ui.openEditor(
149
+ {
150
+ id,
151
+ title: name,
152
+ icon: fileTabIcon(path),
153
+ render: fileRender(id, cwd, path),
154
+ onClose: () => {
155
+ renders.delete(id);
156
+ targets.delete(id);
157
+ OpenFiles.remove(id);
158
+ },
159
+ },
160
+ options,
161
+ );
162
+ }
163
+
164
+ function fileRender(id: string, cwd: string, path: string): React.ComponentType {
165
+ let render = renders.get(id);
166
+ if (!render) {
167
+ render = () => <FileEditor id={id} cwd={cwd} path={path} />;
168
+ renders.set(id, render);
169
+ }
170
+ return render;
171
+ }
172
+
173
+ /** Opens the change of a file: staged (index against HEAD) or not (working tree against the index). */
174
+ export function openDiff(cwd: string, path: string, staged: boolean, options: OpenOptions = {}): void {
175
+ const id = `ta-workspace:diff:${staged ? 'staged' : 'work'}:${cwd}:${path}`;
176
+ const title = t(staged ? 'stagedTitle' : 'diffTitle', { name: WorkspaceUtil.basename(path) });
177
+ OpenFiles.add({ id, kind: 'diff', title, detail: path, cwd, reopen: () => openDiff(cwd, path, staged), kept: { kind: 'diff', cwd, path, staged } });
178
+ pi.ui.openEditor(
179
+ {
180
+ id,
181
+ title: () => t(staged ? 'stagedTitle' : 'diffTitle', { name: WorkspaceUtil.basename(path) }),
182
+ icon: fileTabIcon(path),
183
+ render: () => <DiffEditor id={id} cwd={cwd} path={path} staged={staged} />,
184
+ onClose: () => OpenFiles.remove(id),
185
+ },
186
+ options,
187
+ );
188
+ }
189
+
190
+ /** Closes the tabs of a path and of what was inside it (a file renamed or deleted). */
191
+ export function closeEditorsOf(cwd: string, path: string): void {
192
+ for (const file of OpenFiles.list()) {
193
+ if (file.cwd === cwd && WorkspaceUtil.within(file.detail, path)) {
194
+ closeEditor(file.id);
195
+ }
196
+ }
197
+ }
198
+
199
+ export function closeEditor(id: string): void {
200
+ pi.ui.closeEditor(id);
201
+ OpenFiles.remove(id);
202
+ }
203
+
204
+ function Message({ children, tone }: { children: React.ReactNode; tone?: 'error' }) {
205
+ return <div className={`taw-message ${tone === 'error' ? 'taw-error' : ''}`}>{children}</div>;
206
+ }
207
+
208
+ function Header({ path, extra }: { path: string; extra?: React.ReactNode }) {
209
+ return (
210
+ <header className="taw-editor-head">
211
+ <span className="taw-editor-path" title={path}>
212
+ {path}
213
+ </span>
214
+ {extra}
215
+ </header>
216
+ );
217
+ }
218
+
219
+ /** The ETag and the size of the file at `url`, read again when the agent may have changed files. */
220
+ function useVersion(url: string | undefined): { version?: string; size?: number } {
221
+ const changed = useFilesChanged();
222
+ const [state, setState] = React.useState<{ version?: string; size?: number }>({});
223
+ React.useEffect(() => {
224
+ let live = true;
225
+ if (url) {
226
+ fetch(url, { method: 'HEAD' }).then(
227
+ response =>
228
+ live &&
229
+ setState(previous => {
230
+ const version = response.headers.get('etag') ?? undefined;
231
+ const size = Number(response.headers.get('content-length') ?? 0);
232
+ return previous.version === version && previous.size === size ? previous : { version, size };
233
+ }),
234
+ () => undefined,
235
+ );
236
+ }
237
+ return () => {
238
+ live = false;
239
+ };
240
+ }, [url, changed]);
241
+ return state;
242
+ }
243
+
244
+ type Mode = 'preview' | 'code';
245
+
246
+ function ModeSwitch({ mode, onChange }: { mode: Mode; onChange(mode: Mode): void }) {
247
+ return (
248
+ <fieldset className="taw-segmented">
249
+ <button type="button" className={mode === 'preview' ? 'taw-on' : ''} aria-pressed={mode === 'preview'} onClick={() => onChange('preview')}>
250
+ <Glyph name="Eye" size={13} />
251
+ {t('preview')}
252
+ </button>
253
+ <button type="button" className={mode === 'code' ? 'taw-on' : ''} aria-pressed={mode === 'code'} onClick={() => onChange('code')}>
254
+ <Glyph name="Code" size={13} />
255
+ {t('edit')}
256
+ </button>
257
+ </fieldset>
258
+ );
259
+ }
260
+
261
+ /**
262
+ * A file of the workspace: Markdown, pages, images, videos, sounds and PDFs open as a preview, the rest
263
+ * (and the text behind a preview) in Monaco, saved with Ctrl+S or Cmd+S. A file opened at a line opens
264
+ * in the editor. What the agent changes on disk shows at once while the user has not changed the file.
265
+ */
266
+ function FileEditor({ id, cwd, path }: { id: string; cwd: string; path: string }) {
267
+ const kind = PreviewUtil.kind(path);
268
+ const textual = !kind || PreviewUtil.hasText(path);
269
+ const goTo = useTarget(id);
270
+ const target = goTo?.target;
271
+ const [mode, setMode] = React.useState<Mode>(kind && !target ? 'preview' : 'code');
272
+ // A line to go to shows the text.
273
+ React.useEffect(() => {
274
+ if (goTo && textual) {
275
+ setMode('code');
276
+ }
277
+ }, [goTo, textual]);
278
+ const changed = useFilesChanged();
279
+ const file = useLoad<TaFileContent | undefined>(async () => (textual ? pi.workspace.readFile(path, cwd) : undefined), [cwd, path, changed]);
280
+ const url = useLoad(() => (kind ? pi.workspace.fileUrl(path, cwd) : Promise.resolve(undefined)), [cwd, path]);
281
+ const { version, size } = useVersion(kind && kind !== 'markdown' ? url.value : undefined);
282
+ const [info, setInfo] = React.useState<string>();
283
+ /** The user's text while it differs from the file's; undefined when they are the same. */
284
+ const [draft, setDraft] = React.useState<string>();
285
+ /** The file's text when the user started changing it: another one means the file changed meanwhile. */
286
+ const [base, setBase] = React.useState<string>();
287
+ const [saving, setSaving] = React.useState(false);
288
+ const text = file.value?.text;
289
+ const dirty = draft !== undefined && draft !== text;
290
+ React.useEffect(() => pi.ui.setEditorDirty(id, dirty), [id, dirty]);
291
+
292
+ React.useEffect(() => {
293
+ if (draft !== undefined && draft === text) {
294
+ setDraft(undefined);
295
+ setBase(undefined);
296
+ }
297
+ }, [draft, text]);
298
+
299
+ const save = async (value: string) => {
300
+ if (saving || value === text) {
301
+ return;
302
+ }
303
+ setSaving(true);
304
+ try {
305
+ await pi.workspace.writeFile(path, value, cwd);
306
+ setDraft(value);
307
+ file.reload();
308
+ } catch (error) {
309
+ pi.ui.notify(t('saveFailed', { message: Host.message(error) }), 'error');
310
+ } finally {
311
+ setSaving(false);
312
+ }
313
+ };
314
+
315
+ const discard = () => {
316
+ setDraft(undefined);
317
+ setBase(undefined);
318
+ };
319
+
320
+ const error = file.error ?? url.error;
321
+ if (error) {
322
+ return <Message tone="error">{t('failed', { message: error })}</Message>;
323
+ }
324
+ if ((textual && !file.value) || (kind && !url.value)) {
325
+ return <Message>{t('loading')}</Message>;
326
+ }
327
+ if (file.value?.binary && !kind) {
328
+ return (
329
+ <div className="taw-editor">
330
+ <Header path={path} />
331
+ <Message>{t('binary', { size: WorkspaceUtil.size(file.value.size) })}</Message>
332
+ </div>
333
+ );
334
+ }
335
+ const readOnly = !!file.value?.truncated;
336
+ const showPreview = !!kind && (mode === 'preview' || !textual);
337
+ const extra = (
338
+ <div className="taw-editor-tools">
339
+ {showPreview && info && <span className="taw-note">{info}</span>}
340
+ {!showPreview && readOnly && <span className="taw-note">{t('truncated')}</span>}
341
+ {!showPreview && dirty && base !== undefined && base !== text && (
342
+ <span className="taw-note taw-warning">
343
+ {t('changedOnDisk')}{' '}
344
+ <button type="button" className="taw-link" onClick={discard}>
345
+ {t('reload')}
346
+ </button>
347
+ </span>
348
+ )}
349
+ {!showPreview && dirty && (
350
+ <button type="button" className="taw-button taw-small" disabled={saving} onClick={() => draft !== undefined && void save(draft)}>
351
+ <span className="taw-dot" aria-hidden="true" />
352
+ {t('save')}
353
+ </button>
354
+ )}
355
+ {kind && textual && <ModeSwitch mode={mode} onChange={setMode} />}
356
+ </div>
357
+ );
358
+ const fileUrl = url.value && PreviewUtil.versioned(url.value, version);
359
+ return (
360
+ <div className="taw-editor">
361
+ <Header path={path} extra={extra} />
362
+ {showPreview && fileUrl && kind === 'markdown' && <MarkdownPreview text={draft ?? text ?? ''} url={fileUrl} />}
363
+ {showPreview && fileUrl && kind && kind !== 'markdown' && (
364
+ <MediaPreview key={fileUrl} kind={kind} url={fileUrl} size={file.value?.size ?? size ?? 0} onInfo={setInfo} />
365
+ )}
366
+ {!showPreview && (
367
+ <pi.ui.CodeEditor
368
+ path={path}
369
+ value={draft ?? text ?? ''}
370
+ readOnly={readOnly}
371
+ line={target?.line}
372
+ column={target?.column}
373
+ endColumn={target?.endColumn}
374
+ selection={
375
+ target?.endLine
376
+ ? { startLine: target.line, startColumn: target.column, endLine: target.endLine, endColumn: target.endColumn }
377
+ : undefined
378
+ }
379
+ onChange={value => {
380
+ setBase(previous => (previous === undefined ? text : previous));
381
+ setDraft(value);
382
+ }}
383
+ onSave={value => void save(value)}
384
+ />
385
+ )}
386
+ </div>
387
+ );
388
+ }
389
+
390
+ /**
391
+ * The change of a file in Monaco's diff editor, as source control shows it: side by side (inline when
392
+ * narrow), the unchanged lines folded. A change not staged can be edited on the right and saved, as the
393
+ * file itself; from the head it is staged or unstaged, or the file opened.
394
+ */
395
+ function DiffEditor({ id, cwd, path, staged }: { id: string; cwd: string; path: string; staged: boolean }) {
396
+ const changed = useFilesChanged();
397
+ const diff = useLoad(() => WorkspaceClient.diff(cwd, path, staged), [cwd, path, staged, changed]);
398
+ const [inline, setInline] = React.useState(false);
399
+ const [nav, setNav] = React.useState<{ changes: number; next(): void; previous(): void }>();
400
+ const [draft, setDraft] = React.useState<string>();
401
+ const after = diff.value?.after;
402
+ const dirty = draft !== undefined && draft !== after;
403
+ React.useEffect(() => pi.ui.setEditorDirty(id, dirty), [id, dirty]);
404
+ React.useEffect(() => {
405
+ if (draft !== undefined && draft === after) {
406
+ setDraft(undefined);
407
+ }
408
+ }, [draft, after]);
409
+ const save = async (value: string) => {
410
+ try {
411
+ await pi.workspace.writeFile(path, value, cwd);
412
+ setDraft(value);
413
+ diff.reload();
414
+ } catch (error) {
415
+ pi.ui.notify(t('saveFailed', { message: Host.message(error) }), 'error');
416
+ }
417
+ };
418
+ const run = async (args: string[]) => {
419
+ try {
420
+ await WorkspaceClient.git(cwd, args);
421
+ FilesChanged.notify();
422
+ } catch (error) {
423
+ pi.ui.notify(Host.message(error), 'error');
424
+ }
425
+ };
426
+ if (diff.error) {
427
+ return <Message tone="error">{t('failed', { message: diff.error })}</Message>;
428
+ }
429
+ if (!diff.value) {
430
+ return <Message>{t('loading')}</Message>;
431
+ }
432
+ const extra = (
433
+ <div className="taw-editor-tools">
434
+ {nav && <span className="taw-note">{nav.changes === 0 ? t('unchanged') : t('changeCount', { count: nav.changes })}</span>}
435
+ {nav && nav.changes > 0 && (
436
+ <React.Fragment>
437
+ <Action icon="ArrowUp" label={t('previousChange')} onClick={() => nav.previous()} />
438
+ <Action icon="ArrowDown" label={t('nextChange')} onClick={() => nav.next()} />
439
+ </React.Fragment>
440
+ )}
441
+ <Action icon={inline ? 'Columns2' : 'Rows2'} label={t(inline ? 'sideBySide' : 'inline')} onClick={() => setInline(!inline)} />
442
+ <Action icon="File" label={t('openFile')} onClick={() => openFile(cwd, path)} />
443
+ {staged ? (
444
+ <Action icon="Minus" label={t('unstage')} onClick={() => void run(GitUtil.unstage([path], false))} />
445
+ ) : (
446
+ <Action icon="Plus" label={t('stage')} onClick={() => void run(GitUtil.stage([path]))} />
447
+ )}
448
+ {dirty && (
449
+ <button type="button" className="taw-button taw-small" onClick={() => draft !== undefined && void save(draft)}>
450
+ <span className="taw-dot" aria-hidden="true" />
451
+ {t('save')}
452
+ </button>
453
+ )}
454
+ </div>
455
+ );
456
+ return (
457
+ <div className="taw-editor">
458
+ <Header path={path} extra={extra} />
459
+ <pi.ui.DiffEditor
460
+ path={path}
461
+ original={diff.value.before}
462
+ modified={draft ?? diff.value.after}
463
+ inline={inline}
464
+ readOnly={staged}
465
+ onChange={setDraft}
466
+ onSave={value => void save(value)}
467
+ onDiff={setNav}
468
+ />
469
+ </div>
470
+ );
471
+ }