@rantingjs/studio 0.0.0-stage → 0.1.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.
Files changed (54) hide show
  1. package/README.md +146 -2
  2. package/dist/badge.d.ts +2 -0
  3. package/dist/badge.js +17 -0
  4. package/dist/badge.js.map +1 -0
  5. package/dist/commands.d.ts +8 -0
  6. package/dist/commands.js +49 -0
  7. package/dist/commands.js.map +1 -0
  8. package/dist/config.d.ts +24 -0
  9. package/dist/config.js +26 -0
  10. package/dist/config.js.map +1 -0
  11. package/dist/forge.d.ts +67 -0
  12. package/dist/forge.js +138 -0
  13. package/dist/forge.js.map +1 -0
  14. package/dist/http.d.ts +25 -0
  15. package/dist/http.js +248 -0
  16. package/dist/http.js.map +1 -0
  17. package/dist/index.d.ts +4 -0
  18. package/dist/index.js +4 -0
  19. package/dist/index.js.map +1 -0
  20. package/dist/opencode.d.ts +30 -0
  21. package/dist/opencode.js +113 -0
  22. package/dist/opencode.js.map +1 -0
  23. package/dist/page.d.ts +11 -0
  24. package/dist/page.js +31 -0
  25. package/dist/page.js.map +1 -0
  26. package/dist/studio.module.d.ts +21 -0
  27. package/dist/studio.module.js +129 -0
  28. package/dist/studio.module.js.map +1 -0
  29. package/package.json +99 -4
  30. package/src/config.ts +26 -0
  31. package/ui/app.tsx +862 -0
  32. package/ui/changes.tsx +420 -0
  33. package/ui/code.tsx +194 -0
  34. package/ui/composer.tsx +362 -0
  35. package/ui/conversations.tsx +103 -0
  36. package/ui/editor.ts +144 -0
  37. package/ui/forge.tsx +236 -0
  38. package/ui/icons.tsx +59 -0
  39. package/ui/logic.ts +304 -0
  40. package/ui/logs.tsx +87 -0
  41. package/ui/model-picker.tsx +121 -0
  42. package/ui/notify.ts +45 -0
  43. package/ui/page.ts +27 -0
  44. package/ui/popover.tsx +66 -0
  45. package/ui/prose.tsx +50 -0
  46. package/ui/providers.tsx +386 -0
  47. package/ui/queue.tsx +89 -0
  48. package/ui/shared.ts +74 -0
  49. package/ui/splitter.tsx +70 -0
  50. package/ui/styles.css +2632 -0
  51. package/ui/terminal.tsx +108 -0
  52. package/ui/tsconfig.json +13 -0
  53. package/ui/urls.ts +9 -0
  54. package/ui/usage.tsx +86 -0
