@celljs/ta-workspace 0.0.0-stage → 4.6.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.
@@ -0,0 +1,479 @@
1
+ import type { TaDirEntry } from '@celljs/ta-protocol';
2
+ import { Action, copyText, Empty, Glyph, type MenuItem, NameInput, useContextMenu, useKept, ViewHeader } from './common';
3
+ import { closeEditorsOf, fileId, OpenFiles, openFile } from './editors';
4
+ import { FileIcon } from './file-icon';
5
+ import { Channel, FilesChanged, Host, MAC, PACKAGE, pi, useFilesChanged, useLoad } from './host';
6
+ import { gitLabel, t } from './i18n';
7
+ import { React } from './react';
8
+ import { SearchRequests } from './search';
9
+ import { type GitDecorations, GitUtil } from './util/git';
10
+ import { WorkspaceUtil } from './util/workspace';
11
+ import { WorkspaceClient } from './workspace-client';
12
+
13
+ interface Tree {
14
+ children: Map<string, TaDirEntry[]>;
15
+ expanded: Set<string>;
16
+ error?: string;
17
+ /** The directories open before are open again: from now on, what is open is kept. */
18
+ restored?: boolean;
19
+ }
20
+
21
+ /** A name being typed in the tree: a new file or folder in `parent`, or another name for `path`. */
22
+ type Editing = { kind: 'create'; parent: string; directory: boolean } | { kind: 'rename'; path: string };
23
+
24
+ const trees = new Map<string, Tree>();
25
+ /** The directory shown, by the directory of the conversation: that one, unless another was picked for it. */
26
+ const roots = new Map<string, string>();
27
+ const INDENT = 12;
28
+ /** The directories open, kept for each directory of a conversation (pi.storage.directory). */
29
+ const EXPANDED_KEY = 'explorer.expanded';
30
+ const NO_DECORATIONS: GitDecorations = { files: new Map(), folders: new Map(), ignored: [] };
31
+
32
+ /** Files to show in the explorer, as `reveal in explorer` of source control or open files. */
33
+ export const RevealRequests = new Channel<{ cwd: string; path: string }>();
34
+ /** A directory to show in place of the conversation's, as a link of a reply to it. */
35
+ export const ShowDirectory = new Channel<string>();
36
+
37
+ /** The files of the directory of the conversation shown, which follows the conversation; another can be picked for it. */
38
+ export function ExplorerView() {
39
+ const cwd = pi.ui.useCwd();
40
+ const changed = useFilesChanged();
41
+ const active = pi.ui.useActiveEditor();
42
+ const [root, setRoot] = useKept(roots, cwd, () => cwd);
43
+ const [tree, setTree] = useKept<Tree>(trees, root, () => ({ children: new Map(), expanded: new Set() }));
44
+ const [selected, setSelected] = React.useState<string>();
45
+ const [editing, setEditing] = React.useState<Editing>();
46
+ const [picking, setPicking] = React.useState(false);
47
+ const [menu, openMenu] = useContextMenu();
48
+ const list = React.useRef<HTMLDivElement>(null);
49
+ const git = useLoad(() => WorkspaceClient.status(root, true).catch(() => undefined), [root, changed]);
50
+ const decorations = React.useMemo(() => (git.value?.repository ? GitUtil.decorations(git.value) : NO_DECORATIONS), [git.value]);
51
+ const FolderPicker = pi.ui.FolderPicker;
52
+
53
+ const load = React.useCallback(
54
+ async (dirs: string[]) => {
55
+ const read = await Promise.all(
56
+ dirs.map(async dir => {
57
+ try {
58
+ return [dir, await pi.workspace.listDirectory(dir, root)] as const;
59
+ } catch (error) {
60
+ return [dir, Host.message(error)] as const;
61
+ }
62
+ }),
63
+ );
64
+ setTree(previous => {
65
+ const children = new Map(previous.children);
66
+ let error: string | undefined;
67
+ for (const [dir, result] of read) {
68
+ if (typeof result === 'string') {
69
+ children.delete(dir);
70
+ error = dir ? error : result;
71
+ } else {
72
+ children.set(dir, result);
73
+ }
74
+ }
75
+ return { ...previous, children, error };
76
+ });
77
+ },
78
+ [root, setTree],
79
+ );
80
+
81
+ // What is open is read again when the agent changed files, or the directory changed.
82
+ React.useEffect(() => {
83
+ void load(['', ...tree.expanded]);
84
+ }, [load, changed]);
85
+
86
+ // The directories open when this directory was shown last, in this browser or another.
87
+ React.useEffect(() => {
88
+ if (tree.restored) {
89
+ return;
90
+ }
91
+ let live = true;
92
+ pi.storage
93
+ .directory(root)
94
+ .get<unknown>(EXPANDED_KEY)
95
+ .then(
96
+ kept => {
97
+ const paths = WorkspaceUtil.paths(kept);
98
+ if (live) {
99
+ setTree(previous => ({ ...previous, restored: true, expanded: new Set([...previous.expanded, ...paths]) }));
100
+ void load(paths);
101
+ }
102
+ },
103
+ () => live && setTree(previous => ({ ...previous, restored: true })),
104
+ );
105
+ return () => {
106
+ live = false;
107
+ };
108
+ }, [root]);
109
+
110
+ const expand = (change: (expanded: Set<string>) => Set<string>) => {
111
+ const expanded = change(tree.expanded);
112
+ setTree(previous => ({ ...previous, expanded: change(previous.expanded) }));
113
+ if (tree.restored) {
114
+ pi.storage
115
+ .directory(root)
116
+ .set(EXPANDED_KEY, [...expanded])
117
+ .catch(() => undefined);
118
+ }
119
+ return expanded;
120
+ };
121
+
122
+ /** Shows a path: the folders around it open, it selected and scrolled to. */
123
+ const reveal = (path: string) => {
124
+ const expanded = expand(previous => WorkspaceUtil.reveal(previous, path));
125
+ void load([...expanded].filter(dir => !tree.children.has(dir) && WorkspaceUtil.within(path, dir)));
126
+ setSelected(path);
127
+ };
128
+
129
+ // The file shown in the workbench is the one selected, as an IDE follows the editor.
130
+ React.useEffect(() => {
131
+ const prefix = fileId(root, '');
132
+ if (active?.startsWith(prefix)) {
133
+ reveal(active.slice(prefix.length));
134
+ }
135
+ }, [active, root]);
136
+
137
+ ShowDirectory.useReceive(directory => {
138
+ setRoot(directory);
139
+ setSelected(undefined);
140
+ });
141
+
142
+ RevealRequests.useReceive(request => {
143
+ if (request.cwd === root || request.cwd === cwd) {
144
+ if (request.cwd !== root) {
145
+ setRoot(request.cwd);
146
+ }
147
+ reveal(request.path);
148
+ }
149
+ });
150
+
151
+ React.useEffect(() => {
152
+ if (selected) {
153
+ list.current?.querySelector<HTMLElement>(`[data-path="${CSS.escape(selected)}"]`)?.scrollIntoView({ block: 'nearest' });
154
+ }
155
+ }, [selected]);
156
+
157
+ const toggle = (entry: TaDirEntry) => {
158
+ const opening = !tree.expanded.has(entry.path);
159
+ expand(expanded => WorkspaceUtil.toggle(expanded, entry.path));
160
+ if (opening && !tree.children.has(entry.path)) {
161
+ void load([entry.path]);
162
+ }
163
+ };
164
+
165
+ const entryOf = (path: string): TaDirEntry | undefined => tree.children.get(WorkspaceUtil.dirname(path))?.find(entry => entry.path === path);
166
+
167
+ /** Where a new file goes: the folder selected, or the folder of the file selected. */
168
+ const targetFolder = (path = selected): string => {
169
+ const entry = path === undefined ? undefined : entryOf(path);
170
+ return !entry ? '' : entry.kind === 'directory' ? entry.path : WorkspaceUtil.dirname(entry.path);
171
+ };
172
+
173
+ const startCreate = (directory: boolean, parent = targetFolder()) => {
174
+ if (parent) {
175
+ expand(previous => WorkspaceUtil.reveal(new Set([...previous, parent]), parent));
176
+ if (!tree.children.has(parent)) {
177
+ void load([parent]);
178
+ }
179
+ }
180
+ setEditing({ kind: 'create', parent, directory });
181
+ };
182
+
183
+ const siblings = (dir: string, except?: string) => (tree.children.get(dir) ?? []).filter(entry => entry.path !== except).map(entry => entry.name);
184
+
185
+ const validate = (dir: string, except?: string) => (name: string) => {
186
+ const problem = WorkspaceUtil.validateName(name, siblings(dir, except));
187
+ return problem && { message: t(problem.key, { name }), severity: problem.severity };
188
+ };
189
+
190
+ const finishCreate = async (parent: string, directory: boolean, name: string | undefined) => {
191
+ setEditing(undefined);
192
+ if (!name) {
193
+ return;
194
+ }
195
+ const path = WorkspaceUtil.join(parent, name.replace(/\/+$/, ''));
196
+ try {
197
+ if (directory) {
198
+ await WorkspaceClient.createFolder(root, path);
199
+ } else {
200
+ await WorkspaceClient.createFile(root, path);
201
+ }
202
+ await load([parent, ...[...tree.expanded].filter(dir => WorkspaceUtil.within(dir, parent))]);
203
+ reveal(path);
204
+ if (!directory) {
205
+ openFile(root, path);
206
+ }
207
+ FilesChanged.notify();
208
+ } catch (error) {
209
+ pi.ui.notify(t('createFailed', { message: Host.message(error) }), 'error');
210
+ }
211
+ };
212
+
213
+ const finishRename = async (from: string, name: string | undefined) => {
214
+ setEditing(undefined);
215
+ if (!name) {
216
+ return;
217
+ }
218
+ const dir = WorkspaceUtil.dirname(from);
219
+ const to = WorkspaceUtil.join(dir, name);
220
+ const reopen = OpenFiles.list().filter(file => file.kind === 'file' && file.cwd === root && WorkspaceUtil.within(file.detail, from));
221
+ try {
222
+ await WorkspaceClient.rename(root, from, to);
223
+ closeEditorsOf(root, from);
224
+ for (const file of reopen) {
225
+ openFile(root, to + file.detail.slice(from.length), undefined, { preserveFocus: true });
226
+ }
227
+ expand(previous => new Set([...previous].map(path => (WorkspaceUtil.within(path, from) ? to + path.slice(from.length) : path))));
228
+ await load([dir]);
229
+ setSelected(to);
230
+ FilesChanged.notify();
231
+ } catch (error) {
232
+ pi.ui.notify(t('renameFailed', { message: Host.message(error) }), 'error');
233
+ }
234
+ };
235
+
236
+ const remove = async (entry: TaDirEntry) => {
237
+ const confirmed = await pi.ui.confirm(t(entry.kind === 'directory' ? 'deleteFolder' : 'deleteFile', { name: entry.name }), t('irreversible'), {
238
+ confirmLabel: t('delete'),
239
+ danger: true,
240
+ });
241
+ if (!confirmed) {
242
+ return;
243
+ }
244
+ try {
245
+ await WorkspaceClient.remove(root, entry.path);
246
+ closeEditorsOf(root, entry.path);
247
+ setSelected(previous => (previous && WorkspaceUtil.within(previous, entry.path) ? undefined : previous));
248
+ await load([WorkspaceUtil.dirname(entry.path)]);
249
+ FilesChanged.notify();
250
+ } catch (error) {
251
+ pi.ui.notify(t('deleteFailed', { message: Host.message(error) }), 'error');
252
+ }
253
+ };
254
+
255
+ const absolute = (path: string) => (path ? `${root.replace(/\/+$/, '')}/${path}` : root);
256
+
257
+ const findInFolder = (path: string) => {
258
+ SearchRequests.send({ cwd: root, include: path ? `${path}/**` : '' });
259
+ pi.ui.showView(`${PACKAGE}/search`);
260
+ };
261
+
262
+ const menuFor = (entry?: TaDirEntry): MenuItem[] => {
263
+ const folder = entry ? (entry.kind === 'directory' ? entry.path : WorkspaceUtil.dirname(entry.path)) : '';
264
+ const items: MenuItem[] = [
265
+ { label: t('newFile'), run: () => startCreate(false, folder) },
266
+ { label: t('newFolder'), run: () => startCreate(true, folder) },
267
+ ];
268
+ if (!entry) {
269
+ return [
270
+ ...items,
271
+ '-',
272
+ { label: t('findInFolder'), run: () => findInFolder('') },
273
+ { label: t('refresh'), run: () => void load(['', ...tree.expanded]) },
274
+ ];
275
+ }
276
+ return [
277
+ ...items,
278
+ '-',
279
+ ...(entry.kind === 'file' ? [{ label: t('open'), run: () => openFile(root, entry.path) }] : []),
280
+ ...(entry.kind === 'directory' ? [{ label: t('findInFolder'), run: () => findInFolder(entry.path) }] : []),
281
+ '-',
282
+ { label: t('copyPath'), keys: MAC ? '⌥⌘C' : 'Shift+Alt+C', run: () => copyText(absolute(entry.path), t('copied')) },
283
+ { label: t('copyRelativePath'), run: () => copyText(entry.path, t('copied')) },
284
+ '-',
285
+ { label: t('rename'), keys: MAC ? '↵' : 'F2', run: () => setEditing({ kind: 'rename', path: entry.path }) },
286
+ { label: t('delete'), keys: MAC ? '⌘⌫' : 'Delete', run: () => void remove(entry) },
287
+ ];
288
+ };
289
+
290
+ const rows = WorkspaceUtil.rows(tree.children, tree.expanded);
291
+ const activate = (entry: TaDirEntry, pin: boolean) => {
292
+ setSelected(entry.path);
293
+ if (entry.kind === 'directory') {
294
+ if (!pin) {
295
+ toggle(entry);
296
+ }
297
+ } else {
298
+ openFile(root, entry.path, undefined, { preview: !pin });
299
+ }
300
+ };
301
+
302
+ const onKey = (event: React.KeyboardEvent, entry: TaDirEntry, expanded: boolean) => {
303
+ const row = event.currentTarget as HTMLElement;
304
+ const move = (to: Element | null | undefined) => {
305
+ const path = (to as HTMLElement | null)?.dataset.path;
306
+ if (path !== undefined) {
307
+ setSelected(path);
308
+ (to as HTMLElement).focus();
309
+ }
310
+ };
311
+ const all = () => [...(list.current?.querySelectorAll<HTMLElement>('[data-path]') ?? [])];
312
+ if (event.key === 'ArrowRight' && entry.kind === 'directory') {
313
+ event.preventDefault();
314
+ if (!expanded) {
315
+ toggle(entry);
316
+ } else {
317
+ move(row.nextElementSibling);
318
+ }
319
+ } else if (event.key === 'ArrowLeft') {
320
+ event.preventDefault();
321
+ if (expanded) {
322
+ toggle(entry);
323
+ } else {
324
+ move(list.current?.querySelector(`[data-path="${CSS.escape(WorkspaceUtil.dirname(entry.path))}"]`));
325
+ }
326
+ } else if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
327
+ event.preventDefault();
328
+ move(event.key === 'ArrowDown' ? row.nextElementSibling : row.previousElementSibling);
329
+ } else if (event.key === 'Home' || event.key === 'End') {
330
+ event.preventDefault();
331
+ const rowsShown = all();
332
+ move(event.key === 'Home' ? rowsShown[0] : rowsShown[rowsShown.length - 1]);
333
+ } else if (event.key === 'Enter' && MAC) {
334
+ // As Finder and VS Code on a Mac: Enter renames, Cmd+Down opens.
335
+ event.preventDefault();
336
+ setEditing({ kind: 'rename', path: entry.path });
337
+ } else if (event.key === 'Enter' || (event.key === 'ArrowDown' && event.metaKey) || event.key === ' ') {
338
+ event.preventDefault();
339
+ activate(entry, true);
340
+ } else if (event.key === 'F2') {
341
+ event.preventDefault();
342
+ setEditing({ kind: 'rename', path: entry.path });
343
+ } else if (event.key === 'Delete' || (event.key === 'Backspace' && event.metaKey)) {
344
+ event.preventDefault();
345
+ void remove(entry);
346
+ } else if (event.key === 'c' && event.altKey && (event.metaKey || event.shiftKey)) {
347
+ event.preventDefault();
348
+ copyText(absolute(entry.path), t('copied'));
349
+ } else if (event.key === 'ContextMenu' || (event.key === 'F10' && event.shiftKey)) {
350
+ openMenu(event, menuFor(entry));
351
+ }
352
+ };
353
+
354
+ const creating = editing?.kind === 'create' ? editing : undefined;
355
+ const createRow = (depth: number) =>
356
+ creating && (
357
+ <div key="taw-create" className="taw-row taw-tree-row taw-editing" style={{ paddingLeft: 8 + depth * INDENT }}>
358
+ <Guides depth={depth} />
359
+ <span className="taw-twisty" />
360
+ {creating.directory ? <Glyph name="Folder" /> : <FileIcon path="" />}
361
+ <NameInput initial="" validate={validate(creating.parent)} onDone={name => void finishCreate(creating.parent, creating.directory, name)} />
362
+ </div>
363
+ );
364
+
365
+ const shown: React.ReactNode[] = [];
366
+ if (creating && creating.parent === '') {
367
+ shown.push(createRow(0));
368
+ }
369
+ for (const { entry, depth, expanded, loading } of rows) {
370
+ const renaming = editing?.kind === 'rename' && editing.path === entry.path;
371
+ const letter = entry.kind === 'directory' ? decorations.folders.get(entry.path) : decorations.files.get(entry.path);
372
+ const ignored = !letter && decorations.ignored.length > 0 && GitUtil.ignored(decorations, entry.path);
373
+ const color = WorkspaceUtil.gitColor(letter);
374
+ shown.push(
375
+ <div
376
+ key={entry.path}
377
+ role="treeitem"
378
+ tabIndex={selected === entry.path || (!selected && shown.length === 0) ? 0 : -1}
379
+ data-path={entry.path}
380
+ aria-expanded={entry.kind === 'directory' ? expanded : undefined}
381
+ aria-level={depth + 1}
382
+ aria-selected={selected === entry.path}
383
+ className={`taw-row taw-tree-row ${selected === entry.path ? 'taw-selected' : ''} ${ignored ? 'taw-ignored' : ''} ${letter === 'D' ? 'taw-deleted' : ''}`}
384
+ style={{ paddingLeft: 8 + depth * INDENT }}
385
+ title={letter ? `${entry.path} • ${gitLabel(letter)}` : entry.path}
386
+ onClick={() => !renaming && activate(entry, false)}
387
+ onDoubleClick={() => !renaming && activate(entry, true)}
388
+ onKeyDown={event => !renaming && onKey(event, entry, expanded)}
389
+ onContextMenu={event => {
390
+ setSelected(entry.path);
391
+ openMenu(event, menuFor(entry));
392
+ }}
393
+ >
394
+ <Guides depth={depth} />
395
+ <span className="taw-twisty">
396
+ {entry.kind === 'directory' && <Glyph name={loading ? 'LoaderCircle' : expanded ? 'ChevronDown' : 'ChevronRight'} size={14} />}
397
+ </span>
398
+ {entry.kind === 'directory' ? <Glyph name={expanded ? 'FolderOpen' : 'Folder'} /> : <FileIcon path={entry.name} />}
399
+ {renaming ? (
400
+ <NameInput
401
+ initial={entry.name}
402
+ selectBase={entry.kind === 'file'}
403
+ validate={validate(WorkspaceUtil.dirname(entry.path), entry.path)}
404
+ onDone={name => void finishRename(entry.path, name)}
405
+ />
406
+ ) : (
407
+ <React.Fragment>
408
+ <span className="taw-name" style={color ? { color } : undefined}>
409
+ {entry.name}
410
+ </span>
411
+ {letter && (
412
+ <span className="taw-letter" style={{ color }}>
413
+ {entry.kind === 'directory' ? '•' : letter}
414
+ </span>
415
+ )}
416
+ </React.Fragment>
417
+ )}
418
+ </div>,
419
+ );
420
+ if (creating && creating.parent === entry.path && expanded) {
421
+ shown.push(createRow(depth + 1));
422
+ }
423
+ }
424
+
425
+ return (
426
+ <div className="taw-view">
427
+ <ViewHeader title={WorkspaceUtil.basename(root) || t('explorer')} hint={root}>
428
+ {root !== cwd && (
429
+ <Action icon="RotateCcw" label={t('followConversation', { name: WorkspaceUtil.basename(cwd) || cwd })} onClick={() => setRoot(cwd)} />
430
+ )}
431
+ <Action icon="FilePlus" label={t('newFile')} onClick={() => startCreate(false)} />
432
+ <Action icon="FolderPlus" label={t('newFolder')} onClick={() => startCreate(true)} />
433
+ <Action icon="RefreshCw" label={t('refresh')} onClick={() => void load(['', ...tree.expanded])} />
434
+ <Action icon="ChevronsDownUp" label={t('collapseAll')} onClick={() => expand(() => new Set())} />
435
+ <Action icon="FolderOpen" label={t('changeFolder')} onClick={() => setPicking(true)} />
436
+ </ViewHeader>
437
+ <div
438
+ ref={list}
439
+ className="taw-list taw-tree"
440
+ role="tree"
441
+ aria-label={t('explorer')}
442
+ onContextMenu={event => event.target === event.currentTarget && openMenu(event, menuFor())}
443
+ onClick={event => event.target === event.currentTarget && setSelected(undefined)}
444
+ onKeyDown={event => event.key === 'Escape' && setSelected(undefined)}
445
+ >
446
+ {tree.error && <Empty tone="error">{t('failed', { message: tree.error })}</Empty>}
447
+ {!tree.error && !tree.children.has('') && <Empty>{t('loading')}</Empty>}
448
+ {!tree.error && tree.children.get('')?.length === 0 && !creating && <Empty>{t('empty')}</Empty>}
449
+ {shown}
450
+ </div>
451
+ {menu}
452
+ {picking && (
453
+ <FolderPicker
454
+ initial={root}
455
+ onClose={() => setPicking(false)}
456
+ onPick={path => {
457
+ setRoot(path);
458
+ setSelected(undefined);
459
+ setPicking(false);
460
+ }}
461
+ />
462
+ )}
463
+ </div>
464
+ );
465
+ }
466
+
467
+ /** The lines of the folders a row is in, as an IDE draws them while the pointer is over the tree. */
468
+ function Guides({ depth }: { depth: number }) {
469
+ if (!depth) {
470
+ return null;
471
+ }
472
+ return (
473
+ <span className="taw-guides" aria-hidden="true">
474
+ {Array.from({ length: depth }, (_, index) => (
475
+ <span key={index} className="taw-guide" style={{ left: 15 + index * INDENT }} />
476
+ ))}
477
+ </span>
478
+ );
479
+ }
@@ -0,0 +1,21 @@
1
+ import type { WebIcon } from '@celljs/ta-web/lib/browser/extension/web-extension-api';
2
+ // biome-ignore lint/style/useImportType: the JSX below is React.createElement
3
+ import { React } from './react';
4
+ import { FileIconUtil } from './util/file-icon';
5
+
6
+ /** The icon of a file, drawn with the Seti font (style.ts) in the colors of the page's theme. */
7
+ export function FileIcon({ path, size = 16 }: { path: string; size?: number | string }) {
8
+ const [character, dark, light] = FileIconUtil.of(path);
9
+ const box = typeof size === 'number' ? size : Number.parseFloat(size) || 16;
10
+ const style = { width: box, height: box, fontSize: box * 1.25, '--taw-icon': dark, '--taw-icon-light': light } as React.CSSProperties;
11
+ return (
12
+ <span className="taw-file-icon" style={style} aria-hidden="true">
13
+ {String.fromCharCode(character)}
14
+ </span>
15
+ );
16
+ }
17
+
18
+ /** The icon of a file for a tab of the workbench. */
19
+ export function fileTabIcon(path: string): WebIcon {
20
+ return ({ size }) => <FileIcon path={path} size={size} />;
21
+ }
@@ -0,0 +1,121 @@
1
+ import type { WebExtensionAPI, WebIcon } from '@celljs/ta-web/lib/browser/extension/web-extension-api';
2
+ import { React } from './react';
3
+
4
+ /** The name of this package: the ids of its views are `<name>/<view>`. */
5
+ export const PACKAGE = '@celljs/ta-workspace';
6
+
7
+ /** The API ta gave the extension when it started. */
8
+ export let pi: WebExtensionAPI;
9
+
10
+ export function bindHost(api: WebExtensionAPI): void {
11
+ pi = api;
12
+ }
13
+
14
+ export namespace Host {
15
+ /** An icon of the page by its lucide name; a blank one when the page does not have it. */
16
+ export function icon(name: string): WebIcon {
17
+ return pi.ui.icons[name] ?? (() => null);
18
+ }
19
+
20
+ /** Errors of the server, as the user reads them. */
21
+ export function message(error: unknown): string {
22
+ return error instanceof Error ? error.message : String(error);
23
+ }
24
+ }
25
+
26
+ /** A value that is read again when `deps` change; `reload` reads it again now. */
27
+ export function useLoad<T>(load: () => Promise<T>, deps: unknown[]): { value?: T; error?: string; loading: boolean; reload(): void } {
28
+ const [state, setState] = React.useState<{ value?: T; error?: string; loading: boolean }>({ loading: true });
29
+ const [tick, setTick] = React.useState(0);
30
+ React.useEffect(() => {
31
+ let live = true;
32
+ setState(previous => ({ ...previous, loading: true }));
33
+ load().then(
34
+ value => live && setState({ value, loading: false }),
35
+ error => live && setState({ error: Host.message(error), loading: false }),
36
+ );
37
+ return () => {
38
+ live = false;
39
+ };
40
+ }, [...deps, tick]);
41
+ return { ...state, reload: React.useCallback(() => setTick(value => value + 1), []) };
42
+ }
43
+
44
+ /** Bumped when the agent changed files: a tool ran or a run ended. */
45
+ export function useFilesChanged(): number {
46
+ const [version, setVersion] = React.useState(0);
47
+ React.useEffect(() => FilesChanged.subscribe(() => setVersion(value => value + 1)), []);
48
+ return version;
49
+ }
50
+
51
+ /** A request one view makes of another (reveal a file, search a folder), kept until the view that takes it is there. */
52
+ export class Channel<T> {
53
+ protected pending?: T;
54
+ protected readonly listeners = new Set<() => void>();
55
+
56
+ send(value: T): void {
57
+ this.pending = value;
58
+ for (const listener of this.listeners) {
59
+ listener();
60
+ }
61
+ }
62
+
63
+ take(): T | undefined {
64
+ const value = this.pending;
65
+ this.pending = undefined;
66
+ return value;
67
+ }
68
+
69
+ /** A React hook: `receive` gets each request, also one sent before the view was there. */
70
+ useReceive(receive: (value: T) => void): void {
71
+ const callback = React.useRef(receive);
72
+ callback.current = receive;
73
+ React.useEffect(() => {
74
+ const deliver = () => {
75
+ const value = this.take();
76
+ if (value !== undefined) {
77
+ callback.current(value);
78
+ }
79
+ };
80
+ deliver();
81
+ this.listeners.add(deliver);
82
+ return () => {
83
+ this.listeners.delete(deliver);
84
+ };
85
+ }, []);
86
+ }
87
+ }
88
+
89
+ /** Whether the page runs on a Mac: the keys it names. */
90
+ export const MAC = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform);
91
+
92
+ /** Whoever shows files hears when the agent may have changed them. */
93
+ export namespace FilesChanged {
94
+ const listeners = new Set<() => void>();
95
+ let timer: ReturnType<typeof setTimeout> | undefined;
96
+
97
+ export function subscribe(listener: () => void): () => void {
98
+ listeners.add(listener);
99
+ return () => listeners.delete(listener);
100
+ }
101
+
102
+ /** Many tools end at once: they count as one change. */
103
+ export function notify(): void {
104
+ clearTimeout(timer);
105
+ timer = setTimeout(() => {
106
+ for (const listener of listeners) {
107
+ listener();
108
+ }
109
+ }, 300);
110
+ }
111
+ }
112
+ /** The theme of the page, `light` or `dark`: what pi.ui.theme says, again when it changes. */
113
+ export function useTheme(): string {
114
+ const [theme, setTheme] = React.useState(() => pi.ui.theme);
115
+ React.useEffect(() => {
116
+ const observer = new MutationObserver(() => setTheme(pi.ui.theme));
117
+ observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
118
+ return () => observer.disconnect();
119
+ }, []);
120
+ return theme;
121
+ }