@celljs/ta-workspace 4.8.0 → 4.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +2 -2
  2. package/README.zh-cn.md +2 -2
  3. package/package.json +13 -4
  4. package/web/index.js +913 -294
  5. package/web-src/browser-agent.ts +0 -440
  6. package/web-src/browser-common.tsx +0 -278
  7. package/web-src/browser-import.tsx +0 -126
  8. package/web-src/browser-webview.tsx +0 -270
  9. package/web-src/browser.tsx +0 -80
  10. package/web-src/common.tsx +0 -296
  11. package/web-src/editors.tsx +0 -471
  12. package/web-src/explorer.tsx +0 -717
  13. package/web-src/file-icon.tsx +0 -21
  14. package/web-src/host.ts +0 -121
  15. package/web-src/i18n.ts +0 -395
  16. package/web-src/index.tsx +0 -71
  17. package/web-src/open-files.tsx +0 -80
  18. package/web-src/preview.tsx +0 -132
  19. package/web-src/react.ts +0 -8
  20. package/web-src/scm.tsx +0 -388
  21. package/web-src/search.tsx +0 -485
  22. package/web-src/style.ts +0 -254
  23. package/web-src/terminal.tsx +0 -269
  24. package/web-src/util/browser-snapshot.spec.ts +0 -96
  25. package/web-src/util/browser-snapshot.ts +0 -225
  26. package/web-src/util/file-icon.spec.ts +0 -35
  27. package/web-src/util/file-icon.ts +0 -23
  28. package/web-src/util/git.ts +0 -203
  29. package/web-src/util/preview.spec.ts +0 -48
  30. package/web-src/util/preview.ts +0 -90
  31. package/web-src/util/search.spec.ts +0 -164
  32. package/web-src/util/search.ts +0 -274
  33. package/web-src/util/seti-font.ts +0 -6
  34. package/web-src/util/seti.ts +0 -761
  35. package/web-src/util/upload.spec.ts +0 -66
  36. package/web-src/util/upload.ts +0 -123
  37. package/web-src/util/workspace.spec.ts +0 -220
  38. package/web-src/util/workspace.ts +0 -396
  39. package/web-src/util/zip.spec.ts +0 -60
  40. package/web-src/util/zip.ts +0 -137
  41. package/web-src/workspace-client.ts +0 -221