@@ -0,0 +1,362 @@
1
+ /** @jsxImportSource hono/jsx/dom */
2
+ // The message box: it grows with what is typed (and can be dragged taller), carries attachments as chips, finds
3
+ // project files after an `@` and commands and skills after a `/` that starts the message, switches Build and Plan,
4
+ // and sends or stops.
5
+ import type { FileSystemEntry, ModelInfo } from '@opencode/client';
6
+ import type { Child } from 'hono/jsx';
7
+ import { useEffect, useRef, useState } from 'hono/jsx/dom';
8
+ import { Icon, type IconName } from './icons.js';
9
+ import { insertMention, insertSlash, mentionAt, slashAt, slashOptions, unreadable, type Attachment, type SkillOrigin, type SlashOption } from './logic.js';
10
+ import { Popover } from './popover.js';
11
+ import { client, location_ } from './shared.js';
12
+
13
+ const KIND_ICON: Record<Attachment['kind'], IconName> = { image: 'image', pdf: 'file', text: 'file', folder: 'folder', file: 'file' };
14
+ const size = (bytes: number | undefined) => (bytes === undefined ? '' : bytes < 1024 ? `${bytes} B` : bytes < 1024 * 1024 ? `${Math.round(bytes / 1024)} KB` : `${(bytes / 1024 / 1024).toFixed(1)} MB`);
15
+ const clean = (path: string) => path.replace(/\\/g, '/');
16
+
17
+ const ORIGIN_LABEL: Record<SkillOrigin, string> = { 'built-in': 'OpenCode', project: 'project', repo: 'repository', user: 'yours' };
18
+ const ORIGIN_TITLE: Record<SkillOrigin, string> = {
19
+ 'built-in': 'Comes with OpenCode',
20
+ project: "In this project's skills folder",
21
+ repo: 'In a skills folder above the project (its repository)',
22
+ user: 'In your profile (~/.claude/skills): every project has it',
23
+ };
24
+
25
+ /** The smallest the box is, and how much of the chat column it may take as it grows. */
26
+ const MIN_HEIGHT = 72;
27
+ const MAX_SHARE = 0.5;
28
+
29
+ export function Composer({
30
+ draft,
31
+ setDraft,
32
+ attachments,
33
+ onRemove,
34
+ onFiles,
35
+ onMention,
36
+ model,
37
+ agents,
38
+ agent,
39
+ onAgent,
40
+ busy,
41
+ onSend,
42
+ onStop,
43
+ picker,
44
+ remembered,
45
+ slashChoices,
46
+ onSlashOpen,
47
+ }: {
48
+ draft: string;
49
+ setDraft: (text: string) => void;
50
+ attachments: Attachment[];
51
+ onRemove: (id: string) => void;
52
+ onFiles: (files: File[]) => void;
53
+ onMention: (path: string, folder: boolean) => void;
54
+ model: ModelInfo | undefined;
55
+ agents: { id: string; name: string }[];
56
+ agent: string;
57
+ onAgent: (id: string) => void;
58
+ busy: boolean;
59
+ onSend: () => void;
60
+ onStop: () => void;
61
+ picker: Child;
62
+ remembered: { get(key: string): string | undefined; set(key: string, value: string | undefined): void };
63
+ /** The commands and skills a `/` offers; asked again each time the picker opens. */
64
+ slashChoices: SlashOption[];
65
+ onSlashOpen: () => void;
66
+ }) {
67
+ const field = useRef<HTMLTextAreaElement>(null);
68
+ const fileInput = useRef<HTMLInputElement>(null);
69
+ const [floor, setFloor] = useState(Number(remembered.get('composer-height')) || MIN_HEIGHT);
70
+ const [menu, setMenu] = useState(false);
71
+ const [mention, setMention] = useState<{ start: number; query: string } | undefined>();
72
+ const [found, setFound] = useState<FileSystemEntry[]>([]);
73
+ const [active, setActive] = useState(0);
74
+ const [slash, setSlash] = useState<string | undefined>();
75
+ const choices = slash === undefined ? [] : slashOptions(slash, slashChoices);
76
+ const slashOpen = slash !== undefined;
77
+ useEffect(() => {
78
+ if (slashOpen) onSlashOpen();
79
+ }, [slashOpen]);
80
+ useEffect(() => setActive(0), [slash]);
81
+
82
+ // Grows with its text, from the height dragged to up to half the chat column.
83
+ const fit = () => {
84
+ const element = field.current;
85
+ if (!element) return;
86
+ const cap = Math.max(floor, (element.closest('.chat')?.clientHeight ?? 800) * MAX_SHARE);
87
+ element.style.height = 'auto';
88
+ element.style.height = `${Math.min(cap, Math.max(floor, element.scrollHeight))}px`;
89
+ };
90
+ useEffect(fit, [draft, floor]);
91
+
92
+ // Dragging the handle above the box sets how tall it is at least.
93
+ const drag = (event: PointerEvent) => {
94
+ event.preventDefault();
95
+ const startY = event.clientY;
96
+ const start = field.current?.offsetHeight ?? floor;
97
+ const move = (moved: PointerEvent) => setFloor(Math.max(MIN_HEIGHT, Math.min(window.innerHeight * 0.7, start + startY - moved.clientY)));
98
+ const up = () => {
99
+ window.removeEventListener('pointermove', move);
100
+ window.removeEventListener('pointerup', up);
101
+ setFloor((height) => (remembered.set('composer-height', String(Math.round(height))), height));
102
+ };
103
+ window.addEventListener('pointermove', move);
104
+ window.addEventListener('pointerup', up);
105
+ };
106
+
107
+ // Project files for the `@` being typed, a moment after the typing stops.
108
+ useEffect(() => {
109
+ if (!mention) return setFound([]);
110
+ const timer = setTimeout(() => {
111
+ const search = mention.query
112
+ ? client.file.find({ location: location_, query: mention.query, limit: 12 }).then((result) => result.data)
113
+ : client.file.list({ location: location_ }).then((result) => result.data.slice(0, 12));
114
+ void search.then((entries) => (setFound(entries), setActive(0))).catch(() => setFound([]));
115
+ }, 120);
116
+ return () => clearTimeout(timer);
117
+ }, [mention?.query, mention?.start]);
118
+
119
+ const track = () => {
120
+ const element = field.current;
121
+ if (!element) return;
122
+ setMention(mentionAt(element.value, element.selectionStart));
123
+ setSlash(slashAt(element.value, element.selectionStart));
124
+ };
125
+ const chooseSlash = (option: SlashOption) => {
126
+ const element = field.current;
127
+ if (!element) return;
128
+ const next = insertSlash(element.value, option.token);
129
+ setDraft(next.text);
130
+ setSlash(undefined);
131
+ requestAnimationFrame(() => {
132
+ element.focus();
133
+ element.selectionStart = element.selectionEnd = next.caret;
134
+ });
135
+ };
136
+ const choose = (entry: FileSystemEntry) => {
137
+ const element = field.current;
138
+ if (!element || !mention) return;
139
+ const path = clean(entry.path).replace(/\/$/, '');
140
+ const next = insertMention(element.value, mention.start, element.selectionStart, path);
141
+ setDraft(next.text);
142
+ onMention(path, entry.type === 'directory');
143
+ setMention(undefined);
144
+ requestAnimationFrame(() => {
145
+ element.focus();
146
+ element.selectionStart = element.selectionEnd = next.caret;
147
+ });
148
+ };
149
+ const startMention = () => {
150
+ const element = field.current;
151
+ if (!element) return;
152
+ const at = element.selectionStart;
153
+ const before = element.value.slice(0, at);
154
+ const insert = (before && !/\s$/.test(before) ? ' ' : '') + '@';
155
+ setDraft(before + insert + element.value.slice(at));
156
+ requestAnimationFrame(() => {
157
+ element.focus();
158
+ element.selectionStart = element.selectionEnd = at + insert.length;
159
+ track();
160
+ });
161
+ };
162
+
163
+ const keyDown = (event: KeyboardEvent) => {
164
+ if (slashOpen && choices.length && ['ArrowDown', 'ArrowUp', 'Enter', 'Tab'].includes(event.key) && !event.shiftKey) {
165
+ event.preventDefault();
166
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') setActive((at) => (event.key === 'ArrowDown' ? Math.min(choices.length - 1, at + 1) : Math.max(0, at - 1)));
167
+ else chooseSlash(choices[Math.min(active, choices.length - 1)]!);
168
+ return;
169
+ }
170
+ if (slashOpen && event.key === 'Escape') {
171
+ event.preventDefault();
172
+ setSlash(undefined);
173
+ return;
174
+ }
175
+ if (mention && found.length) {
176
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
177
+ event.preventDefault();
178
+ setActive((at) => (event.key === 'ArrowDown' ? Math.min(found.length - 1, at + 1) : Math.max(0, at - 1)));
179
+ return;
180
+ }
181
+ if (event.key === 'Enter' || event.key === 'Tab') {
182
+ event.preventDefault();
183
+ choose(found[active]!);
184
+ return;
185
+ }
186
+ }
187
+ if (mention && event.key === 'Escape') {
188
+ event.preventDefault();
189
+ setMention(undefined);
190
+ return;
191
+ }
192
+ // Shift+Tab: the next agent (Build, Plan).
193
+ if (event.key === 'Tab' && event.shiftKey && agents.length > 1) {
194
+ event.preventDefault();
195
+ const at = agents.findIndex((entry) => entry.id === agent);
196
+ onAgent(agents[(at + 1) % agents.length]!.id);
197
+ return;
198
+ }
199
+ if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) {
200
+ event.preventDefault();
201
+ if (!busy) onSend();
202
+ }
203
+ };
204
+
205
+ const empty = !draft.trim() && !attachments.length;
206
+ return (
207
+ <form
208
+ class="composer"
209
+ onSubmit={(event: Event) => {
210
+ event.preventDefault();
211
+ if (!busy) onSend();
212
+ }}
213
+ >
214
+ <div class="composer-grip" onPointerDown={drag} title="Drag to resize" />
215
+ {attachments.length > 0 && (
216
+ <div class="attachments">
217
+ {attachments.map((attachment) => {
218
+ const blocked = unreadable(model, attachment);
219
+ return (
220
+ <span class={`attachment${blocked ? ' blocked' : ''}`} title={blocked ? `${model?.name} cannot read this ${attachment.kind}` : attachment.name}>
221
+ {attachment.kind === 'image' ? <img src={attachment.uri} alt="" /> : <Icon name={attachment.mention ? 'at' : KIND_ICON[attachment.kind]} size={14} />}
222
+ <span class="attachment-name">{attachment.name}</span>
223
+ {attachment.size !== undefined && <span class="attachment-size">{size(attachment.size)}</span>}
224
+ {blocked && <Icon name="warning" size={13} class="attachment-warning" />}
225
+ <button type="button" class="icon-button" aria-label={`Remove ${attachment.name}`} onClick={() => onRemove(attachment.id)}>
226
+ <Icon name="x" size={12} />
227
+ </button>
228
+ </span>
229
+ );
230
+ })}
231
+ </div>
232
+ )}
233
+ <div class="anchor composer-field">
234
+ <textarea
235
+ ref={field}
236
+ value={draft}
237
+ rows={1}
238
+ placeholder={busy ? 'The agent is working… type your next message' : 'Ask the agent to change something. @ for a file, / for commands and skills.'}
239
+ onInput={(event: Event) => (setDraft((event.target as HTMLTextAreaElement).value), track())}
240
+ onClick={track}
241
+ onKeyUp={(event: KeyboardEvent) => ['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key) && track()}
242
+ onKeyDown={keyDown}
243
+ // Closed once the box has lost its focus for good (a click on a choice comes first; typing again keeps it).
244
+ onBlur={() => setTimeout(() => document.activeElement !== field.current && (setMention(undefined), setSlash(undefined)), 150)}
245
+ onPaste={(event: ClipboardEvent) => {
246
+ const files = Array.from(event.clipboardData?.files ?? []);
247
+ if (files.length) (event.preventDefault(), onFiles(files));
248
+ }}
249
+ />
250
+ <Popover open={Boolean(mention)} onClose={() => setMention(undefined)} placement="above-start" class="mention-popover">
251
+ <div class="popover-list">
252
+ <div class="list-group-title">Project files</div>
253
+ {found.map((entry, index) => (
254
+ <button type="button" class="list-row" data-active={String(index === active)} onMouseEnter={() => setActive(index)} onMouseDown={(event: Event) => (event.preventDefault(), choose(entry))}>
255
+ <span class="row-check">
256
+ <Icon name={entry.type === 'directory' ? 'folder' : 'file'} size={14} />
257
+ </span>
258
+ <span class="row-main">{clean(entry.path)}</span>
259
+ </button>
260
+ ))}
261
+ {!found.length && <p class="hint popover-empty">{mention?.query ? 'No matching files.' : 'Type to find a file.'}</p>}
262
+ </div>
263
+ </Popover>
264
+ <Popover open={slashOpen} onClose={() => setSlash(undefined)} placement="above-start" class="mention-popover slash-popover">
265
+ <div class="popover-list">
266
+ {choices.map((option, index) => (
267
+ <>
268
+ {(index === 0 || choices[index - 1]!.kind !== option.kind) && <div class="list-group-title">{option.kind === 'command' ? 'Commands' : 'Skills'}</div>}
269
+ <button type="button" class="list-row" title={option.description} data-active={String(index === active)} onMouseEnter={() => setActive(index)} onMouseDown={(event: Event) => (event.preventDefault(), chooseSlash(option))}>
270
+ <span class="row-check">
271
+ <Icon name={option.kind === 'command' ? 'terminal' : 'sparkle'} size={14} />
272
+ </span>
273
+ <span class="row-main">
274
+ <span class="row-title slash-token">/{option.token}</span>
275
+ {option.description && <span class="row-sub">{option.description}</span>}
276
+ </span>
277
+ {option.origin && (
278
+ <span class={`slash-origin origin-${option.origin}`} title={ORIGIN_TITLE[option.origin]}>
279
+ {ORIGIN_LABEL[option.origin]}
280
+ </span>
281
+ )}
282
+ </button>
283
+ </>
284
+ ))}
285
+ {!choices.length && <p class="hint popover-empty">{slashChoices.length ? 'No command or skill by that name.' : 'Loading commands and skills…'}</p>}
286
+ </div>
287
+ <div class="slash-foot">A command runs with the rest of the message; a skill is one the agent must use. Without a /, the agent still picks skills itself.</div>
288
+ </Popover>
289
+ </div>
290
+ <div class="composer-bar">
291
+ <div class="anchor">
292
+ <button type="button" class="icon-button" title="Attach files" aria-label="Attach files" onClick={() => setMenu(!menu)}>
293
+ <Icon name="paperclip" />
294
+ </button>
295
+ <Popover open={menu} onClose={() => setMenu(false)} placement="above-start" class="attach-menu">
296
+ <button
297
+ type="button"
298
+ class="list-row"
299
+ onClick={() => {
300
+ setMenu(false);
301
+ fileInput.current?.click();
302
+ }}
303
+ >
304
+ <span class="row-check">
305
+ <Icon name="upload" size={14} />
306
+ </span>
307
+ <span class="row-main">
308
+ <span class="row-title">Upload files</span>
309
+ <span class="row-sub">Images, PDFs, text, code · up to 20 MB · or drop them here</span>
310
+ </span>
311
+ </button>
312
+ <button
313
+ type="button"
314
+ class="list-row"
315
+ onClick={() => {
316
+ setMenu(false);
317
+ startMention();
318
+ }}
319
+ >
320
+ <span class="row-check">
321
+ <Icon name="at" size={14} />
322
+ </span>
323
+ <span class="row-main">
324
+ <span class="row-title">Mention a project file</span>
325
+ <span class="row-sub">The agent reads it in place · type @ in the message</span>
326
+ </span>
327
+ </button>
328
+ </Popover>
329
+ <input
330
+ ref={fileInput}
331
+ type="file"
332
+ multiple
333
+ hidden
334
+ onChange={(event: Event) => {
335
+ const input = event.target as HTMLInputElement;
336
+ onFiles(Array.from(input.files ?? []));
337
+ input.value = '';
338
+ }}
339
+ />
340
+ </div>
341
+ <div class="segmented agent-switch" role="radiogroup" aria-label="Agent" title="Shift+Tab switches">
342
+ {agents.map((entry) => (
343
+ <button type="button" role="radio" aria-checked={String(entry.id === agent)} class={`${entry.id === agent ? 'on' : ''} agent-${entry.id}`} onClick={() => onAgent(entry.id)}>
344
+ {entry.name.charAt(0).toUpperCase() + entry.name.slice(1)}
345
+ </button>
346
+ ))}
347
+ </div>
348
+ <div class="composer-spacer" />
349
+ {picker}
350
+ {busy ? (
351
+ <button type="button" class="send-button stop" title="Stop the agent" aria-label="Stop the agent" onClick={onStop}>
352
+ <Icon name="stop" size={14} />
353
+ </button>
354
+ ) : (
355
+ <button type="submit" class="send-button" disabled={empty} title="Send (Enter)" aria-label="Send">
356
+ <Icon name="arrowUp" size={16} />
357
+ </button>
358
+ )}
359
+ </div>
360
+ </form>
361
+ );
362
+ }
@@ -0,0 +1,103 @@
1
+ /** @jsxImportSource hono/jsx/dom */
2
+ // The conversation switcher: the open conversation's title as a button; its popover searches them, starts a new one
3
+ // and deletes one.
4
+ import type { ModelInfo, SessionInfo } from '@opencode/client';
5
+ import { useState } from 'hono/jsx/dom';
6
+ import { Icon } from './icons.js';
7
+ import { ago } from './logic.js';
8
+ import { Popover, useListKeys } from './popover.js';
9
+
10
+ export const titleOf = (session: SessionInfo | undefined) => (session ? session.title || 'Untitled conversation' : 'New conversation');
11
+
12
+ export function Conversations({
13
+ sessions,
14
+ current,
15
+ busy,
16
+ models,
17
+ onSelect,
18
+ onNew,
19
+ onDelete,
20
+ }: {
21
+ sessions: SessionInfo[];
22
+ current: string | undefined;
23
+ busy: Record<string, boolean>;
24
+ models: ModelInfo[];
25
+ onSelect: (id: string) => void;
26
+ onNew: () => void;
27
+ onDelete: (id: string) => void;
28
+ }) {
29
+ const [open, setOpen] = useState(false);
30
+ const [query, setQuery] = useState('');
31
+ const term = query.trim().toLowerCase();
32
+ const shown = sessions.filter((session) => !term || titleOf(session).toLowerCase().includes(term));
33
+ const close = () => {
34
+ setOpen(false);
35
+ setQuery('');
36
+ };
37
+ const keys = useListKeys(shown.length, (index) => {
38
+ if (shown[index]) (onSelect(shown[index].id), close());
39
+ });
40
+ const modelName = (session: SessionInfo) => (session.model ? (models.find((model) => model.modelID === session.model?.id && model.providerID === session.model?.providerID)?.name ?? session.model.id) : undefined);
41
+ const selected = sessions.find((session) => session.id === current);
42
+
43
+ return (
44
+ <div class="anchor conversations">
45
+ <button type="button" class={`conversation-button${open ? ' open' : ''}`} onClick={() => setOpen(!open)} title="Conversations">
46
+ <span class="conversation-title">{titleOf(selected)}</span>
47
+ <Icon name="chevronDown" size={14} />
48
+ </button>
49
+ <Popover open={open} onClose={close} placement="below-start" class="conversation-popover">
50
+ <label class="search-field">
51
+ <Icon name="search" />
52
+ <input value={query} placeholder="Search conversations" onInput={(event: Event) => setQuery((event.target as HTMLInputElement).value)} onKeyDown={keys.onKeyDown} />
53
+ </label>
54
+ <button
55
+ type="button"
56
+ class="list-row new-row"
57
+ onClick={() => {
58
+ onNew();
59
+ close();
60
+ }}
61
+ >
62
+ <span class="row-check">
63
+ <Icon name="plus" size={14} />
64
+ </span>
65
+ <span class="row-main">New conversation</span>
66
+ </button>
67
+ <div class="popover-list">
68
+ {shown.map((session, index) => (
69
+ <div class={`list-row conversation-row${session.id === current ? ' selected' : ''}`} data-active={String(index === keys.active)} onMouseEnter={() => keys.setActive(index)}>
70
+ <button
71
+ type="button"
72
+ class="conversation-pick"
73
+ onClick={() => {
74
+ onSelect(session.id);
75
+ close();
76
+ }}
77
+ >
78
+ <span class="row-check">{busy[session.id] ? <span class="busy-dot" title="Working" /> : session.id === current && <Icon name="check" size={14} />}</span>
79
+ <span class="row-main">
80
+ <span class="row-title">{titleOf(session)}</span>
81
+ <span class="row-sub">
82
+ {[session.agent === 'plan' ? 'Plan' : 'Build', modelName(session), ago(session.time.updated)].filter(Boolean).join(' · ')}
83
+ </span>
84
+ </span>
85
+ </button>
86
+ <button
87
+ type="button"
88
+ class="icon-button row-delete"
89
+ title="Delete conversation"
90
+ onClick={() => {
91
+ if (confirm(`Delete “${titleOf(session)}”?`)) onDelete(session.id);
92
+ }}
93
+ >
94
+ <Icon name="trash" size={14} />
95
+ </button>
96
+ </div>
97
+ ))}
98
+ {!shown.length && <p class="hint popover-empty">{sessions.length ? 'No conversation by that name.' : 'No conversations yet.'}</p>}
99
+ </div>
100
+ </Popover>
101
+ </div>
102
+ );
103
+ }
package/ui/editor.ts ADDED
@@ -0,0 +1,144 @@
1
+ // The Code panel's editor: CodeMirror with the language of the file, colors from the page's theme (light or dark),
2
+ // Ctrl+S to save, and what a code editor does besides (line numbers, undo, search, brackets, indentation).
3
+ import { autocompletion, closeBrackets, closeBracketsKeymap, completionKeymap } from '@codemirror/autocomplete';
4
+ import { defaultKeymap, history, historyKeymap, indentWithTab } from '@codemirror/commands';
5
+ import { css } from '@codemirror/lang-css';
6
+ import { html } from '@codemirror/lang-html';
7
+ import { javascript } from '@codemirror/lang-javascript';
8
+ import { json } from '@codemirror/lang-json';
9
+ import { markdown } from '@codemirror/lang-markdown';
10
+ import { yaml } from '@codemirror/lang-yaml';
11
+ import { bracketMatching, foldGutter, foldKeymap, HighlightStyle, indentOnInput, indentUnit, syntaxHighlighting } from '@codemirror/language';
12
+ import { highlightSelectionMatches, searchKeymap } from '@codemirror/search';
13
+ import { Compartment, EditorState, type Extension } from '@codemirror/state';
14
+ import { crosshairCursor, drawSelection, dropCursor, EditorView, highlightActiveLine, highlightActiveLineGutter, highlightSpecialChars, keymap, lineNumbers, rectangularSelection } from '@codemirror/view';
15
+ import { tags as t } from '@lezer/highlight';
16
+
17
+ /** The language of a file, by its extension; none for the rest (plain text). */
18
+ export function languageFor(path: string): Extension {
19
+ const extension = path.slice(path.lastIndexOf('.') + 1).toLowerCase();
20
+ switch (extension) {
21
+ case 'ts':
22
+ case 'mts':
23
+ case 'cts':
24
+ return javascript({ typescript: true });
25
+ case 'tsx':
26
+ return javascript({ typescript: true, jsx: true });
27
+ case 'js':
28
+ case 'mjs':
29
+ case 'cjs':
30
+ return javascript();
31
+ case 'jsx':
32
+ return javascript({ jsx: true });
33
+ case 'json':
34
+ case 'jsonc':
35
+ return json();
36
+ case 'css':
37
+ return css();
38
+ case 'html':
39
+ case 'htm':
40
+ case 'vue':
41
+ case 'svelte':
42
+ return html();
43
+ case 'md':
44
+ case 'markdown':
45
+ return markdown();
46
+ case 'yml':
47
+ case 'yaml':
48
+ return yaml();
49
+ default:
50
+ return [];
51
+ }
52
+ }
53
+
54
+ /** Syntax colors as the page's CSS variables (styles.css sets them for light and dark). */
55
+ const colors = HighlightStyle.define([
56
+ { tag: [t.keyword, t.modifier, t.controlKeyword, t.operatorKeyword, t.definitionKeyword, t.moduleKeyword], color: 'var(--syn-keyword)' },
57
+ { tag: [t.string, t.special(t.string), t.regexp, t.character], color: 'var(--syn-string)' },
58
+ { tag: [t.number, t.bool, t.null, t.atom], color: 'var(--syn-number)' },
59
+ { tag: [t.comment, t.lineComment, t.blockComment, t.docComment], color: 'var(--syn-comment)', fontStyle: 'italic' },
60
+ { tag: [t.function(t.variableName), t.function(t.propertyName), t.function(t.definition(t.variableName))], color: 'var(--syn-function)' },
61
+ { tag: [t.typeName, t.className, t.namespace, t.standard(t.typeName)], color: 'var(--syn-type)' },
62
+ { tag: [t.tagName, t.angleBracket], color: 'var(--syn-tag)' },
63
+ { tag: [t.attributeName, t.propertyName], color: 'var(--syn-property)' },
64
+ { tag: [t.definition(t.variableName), t.definition(t.propertyName)], color: 'var(--syn-definition)' },
65
+ { tag: [t.heading], color: 'var(--syn-keyword)', fontWeight: '700' },
66
+ { tag: [t.link, t.url], color: 'var(--syn-string)', textDecoration: 'underline' },
67
+ { tag: [t.emphasis], fontStyle: 'italic' },
68
+ { tag: [t.strong], fontWeight: '700' },
69
+ { tag: [t.invalid], color: 'var(--bad)' },
70
+ ]);
71
+
72
+ const theme = EditorView.theme({
73
+ '&': { height: '100%', backgroundColor: 'var(--raised)', color: 'var(--ink)', fontSize: '13px' },
74
+ '&.cm-focused': { outline: 'none' },
75
+ '.cm-scroller': { fontFamily: 'var(--mono)', lineHeight: '1.55' },
76
+ '.cm-content': { caretColor: 'var(--accent)', padding: '8px 0' },
77
+ '&.cm-focused .cm-cursor': { borderLeftColor: 'var(--accent)' },
78
+ '.cm-gutters': { backgroundColor: 'var(--panel)', color: 'var(--faint)', border: 'none', borderRight: '1px solid var(--line)' },
79
+ '.cm-activeLine': { backgroundColor: 'color-mix(in srgb, var(--accent) 6%, transparent)' },
80
+ '.cm-activeLineGutter': { backgroundColor: 'color-mix(in srgb, var(--accent) 10%, transparent)', color: 'var(--ink)' },
81
+ '&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection': { backgroundColor: 'color-mix(in srgb, var(--accent) 24%, transparent)' },
82
+ '.cm-selectionMatch': { backgroundColor: 'color-mix(in srgb, var(--accent) 14%, transparent)' },
83
+ '&.cm-focused .cm-matchingBracket': { backgroundColor: 'color-mix(in srgb, var(--accent) 20%, transparent)', outline: 'none' },
84
+ '.cm-foldPlaceholder': { backgroundColor: 'var(--code)', border: 'none', color: 'var(--muted)' },
85
+ '.cm-panels': { backgroundColor: 'var(--panel)', color: 'var(--ink)', borderColor: 'var(--line)' },
86
+ '.cm-panel input, .cm-panel button': { fontFamily: 'inherit' },
87
+ '.cm-tooltip': { backgroundColor: 'var(--raised)', border: '1px solid var(--line)', color: 'var(--ink)' },
88
+ });
89
+
90
+ export interface CodeEditor {
91
+ /** Shows another file (its undo history starts anew). */
92
+ open(path: string, text: string, readOnly: boolean): void;
93
+ /** Replaces the text of the file shown, as it is on disk now. */
94
+ replace(text: string): void;
95
+ text(): string;
96
+ destroy(): void;
97
+ }
98
+
99
+ /** An editor in `parent`: `changed` hears every edit, `save` runs on Ctrl+S (Cmd+S). */
100
+ export function createEditor(parent: HTMLElement, changed: (text: string) => void, save: () => void): CodeEditor {
101
+ const language = new Compartment();
102
+ const readOnly = new Compartment();
103
+ const state = (text: string, path: string, locked: boolean) =>
104
+ EditorState.create({
105
+ doc: text,
106
+ extensions: [
107
+ lineNumbers(),
108
+ highlightActiveLineGutter(),
109
+ highlightSpecialChars(),
110
+ history(),
111
+ foldGutter(),
112
+ drawSelection(),
113
+ dropCursor(),
114
+ EditorState.allowMultipleSelections.of(true),
115
+ EditorState.tabSize.of(2),
116
+ indentUnit.of(' '),
117
+ indentOnInput(),
118
+ syntaxHighlighting(colors),
119
+ bracketMatching(),
120
+ closeBrackets(),
121
+ autocompletion(),
122
+ rectangularSelection(),
123
+ crosshairCursor(),
124
+ highlightActiveLine(),
125
+ highlightSelectionMatches(),
126
+ keymap.of([{ key: 'Mod-s', preventDefault: true, run: () => (save(), true) }, ...closeBracketsKeymap, ...defaultKeymap, ...searchKeymap, ...historyKeymap, ...foldKeymap, ...completionKeymap, indentWithTab]),
127
+ language.of(languageFor(path)),
128
+ readOnly.of([EditorState.readOnly.of(locked), EditorView.editable.of(!locked)]),
129
+ theme,
130
+ EditorView.updateListener.of((update) => update.docChanged && changed(update.state.doc.toString())),
131
+ ],
132
+ });
133
+ const view = new EditorView({ parent, state: state('', '', true) });
134
+ return {
135
+ open(path, text, locked) {
136
+ view.setState(state(text, path, locked));
137
+ },
138
+ replace(text) {
139
+ if (text !== view.state.doc.toString()) view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: text } });
140
+ },
141
+ text: () => view.state.doc.toString(),
142
+ destroy: () => view.destroy(),
143
+ };
144
+ }