@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,320 @@
1
+ import { pi } from './host';
2
+
3
+ const ZH = {
4
+ newFile: '新建文件…',
5
+ newFolder: '新建文件夹…',
6
+ rename: '重命名…',
7
+ delete: '删除',
8
+ open: '打开',
9
+ copyPath: '复制路径',
10
+ copyRelativePath: '复制相对路径',
11
+ copied: '已复制',
12
+ findInFolder: '在文件夹中查找…',
13
+ revealInExplorer: '在资源管理器中显示',
14
+ nameEmpty: '必须提供文件或文件夹名称。',
15
+ nameSlash: '文件或文件夹名称不能以斜杠开头。',
16
+ nameInvalid: '名称 {name} 不能用作文件或文件夹名称,请换一个。',
17
+ nameExists: '此位置已存在文件或文件夹 {name},请换一个名称。',
18
+ nameWhitespace: '文件或文件夹名称的开头或结尾有空格。',
19
+ deleteFile: '确定要永久删除“{name}”吗?',
20
+ deleteFolder: '确定要永久删除“{name}”及其内容吗?',
21
+ irreversible: '此操作不可撤销!',
22
+ createFailed: '创建失败:{message}',
23
+ renameFailed: '重命名失败:{message}',
24
+ deleteFailed: '删除失败:{message}',
25
+ gitM: '已修改',
26
+ gitA: '已添加',
27
+ gitD: '已删除',
28
+ gitR: '已重命名',
29
+ gitC: '已复制',
30
+ gitU: '未跟踪',
31
+ gitT: '类型已更改',
32
+ gitConflict: '冲突',
33
+ matchWholeWord: '全字匹配',
34
+ toggleReplace: '切换替换',
35
+ replacePlaceholder: '替换',
36
+ replace: '替换',
37
+ replaceAll: '全部替换',
38
+ replaceAllInFile: '在此文件中全部替换',
39
+ replaceAllInFolder: '在此文件夹中全部替换',
40
+ replaceAllTitle: '将 {files} 个文件中的 {count} 处匹配替换为“{text}”?',
41
+ cannotReplace: '{path} 太大或不是文本,不能替换。',
42
+ toggleDetails: '切换搜索详细信息',
43
+ filesToInclude: '包含的文件',
44
+ filesToExclude: '排除的文件',
45
+ excludePlaceholder: '例如 *.test.ts, dist',
46
+ dismiss: '关闭',
47
+ clearResults: '清除搜索结果',
48
+ expandAll: '全部展开',
49
+ copy: '复制',
50
+ mergeChanges: '合并更改',
51
+ commit: '提交',
52
+ commitMessage: '提交信息',
53
+ commitPlaceholder: '消息(按 {keys} 提交)',
54
+ commitPlaceholderBranch: '消息(按 {keys} 在“{branch}”提交)',
55
+ commitMessageMissing: '请先写提交信息。',
56
+ nothingToCommit: '没有可提交的更改。',
57
+ stageAllTitle: '没有暂存的更改。要暂存全部更改并直接提交吗?',
58
+ stageAllMessage: '会把工作区里所有更改(包括未跟踪的文件)加入这次提交。',
59
+ stageAllCommit: '暂存全部并提交',
60
+ stage: '暂存更改',
61
+ unstage: '取消暂存更改',
62
+ discard: '放弃更改',
63
+ stageAll: '暂存所有更改',
64
+ unstageAll: '取消暂存所有更改',
65
+ discardAll: '放弃所有更改',
66
+ discardOne: '确定要放弃“{name}”中的更改吗?',
67
+ discardMany: '确定要放弃 {count} 个文件中的更改吗?',
68
+ deleteUntracked: '确定要删除未跟踪的文件“{name}”吗?',
69
+ deleteUntrackedMany: '确定要删除 {count} 个未跟踪的文件吗?',
70
+ openChanges: '打开更改',
71
+ openFile: '打开文件',
72
+ pull: '拉取',
73
+ push: '推送',
74
+ fetch: '抓取',
75
+ pullDone: '已拉取。',
76
+ pushDone: '已推送。',
77
+ fetchDone: '已抓取。',
78
+ moreActions: '更多操作…',
79
+ viewAsTree: '以树形式查看',
80
+ viewAsList: '以列表形式查看',
81
+ aheadBehind: '领先 {ahead},落后 {behind}',
82
+ changes: '更改',
83
+ changeCount: '{count} 处更改',
84
+ previousChange: '上一个更改',
85
+ nextChange: '下一个更改',
86
+ inline: '内联视图',
87
+ sideBySide: '并排视图',
88
+ closeOthers: '关闭其他',
89
+ closeToTheRight: '关闭下方的',
90
+ closeToTheLeft: '关闭左侧',
91
+ closeTabsToTheRight: '关闭右侧',
92
+ closeEnded: '关闭已退出的',
93
+ openCount: '{count} 个已打开',
94
+ explorer: '资源管理器',
95
+ openFiles: '打开的文件',
96
+ search: '搜索',
97
+ scm: '源代码管理',
98
+ terminal: '终端',
99
+ browser: '浏览器',
100
+ refresh: '刷新',
101
+ collapseAll: '全部折叠',
102
+ changeFolder: '切换目录',
103
+ followConversation: '回到对话的目录({name})',
104
+ loading: '加载中…',
105
+ empty: '空目录',
106
+ noOpenFiles: '还没有打开的文件。在资源管理器、搜索或源代码管理里点一个文件。',
107
+ close: '关闭',
108
+ closeAll: '全部关闭',
109
+ searchPlaceholder: '搜索',
110
+ includePlaceholder: '例如 src/**/*.ts, *.md',
111
+ matchCase: '区分大小写',
112
+ useRegex: '使用正则表达式',
113
+ noResults: '没有结果。',
114
+ results: '{files} 个文件中有 {count} 个结果',
115
+ moreResults: '结果太多,只显示前 {count} 个。',
116
+ notRepository: '当前目录不是 git 仓库。',
117
+ noChanges: '没有更改。',
118
+ staged: '暂存的更改',
119
+ ahead: '领先 {count}',
120
+ behind: '落后 {count}',
121
+ newTerminal: '新建终端',
122
+ noTerminals: '没有打开的终端。',
123
+ terminalEnded: '[进程已结束,退出码 {code}]',
124
+ pipeMode: '服务器上没有 script,终端运行在管道上:全屏程序(vim、top)和密码输入不可用。',
125
+ address: '输入网址或搜索',
126
+ back: '后退',
127
+ forward: '前进',
128
+ openExternal: '在新窗口打开',
129
+ recent: '最近访问',
130
+ browserTitle: '在这里打开网页',
131
+ browserHint: '输入网址或搜索,也可以打开本机的开发服务器。',
132
+ home: '起始页',
133
+ removeRecent: '从最近访问中移除',
134
+ frameHint: '有的网站不允许被嵌入,页面空白时请在新窗口打开。',
135
+ binary: '二进制文件,不显示内容({size})。',
136
+ truncated: '文件较大,只显示前 1 MB,不能编辑。',
137
+ line: '第 {line} 行',
138
+ diffTitle: '{name}(更改)',
139
+ stagedTitle: '{name}(已暂存)',
140
+ unchanged: '内容相同。',
141
+ skipped: '⋯ {count} 行未更改',
142
+ failed: '出错了:{message}',
143
+ preview: '预览',
144
+ edit: '编辑',
145
+ save: '保存',
146
+ saveFailed: '保存失败:{message}',
147
+ changedOnDisk: '文件已在磁盘上更改。',
148
+ reload: '放弃我的更改',
149
+ fit: '适应窗口',
150
+ actualSize: '实际大小',
151
+ };
152
+
153
+ type Key = keyof typeof ZH;
154
+
155
+ const EN: Record<Key, string> = {
156
+ newFile: 'New File…',
157
+ newFolder: 'New Folder…',
158
+ rename: 'Rename…',
159
+ delete: 'Delete',
160
+ open: 'Open',
161
+ copyPath: 'Copy Path',
162
+ copyRelativePath: 'Copy Relative Path',
163
+ copied: 'Copied',
164
+ findInFolder: 'Find in Folder…',
165
+ revealInExplorer: 'Reveal in Explorer',
166
+ nameEmpty: 'A file or folder name must be provided.',
167
+ nameSlash: 'A file or folder name cannot start with a slash.',
168
+ nameInvalid: 'The name {name} is not valid as a file or folder name. Please choose a different name.',
169
+ nameExists: 'A file or folder {name} already exists at this location. Please choose a different name.',
170
+ nameWhitespace: 'Leading or trailing whitespace detected in file or folder name.',
171
+ deleteFile: "Are you sure you want to permanently delete '{name}'?",
172
+ deleteFolder: "Are you sure you want to permanently delete '{name}' and its contents?",
173
+ irreversible: 'This action is irreversible!',
174
+ createFailed: 'Could not create it: {message}',
175
+ renameFailed: 'Could not rename it: {message}',
176
+ deleteFailed: 'Could not delete it: {message}',
177
+ gitM: 'Modified',
178
+ gitA: 'Added',
179
+ gitD: 'Deleted',
180
+ gitR: 'Renamed',
181
+ gitC: 'Copied',
182
+ gitU: 'Untracked',
183
+ gitT: 'Type changed',
184
+ gitConflict: 'Conflict',
185
+ matchWholeWord: 'Match Whole Word',
186
+ toggleReplace: 'Toggle Replace',
187
+ replacePlaceholder: 'Replace',
188
+ replace: 'Replace',
189
+ replaceAll: 'Replace All',
190
+ replaceAllInFile: 'Replace All in File',
191
+ replaceAllInFolder: 'Replace All in Folder',
192
+ replaceAllTitle: "Replace {count} occurrences across {files} files with '{text}'?",
193
+ cannotReplace: '{path} is too large or not text; it cannot be replaced in.',
194
+ toggleDetails: 'Toggle Search Details',
195
+ filesToInclude: 'files to include',
196
+ filesToExclude: 'files to exclude',
197
+ excludePlaceholder: 'e.g. *.test.ts, dist',
198
+ dismiss: 'Dismiss',
199
+ clearResults: 'Clear Search Results',
200
+ expandAll: 'Expand All',
201
+ copy: 'Copy',
202
+ mergeChanges: 'Merge Changes',
203
+ commit: 'Commit',
204
+ commitMessage: 'Commit message',
205
+ commitPlaceholder: 'Message ({keys} to commit)',
206
+ commitPlaceholderBranch: "Message ({keys} to commit on '{branch}')",
207
+ commitMessageMissing: 'Write a commit message first.',
208
+ nothingToCommit: 'There are no changes to commit.',
209
+ stageAllTitle: 'There are no staged changes to commit. Stage all your changes and commit them directly?',
210
+ stageAllMessage: 'All the changes of the working tree, untracked files too, go into the commit.',
211
+ stageAllCommit: 'Stage All and Commit',
212
+ stage: 'Stage Changes',
213
+ unstage: 'Unstage Changes',
214
+ discard: 'Discard Changes',
215
+ stageAll: 'Stage All Changes',
216
+ unstageAll: 'Unstage All Changes',
217
+ discardAll: 'Discard All Changes',
218
+ discardOne: "Are you sure you want to discard changes in '{name}'?",
219
+ discardMany: 'Are you sure you want to discard changes in {count} files?',
220
+ deleteUntracked: "Are you sure you want to DELETE the untracked file '{name}'?",
221
+ deleteUntrackedMany: 'Are you sure you want to DELETE the {count} untracked files?',
222
+ openChanges: 'Open Changes',
223
+ openFile: 'Open File',
224
+ pull: 'Pull',
225
+ push: 'Push',
226
+ fetch: 'Fetch',
227
+ pullDone: 'Pulled.',
228
+ pushDone: 'Pushed.',
229
+ fetchDone: 'Fetched.',
230
+ moreActions: 'More Actions…',
231
+ viewAsTree: 'View as Tree',
232
+ viewAsList: 'View as List',
233
+ aheadBehind: '{ahead} ahead, {behind} behind',
234
+ changes: 'Changes',
235
+ changeCount: '{count} changes',
236
+ previousChange: 'Previous Change',
237
+ nextChange: 'Next Change',
238
+ inline: 'Inline View',
239
+ sideBySide: 'Side by Side View',
240
+ closeOthers: 'Close Others',
241
+ closeToTheRight: 'Close Below',
242
+ closeToTheLeft: 'Close to the Left',
243
+ closeTabsToTheRight: 'Close to the Right',
244
+ closeEnded: 'Close Exited',
245
+ openCount: '{count} open',
246
+ explorer: 'Explorer',
247
+ openFiles: 'Open files',
248
+ search: 'Search',
249
+ scm: 'Source control',
250
+ terminal: 'Terminal',
251
+ browser: 'Browser',
252
+ refresh: 'Refresh',
253
+ collapseAll: 'Collapse all',
254
+ changeFolder: 'Change folder',
255
+ followConversation: 'Back to the folder of the conversation ({name})',
256
+ loading: 'Loading…',
257
+ empty: 'Empty folder',
258
+ noOpenFiles: 'No files are open. Click a file in the explorer, search or source control.',
259
+ close: 'Close',
260
+ closeAll: 'Close all',
261
+ searchPlaceholder: 'Search',
262
+ includePlaceholder: 'e.g. src/**/*.ts, *.md',
263
+ matchCase: 'Match case',
264
+ useRegex: 'Use regular expression',
265
+ noResults: 'No results.',
266
+ results: '{count} results in {files} files',
267
+ moreResults: 'Too many results; the first {count} are shown.',
268
+ notRepository: 'This folder is not a git repository.',
269
+ noChanges: 'No changes.',
270
+ staged: 'Staged changes',
271
+ ahead: '{count} ahead',
272
+ behind: '{count} behind',
273
+ newTerminal: 'New terminal',
274
+ noTerminals: 'No terminals are open.',
275
+ terminalEnded: '[The process ended with code {code}]',
276
+ pipeMode: 'The server has no script: the terminal runs on pipes, so full-screen programs (vim, top) and password prompts do not work.',
277
+ address: 'Enter an address or search',
278
+ back: 'Back',
279
+ forward: 'Forward',
280
+ openExternal: 'Open in a new window',
281
+ recent: 'Recent',
282
+ browserTitle: 'Open a page here',
283
+ browserHint: 'Enter an address or search, or open a dev server on this machine.',
284
+ home: 'Start page',
285
+ removeRecent: 'Remove from recent',
286
+ frameHint: 'Some sites refuse to be embedded; if the page stays blank, open it in a new window.',
287
+ binary: 'A binary file; its content is not shown ({size}).',
288
+ truncated: 'A large file: only the first 1 MB is shown, read-only.',
289
+ line: 'Line {line}',
290
+ diffTitle: '{name} (changes)',
291
+ stagedTitle: '{name} (staged)',
292
+ unchanged: 'The contents are the same.',
293
+ skipped: '⋯ {count} unchanged lines',
294
+ failed: 'Failed: {message}',
295
+ preview: 'Preview',
296
+ edit: 'Edit',
297
+ save: 'Save',
298
+ saveFailed: 'Could not save: {message}',
299
+ changedOnDisk: 'The file changed on disk.',
300
+ reload: 'Discard my changes',
301
+ fit: 'Fit to window',
302
+ actualSize: 'Actual size',
303
+ };
304
+
305
+ /** Words in the language of the page; `{name}` takes `vars.name`. */
306
+ export function t(key: Key, vars: Record<string, string | number> = {}): string {
307
+ const words = pi.ui.language === 'zh-CN' ? ZH : EN;
308
+ return words[key].replace(/\{(\w+)\}/g, (all, name: string) => (name in vars ? String(vars[name]) : all));
309
+ }
310
+
311
+ /** The words of a letter of git (M, A, D, R, C, U, T, !), as VS Code names the states. */
312
+ export function gitLabel(letter: string): string {
313
+ const keys: Record<string, Key> = { M: 'gitM', A: 'gitA', D: 'gitD', R: 'gitR', C: 'gitC', U: 'gitU', T: 'gitT', '!': 'gitConflict' };
314
+ return keys[letter] ? t(keys[letter]) : letter;
315
+ }
316
+
317
+ /** A label read again when the language changes. */
318
+ export function label(key: Key): () => string {
319
+ return () => t(key);
320
+ }
@@ -0,0 +1,65 @@
1
+ import type { WebExtensionAPI, WebLink } from '@celljs/ta-web/lib/browser/extension/web-extension-api';
2
+ import { BrowserView, ShowPage } from './browser';
3
+ import { OpenFiles, openFile } from './editors';
4
+ import { ExplorerView, ShowDirectory } from './explorer';
5
+ import { bindHost, FilesChanged, Host, PACKAGE } from './host';
6
+ import { label } from './i18n';
7
+ import { OpenFilesView } from './open-files';
8
+ import { bind } from './react';
9
+ import { ScmView } from './scm';
10
+ import { SearchView } from './search';
11
+ import { injectStyle } from './style';
12
+ import { Terminals, TerminalView } from './terminal';
13
+ import { WorkspaceUtil } from './util/workspace';
14
+
15
+ /** Links of replies: a file at its lines, a directory in the explorer, a page in the browser. */
16
+ function openLink(pi: WebExtensionAPI, link: WebLink): boolean {
17
+ if (link.type === 'file') {
18
+ const selection = link.selection;
19
+ openFile(
20
+ link.cwd,
21
+ link.path,
22
+ selection && { line: selection.startLine, column: selection.startColumn, endLine: selection.endLine, endColumn: selection.endColumn },
23
+ );
24
+ } else if (link.type === 'directory') {
25
+ ShowDirectory.send(WorkspaceUtil.absolute(link.cwd, link.path));
26
+ pi.ui.showView(`${PACKAGE}/explorer`);
27
+ } else {
28
+ ShowPage.send(link.url);
29
+ pi.ui.showView(`${PACKAGE}/browser`);
30
+ }
31
+ return true;
32
+ }
33
+
34
+ /**
35
+ * The workspace of the conversation shown, as the tools of an IDE: its files, the files opened, a
36
+ * search, the changes of git, terminals and a browser. Each is a `panel` view, a tool of the workbench
37
+ * beside the conversation; files and diffs open as more of its tabs.
38
+ */
39
+ export default function activate(pi: WebExtensionAPI): () => void {
40
+ bind(pi.React);
41
+ bindHost(pi);
42
+ const removeStyle = injectStyle();
43
+ const views = [
44
+ ['explorer', 'explorer', 'Files', ExplorerView],
45
+ ['open-files', 'openFiles', 'FileText', OpenFilesView],
46
+ ['search', 'search', 'Search', SearchView],
47
+ ['scm', 'scm', 'GitBranch', ScmView],
48
+ ['terminal', 'terminal', 'SquareTerminal', TerminalView],
49
+ ['browser', 'browser', 'Globe', BrowserView],
50
+ ] as const;
51
+ views.forEach(([name, title, icon, render], index) => {
52
+ pi.registerView(name, { title: label(title), icon: Host.icon(icon), render, location: 'panel', order: 10 + index * 10 });
53
+ });
54
+ // The agent changes files with its tools: what is shown is read again.
55
+ pi.on('tool_execution_end', () => FilesChanged.notify());
56
+ pi.on('agent_end', () => FilesChanged.notify());
57
+ pi.registerOpener(link => openLink(pi, link));
58
+ const stopTerminals = pi.onTerminalData((terminalId, data, exitCode) => Terminals.receive(terminalId, data, exitCode));
59
+ // The files open when the page closed open again, behind what is shown.
60
+ void OpenFiles.restore();
61
+ return () => {
62
+ stopTerminals();
63
+ removeStyle();
64
+ };
65
+ }
@@ -0,0 +1,80 @@
1
+ import { Action, copyText, Empty, type MenuItem, useContextMenu, ViewHeader } from './common';
2
+ import { closeEditor, type OpenFile, OpenFiles, useOpenFiles } from './editors';
3
+ import { RevealRequests } from './explorer';
4
+ import { FileIcon } from './file-icon';
5
+ import { PACKAGE, pi } from './host';
6
+ import { t } from './i18n';
7
+ // biome-ignore lint/correctness/noUnusedImports: the JSX below is React.createElement
8
+ import { React } from './react';
9
+ import { WorkspaceUtil } from './util/workspace';
10
+
11
+ function close(files: readonly OpenFile[]): void {
12
+ for (const file of files) {
13
+ closeEditor(file.id);
14
+ }
15
+ }
16
+
17
+ /** The tabs of files and changes this package opened, as the open editors of an IDE; a click shows one again. */
18
+ export function OpenFilesView() {
19
+ const files = useOpenFiles();
20
+ const active = pi.ui.useActiveEditor();
21
+ const [menu, openMenu] = useContextMenu();
22
+
23
+ const reveal = (file: OpenFile) => {
24
+ RevealRequests.send({ cwd: file.cwd, path: file.detail });
25
+ pi.ui.showView(`${PACKAGE}/explorer`);
26
+ };
27
+
28
+ const menuFor = (file: OpenFile): MenuItem[] => {
29
+ const others = files.filter(other => other.id !== file.id);
30
+ const below = files.slice(files.indexOf(file) + 1);
31
+ return [
32
+ { label: t('close'), run: () => closeEditor(file.id) },
33
+ { label: t('closeOthers'), run: () => close(others), disabled: others.length === 0 },
34
+ { label: t('closeToTheRight'), run: () => close(below), disabled: below.length === 0 },
35
+ { label: t('closeAll'), run: () => close(OpenFiles.list()) },
36
+ '-',
37
+ { label: t('copyRelativePath'), run: () => copyText(file.detail, t('copied')) },
38
+ { label: t('revealInExplorer'), run: () => reveal(file) },
39
+ ];
40
+ };
41
+
42
+ return (
43
+ <div className="taw-view">
44
+ <ViewHeader title={files.length > 0 ? t('openCount', { count: files.length }) : undefined}>
45
+ {files.length > 0 && <Action icon="CopyMinus" label={t('closeAll')} onClick={() => close(OpenFiles.list())} />}
46
+ </ViewHeader>
47
+ <div className="taw-list" role="listbox" aria-label={t('openFiles')}>
48
+ {files.length === 0 && <Empty>{t('noOpenFiles')}</Empty>}
49
+ {files.map(file => (
50
+ <div
51
+ key={file.id}
52
+ role="option"
53
+ tabIndex={0}
54
+ aria-selected={file.id === active}
55
+ className={`taw-row ${file.id === active ? 'taw-selected' : ''}`}
56
+ title={`${file.cwd}/${file.detail}`}
57
+ onClick={() => file.reopen()}
58
+ onKeyDown={event => {
59
+ if (event.key === 'Enter') {
60
+ file.reopen();
61
+ } else if (event.key === 'Delete' || event.key === 'Backspace') {
62
+ closeEditor(file.id);
63
+ }
64
+ }}
65
+ onAuxClick={event => event.button === 1 && closeEditor(file.id)}
66
+ onContextMenu={event => openMenu(event, menuFor(file))}
67
+ >
68
+ <FileIcon path={file.detail} />
69
+ <span className="taw-name">{file.title}</span>
70
+ <span className="taw-detail">{WorkspaceUtil.dirname(file.detail)}</span>
71
+ <span className="taw-row-actions taw-keep">
72
+ <Action icon="X" label={t('close')} onClick={() => closeEditor(file.id)} />
73
+ </span>
74
+ </div>
75
+ ))}
76
+ </div>
77
+ {menu}
78
+ </div>
79
+ );
80
+ }
@@ -0,0 +1,132 @@
1
+ import { marked } from 'marked';
2
+ import { pi, useTheme } from './host';
3
+ import { t } from './i18n';
4
+ import { React } from './react';
5
+ import { type PreviewKind, PreviewUtil } from './util/preview';
6
+ import { WorkspaceUtil } from './util/workspace';
7
+
8
+ /** What a page may do in the preview of an HTML file; the server answers it sandboxed as well. */
9
+ const PAGE_SANDBOX = 'allow-scripts allow-forms allow-popups allow-modals allow-downloads';
10
+ /** Rendered Markdown runs no scripts; its links open in a tab of their own. */
11
+ const MARKDOWN_SANDBOX = 'allow-popups allow-popups-to-escape-sandbox';
12
+ /** Elements of rendered Markdown whose URLs point beside the file. */
13
+ const LINKED = [
14
+ ['img', 'src'],
15
+ ['source', 'src'],
16
+ ['video', 'src'],
17
+ ['video', 'poster'],
18
+ ['audio', 'src'],
19
+ ['a', 'href'],
20
+ ] as const;
21
+
22
+ /** The value of a variable of the page's theme, for a document that cannot read the page's styles. */
23
+ function themeValue(name: string): string {
24
+ return getComputedStyle(document.documentElement).getPropertyValue(name).trim();
25
+ }
26
+
27
+ function markdownStyle(): string {
28
+ const v = (name: string) => themeValue(`--ta-${name}`);
29
+ return `
30
+ :root { color-scheme: ${pi.ui.theme}; }
31
+ html, body { margin: 0; overscroll-behavior: none; background: ${v('main')}; color: ${v('body')}; font: 14px/1.7 ${v('sans')}; -webkit-font-smoothing: antialiased; }
32
+ .markdown { max-width: 860px; margin: 0 auto; padding: 24px 32px 48px; overflow-wrap: break-word; }
33
+ .markdown > :first-child { margin-top: 0; }
34
+ h1, h2, h3, h4, h5, h6 { margin: 1.5em 0 0.6em; color: ${v('text')}; font-weight: 600; line-height: 1.3; }
35
+ h1 { font-size: 1.85em; padding-bottom: 0.3em; border-bottom: 1px solid ${v('border-muted')}; }
36
+ h2 { font-size: 1.45em; padding-bottom: 0.3em; border-bottom: 1px solid ${v('border-muted')}; }
37
+ h3 { font-size: 1.2em; } h4 { font-size: 1em; } h5, h6 { font-size: 0.9em; color: ${v('secondary')}; }
38
+ p, ul, ol, pre, table, blockquote, details { margin: 0 0 1em; }
39
+ a { color: ${v('link')}; text-decoration: none; } a:hover { text-decoration: underline; }
40
+ strong { color: ${v('text')}; }
41
+ ul, ol { padding-left: 1.6em; } li + li { margin-top: 0.25em; } li > ul, li > ol { margin: 0.25em 0 0; }
42
+ ul:has(> li > input[type='checkbox']) { padding-left: 0.3em; } li:has(> input[type='checkbox']) { list-style: none; } li:has(> input[type='checkbox']) > :is(ul, ol) { padding-left: 2.8em; } input[type='checkbox'] { margin: 0 0.45em 0 0; vertical-align: -1px; }
43
+ code { padding: 0.15em 0.4em; border-radius: 5px; background: ${v('chip')}; font-family: ${v('mono')}; font-size: 0.86em; }
44
+ pre { padding: 12px 14px; overflow: auto; border: 1px solid ${v('border')}; border-radius: 10px; background: ${v('code')}; line-height: 1.55; }
45
+ pre code { padding: 0; background: none; font-size: 12.5px; }
46
+ blockquote { padding: 0 1em; border-left: 3px solid ${v('border-field')}; color: ${v('secondary')}; }
47
+ table { display: block; max-width: 100%; overflow: auto; border-collapse: collapse; }
48
+ th, td { padding: 6px 12px; border: 1px solid ${v('border')}; } th { background: ${v('raised')}; font-weight: 600; }
49
+ img, video { max-width: 100%; } img { border-radius: 4px; }
50
+ hr { height: 0; margin: 1.6em 0; border: 0; border-top: 1px solid ${v('border')}; }
51
+ @media (max-width: 600px) { .markdown { padding: 16px 18px 32px; } }
52
+ kbd { padding: 1px 5px; border: 1px solid ${v('border')}; border-bottom-width: 2px; border-radius: 4px; font-family: ${v('mono')}; font-size: 0.85em; }
53
+ `;
54
+ }
55
+
56
+ /**
57
+ * Markdown as GitHub shows it: relative images and links point beside the file, links open in a tab of
58
+ * their own, headings get ids for links to them. Parsed by the browser without running anything.
59
+ */
60
+ function renderMarkdown(text: string, directory: string): string {
61
+ const html = marked.parse(text, { async: false, gfm: true }) as string;
62
+ const body = new DOMParser().parseFromString(html, 'text/html').body;
63
+ for (const [tag, attribute] of LINKED) {
64
+ for (const element of body.querySelectorAll(`${tag}[${attribute}]`)) {
65
+ element.setAttribute(attribute, PreviewUtil.resolve(element.getAttribute(attribute) ?? '', directory));
66
+ }
67
+ }
68
+ for (const link of body.querySelectorAll('a[href]')) {
69
+ if (!link.getAttribute('href')?.startsWith('#')) {
70
+ link.setAttribute('target', '_blank');
71
+ link.setAttribute('rel', 'noopener noreferrer');
72
+ }
73
+ }
74
+ const taken = new Map<string, number>();
75
+ for (const heading of body.querySelectorAll('h1, h2, h3, h4, h5, h6')) {
76
+ heading.id ||= PreviewUtil.slug(heading.textContent ?? '', taken);
77
+ }
78
+ return PreviewUtil.markdownDocument(body.innerHTML, markdownStyle());
79
+ }
80
+
81
+ export function MarkdownPreview({ text, url }: { text: string; url: string }) {
82
+ const theme = useTheme();
83
+ const document = React.useMemo(() => renderMarkdown(text, PreviewUtil.directoryUrl(new URL(url, location.href).href)), [text, url, theme]);
84
+ return <iframe className="taw-preview-frame" title="Markdown" sandbox={MARKDOWN_SANDBOX} srcDoc={document} />;
85
+ }
86
+
87
+ function ImagePreview({ url, size, onInfo }: { url: string; size: number; onInfo(info: string): void }) {
88
+ const [actual, setActual] = React.useState(false);
89
+ return (
90
+ <div className={`taw-preview-media taw-preview-image ${actual ? 'taw-actual' : ''}`}>
91
+ <button type="button" className="taw-image-toggle" title={t(actual ? 'fit' : 'actualSize')} onClick={() => setActual(value => !value)}>
92
+ <img
93
+ src={url}
94
+ alt=""
95
+ onLoad={event => {
96
+ const image = event.currentTarget;
97
+ onInfo(`${image.naturalWidth} × ${image.naturalHeight} · ${WorkspaceUtil.size(size)}`);
98
+ }}
99
+ />
100
+ </button>
101
+ </div>
102
+ );
103
+ }
104
+
105
+ /**
106
+ * A file as it is: a page, an image, a video, a sound or a PDF, loaded from ta serve (TaWorkspaceServer.fileUrl).
107
+ * It loads again when the file changed (its ETag), not on every run of a tool.
108
+ */
109
+ export function MediaPreview({ kind, url, size, onInfo }: { kind: Exclude<PreviewKind, 'markdown'>; url: string; size: number; onInfo(info: string): void }) {
110
+ switch (kind) {
111
+ case 'html':
112
+ return <iframe className="taw-preview-frame taw-preview-page" title="HTML" sandbox={PAGE_SANDBOX} src={url} />;
113
+ case 'pdf':
114
+ return <iframe className="taw-preview-frame" title="PDF" src={url} />;
115
+ case 'image':
116
+ return <ImagePreview url={url} size={size} onInfo={onInfo} />;
117
+ case 'video':
118
+ return (
119
+ <div className="taw-preview-media">
120
+ {/* biome-ignore lint/a11y/useMediaCaption: a file of the workspace, which has no captions to give */}
121
+ <video src={url} controls preload="metadata" />
122
+ </div>
123
+ );
124
+ case 'audio':
125
+ return (
126
+ <div className="taw-preview-media">
127
+ {/* biome-ignore lint/a11y/useMediaCaption: a file of the workspace, which has no captions to give */}
128
+ <audio src={url} controls preload="metadata" />
129
+ </div>
130
+ );
131
+ }
132
+ }
@@ -0,0 +1,8 @@
1
+ import type * as ReactModule from 'react';
2
+
3
+ /** The React of the page; a web extension brings none of its own, and gets it only when it starts. */
4
+ export let React: typeof ReactModule;
5
+
6
+ export function bind(react: typeof ReactModule): void {
7
+ React = react;
8
+ }