@@ -1,225 +0,0 @@
1
- /** A node of Accessibility.getFullAXTree, as much of it as a snapshot reads. */
2
- export interface AXNode {
3
- nodeId: string;
4
- parentId?: string;
5
- ignored?: boolean;
6
- role?: { value?: unknown };
7
- name?: { value?: unknown };
8
- value?: { value?: unknown };
9
- description?: { value?: unknown };
10
- properties?: { name: string; value?: { value?: unknown } }[];
11
- childIds?: string[];
12
- backendDOMNodeId?: number;
13
- }
14
-
15
- /** Roles of what one acts on: they get a ref, the number in brackets. */
16
- const ACTIONABLE: ReadonlySet<string> = new Set([
17
- 'button',
18
- 'checkbox',
19
- 'combobox',
20
- 'link',
21
- 'listbox',
22
- 'menuitem',
23
- 'menuitemcheckbox',
24
- 'menuitemradio',
25
- 'option',
26
- 'radio',
27
- 'searchbox',
28
- 'slider',
29
- 'spinbutton',
30
- 'switch',
31
- 'tab',
32
- 'textbox',
33
- 'treeitem',
34
- ]);
35
- /** Roles that say nothing: their children are shown in their place. */
36
- const SKIPPED: ReadonlySet<string> = new Set(['none', 'presentation', 'InlineTextBox', 'LineBreak']);
37
- /** Containers shown only when they have a name. */
38
- const TRANSPARENT: ReadonlySet<string> = new Set([
39
- 'generic',
40
- 'group',
41
- 'paragraph',
42
- 'Section',
43
- 'LayoutTable',
44
- 'LayoutTableRow',
45
- 'LayoutTableCell',
46
- 'LabelText',
47
- 'RootWebArea',
48
- 'WebArea',
49
- ]);
50
- const STATES = ['focused', 'checked', 'selected', 'pressed', 'disabled', 'required', 'readonly', 'invalid'] as const;
51
- const MAX_NAME = 120;
52
-
53
- export interface KeyPress {
54
- key: string;
55
- code: string;
56
- windowsVirtualKeyCode: number;
57
- /** Alt 1, Control 2, Meta 4, Shift 8, as the DevTools protocol counts them. */
58
- modifiers: number;
59
- /** What the key types; none for a shortcut. */
60
- text?: string;
61
- }
62
-
63
- const MODIFIERS: Record<string, number> = { alt: 1, option: 1, control: 2, ctrl: 2, meta: 4, cmd: 4, command: 4, shift: 8 };
64
- const NAMED: Record<string, [code: number, text?: string]> = {
65
- Enter: [13, '\r'],
66
- Tab: [9],
67
- Escape: [27],
68
- Backspace: [8],
69
- Delete: [46],
70
- ArrowUp: [38],
71
- ArrowDown: [40],
72
- ArrowLeft: [37],
73
- ArrowRight: [39],
74
- Home: [36],
75
- End: [35],
76
- PageUp: [33],
77
- PageDown: [34],
78
- Space: [32, ' '],
79
- };
80
-
81
- /** How the agent reads a page and gives it keys: the accessibility tree as lines, key names as key events. */
82
- export namespace BrowserSnapshot {
83
- function text(value: unknown, max = MAX_NAME): string {
84
- const line = String(value ?? '')
85
- .replace(/\s+/g, ' ')
86
- .trim();
87
- return line.length > max ? `${line.slice(0, max - 1)}…` : line;
88
- }
89
-
90
- function property(node: AXNode, name: string): unknown {
91
- return node.properties?.find(item => item.name === name)?.value?.value;
92
- }
93
-
94
- /**
95
- * The page as indented lines, `[ref] role "name" (states) value=…`: what one can act on has a ref (its
96
- * backendDOMNodeId, the same until the page changes), containers without a name give way to their
97
- * children, text is shown where its parent's name does not already say it. At most `maxLines`.
98
- */
99
- export function render(nodes: AXNode[], maxLines = 800): string {
100
- const byId = new Map(nodes.map(node => [node.nodeId, node]));
101
- const lines: string[] = [];
102
- let more = 0;
103
- const add = (line: string) => {
104
- if (lines.length < maxLines) {
105
- lines.push(line);
106
- } else {
107
- more++;
108
- }
109
- };
110
- const visit = (node: AXNode, depth: number, parentName: string, inActionable = false) => {
111
- const role = String(node.role?.value ?? '');
112
- const name = text(node.name?.value);
113
- const children = (node.childIds ?? []).map(id => byId.get(id)).filter((child): child is AXNode => child !== undefined);
114
- const pass = (nextDepth: number, nextName: string, nextInActionable = inActionable) => {
115
- for (const child of children) {
116
- visit(child, nextDepth, nextName, nextInActionable);
117
- }
118
- };
119
- if (node.ignored || SKIPPED.has(role)) {
120
- pass(depth, parentName);
121
- return;
122
- }
123
- if (role === 'StaticText') {
124
- if (name && !parentName.includes(name)) {
125
- add(`${' '.repeat(depth)}${JSON.stringify(name)}`);
126
- }
127
- return;
128
- }
129
- // The editor inside a text field is editable too: the field is what one acts on.
130
- const actionable = (ACTIONABLE.has(role) || (property(node, 'editable') !== undefined && !inActionable)) && node.backendDOMNodeId !== undefined;
131
- if (!actionable && TRANSPARENT.has(role) && !name) {
132
- pass(depth, parentName);
133
- return;
134
- }
135
- let line = `${' '.repeat(depth)}${actionable ? `[${node.backendDOMNodeId}] ` : ''}${role}${name ? ` ${JSON.stringify(name)}` : ''}`;
136
- const level = property(node, 'level');
137
- if (level !== undefined) {
138
- line += ` level=${level}`;
139
- }
140
- const states: string[] = STATES.filter(state => {
141
- const value = property(node, state);
142
- return value === true || value === 'true' || value === 'mixed';
143
- }).map(state => (property(node, state) === 'mixed' ? `${state}=mixed` : state));
144
- const expanded = property(node, 'expanded');
145
- if (expanded !== undefined) {
146
- states.push(expanded ? 'expanded' : 'collapsed');
147
- }
148
- if (states.length > 0) {
149
- line += ` (${states.join(', ')})`;
150
- }
151
- const value = text(node.value?.value);
152
- if (value && value !== name) {
153
- line += ` value=${JSON.stringify(value)}`;
154
- }
155
- const description = text(node.description?.value, 80);
156
- if (description && description !== name) {
157
- line += ` description=${JSON.stringify(description)}`;
158
- }
159
- add(line);
160
- pass(depth + 1, name, inActionable || actionable);
161
- };
162
- for (const root of nodes.filter(node => !node.parentId || !byId.has(node.parentId))) {
163
- visit(root, 0, '');
164
- }
165
- if (more > 0) {
166
- lines.push(`… ${more} more lines: scroll, or evaluate to read a part of the page.`);
167
- }
168
- return lines.length > 0 ? lines.join('\n') : '(the page shows nothing to read yet)';
169
- }
170
-
171
- /** The middle of a quad of DOM.getContentQuads: x1, y1 … x4, y4. */
172
- export function center(quad: number[]): { x: number; y: number } {
173
- const xs = [quad[0], quad[2], quad[4], quad[6]];
174
- const ys = [quad[1], quad[3], quad[5], quad[7]];
175
- return { x: (Math.min(...xs) + Math.max(...xs)) / 2, y: (Math.min(...ys) + Math.max(...ys)) / 2 };
176
- }
177
-
178
- /** `Enter`, `a`, `Control+A`, `Meta+Shift+ArrowLeft`, `F5`: what to send for it; `undefined` for no key. */
179
- export function key(input: string): KeyPress | undefined {
180
- const parts = input.split('+');
181
- // "+" itself, or a shortcut ending in it ("Control++").
182
- const name = input.endsWith('++') || input === '+' ? '+' : parts.pop();
183
- if (!name) {
184
- return undefined;
185
- }
186
- let modifiers = 0;
187
- for (const part of input === '+' ? [] : parts.filter(Boolean)) {
188
- const bit = MODIFIERS[part.toLowerCase()];
189
- if (bit === undefined) {
190
- return undefined;
191
- }
192
- modifiers |= bit;
193
- }
194
- const shortcut = (modifiers & (2 | 4)) !== 0;
195
- const named = Object.keys(NAMED).find(candidate => candidate.toLowerCase() === name.toLowerCase());
196
- if (named) {
197
- const [code, typed] = NAMED[named];
198
- return {
199
- key: named === 'Space' ? ' ' : named,
200
- code: named,
201
- windowsVirtualKeyCode: code,
202
- modifiers,
203
- ...(typed && !shortcut ? { text: typed } : {}),
204
- };
205
- }
206
- const fn = /^F([1-9]|1[0-2])$/i.exec(name);
207
- if (fn) {
208
- return { key: `F${fn[1]}`, code: `F${fn[1]}`, windowsVirtualKeyCode: 111 + Number(fn[1]), modifiers };
209
- }
210
- if ([...name].length !== 1) {
211
- return undefined;
212
- }
213
- const shifted = (modifiers & 8) !== 0;
214
- const letter = /^[a-z]$/i.test(name);
215
- const digit = /^[0-9]$/.test(name);
216
- const key = letter ? (shifted ? name.toUpperCase() : name.toLowerCase()) : name;
217
- return {
218
- key,
219
- code: letter ? `Key${name.toUpperCase()}` : digit ? `Digit${name}` : '',
220
- windowsVirtualKeyCode: letter ? name.toUpperCase().charCodeAt(0) : digit ? name.charCodeAt(0) : 0,
221
- modifiers,
222
- ...(shortcut ? {} : { text: key }),
223
- };
224
- }
225
- }
@@ -1,35 +0,0 @@
1
- import { describe, expect, it } from 'bun:test';
2
- import { FileIconUtil } from './file-icon';
3
- import { SETI_EXTENSIONS, SETI_FILE, SETI_FILE_NAMES, SETI_ICONS } from './seti';
4
-
5
- describe('FileIconUtil', () => {
6
- it('picks by the whole name first, in any case', () => {
7
- expect(FileIconUtil.of('src/README.md')).toBe(SETI_ICONS[SETI_FILE_NAMES['readme.md']]);
8
- expect(FileIconUtil.of('Dockerfile')).toBe(SETI_ICONS[SETI_FILE_NAMES.dockerfile]);
9
- });
10
-
11
- it('picks the longest extension, then shorter ones', () => {
12
- expect(FileIconUtil.of('a/b.spec.ts')).toBe(SETI_ICONS[SETI_EXTENSIONS['spec.ts']]);
13
- expect(FileIconUtil.of('a/b.ts')).toBe(SETI_ICONS[SETI_EXTENSIONS.ts]);
14
- expect(FileIconUtil.of('a/b.d.ts')).toBe(SETI_ICONS[SETI_EXTENSIONS.ts]);
15
- expect(FileIconUtil.of('.gitignore')).toBe(SETI_ICONS[SETI_EXTENSIONS.gitignore]);
16
- });
17
-
18
- it('maps the languages of VS Code to extensions', () => {
19
- expect(SETI_EXTENSIONS.ts).not.toBe(SETI_FILE);
20
- expect(FileIconUtil.of('main.py')).not.toBe(SETI_ICONS[SETI_FILE]);
21
- expect(FileIconUtil.of('index.tsx')).toBe(FileIconUtil.of('index.jsx'));
22
- });
23
-
24
- it('falls back to the icon of any file', () => {
25
- expect(FileIconUtil.of('LICENSE.unknown-kind')).toBe(SETI_ICONS[SETI_FILE]);
26
- expect(FileIconUtil.of('noextension')).toBe(SETI_ICONS[SETI_FILE]);
27
- });
28
-
29
- it('gives a character of the font and a color for each theme', () => {
30
- const [character, dark, light] = FileIconUtil.of('a.ts');
31
- expect(character).toBeGreaterThanOrEqual(0xe000);
32
- expect(dark).toMatch(/^#[0-9a-f]{6}$/i);
33
- expect(light).toMatch(/^#[0-9a-f]{6}$/i);
34
- });
35
- });
@@ -1,23 +0,0 @@
1
- import { SETI_EXTENSIONS, SETI_FILE, SETI_FILE_NAMES, SETI_ICONS, type SetiIcon } from './seti';
2
-
3
- /** The icons of files, as VS Code draws them by default (its Seti theme). */
4
- export namespace FileIconUtil {
5
- /**
6
- * The icon of a file by its name, as VS Code picks it: the whole name, then the longest
7
- * extension (`a.spec.ts` tries `spec.ts`, then `ts`), then the icon of any file.
8
- */
9
- export function of(path: string): SetiIcon {
10
- const name = path.slice(path.lastIndexOf('/') + 1).toLowerCase();
11
- const byName = SETI_FILE_NAMES[name];
12
- if (byName !== undefined) {
13
- return SETI_ICONS[byName];
14
- }
15
- for (let dot = name.indexOf('.'); dot >= 0; dot = name.indexOf('.', dot + 1)) {
16
- const byExtension = SETI_EXTENSIONS[name.slice(dot + 1)];
17
- if (byExtension !== undefined) {
18
- return SETI_ICONS[byExtension];
19
- }
20
- }
21
- return SETI_ICONS[SETI_FILE];
22
- }
23
- }
@@ -1,203 +0,0 @@
1
- export interface GitFile {
2
- path: string;
3
- /** The letter of `git status --porcelain` for the index, when it changed there. */
4
- staged?: string;
5
- /** The letter for the working tree, when it changed there (`?` for untracked). */
6
- unstaged?: string;
7
- /** Renamed or copied in the index: the path it came from, relative to the directory when inside it. */
8
- from?: string;
9
- }
10
-
11
- export interface GitStatus {
12
- /** False when the directory is not in a git repository: the rest is left out. */
13
- repository: boolean;
14
- branch?: string;
15
- ahead?: number;
16
- behind?: number;
17
- /** No commit yet: there is no HEAD to unstage against. */
18
- initial?: boolean;
19
- files: GitFile[];
20
- /** Asked with `ignored`: what .gitignore leaves out; a directory left out whole ends with `/`. */
21
- ignored?: string[];
22
- }
23
-
24
- export interface FileDiff {
25
- path: string;
26
- /** The file in HEAD (or the index, for a change not staged); empty when new. */
27
- before: string;
28
- /** The file in the index (staged) or the working tree; empty when deleted. */
29
- after: string;
30
- }
31
-
32
- /** How the explorer marks files: the letter of each changed file and folder, and what is ignored. */
33
- export interface GitDecorations {
34
- files: Map<string, string>;
35
- /** A folder takes the letter of the change inside it that matters most (a conflict, then a change, then a new file). */
36
- folders: Map<string, string>;
37
- ignored: string[];
38
- }
39
-
40
- /** Conflicts first, as VS Code colors folders. */
41
- const PRIORITY: Record<string, number> = { '!': 4, M: 3, R: 3, D: 3, C: 3, A: 2, U: 2 };
42
-
43
- /** The arguments of git for the views, and its output read back. */
44
- export namespace GitUtil {
45
- export const PREFIX = ['rev-parse', '--show-prefix'];
46
- export const COMMIT = ['commit', '-q', '-F', '-'];
47
-
48
- /** `git status`, with what is ignored for the explorer (`--ignored=matching` stops at a directory ignored whole). */
49
- export function status(ignored = false): string[] {
50
- return [
51
- '-c',
52
- 'core.quotepath=off',
53
- 'status',
54
- '--porcelain=v1',
55
- '-b',
56
- '-z',
57
- '--untracked-files=all',
58
- ...(ignored ? ['--ignored=matching'] : []),
59
- '--',
60
- '.',
61
- ];
62
- }
63
-
64
- /** The file at `revision` (`HEAD`, or `''` for the index), by its path relative to the directory. */
65
- export function show(revision: string, path: string): string[] {
66
- return ['show', `${revision}:./${path}`];
67
- }
68
-
69
- export function tracked(path: string): string[] {
70
- return ['ls-files', '--error-unmatch', '--', literal(path)];
71
- }
72
-
73
- /** A path as git reads it, without its wildcards: `a[1].ts` is that file. `.` is the whole directory. */
74
- export function literal(path: string): string {
75
- return path === '.' ? '.' : `:(literal)${path}`;
76
- }
77
-
78
- export function stage(paths: string[]): string[] {
79
- return ['add', '-A', '--', ...paths.map(literal)];
80
- }
81
-
82
- /** Before the first commit there is no HEAD: the files leave the index instead. */
83
- export function unstage(paths: string[], initial: boolean): string[] {
84
- return initial ? ['rm', '--cached', '-r', '-q', '--', ...paths.map(literal)] : ['reset', '-q', '--', ...paths.map(literal)];
85
- }
86
-
87
- /** The working tree back to the index, for files git tracks. */
88
- export function discard(paths: string[]): string[] {
89
- return ['checkout', '-q', '--', ...paths.map(literal)];
90
- }
91
-
92
- /** Deletes untracked files. */
93
- export function clean(paths: string[]): string[] {
94
- return ['clean', '-f', '-q', '--', ...paths.map(literal)];
95
- }
96
-
97
- /**
98
- * `git status --porcelain=v1 -b -z`: the branch and the files, with paths relative to `prefix`
99
- * (`git rev-parse --show-prefix`, the directory asked for inside the repository); others are left out.
100
- */
101
- export function parseStatus(output: string, prefix: string): GitStatus {
102
- const status: GitStatus = { repository: true, files: [] };
103
- const fields = output.split('\0');
104
- const inside = (path: string) => path.startsWith(prefix);
105
- for (let i = 0; i < fields.length; i++) {
106
- const field = fields[i];
107
- if (field.startsWith('## ')) {
108
- Object.assign(status, parseBranch(field.slice(3)));
109
- continue;
110
- }
111
- if (field.length < 4) {
112
- continue;
113
- }
114
- const x = field[0];
115
- const y = field[1];
116
- const path = field.slice(3);
117
- // The path it came from follows.
118
- const from = x === 'R' || x === 'C' ? fields[++i] : undefined;
119
- if (!inside(path)) {
120
- continue;
121
- }
122
- const relative = path.slice(prefix.length);
123
- if (x === '!') {
124
- status.ignored ??= [];
125
- status.ignored.push(relative);
126
- continue;
127
- }
128
- const file: GitFile = { path: relative };
129
- if (x === '?') {
130
- file.unstaged = '?';
131
- } else {
132
- if (x !== ' ') {
133
- file.staged = x;
134
- }
135
- if (y !== ' ') {
136
- file.unstaged = y;
137
- }
138
- }
139
- if (from !== undefined) {
140
- file.from = inside(from) ? from.slice(prefix.length) : from;
141
- }
142
- status.files.push(file);
143
- }
144
- return status;
145
- }
146
-
147
- /** `main...origin/main [ahead 1, behind 2]`, `No commits yet on main`, `HEAD (no branch)`. */
148
- export function parseBranch(line: string): Pick<GitStatus, 'branch' | 'ahead' | 'behind' | 'initial'> {
149
- const initial = /^(?:No commits yet on|Initial commit on) (.+)$/.exec(line);
150
- if (initial) {
151
- return { branch: initial[1], initial: true };
152
- }
153
- const [, branch = line, rest = ''] = /^(.+?)(?:\.\.\.\S+)?(?: \[(.+)\])?$/.exec(line) ?? [];
154
- const result: Pick<GitStatus, 'branch' | 'ahead' | 'behind'> = { branch: branch === 'HEAD (no branch)' ? undefined : branch };
155
- const ahead = /ahead (\d+)/.exec(rest);
156
- const behind = /behind (\d+)/.exec(rest);
157
- if (ahead) {
158
- result.ahead = Number(ahead[1]);
159
- }
160
- if (behind) {
161
- result.behind = Number(behind[1]);
162
- }
163
- return result;
164
- }
165
-
166
- /** A conflict: both sides changed the file (`UU`, `AA`, `DD`, or a `U` on either). */
167
- export function conflict(file: GitFile): boolean {
168
- return file.staged === 'U' || file.unstaged === 'U' || (file.staged === 'A' && file.unstaged === 'A') || (file.staged === 'D' && file.unstaged === 'D');
169
- }
170
-
171
- /** The letter VS Code shows for a file: the working tree's over the index's, `U` untracked, `!` a conflict. */
172
- export function letter(file: GitFile): string {
173
- if (conflict(file)) {
174
- return '!';
175
- }
176
- if (file.unstaged === '?') {
177
- return 'U';
178
- }
179
- return file.unstaged ?? file.staged ?? 'M';
180
- }
181
-
182
- export function decorations(status: GitStatus): GitDecorations {
183
- const files = new Map<string, string>();
184
- const folders = new Map<string, string>();
185
- for (const file of status.files) {
186
- const mark = letter(file);
187
- files.set(file.path, mark);
188
- for (let slash = file.path.indexOf('/'); slash > 0; slash = file.path.indexOf('/', slash + 1)) {
189
- const folder = file.path.slice(0, slash);
190
- const previous = folders.get(folder);
191
- if (!previous || (PRIORITY[mark] ?? 0) > (PRIORITY[previous] ?? 0)) {
192
- folders.set(folder, mark);
193
- }
194
- }
195
- }
196
- return { files, folders, ignored: status.ignored ?? [] };
197
- }
198
-
199
- /** Whether .gitignore leaves the path out: it, or a directory around it. */
200
- export function ignored(decorations: GitDecorations, path: string): boolean {
201
- return decorations.ignored.some(entry => (entry.endsWith('/') ? path === entry.slice(0, -1) || path.startsWith(entry) : path === entry));
202
- }
203
- }
@@ -1,48 +0,0 @@
1
- import { describe, expect, it } from 'bun:test';
2
- import { PreviewUtil } from './preview';
3
-
4
- describe('PreviewUtil', () => {
5
- it('knows what a file is shown as', () => {
6
- expect(PreviewUtil.kind('docs/README.md')).toBe('markdown');
7
- expect(PreviewUtil.kind('site/index.HTML')).toBe('html');
8
- expect(PreviewUtil.kind('logo.svg')).toBe('image');
9
- expect(PreviewUtil.kind('a/clip.mov')).toBe('video');
10
- expect(PreviewUtil.kind('sound.flac')).toBe('audio');
11
- expect(PreviewUtil.kind('paper.pdf')).toBe('pdf');
12
- expect(PreviewUtil.kind('src/app.ts')).toBeUndefined();
13
- expect(PreviewUtil.kind('.md')).toBeUndefined();
14
- expect(PreviewUtil.kind('md.dir/Makefile')).toBeUndefined();
15
- });
16
-
17
- it('edits only the previews that have a text', () => {
18
- expect(PreviewUtil.hasText('README.md')).toBe(true);
19
- expect(PreviewUtil.hasText('logo.svg')).toBe(true);
20
- expect(PreviewUtil.hasText('photo.png')).toBe(false);
21
- expect(PreviewUtil.hasText('clip.mp4')).toBe(false);
22
- });
23
-
24
- it('builds URLs beside a file and again after a change', () => {
25
- expect(PreviewUtil.directoryUrl('/api/files/id/docs/README.md')).toBe('/api/files/id/docs/');
26
- expect(PreviewUtil.versioned('/api/files/id/a.html', undefined)).toBe('/api/files/id/a.html');
27
- expect(PreviewUtil.versioned('/api/files/id/a.html', '"1-2"')).toBe('/api/files/id/a.html?v=%221-2%22');
28
- const base = 'http://127.0.0.1:1/api/files/id/docs/';
29
- expect(PreviewUtil.resolve('img/a b.png', base)).toBe('http://127.0.0.1:1/api/files/id/docs/img/a%20b.png');
30
- expect(PreviewUtil.resolve('../README.md', base)).toBe('http://127.0.0.1:1/api/files/id/README.md');
31
- expect(PreviewUtil.resolve('#usage', base)).toBe('#usage');
32
- expect(PreviewUtil.resolve('https://example.com/x', base)).toBe('https://example.com/x');
33
- expect(PreviewUtil.resolve('mailto:a@b.c', base)).toBe('mailto:a@b.c');
34
- });
35
-
36
- it('gives headings the ids GitHub gives them', () => {
37
- const taken = new Map<string, number>();
38
- expect(PreviewUtil.slug('Getting Started!', taken)).toBe('getting-started');
39
- expect(PreviewUtil.slug('Getting Started', taken)).toBe('getting-started-1');
40
- expect(PreviewUtil.slug('快速 开始', taken)).toBe('快速-开始');
41
- });
42
-
43
- it('puts rendered Markdown in a document of its own', () => {
44
- const page = PreviewUtil.markdownDocument('<h1>Hi</h1>', 'body{}');
45
- expect(page).toContain('<style>body{}</style>');
46
- expect(page).toContain('<article class="markdown"><h1>Hi</h1></article>');
47
- });
48
- });
@@ -1,90 +0,0 @@
1
- /** How a file is shown as it is, rather than as text. */
2
- export type PreviewKind = 'markdown' | 'html' | 'image' | 'video' | 'audio' | 'pdf';
3
-
4
- const KINDS: Record<string, PreviewKind> = {
5
- md: 'markdown',
6
- markdown: 'markdown',
7
- html: 'html',
8
- htm: 'html',
9
- svg: 'image',
10
- png: 'image',
11
- jpg: 'image',
12
- jpeg: 'image',
13
- gif: 'image',
14
- webp: 'image',
15
- avif: 'image',
16
- bmp: 'image',
17
- ico: 'image',
18
- mp4: 'video',
19
- m4v: 'video',
20
- webm: 'video',
21
- ogv: 'video',
22
- mov: 'video',
23
- mp3: 'audio',
24
- m4a: 'audio',
25
- aac: 'audio',
26
- wav: 'audio',
27
- ogg: 'audio',
28
- oga: 'audio',
29
- flac: 'audio',
30
- pdf: 'pdf',
31
- };
32
-
33
- /** Files with text behind their preview: they open as a preview and switch to the editor. */
34
- const TEXT_KINDS = new Set(['md', 'markdown', 'html', 'htm', 'svg']);
35
-
36
- export namespace PreviewUtil {
37
- function extension(path: string): string {
38
- const name = path.slice(path.lastIndexOf('/') + 1);
39
- const dot = name.lastIndexOf('.');
40
- return dot > 0 ? name.slice(dot + 1).toLowerCase() : '';
41
- }
42
-
43
- export function kind(path: string): PreviewKind | undefined {
44
- return KINDS[extension(path)];
45
- }
46
-
47
- /** The preview has a text to edit, as Markdown, HTML and SVG; the others are only shown. */
48
- export function hasText(path: string): boolean {
49
- return TEXT_KINDS.has(extension(path));
50
- }
51
-
52
- /** The URL of the directory of a file's URL, for the files a page or a document loads beside it. */
53
- export function directoryUrl(fileUrl: string): string {
54
- return fileUrl.slice(0, fileUrl.lastIndexOf('/') + 1);
55
- }
56
-
57
- /** A URL that loads again when the file changed (`version`, its ETag); the server ignores the query. */
58
- export function versioned(url: string, version: string | undefined): string {
59
- return version ? `${url}${url.includes('?') ? '&' : '?'}v=${encodeURIComponent(version)}` : url;
60
- }
61
-
62
- /** A URL of a document beside the file at `base` (absolute); fragments and absolute URLs stay as they are. */
63
- export function resolve(url: string, base: string): string {
64
- if (!url || url.startsWith('#')) {
65
- return url;
66
- }
67
- try {
68
- return new URL(url, base).href;
69
- } catch {
70
- return url;
71
- }
72
- }
73
-
74
- /** The id GitHub gives a heading, for links to `#it`; `taken` makes repeated ones unique. */
75
- export function slug(text: string, taken: Map<string, number>): string {
76
- const base = text
77
- .trim()
78
- .toLowerCase()
79
- .replace(/[^\p{L}\p{N}\s_-]/gu, '')
80
- .replace(/\s/g, '-');
81
- const count = taken.get(base) ?? 0;
82
- taken.set(base, count + 1);
83
- return count ? `${base}-${count}` : base;
84
- }
85
-
86
- /** A document of rendered Markdown, with `style` for the look of the page; it is shown in a frame that runs no scripts. */
87
- export function markdownDocument(body: string, style: string): string {
88
- return `<!doctype html><html><head><meta charset="utf-8"><style>${style}</style></head><body><article class="markdown">${body}</article></body></html>`;
89
- }
90
- }