Preview Markdown and Mermaid: /xorio:preview [path] with a file picker, and one-key previews of the docs and diagrams Claude writes

A Claude Code mod (a plugin of function hooks) that previews Markdown and Mermaid files inside the session, and puts the docs and diagrams Claude produces one key away.
[!NOTE] Mods run on Claude Code's function-hooks API, which is early access and may change between releases. This mod was built and tested against Claude Code 2.1.291.
| App | Panel and band | Diagrams inline |
|---|---|---|
| Claude Code in a terminal | Yes | PNG on kitty and Ghostty, text elsewhere (see How things are drawn) |
| Claude desktop app | Yes | SVG, drawn by pele |
| Claude Code for VS Code | Yes | Text by mermaid-ascii, as in a terminal: the extension's panel draws no images, and neither does VS Code's integrated terminal |
| Claude web app (claude.ai/code) | No | — |
A mod draws only on the surfaces Claude Code's mod engine knows. In 2.1.304 those are the terminal, the desktop app, VS Code and the Claude mobile app; the web app at claude.ai/code isn't one of them, so the mod has nothing to draw on there. In every app, "open in browser" (b) shows every diagram drawn in full.
Taken from a real Claude Code 2.1.303 session in kitty, with resvg installed: pele draws each diagram as SVG inside the mod and resvg turns it into the PNG the terminal shows, in the colors of Claude Code's theme.
/xorio:preview examples/sample.md in full screen (z), with the dark theme:

Scrolled down: an ER and a state diagram, then a gantt and a pie chart, all drawn by pele:

With the light theme (/theme), the diagrams are drawn light; switching the theme redraws the ones on screen:

Claude Code draws images only in terminals that support kitty's Unicode placeholder images (kitty and Ghostty today). In other terminals, Warp, iTerm2 and WezTerm among them, it draws an image's alt text, so the pane draws the diagrams as text there. The mod goes by TERM and TERM_PROGRAM, so a terminal opened from kitty or Ghostty (VS Code started from Ghostty, say) still gets text. To try images in a terminal that isn't detected, start Claude Code with DOC_PREVIEW_IMAGES=1. With DOC_PREVIEW_IMAGES=0 the pane draws text everywhere. Either way, "open in browser" shows every diagram drawn in full.
Taken from real sessions in a 200-column terminal, with mermaid-ascii installed.
Ask Claude for a diagram (or have it write a .md file) and a line above the prompt offers it:

Open shows it in a panel beside the conversation, drawn by mermaid-ascii:



examples/sample.md in full screen (z): the toolbar pinned on top, Markdown drawn by Claude Code's renderer, and a flowchart drawn inline by mermaid-ascii.

Scrolled down: a gantt chart and a pie chart drawn as text by the mod, and a wide table drawn as a grid fitted to the panel. The toolbar stays pinned as you scroll.

The file picker (/xorio:preview with no path):

In the browser (b): every diagram drawn by pele, in the light or dark scheme your browser asks for.

/plugin marketplace add radumarias/xorio-claude-plugin
/plugin install doc-preview@xorio
Preview what Claude generates. When Claude writes or edits a .md / .markdown / .mdx / .mmd / .mermaid file (plan-mode plans included), or puts a ``` `mermaid ``` block in a reply, a band appears above the prompt:
Preview: docs/plan.md, 1 diagram [ Open ] [ Browser ] [ Dismiss ]
Click a button, or press ctrl+x tab then p / b / x.
Preview a file by path.
| Command | What it does |
|---|---|
/xorio:preview docs/plan.md | Opens the file: relative to the project, absolute, ~/… or file://… |
/xorio:preview some/folder | Opens the file picker in that folder |
/xorio:preview | Opens the file picker: type a path, pick from Recent (what Claude generated this session), or Browse folders (only Markdown and Mermaid files are listed) |
The command is a file in the xorio plugin (commands/preview.md) that this mod answers. Without xorio installed, the mod registers it as plain /preview instead. Paths with any other extension are refused, so a secrets file such as .env is never shown.
In the panel: a toolbar stays at the top of the panel as you scroll (on the terminal): b: browser w: wider n: narrower z: full r: reload f: files q: close. The keys work while the panel has focus; click it, or press ctrl+x tab. You can also close it with the × in its corner.
w and n widen and narrow the panel by 20 columns, between 40 columns and 30 short of the screen's width. z toggles full screen, and pressing it again returns to the width before. Full screen asks for the whole terminal, but Claude Code keeps part of it for the conversation (about 70 columns in a 200-column terminal). A width you drag the divider to yourself takes precedence over all three.<br> breaks a line, and code, bold and links keep their styling. Only a table that can't fit even with narrow columns becomes a list (one item per row, Column: value under it). Desktop and VS Code draw tables natively.~/.cache/claude-doc-preview/ and opens it with the system opener (xdg-open, open or explorer). The page renders the Markdown and every Mermaid diagram. It loads marked, DOMPurify and pele from jsDelivr at exact versions with SRI hashes; a strict Content-Security-Policy, DOMPurify (which also sanitizes each diagram's SVG) and pele's own escaping keep the document's own HTML from running script.hooks/vendor/pele.js), so it runs inside Claude Code with no browser. Pele covers every Mermaid diagram type, with its own layout and look, so a diagram won't match mermaid.js pixel for pixel. Neither a terminal nor VS Code shows SVG, so what they show depends on what is installed:| Where | Needs | Drawn as |
|---|---|---|
| Desktop app | — | SVG image, by pele, light or dark as the app is |
| kitty or Ghostty | resvg (cargo install resvg, brew install resvg) or rsvg-convert (librsvg) | PNG image: pele's SVG rasterized at 2×, light or dark as Claude Code's theme is |
| kitty or Ghostty, neither of those | mmdc (@mermaid-js/mermaid-cli) | PNG image, by mermaid.js in a headless browser |
| Terminal or VS Code | mermaid-ascii | Text-art diagram: flowcharts, sequence and ER diagrams, plus state and class diagrams, which the mod rewrites as flowcharts first (class members are left out) |
| Terminal or VS Code, no pixels | — | Pie charts as labelled bars and gantt charts as a day-scale timeline, drawn by the mod itself |
| Terminal or VS Code, no tool for the type | — | The diagram's source, with a hint to press b |
In a terminal without pixels, and in VS Code, state diagrams with composite states, forks or concurrency, gantt charts with dates other than YYYY-MM-DD, and other types (mindmap, timeline, journey, …) fall back to the source.
The mod checks for these tools when it loads; reload the plugin (/reload-plugins) after installing one. Besides PATH it looks in ~/go/bin, $GOPATH/bin, ~/.cargo/bin, ~/.local/bin, ~/.npm-global/bin and Homebrew's and /usr/local's bins, since an app started from the desktop (VS Code, say) often runs with a shorter PATH than your shell. Rendered files are cached in ~/.cache/claude-doc-preview/.
claude --plugin-dir /path/to/xorio-claude-plugin/mods/doc-preview # load live; edits hot-reload
claude plugin validate mods/doc-preview # manifest + hooks module check
claude plugin test mods/doc-preview # tests/*.test.tsx
tsc -p mods/doc-preview # once the mod has loaded once
| Path | Purpose |
|---|---|
hooks/register.tsx | The hooks: /xorio:preview, the band, the pane, Write/Edit and reply tracking, rendering, the browser page |
hooks/docs.ts | Pure helpers (splitting a doc into prose, tables and diagrams, drawing tables and text charts, diagram-to-flowchart conversion, pele's SVG, paths, hashing, PNG size, the browser page's HTML); no $ |
hooks/vendor/ | Pele's dist/pele.js, unmodified, with its license and the types the mod uses (pele.d.ts says how to update it) |
types/index.d.ts | The $.state contract the module reads and writes |
tests/ | claude plugin test suites. They are .test.tsx so the repo's bare node --test doesn't pick them up |
Claude Code writes .claude-plugin/types/ (the API declarations and the tsconfig.json this folder's one extends) each time it loads the mod from disk. That folder ignores itself in git.
hooks/register.tsx 1065 lines1import { atom, read, update } from 'claude-code'
2import type {
3 ConfigValue,
4 ElementTable,
5 EngineInterface,
6 Register,
7 RenderChildren,
8 RenderElement,
9 RenderSurface,
10 SelectOption,
11 Timer,
12} from 'claude-code'
13
14import type { DiagramRender, DocView, GeneratedDoc, PaneSize, Rasterizer, Renderers, ReplyDiagram, Scheme } from '../types'
15import {
16 MAX_SVG,
17 PANE,
18 PELE_THEMES,
19 asciiSource,
20 baseName,
21 countOf,
22 diagramKind,
23 diagramTitle,
24 displayPath,
25 drawsImagesIn,
26 errorText,
27 expandPath,
28 firstLine,
29 formatFor,
30 formatSize,
31 hashText,
32 imageBox,
33 isMermaidFile,
34 isPreviewable,
35 isTextChart,
36 mermaidSources,
37 newestFirst,
38 parentDir,
39 peleSvg,
40 peleSvgAdaptive,
41 pngSize,
42 previewHtml,
43 rasterArgv,
44 renderKey,
45 rendererError,
46 schemeFor,
47 splitDoc,
48 stripAnsi,
49 tableAsList,
50 tableLines,
51 textChart,
52 toolDirs,
53} from './docs'
54import type { InlineFormat, Run, TableLine } from './docs'
55
56type Engine = EngineInterface
57/** What the pane can show a document for: a file or a reply's diagram. */
58type DocTarget = Exclude<DocView, { kind: 'picker' }>
59/** A loaded doc, or why not; `mtimeMs` is the file's time as read, which the poll compares with. */
60type Loaded =
61 | { title: string; source: string; isMermaid: boolean; path?: string; size?: number; mtimeMs?: number }
62 | { error: string; mtimeMs?: number }
63type Shown = Exclude<Loaded, { error: string }>
64/** A block of the shown doc, prepared once per doc, width, surface and format. */
65type DrawnBlock =
66 | { kind: 'prose'; text: string }
67 | { kind: 'table'; lines: TableLine[] | null; list: string }
68 | { kind: 'mermaid'; source: string; title: string; type: string; isText: boolean; chart: string | null; key: string | null }
69type Listing = { entries: SelectOption[]; total: number } | { error: string }
70/** `scheme` and `rasterizer` say how a PNG is drawn; only `scheme` is in its key. */
71type RenderJob = { format: InlineFormat; source: string; scheme: Scheme; rasterizer: Rasterizer | null }
72/** What both pane views draw with: the surface's elements, the room, and the state they read. */
73type PaneContext = {
74 el: ElementTable
75 surface: RenderSurface
76 columns: number
77 offset: number
78 cwd: string
79 home: string | undefined
80 recent: SelectOption[]
81 asked: PaneSize
82 found: Renderers | null
83 done: Record<string, DiagramRender>
84 problem: string | null
85}
86
87const view = atom({ plugin: 'doc-preview', key: 'view' } as const, null)
88const generated = atom({ plugin: 'doc-preview', key: 'generated' } as const, [])
89const diagrams = atom({ plugin: 'doc-preview', key: 'diagrams' } as const, [])
90const seenAt = atom({ plugin: 'doc-preview', key: 'seenAt' } as const, 0)
91const renders = atom({ plugin: 'doc-preview', key: 'renders' } as const, {})
92const renderers = atom({ plugin: 'doc-preview', key: 'renderers' } as const, null)
93const notice = atom({ plugin: 'doc-preview', key: 'notice' } as const, null)
94const sizing = atom({ plugin: 'doc-preview', key: 'size' } as const, { columns: null, isFull: false })
95
96const PLUGIN = 'doc-preview'
97/** The command xorio ships (`commands/preview.md`); this mod answers it. */
98const COMMAND = 'xorio:preview'
99/** Registered only when xorio's command is missing, so the mod still has an entry point. */
100const FALLBACK_COMMAND = 'preview'
101const MAX_RECENT = 20
102const MAX_RENDERS = 40
103const MAX_ENTRIES = 300
104/**
105 * Where detection found each tool PATH doesn't have, by name: an app started
106 * from the desktop (VS Code) often runs with a shorter PATH than a shell.
107 */
108const toolPaths = new Map<string, string>()
109
110/** Renders running at once across all passes: an mmdc run starts a headless browser. */
111const RENDER_CONCURRENCY = 3
112const POLL_MS = 2000
113/** `w` and `n` move the pane's width by this many columns, between these bounds. */
114const WIDTH_STEP = 20
115const MIN_WIDTH = 40
116/** Widening stops short of the screen's edge by this many columns; full screen asks for all of it. */
117const MIN_TRANSCRIPT = 30
118const FULL_FALLBACK = 1000
119/** Theme colors for inline code and link text in drawn tables. */
120const CODE_COLOR = 'permission'
121const LINK_COLOR = 'suggestion'
122const BROWSER_HINT = 'press b to see it drawn in the browser.'
123const PICK: SelectOption = { value: '', label: 'choose…' }
124const SKIPPED_DIRS = new Set(['.git', 'node_modules'])
125
126/** Diagrams waiting to render, the keys being rendered, and the workers draining the queue. */
127const queue: RenderJob[] = []
128const rendering = new Set<string>()
129let workers = 0
130/** The render keys the shown doc needs: never pruned from `renders` while it is shown. */
131let needed = new Set<string>()
132/** The terminal's size and the pane's body width as the pane last drew; what resizing starts from. */
133let screen: { columns: number; rows: number } | undefined
134let paneColumns: number | undefined
135/** Checks the shown file for outside edits; runs only while a file is shown. */
136let poll: Timer | null = null
137/** The shown doc's load, shared by every caller (even ones arriving mid-load); the key changes with `rev`. */
138let loaded: { key: string; doc: Promise<Loaded> } | null = null
139/** The shown doc laid out for one width, surface and format: all a scroll's redraw has to reuse. */
140let layout: { key: string; blocks: DrawnBlock[]; diagramCount: number } | null = null
141/** SVG markup by file, for the svg renders `renders` still holds. */
142const svgs = new Map<string, string>()
143/** The picker's folder listing, kept across redraws until the picker opens again. */
144let listing: { dir: string; result: Listing } | null = null
145
146// ── showing things ──────────────────────────────────────────────────────────
147
148const markSeen = ($: Engine) => update($, seenAt, () => Date.now())
149
150const docKey = (v: DocTarget): string => (v.kind === 'file' ? `file:${v.path}:${v.rev}` : `diagram:${v.id}`)
151
152const titleOf = (v: DocView | null): string =>
153 v === null || v.kind === 'picker'
154 ? 'Preview · pick a file'
155 : v.kind === 'file'
156 ? `Preview · ${baseName(v.path)}`
157 : 'Preview · diagram'
158
159/**
160 * Opens or retitles the pane at the size asked for: the whole screen, a
161 * width (`rows` matters only inline above the prompt, `columns` only docked),
162 * or, with neither, the engine's default share.
163 */
164async function openPane($: Engine, shown: DocView | null): Promise<void> {
165 const asked = await read($, sizing)
166 // Right after a reload the screen is unknown until the pane draws: full then asks for
167 // more than any screen has, which the engine clamps to what it can spare.
168 const request = asked.isFull
169 ? { columns: screen?.columns ?? FULL_FALLBACK, rows: screen?.rows ?? FULL_FALLBACK }
170 : asked.columns !== null
171 ? { columns: asked.columns }
172 : {}
173 await $.ui.open({ id: PANE, title: titleOf(shown), focus: true, ...request })
174}
175
176/** `w` (+1) and `n` (-1): one step wider or narrower than the pane is now; leaves full screen. */
177async function resize($: Engine, direction: 1 | -1): Promise<void> {
178 const widest = screen === undefined ? Number.MAX_SAFE_INTEGER : Math.max(MIN_WIDTH, screen.columns - MIN_TRANSCRIPT)
179 await update($, sizing, asked => {
180 const from = asked.columns ?? paneColumns ?? MIN_WIDTH
181 return { columns: Math.min(widest, Math.max(MIN_WIDTH, from + direction * WIDTH_STEP)), isFull: false }
182 })
183 await openPane($, await read($, view))
184}
185
186/** `z`: the whole screen, and back to the width before. */
187async function toggleFull($: Engine): Promise<void> {
188 await update($, sizing, asked => ({ ...asked, isFull: !asked.isFull }))
189 await openPane($, await read($, view))
190}
191
192async function showTarget($: Engine, target: DocTarget): Promise<void> {
193 const current = await read($, view)
194 const next: DocTarget =
195 target.kind === 'file' && current?.kind === 'file' && current.path === target.path
196 ? { ...target, rev: current.rev + 1 }
197 : target
198 await Promise.all([update($, view, () => next), update($, notice, () => null), markSeen($)])
199 await openPane($, next)
200 if (next.kind === 'file') ensurePolling($)
201 ensureRenders($)
202}
203
204async function showPicker($: Engine, dir?: string): Promise<void> {
205 listing = null
206 loaded = null
207 layout = null
208 const next: DocView = { kind: 'picker', dir: dir ?? '' }
209 await Promise.all([update($, view, () => next), update($, notice, () => null)])
210 await openPane($, next)
211}
212
213/** A picked value: `dir:<path>`, `file:<path>` or `diagram:<id>`. */
214async function showItem($: Engine, value: string): Promise<void> {
215 const [kind, rest] = [value.slice(0, value.indexOf(':')), value.slice(value.indexOf(':') + 1)]
216 if (kind === 'dir') await showPicker($, rest)
217 else if (kind === 'file') await showTarget($, { kind: 'file', path: rest, rev: 0 })
218 else if (kind === 'diagram') await showTarget($, { kind: 'diagram', id: rest })
219}
220
221/** Shows the file again from disk: a new `rev` makes the pane load it afresh. */
222async function refresh($: Engine): Promise<void> {
223 await update($, view, current => (current?.kind === 'file' ? { ...current, rev: current.rev + 1 } : current))
224 ensureRenders($)
225}
226
227/** `/xorio:preview [path]`: the picker without a path, else the doc, or why not. */
228async function runPreview($: Engine, args: string): Promise<{ text?: string }> {
229 const arg = args.trim()
230 if (arg === '') {
231 await showPicker($)
232 return {}
233 }
234 const problem = await openPath($, arg)
235
236 return problem === undefined ? {} : { text: problem }
237}
238
239/** What a typed path or `/xorio:preview <path>` names: a doc, a folder to browse, or why not. */
240async function openPath($: Engine, input: string): Promise<string | undefined> {
241 const [cwd, home] = await Promise.all([$.session.cwd(), $.env.get('HOME')])
242 const path = expandPath(input, cwd, home)
243 const stat = await $.fs.stat(path).catch(() => undefined)
244 if (stat === undefined) return `Not found: ${input}`
245 if (stat.kind === 'dir') {
246 await showPicker($, path)
247 return undefined
248 }
249 if (!isPreviewable(path)) {
250 return `Not a Markdown or Mermaid file (.md .markdown .mdx .mmd .mermaid): ${input}`
251 }
252 await showTarget($, { kind: 'file', path, rev: 0 })
253
254 return undefined
255}
256
257// ── loading and rendering ───────────────────────────────────────────────────
258
259async function load($: Engine, v: DocTarget): Promise<Loaded> {
260 if (v.kind === 'diagram') {
261 const diagram = (await read($, diagrams)).find(d => d.id === v.id)
262 return diagram === undefined
263 ? { error: 'That diagram is no longer in the recent list.' }
264 : { title: diagram.title, source: diagram.source, isMermaid: true }
265 }
266 // The time is taken before the read: an edit landing in between shows as a change on the next poll.
267 let mtimeMs: number | undefined
268 try {
269 const stat = await $.fs.stat(v.path)
270 mtimeMs = stat.mtimeMs
271 const source = await $.fs.read(v.path)
272 return { title: baseName(v.path), source, isMermaid: isMermaidFile(v.path), path: v.path, size: stat.size, mtimeMs }
273 } catch (err) {
274 return { error: `Can't read ${v.path}: ${errorText(err)}`, mtimeMs }
275 }
276}
277
278function loadShown($: Engine, v: DocTarget): { key: string; doc: Promise<Loaded> } {
279 const key = docKey(v)
280 if (loaded?.key !== key) loaded = { key, doc: load($, v) }
281
282 return loaded
283}
284
285/** The shown doc's blocks for one width, surface and format, made once and reused by every scroll's redraw. */
286function layoutOf(
287 key: string,
288 doc: Shown,
289 columns: number,
290 surface: RenderSurface,
291 format: InlineFormat | null,
292 scheme: Scheme,
293) {
294 const layoutKey = `${key}|${columns}|${surface}|${format}|${scheme}`
295 if (layout?.key === layoutKey) return layout
296 // The terminal's Markdown draws a table at its full width and the terminal wraps the
297 // overflow, breaking its borders: there tables are drawn here, fitted to the pane.
298 const blocks = splitDoc(doc.source, doc.isMermaid).map((block): DrawnBlock => {
299 if (block.kind === 'prose') return block
300 if (block.kind === 'table') {
301 if (surface !== 'terminal') return { kind: 'prose', text: block.source }
302 const lines = tableLines(block.table, columns)
303 return { kind: 'table', lines, list: lines === null ? tableAsList(block.table) : '' }
304 }
305 const { source } = block
306 return {
307 kind: 'mermaid',
308 source,
309 title: diagramTitle(source),
310 type: diagramKind(source),
311 isText: isTextChart(source),
312 chart: textChart(source, columns - 4),
313 key: format === null ? null : renderKey(source, format, scheme),
314 }
315 })
316 layout = { key: layoutKey, blocks, diagramCount: blocks.filter(b => b.kind === 'mermaid').length }
317
318 return layout
319}
320
321/** Reads the shown doc's SVG files once each, and forgets the ones `renders` no longer holds. */
322async function loadSvgs($: Engine, files: string[], live: Set<string>): Promise<void> {
323 for (const file of svgs.keys()) if (!live.has(file)) svgs.delete(file)
324 const missing = [...new Set(files)].filter(file => !svgs.has(file))
325 if (missing.length === 0) return
326 const texts = await Promise.all(missing.map(file => $.fs.read(file).catch(() => '')))
327 missing.forEach((file, i) => svgs.set(file, texts[i] ?? ''))
328}
329
330async function cacheDir($: Engine): Promise<string> {
331 const [xdg, local, home] = await Promise.all([
332 $.env.get('XDG_CACHE_HOME'),
333 $.env.get('LOCALAPPDATA'),
334 $.env.get('HOME'),
335 ])
336
337 // `||`, not `??`: a variable set but empty names no folder.
338 return `${xdg || local || `${home || '/tmp'}/.cache`}/claude-doc-preview`
339}
340
341const failed = (tool: string, ran: { exitCode: number; stdout: string; stderr: string }): DiagramRender => ({
342 format: 'error',
343 message: firstLine(ran.stderr || ran.stdout) || `${tool} exited ${ran.exitCode}`,
344})
345
346/**
347 * A drawing of pele's, written to the cache under a hash of the SVG itself: a
348 * change to pele, its palette or its fonts names a new file, and an unchanged
349 * drawing is reused across sessions.
350 */
351async function peleFile($: Engine, dir: string, svg: string): Promise<string> {
352 const file = `${dir}/${hashText(svg)}.svg`
353 if (!(await $.fs.exists(file))) await $.fs.write(file, svg)
354
355 return file
356}
357
358/** mmdc's own drawing of the diagram as a PNG, at 2x, in its theme nearest the scheme. */
359async function runMmdc($: Engine, dir: string, source: string, scheme: Scheme, output: string) {
360 const input = `${dir}/${hashText(source)}.mmd`
361 await $.fs.write(input, source)
362 const colors = [...(scheme === 'dark' ? ['-t', 'dark'] : []), '-b', PELE_THEMES[scheme].bg]
363
364 return runTool($, ['mmdc', '-q', '-i', input, '-o', output, ...colors, '-s', '2'], { timeoutMs: 90_000 })
365}
366
367/** A PNG of the diagram in the scheme's colors: pele's SVG through resvg or rsvg-convert, or mmdc when neither is installed. */
368async function renderPng($: Engine, dir: string, { source, scheme, rasterizer }: RenderJob): Promise<DiagramRender> {
369 const svg = rasterizer === null ? null : peleSvg(source, scheme)
370 const tool = rasterizer ?? 'mmdc'
371 const output = svg === null ? `${dir}/${hashText(source)}.mmdc.${scheme}.png` : `${dir}/${hashText(svg)}.png`
372 if (!(await $.fs.exists(output))) {
373 const ran =
374 rasterizer === null || svg === null
375 ? await runMmdc($, dir, source, scheme, output)
376 : await runTool($, rasterArgv(rasterizer, await peleFile($, dir, svg), output), { timeoutMs: 30_000 })
377 if (ran.exitCode !== 0) return failed(tool, ran)
378 }
379 const { base64 } = await $.fs.read(output, { as: 'bytes' })
380 const size = pngSize(base64)
381
382 return size === null ? { format: 'error', message: `${tool} wrote no PNG.` } : { format: 'png', file: output, ...size }
383}
384
385async function renderDiagram($: Engine, job: RenderJob): Promise<DiagramRender> {
386 const { format, source } = job
387 try {
388 if (format === 'ascii') {
389 const ran = await runTool($, ['mermaid-ascii'], { stdin: asciiSource(source), timeoutMs: 20_000 })
390 return ran.exitCode === 0 ? { format: 'ascii', text: stripAnsi(ran.stdout).trimEnd() } : failed('mermaid-ascii', ran)
391 }
392 const dir = await cacheDir($)
393 if (format === 'png') return await renderPng($, dir, job)
394
395 const svg = peleSvgAdaptive(source)
396 return svg.length > MAX_SVG
397 ? { format: 'error', message: `Too large to draw inline: ${BROWSER_HINT}` }
398 : { format: 'svg', file: await peleFile($, dir, svg) }
399 } catch (err) {
400 return { format: 'error', message: errorText(err) }
401 }
402}
403
404/** Runs work nobody awaits, so a failure lands in the debug log and nowhere else. */
405function inBackground($: Engine, work: Promise<void>): void {
406 work.catch((err: unknown) => $.ui.log(`doc-preview: ${errorText(err)}`, { to: 'debug' }))
407}
408
409const ensureRenders = ($: Engine): void => inBackground($, renderShown($))
410
411/**
412 * Queues the shown doc's diagrams that have no render yet, in the format of
413 * each surface the session draws on; the pane redraws as each lands. Pie and
414 * gantt charts are drawn as text instead, never by mermaid-ascii.
415 */
416async function renderShown($: Engine): Promise<void> {
417 const [v, found, surfaces, done] = await Promise.all([
418 read($, view),
419 read($, renderers),
420 $.session.surfaces(),
421 read($, renders),
422 ])
423 if (v === null || v.kind === 'picker') return
424 const formats = new Set(surfaces.map(surface => formatFor(surface, found)).filter(f => f !== null))
425 if (formats.size === 0) return
426 const doc = await loadShown($, v).doc
427 if ('error' in doc) return
428
429 const sources = mermaidSources(doc.source, doc.isMermaid)
430 const scheme = found?.scheme ?? 'dark'
431 const rasterizer = found?.rasterizer ?? null
432 const jobs = [...formats].flatMap(format =>
433 sources
434 .filter(source => !(format === 'ascii' && isTextChart(source)))
435 .map(source => ({ format, source, scheme, rasterizer })),
436 )
437 needed = new Set(jobs.map(jobKey))
438 // The queue holds only the shown doc's jobs: a doc no longer shown doesn't keep the
439 // workers busy, and a job is queued once however often the doc reloads.
440 queue.splice(0, queue.length, ...jobs.filter(job => done[jobKey(job)] === undefined))
441 while (workers < RENDER_CONCURRENCY && queue.length > 0) {
442 workers += 1
443 inBackground(
444 $,
445 drainQueue($).finally(() => {
446 workers -= 1
447 }),
448 )
449 }
450}
451
452async function drainQueue($: Engine): Promise<void> {
453 for (let job = queue.shift(); job !== undefined; job = queue.shift()) await renderJob($, job)
454}
455
456/**
457 * Renders one diagram unless another worker is on it or has finished it: the
458 * key is claimed before the current renders are read, so it is drawn once.
459 */
460async function renderJob($: Engine, job: RenderJob): Promise<void> {
461 const key = jobKey(job)
462 if (rendering.has(key)) return
463 rendering.add(key)
464 try {
465 const done = await read($, renders)
466 if (done[key] !== undefined) return
467 const result = await renderDiagram($, job)
468 await update($, renders, all => pruneRenders({ ...withoutKey(all, key), [key]: result }))
469 } finally {
470 rendering.delete(key)
471 }
472}
473
474const jobKey = ({ source, format, scheme }: RenderJob): string => renderKey(source, format, scheme)
475
476const withoutKey = <T,>(all: Record<string, T>, key: string): Record<string, T> =>
477 Object.fromEntries(Object.entries(all).filter(([k]) => k !== key))
478
479/** Every render the shown doc needs, then the newest others, up to the cap. */
480function pruneRenders(all: Record<string, DiagramRender>): Record<string, DiagramRender> {
481 const entries = Object.entries(all)
482 let spare = entries.length - Math.max(MAX_RENDERS, needed.size)
483 if (spare <= 0) return all
484
485 return Object.fromEntries(entries.filter(([key]) => needed.has(key) || spare-- <= 0))
486}
487
488async function canRun($: Engine, argv: string[]): Promise<boolean> {
489 try {
490 return (await $.process.run(argv, { timeoutMs: 30_000 })).exitCode === 0
491 } catch {
492 return false
493 }
494}
495
496/** Runs a tool from where detection found it, else by name. */
497function runTool($: Engine, [name = '', ...args]: string[], options: { stdin?: string; timeoutMs: number }) {
498 return $.process.run([toolPaths.get(name) ?? name, ...args], options)
499}
500
501/** Whether a tool runs, by name or from one of `dirs`; where it ran is kept for `runTool`. */
502async function findTool($: Engine, name: string, flag: string, dirs: string[]): Promise<boolean> {
503 toolPaths.delete(name)
504 for (const dir of [null, ...dirs]) {
505 const command = dir === null ? name : `${dir}/${name}`
506 if (await canRun($, [command, flag])) {
507 if (dir !== null) toolPaths.set(name, command)
508 return true
509 }
510 }
511
512 return false
513}
514
515/**
516 * Light or dark for the terminal's PNGs, from Claude Code's theme setting:
517 * the value given (a change being made), else the one `/config` holds.
518 */
519async function currentScheme($: Engine, theme?: ConfigValue): Promise<Scheme> {
520 const [rows, colorfgbg] = await Promise.all([
521 theme === undefined ? $.config.list().catch(() => []) : [],
522 $.env.get('COLORFGBG'),
523 ])
524
525 return schemeFor(theme ?? (rows ?? []).find(row => row.key === 'theme')?.value, colorfgbg)
526}
527
528/** Draws the PNGs in the other scheme's colors when the theme setting flips light and dark. */
529async function followTheme($: Engine, theme: ConfigValue): Promise<void> {
530 const scheme = await currentScheme($, theme)
531 // Changed on the stored value, not a copy read earlier: a detection landing in
532 // between keeps its tools.
533 let isFlipped = false
534 await update($, renderers, found => {
535 if (found === null || found.scheme === scheme) return found
536 isFlipped = true
537 return { ...found, scheme }
538 })
539 if (isFlipped) ensureRenders($)
540}
541
542async function detectRenderers($: Engine): Promise<void> {
543 const [term, program, kittyWindow, ghostty, forced] = await Promise.all([
544 $.env.get('TERM'),
545 $.env.get('TERM_PROGRAM'),
546 $.env.get('KITTY_WINDOW_ID'),
547 $.env.get('GHOSTTY_RESOURCES_DIR'),
548 $.env.get('DOC_PREVIEW_IMAGES'),
549 ])
550 const drawsImages = drawsImagesIn({ term, program, kittyWindow, ghostty, forced })
551 const [home, gopath] = await Promise.all([$.env.get('HOME'), $.env.get('GOPATH')])
552 const dirs = toolDirs(home, gopath)
553 // The PNG tools are probed only where images are drawn, and mmdc (it starts Node)
554 // only when neither rasterizer is installed.
555 const pixels = (name: string) => (drawsImages ? findTool($, name, '--version', dirs) : Promise.resolve(false))
556 const [ascii, resvg, rsvg, scheme] = await Promise.all([
557 findTool($, 'mermaid-ascii', '--help', dirs),
558 pixels('resvg'),
559 pixels('rsvg-convert'),
560 currentScheme($),
561 ])
562 const rasterizer: Rasterizer | null = resvg ? 'resvg' : rsvg ? 'rsvg-convert' : null
563 const mmdc = rasterizer === null && (await pixels('mmdc'))
564 await update($, renderers, () => ({ ascii, mmdc, rasterizer, drawsImages, scheme }))
565 ensureRenders($)
566}
567
568/** Registers `/preview` when neither xorio's `/xorio:preview` nor another `/preview` is installed. */
569async function registerFallback($: Engine): Promise<void> {
570 const commands = await $.command.list()
571 if (commands.some(command => command.name === COMMAND || command.name === FALLBACK_COMMAND)) return
572 await $.command.register({
573 name: FALLBACK_COMMAND,
574 description: 'Preview a Markdown or Mermaid file; no path opens a file picker',
575 argumentHint: '[path]',
576 immediate: true,
577 })
578}
579
580/** Whether `/preview` is this mod's fallback, not the person's own command or another plugin's. */
581async function ownsFallback($: Engine): Promise<boolean> {
582 const commands = await $.command.list()
583 return commands.some(
584 command => command.name === FALLBACK_COMMAND && command.source === 'plugin' && (command.plugin ?? PLUGIN) === PLUGIN,
585 )
586}
587
588function ensurePolling($: Engine): void {
589 if (poll === null) poll = $.clock.every(POLL_MS, () => inBackground($, pollShownFile($)))
590}
591
592/**
593 * Picks up edits made outside Claude Code while the pane shows a file, by
594 * comparing the file's time with the time it was read at; stops once no
595 * file is shown.
596 */
597async function pollShownFile($: Engine): Promise<void> {
598 const [v, panes] = await Promise.all([read($, view), $.ui.panes()])
599 if (v?.kind !== 'file' || !panes.some(pane => pane.id === PANE)) {
600 poll?.cancel()
601 poll = null
602 return
603 }
604 const shown = loaded
605 if (shown?.key !== docKey(v)) return // a reload is under way
606 const [doc, stat] = await Promise.all([shown.doc, $.fs.stat(v.path).catch(() => undefined)])
607 if (stat !== undefined && stat.mtimeMs !== doc.mtimeMs) await refresh($)
608}
609
610// ── the browser ─────────────────────────────────────────────────────────────
611
612async function openExternal($: Engine, file: string): Promise<boolean> {
613 const isWindows = (await $.env.get('OS')) === 'Windows_NT'
614 const isMac = !isWindows && (await $.fs.exists('/System/Library/CoreServices'))
615 const argv = isWindows
616 ? ['explorer', file]
617 : isMac
618 ? ['open', file]
619 : // Backgrounded so the browser can't hold the call; a missing xdg-open still fails it.
620 ['sh', '-c', 'command -v xdg-open >/dev/null || exit 1; xdg-open "$1" >/dev/null 2>&1 &', 'sh', file]
621 try {
622 const ran = await $.process.run(argv, { timeoutMs: 15_000 })
623 return isWindows || ran.exitCode === 0
624 } catch {
625 return false
626 }
627}
628
629async function openInBrowser($: Engine, v: DocTarget): Promise<void> {
630 const doc = await load($, v)
631 if ('error' in doc) {
632 $.ui.toast(doc.error)
633 return
634 }
635 const html = previewHtml({
636 title: doc.path ?? doc.title,
637 source: doc.source,
638 isMermaid: doc.isMermaid,
639 baseDir: doc.path === undefined ? undefined : parentDir(doc.path),
640 })
641 const slug = doc.title.replace(/[^\w.-]+/g, '-').slice(0, 40)
642 const file = `${await cacheDir($)}/${slug}-${hashText(doc.source)}.html`
643 await $.fs.write(file, html)
644 const isOpened = await openExternal($, file)
645 $.ui.toast(isOpened ? `Opened ${doc.title} in the browser` : `Couldn't start a browser; the page is at ${file}`)
646}
647
648// ── what Claude generates ───────────────────────────────────────────────────
649
650async function recordGenerated($: Engine, path: string): Promise<void> {
651 const [, v] = await Promise.all([
652 update($, generated, list => newestFirst([{ path, at: Date.now() }], list, d => d.path, MAX_RECENT)),
653 read($, view),
654 ])
655 if (v?.kind === 'file' && v.path === path) await refresh($)
656}
657
658async function recordDiagrams($: Engine, sources: string[]): Promise<void> {
659 const at = Date.now()
660 const found = sources.map((source): ReplyDiagram => ({ id: hashText(source), source, title: diagramTitle(source), at }))
661 await update($, diagrams, list => newestFirst(found, list, d => d.id, MAX_RECENT))
662}
663
664const textBlocks = (content: unknown): string[] => {
665 if (typeof content === 'string') return [content]
666 if (!Array.isArray(content)) return []
667 return content.flatMap(block => {
668 const b = block as { type?: unknown; text?: unknown }
669 return b.type === 'text' && typeof b.text === 'string' ? [b.text] : []
670 })
671}
672
673/** The docs and diagrams from this session, newest first, as Select options. */
674function recentOptions(
675 docs: readonly GeneratedDoc[],
676 replies: readonly ReplyDiagram[],
677 cwd: string,
678 home: string | undefined,
679): SelectOption[] {
680 const items = [
681 ...docs.map(d => ({ at: d.at, value: `file:${d.path}`, label: displayPath(d.path, cwd, home) })),
682 ...replies.map(d => ({ at: d.at, value: `diagram:${d.id}`, label: `◇ ${d.title} (reply, ${clock(d.at)})` })),
683 ]
684
685 return items.sort((a, b) => b.at - a.at).map(({ value, label }) => ({ value, label }))
686}
687
688const clock = (at: number): string => {
689 const date = new Date(at)
690 return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
691}
692
693async function freshItems($: Engine): Promise<{ docs: GeneratedDoc[]; replies: ReplyDiagram[] }> {
694 const [seen, docs, replies] = await Promise.all([read($, seenAt), read($, generated), read($, diagrams)])
695 return { docs: docs.filter(d => d.at > seen), replies: replies.filter(d => d.at > seen) }
696}
697
698/** The newest doc or diagram Claude produced since the person last looked. */
699async function newestFresh($: Engine): Promise<DocTarget | null> {
700 const { docs, replies } = await freshItems($)
701 const doc = docs[0]
702 const reply = replies[0]
703 if (doc !== undefined && (reply === undefined || doc.at >= reply.at)) {
704 return { kind: 'file', path: doc.path, rev: 0 }
705 }
706 return reply === undefined ? null : { kind: 'diagram', id: reply.id }
707}
708
709// ── the pane ────────────────────────────────────────────────────────────────
710
711/** The folder's subfolders and previewable files as picker options, listed once per opening. */
712async function listFolder($: Engine, dir: string): Promise<Listing> {
713 if (listing?.dir === dir) return listing.result
714 const result = await $.fs.list(dir).then(
715 async entries => {
716 // A link is listed as `other`: follow it to tell a folder from a file.
717 const kinds = await Promise.all(
718 entries.map(async entry => {
719 const path = `${dir === '/' ? '' : dir}/${entry.name}`
720 const kind = entry.isLink ? ((await $.fs.stat(path).catch(() => undefined))?.kind ?? 'other') : entry.kind
721 return { name: entry.name, path, kind }
722 }),
723 )
724 const sorted = kinds.sort((a, b) => a.name.localeCompare(b.name))
725 const options: SelectOption[] = [
726 { value: `dir:${parentDir(dir)}`, label: '../' },
727 ...sorted
728 .filter(entry => entry.kind === 'dir' && !SKIPPED_DIRS.has(entry.name))
729 .map(entry => ({ value: `dir:${entry.path}`, label: `${entry.name}/` })),
730 ...sorted
731 .filter(entry => entry.kind === 'file' && isPreviewable(entry.name))
732 .map(entry => ({ value: `file:${entry.path}`, label: entry.name })),
733 ]
734 return { entries: options.slice(0, MAX_ENTRIES), total: options.length }
735 },
736 (err: unknown) => ({ error: errorText(err) }),
737 )
738 listing = { dir, result }
739
740 return result
741}
742
743async function renderPicker($: Engine, ctx: PaneContext, dir: string): Promise<RenderElement> {
744 const { el, cwd, home, recent, problem } = ctx
745 const { Box, Button, Text } = el
746 const Select = 'Select' in el ? el.Select : undefined
747 const Input = 'Input' in el ? el.Input : undefined
748 const folder = await listFolder($, dir)
749
750 return (
751 <Box flexDirection="column" rowGap={1}>
752 <Text bold>Preview a Markdown or Mermaid file</Text>
753 {problem !== null && <Text color="yellow">{problem}</Text>}
754 {Input !== undefined ? (
755 <Input
756 key="path"
757 label="Path"
758 placeholder="relative to the project, absolute, or ~/…"
759 submitLabel="open"
760 autoFocus
761 onSubmit={async value => {
762 const why = await openPath($, value)
763 await update($, notice, () => why ?? null)
764 }}
765 />
766 ) : (
767 <Text dimColor>{'Type /xorio:preview <path> to open a file.'}</Text>
768 )}
769 {Select !== undefined && recent.length > 0 && (
770 <Select key="recent" label="Recent" options={[PICK, ...recent]} value="" onSelect={value => showItem($, value)} />
771 )}
772 {Select !== undefined && 'entries' in folder && (
773 <Select
774 key="browse"
775 label={`Browse ${displayPath(dir, cwd, home)}`}
776 options={[PICK, ...folder.entries]}
777 value=""
778 onSelect={value => showItem($, value)}
779 />
780 )}
781 {'error' in folder && <Text color="red">{`Can't list ${dir}: ${folder.error}`}</Text>}
782 {'total' in folder && folder.total > MAX_ENTRIES && <Text dimColor>{`Showing the first ${MAX_ENTRIES} entries.`}</Text>}
783 <Box>
784 <Button key="close" label="Close" role="dismiss" onPress={() => $.ui.close({ id: PANE })} />
785 </Box>
786 </Box>
787 )
788}
789
790async function renderDoc($: Engine, ctx: PaneContext, v: DocTarget): Promise<RenderElement> {
791 const { el, surface, columns, cwd, home, recent, asked, found, done } = ctx
792 const { Box, Button, Code, Markdown, Text } = el
793 const Select = 'Select' in el ? el.Select : undefined
794 const shown = loadShown($, v)
795 const doc = await shown.doc
796 const current = v.kind === 'file' ? `file:${v.path}` : `diagram:${v.id}`
797 const options = recent.some(o => o.value === current)
798 ? recent
799 : [{ value: current, label: 'path' in doc && doc.path ? displayPath(doc.path, cwd, home) : 'this diagram' }, ...recent]
800 const actions = [
801 { key: 'browser', hotkey: 'b', label: 'browser', press: () => openInBrowser($, v) },
802 { key: 'wider', hotkey: 'w', label: 'wider', press: () => resize($, 1) },
803 { key: 'narrower', hotkey: 'n', label: 'narrower', press: () => resize($, -1) },
804 { key: 'full', hotkey: 'z', label: asked.isFull ? 'exit full' : 'full', press: () => toggleFull($) },
805 ...(v.kind === 'file' ? [{ key: 'reload', hotkey: 'r', label: 'reload', press: () => refresh($) }] : []),
806 {
807 key: 'pick',
808 hotkey: 'f',
809 label: 'files',
810 press: () => showPicker($, v.kind === 'file' ? parentDir(v.path) : undefined),
811 },
812 { key: 'close', hotkey: 'q', label: 'close', press: () => $.ui.close({ id: PANE }) },
813 ]
814 // A plain Button draws `k: label`, two columns apart; the bar wraps onto as many rows as that takes.
815 let barRows = 1
816 let used = 0
817 for (const a of actions) {
818 const width = a.hotkey.length + 2 + a.label.length
819 if (used > 0 && used + 2 + width > columns) {
820 barRows += 1
821 used = width
822 } else {
823 used += (used > 0 ? 2 : 0) + width
824 }
825 }
826 // On the terminal the bar is pinned to the window's top rows: each scroll redraws
827 // with the new offset, and an absolute Box paints over the rows beneath it.
828 const isPinned = surface === 'terminal'
829 const pin = isPinned
830 ? ({ position: 'absolute', top: ctx.offset, left: 0, backgroundColor: 'inverseText' } as const)
831 : {}
832 const toolbar = (
833 <Box key="toolbar" flexDirection="row" flexWrap="wrap" columnGap={2} width={columns} height={barRows} overflow="hidden" {...pin}>
834 {actions.map(a => (
835 <Button
836 key={a.key}
837 label={a.label}
838 hotkey={a.hotkey}
839 plain
840 {...(a.key === 'close' ? { role: 'dismiss' as const } : {})}
841 onPress={a.press}
842 />
843 ))}
844 </Box>
845 )
846 /** The page under the bar: pinned, the bar overlays the first rows, so the page starts below them. */
847 const page = (...children: RenderChildren[]) => (
848 <Box flexDirection="column">
849 <Box flexDirection="column" rowGap={1} marginTop={isPinned ? barRows : 0}>
850 {!isPinned && toolbar}
851 {Select !== undefined && options.length > 1 && (
852 <Select key="recent" label="Doc" options={options} value={current} onSelect={value => showItem($, value)} />
853 )}
854 {children}
855 </Box>
856 {isPinned && toolbar}
857 </Box>
858 )
859 if ('error' in doc) return page(<Text color="red">{doc.error}</Text>)
860
861 const format = formatFor(surface, found)
862 const { blocks, diagramCount } = layoutOf(shown.key, doc, columns, surface, format, found?.scheme ?? 'dark')
863 const renderOf = (key: string | null) => (key === null ? undefined : done[key])
864 await loadSvgs(
865 $,
866 blocks.flatMap(b => {
867 const r = b.kind === 'mermaid' ? renderOf(b.key) : undefined
868 return r?.format === 'svg' ? [r.file] : []
869 }),
870 new Set(Object.values(done).flatMap(r => (r.format === 'svg' ? [r.file] : []))),
871 )
872 const where = doc.path === undefined ? 'from a reply' : displayPath(doc.path, cwd, home)
873 const meta = [where, doc.size === undefined ? '' : formatSize(doc.size), diagramCount > 0 ? countOf(diagramCount, 'diagram') : '']
874 .filter(Boolean)
875 .join(' · ')
876
877 // An image beats a text chart, which beats mermaid-ascii's drawing, which beats the source.
878 const diagram = (d: Extract<DrawnBlock, { kind: 'mermaid' }>) => {
879 const r = renderOf(d.key)
880 const svg = r?.format === 'svg' ? (svgs.get(r.file) ?? '') : ''
881 // A render is on its way only in a format this diagram goes to: never mermaid-ascii for a text chart.
882 const isRendered = format !== null && !(format === 'ascii' && d.isText)
883 let body: RenderElement = <Code source={d.source} language="mermaid" />
884 let note: RenderElement | null = null
885 if (r?.format === 'png' && 'Image' in el) {
886 const box = imageBox(r, columns - 4)
887 body = <el.Image source={{ file: r.file, format: 'png' }} columns={box.columns} rows={box.rows} alt="Mermaid diagram" />
888 } else if (svg !== '' && 'Svg' in el) {
889 body = <el.Svg source={svg} alt="Mermaid diagram" />
890 } else if (d.chart !== null) {
891 body = <Code source={d.chart} language="text" wrap="truncate-end" />
892 } else if (r?.format === 'ascii') {
893 body = <Code source={r.text} language="text" wrap="truncate-end" />
894 } else if (r?.format === 'error') {
895 note = <Text color="yellow" wrap="wrap">{`${rendererError(r.message, d.type)}; ${BROWSER_HINT}`}</Text>
896 } else if (isRendered && r === undefined) {
897 note = <Text dimColor>Drawing…</Text>
898 } else if (d.isText) {
899 note = <Text color="yellow" wrap="wrap">{`Couldn't read this ${d.type} chart; ${BROWSER_HINT}`}</Text>
900 }
901
902 return (
903 <Box flexDirection="column" borderStyle="round" borderDimColor paddingX={1} width={columns}>
904 <Text dimColor>{`◇ ${d.title}`}</Text>
905 {body}
906 {note}
907 </Box>
908 )
909 }
910
911 return page(
912 <Text dimColor wrap="truncate-start">{meta}</Text>,
913 diagramCount > 0 && format === null && (
914 <Text dimColor>
915 {'Diagrams show as source here. Press b for the browser, or install mermaid-ascii (or resvg, on kitty and Ghostty) to draw them inline.'}
916 </Text>
917 ),
918 blocks.map(block => {
919 if (block.kind === 'prose') return <Markdown text={block.text} />
920 if (block.kind === 'mermaid') return diagram(block)
921 if (block.lines === null) return <Markdown text={block.list} />
922 return (
923 <Box flexDirection="column">
924 {block.lines.map(line => (
925 <Text wrap="truncate-end">
926 {line.map(run => (
927 <Text {...runStyle(run)}>{run.text}</Text>
928 ))}
929 </Text>
930 ))}
931 </Box>
932 )
933 }),
934 )
935}
936
937/** The Text props a drawn table's run carries: only the styles it sets. */
938const runStyle = (run: Run) => ({
939 ...(run.bold ? { bold: true } : {}),
940 ...(run.italic ? { italic: true } : {}),
941 ...(run.dim ? { dimColor: true } : {}),
942 ...(run.code ? { color: CODE_COLOR } : {}),
943 ...(run.link ? { color: LINK_COLOR, underline: true } : {}),
944})
945
946// ── the module ──────────────────────────────────────────────────────────────
947
948export const register: Register = on => {
949 on('session.start', async ($, e, next) => {
950 const started = await next(e)
951 inBackground($, registerFallback($))
952 if (e.isInteractive) {
953 inBackground($, detectRenderers($))
954 // After a reload a file may still be shown; the poll stops on its first tick if not.
955 ensurePolling($)
956 }
957
958 return started
959 })
960
961 on('config.set', { key: 'theme' }, async ($, e, next) => {
962 const result = await next(e)
963 // The value as stored: `/config` may still read the old one right after.
964 if (result.deny === undefined) inBackground($, followTheme($, result.value))
965
966 return result
967 }).catch(($, e, next) => next(e))
968
969 // Answered here without `next`, so xorio's command file never reaches the model.
970 // A `/preview` this mod didn't register (the person's own, say) runs untouched.
971 on('command.run', { command: [COMMAND, FALLBACK_COMMAND] }, async ($, e, next) =>
972 e.command === FALLBACK_COMMAND && !(await ownsFallback($)) ? next(e) : runPreview($, e.args),
973 )
974
975 // Bookkeeping runs beside the tool's result, never in front of it.
976 on('tool.call', { tool: ['Write', 'Edit'] }, async ($, e, next) => {
977 const ran = await next(e)
978 if (ran.deny === undefined && ran.isError !== true && isPreviewable(e.file_path)) {
979 inBackground($, recordGenerated($, e.file_path))
980 }
981 return ran
982 }).catch(($, e, next) => next(e))
983
984 // A response row is always stored, so the diagrams are recorded before passing it on.
985 on('session.append', { door: 'response' }, async ($, e, next) => {
986 if (e.agentId === undefined && e.message.type === 'assistant') {
987 const texts = textBlocks(e.message.content).filter(text => text.includes('mermaid'))
988 const sources = texts.flatMap(text => mermaidSources(text, false))
989 if (sources.length > 0) await recordDiagrams($, sources)
990 }
991 return next(e)
992 }).catch(($, e, next) => next(e))
993
994 // The band above the prompt: what Claude just wrote, one key from a preview.
995 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
996 if (e.props.hasSurvey) return next(e)
997 const { docs, replies } = await freshItems($)
998 if (docs.length === 0 && replies.length === 0) return next(e)
999
1000 const { Box, Button, Text } = $.ui.resolve(e)
1001 const [cwd, home] = await Promise.all([$.session.cwd(), $.env.get('HOME')])
1002 const names = docs.slice(0, 2).map(d => displayPath(d.path, cwd, home))
1003 const more = docs.length > 2 ? [`+${docs.length - 2} more`] : []
1004 const drawn = replies.length > 0 ? [countOf(replies.length, 'diagram')] : []
1005 const summary = [...names, ...more, ...drawn].join(', ')
1006 const press = (act: (target: DocTarget) => Promise<void>) => async () => {
1007 const target = await newestFresh($)
1008 if (target !== null) await act(target)
1009 }
1010
1011 return (
1012 <Box flexDirection="row" columnGap={1}>
1013 <Text dimColor>Preview:</Text>
1014 <Box flexShrink={1}>
1015 <Text bold wrap="truncate-end">{summary}</Text>
1016 </Box>
1017 <Button key="preview" label="Open" hotkey="p" variant="primary" onPress={press(target => showTarget($, target))} />
1018 <Button
1019 key="browser"
1020 label="Browser"
1021 hotkey="b"
1022 onPress={press(async target => {
1023 await markSeen($)
1024 await openInBrowser($, target)
1025 })}
1026 />
1027 <Button key="dismiss" label="Dismiss" hotkey="x" role="dismiss" onPress={() => markSeen($)} />
1028 </Box>
1029 )
1030 })
1031
1032 // The pane: a doc (Markdown, tables and diagrams) or the file picker. Everything it
1033 // reads is read in one round trip: it redraws on every scroll step.
1034 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
1035 if (e.viewport !== undefined) screen = { columns: e.viewport.columns, rows: e.viewport.rows }
1036 paneColumns = e.props.bodyColumns
1037 const [v, cwd, home, docs, replies, asked, found, done, problem] = await Promise.all([
1038 read($, view),
1039 $.session.cwd(),
1040 $.env.get('HOME'),
1041 read($, generated),
1042 read($, diagrams),
1043 read($, sizing),
1044 read($, renderers),
1045 read($, renders),
1046 read($, notice),
1047 ])
1048 const ctx: PaneContext = {
1049 el: $.ui.resolve(e),
1050 surface: e.surface,
1051 columns: e.props.bodyColumns,
1052 offset: e.props.scroll.offset,
1053 cwd,
1054 home,
1055 recent: recentOptions(docs, replies, cwd, home),
1056 asked,
1057 found,
1058 done,
1059 problem,
1060 }
1061
1062 return v === null || v.kind === 'picker' ? renderPicker($, ctx, v?.dir || cwd) : renderDoc($, ctx, v)
1063 })
1064}
1065hooks/docs.ts 1019 lines1// Pure helpers: no `$`, so the tests exercise them directly.
2
3import type { Rasterizer, Renderers, Scheme } from '../types'
4import { render as peleRender } from './vendor/pele.js'
5
6export const PANE = 'doc-preview'
7/** `Svg` takes at most 131072 characters. */
8export const MAX_SVG = 131072
9
10const MARKDOWN_FILE = /\.(md|markdown|mdx)$/i
11const MERMAID_FILE = /\.(mmd|mermaid)$/i
12const FENCE_OPEN = /^ {0,3}(`{3,}|~{3,})\s*([^`\s]*)/
13const FENCE_CLOSE = /^ {0,3}(`{3,}|~{3,})\s*$/
14const ESCAPED_PIPE = /\\\|/g
15const LINE_BREAK = /<br\s*\/?>/i
16
17export const isMermaidFile = (path: string): boolean => MERMAID_FILE.test(path)
18export const isPreviewable = (path: string): boolean =>
19 MARKDOWN_FILE.test(path) || MERMAID_FILE.test(path)
20
21export type InlineFormat = 'ascii' | 'svg' | 'png'
22type Align = 'left' | 'center' | 'right'
23export type Table = { header: string[]; align: Align[]; rows: string[][] }
24/** A document in drawing order. A table keeps its Markdown (`source`) for surfaces that draw tables themselves. */
25type Block =
26 | { kind: 'prose'; text: string }
27 | { kind: 'table'; table: Table; source: string }
28 | { kind: 'mermaid'; source: string }
29
30export const errorText = (err: unknown): string => (err instanceof Error ? err.message : String(err))
31
32/** Windows (`\r\n`) and old Mac (`\r`) line endings as `\n`. */
33const toLf = (text: string): string => text.replace(/\r\n?/g, '\n')
34
35/** `1 diagram`, `2 diagrams`. */
36export const countOf = (n: number, noun: string): string => `${n} ${noun}${n === 1 ? '' : 's'}`
37
38/** `fresh` then `old`, each id once (its first, so newest, entry), at most `max`. */
39export function newestFirst<T>(fresh: readonly T[], old: readonly T[], idOf: (item: T) => string, max: number): T[] {
40 const byId = new Map<string, T>()
41 for (const item of [...fresh, ...old]) if (!byId.has(idOf(item))) byId.set(idOf(item), item)
42
43 return [...byId.values()].slice(0, max)
44}
45
46const closes = (line: string, marker: string): boolean => {
47 const fence = FENCE_CLOSE.exec(line)?.[1]
48 return fence !== undefined && fence[0] === marker[0] && fence.length >= marker.length
49}
50
51/**
52 * Splits a document into prose, GFM tables and ```mermaid blocks, in order,
53 * in one pass. Fenced code stays prose (tables and mermaid inside it too); an
54 * unclosed mermaid fence is shown as written.
55 */
56export function splitDoc(text: string, isMermaid: boolean): Block[] {
57 const lf = toLf(text)
58 if (isMermaid) return lf.trim() === '' ? [] : [{ kind: 'mermaid', source: lf.trim() }]
59 const lines = lf.split('\n')
60 const blocks: Block[] = []
61 let prose: string[] = []
62 const flush = () => {
63 if (prose.join('').trim() !== '') blocks.push({ kind: 'prose', text: prose.join('\n') })
64 prose = []
65 }
66 for (let i = 0; i < lines.length; i++) {
67 const line = lines[i] ?? ''
68 const open = FENCE_OPEN.exec(line)
69 if (open) {
70 const marker = open[1] ?? '```'
71 let end = i + 1
72 while (end < lines.length && !closes(lines[end] ?? '', marker)) end++
73 if (end < lines.length && (open[2] ?? '').toLowerCase() === 'mermaid') {
74 flush()
75 blocks.push({ kind: 'mermaid', source: lines.slice(i + 1, end).join('\n') })
76 } else {
77 prose.push(...lines.slice(i, end + 1))
78 }
79 i = end
80 continue
81 }
82 const table = tableAt(lines, i)
83 if (table === null) {
84 prose.push(line)
85 continue
86 }
87 flush()
88 blocks.push(table.block)
89 i = table.end - 1
90 }
91 flush()
92
93 return blocks
94}
95
96export const mermaidSources = (text: string, isMermaid: boolean): string[] =>
97 splitDoc(text, isMermaid).flatMap(b => (b.kind === 'mermaid' ? [b.source] : []))
98
99const TABLE_DELIMITER = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/
100
101const splitRow = (line: string): string[] => {
102 let row = line.trim()
103 if (row.startsWith('|')) row = row.slice(1)
104 if (row.endsWith('|') && !row.endsWith('\\|')) row = row.slice(0, -1)
105 return row.split(/(?<!\\)\|/).map(cell => cell.trim())
106}
107
108const alignOf = (cell: string): Align => {
109 const c = cell.trim()
110 if (c.startsWith(':') && c.endsWith(':')) return 'center'
111 return c.endsWith(':') ? 'right' : 'left'
112}
113
114/** The GFM table starting at `lines[i]` (a header row, then a delimiter row), and the line after it. */
115function tableAt(lines: string[], i: number): { block: Block; end: number } | null {
116 const line = lines[i] ?? ''
117 const delimiter = lines[i + 1] ?? ''
118 if (!line.includes('|') || !delimiter.includes('|') || !TABLE_DELIMITER.test(delimiter)) return null
119 const header = splitRow(line)
120 const align = splitRow(delimiter).map(alignOf)
121 if (align.length !== header.length) return null
122 let end = i + 2
123 while (end < lines.length && (lines[end] ?? '').includes('|') && (lines[end] ?? '').trim() !== '') end++
124 const rows = lines
125 .slice(i + 2, end)
126 .map(splitRow)
127 .map(row => header.map((_, c) => row[c] ?? ''))
128
129 return { block: { kind: 'table', table: { header, align, rows }, source: lines.slice(i, end).join('\n') }, end }
130}
131
132/** A table as nested list items: the first cell names the item, the rest are `header: cell`. */
133export function tableAsList(table: Table): string {
134 const unescape = (cell: string) => cell.replace(ESCAPED_PIPE, '|').replace(new RegExp(LINE_BREAK, 'gi'), ' ')
135 return table.rows
136 .flatMap(row => {
137 const [first = '', ...rest] = row
138 const fields = rest.flatMap((cell, c) => {
139 const name = table.header[c + 1] ?? ''
140 return cell === '' ? [] : [` - ${name === '' ? '' : `${unescape(name)}: `}${unescape(cell)}`]
141 })
142 return [`- **${unescape(first) || '—'}**`, ...fields]
143 })
144 .join('\n')
145}
146
147/** A styled stretch of text in a drawn table: a cell's inline Markdown, or a border. */
148export type Run = { text: string; code?: true; bold?: true; italic?: true; link?: true; dim?: true }
149export type TableLine = Run[]
150
151const INLINE =
152 /`([^`]+)`|\*\*(.+?)\*\*|__(.+?)__|(?<![\w*])\*(?!\s)(.+?)\*(?!\w)|(?<![\w_])_(?!\s)(.+?)_(?!\w)|!?\[([^\]]*)\]\([^)]*\)/g
153
154/** A cell's inline Markdown as runs: code, bold, italic and link text, the rest plain. */
155export function inlineRuns(text: string, base: Omit<Run, 'text'> = {}): Run[] {
156 const runs: Run[] = []
157 let at = 0
158 for (const m of text.matchAll(INLINE)) {
159 if (m.index > at) runs.push({ ...base, text: text.slice(at, m.index) })
160 const [, code, bold1, bold2, italic1, italic2, link] = m
161 if (code !== undefined) runs.push({ ...base, text: code, code: true })
162 else if (bold1 !== undefined || bold2 !== undefined) runs.push({ ...base, text: bold1 ?? bold2 ?? '', bold: true })
163 else if (italic1 !== undefined || italic2 !== undefined) runs.push({ ...base, text: italic1 ?? italic2 ?? '', italic: true })
164 else runs.push({ ...base, text: link ?? '', link: true })
165 at = m.index + m[0].length
166 }
167 if (at < text.length) runs.push({ ...base, text: text.slice(at) })
168
169 return runs.filter(run => run.text !== '')
170}
171
172const widthOf = (text: string): number => [...text].length
173const runsWidth = (runs: readonly Run[]): number => runs.reduce((sum, run) => sum + widthOf(run.text), 0)
174const sameStyle = (a: Run, b: Run) =>
175 a.code === b.code && a.bold === b.bold && a.italic === b.italic && a.link === b.link && a.dim === b.dim
176
177/** A cell's lines (`<br>` breaks, `\|` unescaped), each as runs. */
178const cellLines = (cell: string, base: Omit<Run, 'text'>): Run[][] =>
179 cell
180 .replace(ESCAPED_PIPE, '|')
181 .split(LINE_BREAK)
182 .map(line => inlineRuns(line.trim(), base))
183
184/** Word-wraps runs to `width`, breaking a word only when it is wider than a line. */
185export function wrapRuns(runs: readonly Run[], width: number): Run[][] {
186 const lines: Run[][] = [[]]
187 let used = 0
188 const newLine = () => {
189 lines.push([])
190 used = 0
191 }
192 const put = (run: Run) => {
193 const line = lines[lines.length - 1] ?? []
194 const last = line[line.length - 1]
195 if (last !== undefined && sameStyle(last, run)) last.text += run.text
196 else line.push({ ...run })
197 used += widthOf(run.text)
198 }
199 for (const run of runs) {
200 for (const token of run.text.split(/(\s+)/)) {
201 if (token === '') continue
202 if (/^\s+$/.test(token)) {
203 if (used > 0 && used < width) put({ ...run, text: ' ' })
204 continue
205 }
206 let chars = [...token]
207 while (chars.length > 0) {
208 if (chars.length <= width - used) {
209 put({ ...run, text: chars.join('') })
210 break
211 }
212 if (used > 0) {
213 newLine()
214 continue
215 }
216 put({ ...run, text: chars.slice(0, width).join('') })
217 chars = chars.slice(width)
218 if (chars.length > 0) newLine()
219 }
220 }
221 }
222 for (const line of lines) {
223 const last = line[line.length - 1]
224 if (last !== undefined) last.text = last.text.trimEnd()
225 }
226
227 return lines.map(line => line.filter(run => run.text !== ''))
228}
229
230/**
231 * Column widths that fit `available` cells: columns at their natural width
232 * when they all fit, else the widest ones capped at one level (they wrap) so
233 * the narrow ones keep theirs. Null when even the minimums don't fit.
234 */
235export function layoutColumns(natural: number[], minimum: number[], available: number): number[] | null {
236 const sum = (widths: number[]) => widths.reduce((total, w) => total + w, 0)
237 if (sum(natural) <= available) return natural
238 if (sum(minimum) > available) return null
239 const capped = (level: number) => natural.map((w, c) => Math.max(minimum[c] ?? 1, Math.min(w, level)))
240 let level = 1
241 while (sum(capped(level + 1)) <= available) level++
242 const widths = capped(level)
243 // Hand the cells left over to the capped columns, one each, left to right.
244 for (let c = 0; c < widths.length && sum(widths) < available; c++) {
245 if ((natural[c] ?? 0) > (widths[c] ?? 0)) widths[c] = (widths[c] ?? 0) + 1
246 }
247
248 return widths
249}
250
251const pad = (runs: Run[], width: number, align: Align): Run[] => {
252 const room = Math.max(0, width - runsWidth(runs))
253 const left = align === 'right' ? room : align === 'center' ? Math.floor(room / 2) : 0
254 const space = (n: number): Run[] => (n > 0 ? [{ text: ' '.repeat(n) }] : [])
255
256 return [...space(left), ...runs, ...space(room - left)]
257}
258
259/** The narrowest a column may wrap to: its longest word (up to a cap), or less when that won't fit. */
260const MIN_COLUMN = 6
261const WORD_CAP = 24
262
263/**
264 * A table drawn as boxed text lines that fit `columns` cells: cells wrap
265 * inside their column, `<br>` breaks a line, the header is bold, and a rule
266 * separates the rows once any of them wraps. Null when it cannot fit.
267 */
268export function tableLines(table: Table, columns: number): TableLine[] | null {
269 const count = table.header.length
270 const cells = [table.header, ...table.rows].map((row, r) =>
271 row.map(cell => cellLines(cell, r === 0 ? { bold: true } : {})),
272 )
273 const natural = table.header.map((_, c) =>
274 Math.max(1, ...cells.map(row => Math.max(0, ...(row[c] ?? []).map(runsWidth)))),
275 )
276 const longestWord = table.header.map((_, c) =>
277 Math.max(
278 1,
279 ...cells.flatMap(row => (row[c] ?? []).flatMap(line => line.flatMap(run => run.text.split(/\s+/).map(widthOf)))),
280 ),
281 )
282 const available = columns - (3 * count + 1)
283 const widths =
284 layoutColumns(natural, natural.map((w, c) => Math.min(w, Math.max(MIN_COLUMN, Math.min(longestWord[c] ?? 1, WORD_CAP)))), available) ??
285 layoutColumns(natural, natural.map(w => Math.min(w, MIN_COLUMN)), available)
286 if (widths === null) return null
287
288 const border = (left: string, joint: string, right: string): TableLine => [
289 { text: `${left}${widths.map(w => '─'.repeat(w + 2)).join(joint)}${right}`, dim: true },
290 ]
291 const bar: Run = { text: '│', dim: true }
292 const drawRow = (row: Run[][][]): TableLine[] => {
293 const wrapped = row.map((lines, c) => lines.flatMap(line => wrapRuns(line, widths[c] ?? 1)))
294 const height = Math.max(1, ...wrapped.map(lines => lines.length))
295 return Array.from({ length: height }, (_, l) => [
296 bar,
297 ...wrapped.flatMap((lines, c) => [
298 { text: ' ' },
299 ...pad(lines[l] ?? [], widths[c] ?? 1, table.align[c] ?? 'left'),
300 { text: ' ' },
301 bar,
302 ]),
303 ])
304 }
305 const [header = [], ...body] = cells
306 const drawnBody = body.map(drawRow)
307 const hasWrapped = drawnBody.some(lines => lines.length > 1)
308
309 return [
310 border('┌', '┬', '┐'),
311 ...drawRow(header),
312 border('├', '┼', '┤'),
313 ...drawnBody.flatMap((lines, r) => (hasWrapped && r > 0 ? [border('├', '┼', '┤'), ...lines] : lines)),
314 border('└', '┴', '┘'),
315 ]
316}
317
318/** Resolves what the person typed: quotes, `file://`, `~`, relative to `cwd`, `.` and `..`. */
319export function expandPath(input: string, cwd: string, home: string | undefined): string {
320 let path = input.trim().replace(/^(['"])(.*)\1$/, '$2')
321 if (path.startsWith('file://')) path = decodeURIComponent(path.slice('file://'.length))
322 if (home !== undefined && (path === '~' || path.startsWith('~/'))) path = home + path.slice(1)
323 if (/^[A-Za-z]:[\\/]/.test(path)) return path
324
325 return normalize(path.startsWith('/') ? path : `${cwd}/${path}`)
326}
327
328function normalize(path: string): string {
329 const isAbsolute = path.startsWith('/')
330 const parts: string[] = []
331 for (const part of path.split('/')) {
332 if (part === '' || part === '.') continue
333 if (part !== '..') parts.push(part)
334 else if (parts.length > 0 && parts[parts.length - 1] !== '..') parts.pop()
335 else if (!isAbsolute) parts.push('..')
336 }
337
338 return (isAbsolute ? '/' : '') + parts.join('/')
339}
340
341export const parentDir = (path: string): string => normalize(`${path}/..`)
342export const baseName = (path: string): string => path.split('/').pop() || path
343
344/** Short form for display: relative under `cwd`, `~/` under `home`, else as is. */
345export function displayPath(path: string, cwd: string, home: string | undefined): string {
346 if (path === cwd) return '.'
347 if (path.startsWith(`${cwd}/`)) return path.slice(cwd.length + 1)
348 if (home !== undefined && path.startsWith(`${home}/`)) return `~${path.slice(home.length)}`
349
350 return path
351}
352
353export function formatSize(bytes: number): string {
354 if (bytes < 1024) return `${bytes} B`
355 if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
356
357 return `${(bytes / 1024 / 1024).toFixed(1)} MB`
358}
359
360/** A short, stable hash (cyrb53) for cache keys and file names. */
361export function hashText(text: string): string {
362 let h1 = 0xdeadbeef
363 let h2 = 0x41c6ce57
364 for (let i = 0; i < text.length; i++) {
365 const c = text.charCodeAt(i)
366 h1 = Math.imul(h1 ^ c, 2654435761)
367 h2 = Math.imul(h2 ^ c, 1597334677)
368 }
369 h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909)
370 h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909)
371
372 return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36)
373}
374
375/** A diagram's frontmatter title, its kind, and its lines trimmed, with blanks and `%%` comments dropped. */
376function diagramParts(raw: string): { title: string | undefined; kind: string; lines: string[] } {
377 const source = toLf(raw)
378 const frontmatter = /^\s*---\n([\s\S]*?)\n---\s*\n/.exec(source)
379 const title = /^\s*title:\s*(.+)$/m.exec(frontmatter?.[1] ?? '')?.[1]?.trim()
380 const body = frontmatter ? source.slice(frontmatter[0].length) : source
381 const lines = body
382 .split('\n')
383 .map(line => line.trim())
384 .filter(line => line !== '' && !line.startsWith('%%'))
385
386 return { title, kind: lines[0]?.split(/\s+/)[0] ?? 'diagram', lines }
387}
388
389/** The diagram type: the first word of its first line (`flowchart`, `pie`, `stateDiagram-v2`). */
390export const diagramKind = (source: string): string => diagramParts(source).kind
391
392/** `flowchart`, `sequenceDiagram: Login`, ...: the diagram type plus its title, if any. */
393export function diagramTitle(source: string): string {
394 const { title, kind } = diagramParts(source)
395 const label = title ? `${kind}: ${title}` : kind
396
397 return label.length > 48 ? `${label.slice(0, 47)}…` : label
398}
399
400/** Text padded, or cut with an ellipsis, to exactly `width` cells. */
401const fit = (text: string, width: number): string => {
402 const chars = [...text]
403 return chars.length > width
404 ? `${chars.slice(0, Math.max(0, width - 1)).join('')}…`
405 : text + ' '.repeat(width - chars.length)
406}
407
408/**
409 * How the terminal draws the kinds mermaid-ascii can't take as written
410 * (it draws flowcharts, sequence and ER diagrams): as plain text here, which
411 * needs no renderer, or rewritten as a flowchart first. Every other kind goes
412 * to mermaid-ascii as is.
413 */
414const TEXT_CHARTS: Record<string, (source: string, width: number) => string | null> = {
415 pie: pieChart,
416 gantt: ganttChart,
417}
418const AS_FLOWCHART: Record<string, (source: string) => string | null> = {
419 stateDiagram: stateToFlowchart,
420 'stateDiagram-v2': stateToFlowchart,
421 classDiagram: classToFlowchart,
422 'classDiagram-v2': classToFlowchart,
423}
424
425/** Whether the kind is drawn as text here (pie, gantt), never by mermaid-ascii. */
426export const isTextChart = (source: string): boolean => diagramKind(source) in TEXT_CHARTS
427
428/** A pie or gantt chart as text; null for other kinds and for syntax the parsers don't follow. */
429export const textChart = (source: string, width: number): string | null =>
430 TEXT_CHARTS[diagramKind(source)]?.(source, width) ?? null
431
432/** What mermaid-ascii is given: the source, or a state or class diagram rewritten as a flowchart. */
433export const asciiSource = (source: string): string => AS_FLOWCHART[diagramKind(source)]?.(source) ?? source
434
435/** A pie chart as labelled bars scaled to the largest slice, each with its value and share. */
436export function pieChart(source: string, width: number): string | null {
437 const parts = diagramParts(source)
438 let title = parts.title
439 const slices: { label: string; value: number }[] = []
440 for (const line of parts.lines) {
441 const head = /^pie\b(?:\s+showData)?(?:\s+title\s+(.+))?$/.exec(line)
442 const named = /^title\s+(.+)$/.exec(line)
443 const slice = /^"([^"]*)"\s*:\s*(\d*\.?\d+)$/.exec(line)
444 if (head) title = head[1]?.trim() ?? title
445 else if (named) title = named[1]?.trim() ?? title
446 else if (slice) slices.push({ label: slice[1] ?? '', value: Number(slice[2]) })
447 else if (line !== 'showData') return null
448 }
449 const total = slices.reduce((sum, s) => sum + s.value, 0)
450 const largest = Math.max(0, ...slices.map(s => s.value))
451 if (slices.length === 0 || largest <= 0) return null
452
453 const labelWidth = Math.min(Math.max(...slices.map(s => widthOf(s.label))), Math.max(8, Math.floor(width / 3)))
454 const values = slices.map(s => String(s.value))
455 const valueWidth = Math.max(...values.map(v => v.length))
456 // label, 2 spaces, bar, 1 space, value, 2 spaces, a share like "100.0%"
457 const barWidth = Math.max(4, width - labelWidth - valueWidth - 11)
458 const rows = slices.map((s, i) => {
459 const length = Math.max(s.value > 0 ? 1 : 0, Math.round((s.value / largest) * barWidth))
460 const share = `${((s.value / total) * 100).toFixed(1)}%`
461 return `${fit(s.label, labelWidth)} ${'█'.repeat(length).padEnd(barWidth)} ${(values[i] ?? '').padStart(valueWidth)} ${share.padStart(6)}`
462 })
463
464 return [...(title ? [title, ''] : []), ...rows].join('\n')
465}
466
467const DAY_MS = 86_400_000
468const GANTT_TAGS = new Set(['done', 'active', 'crit', 'milestone'])
469const GANTT_SETTINGS =
470 /^(title|dateFormat|axisFormat|tickInterval|excludes|includes|todayMarker|weekday|inclusiveEndDates|topAxis)\b\s*(.*)$/
471
472const parseDay = (text: string): number | null => {
473 const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text.trim())
474 return m ? Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3])) / DAY_MS : null
475}
476const formatDay = (day: number): string => new Date(day * DAY_MS).toISOString().slice(0, 10)
477const parseLength = (text: string): number | null => {
478 const m = /^(\d*\.?\d+)\s*([dwh])$/.exec(text.trim())
479 if (!m) return null
480 const n = Number(m[1])
481 return m[2] === 'w' ? n * 7 : m[2] === 'h' ? n / 24 : n
482}
483const startOf = (text: string, ends: Map<string, number>): number | null => {
484 const after = /^after\s+(.+)$/.exec(text)
485 if (!after) return parseDay(text)
486 const days = (after[1] ?? '').split(/\s+/).map(id => ends.get(id))
487 return days.every(day => day !== undefined) ? Math.max(...(days as number[])) : null
488}
489
490/**
491 * A gantt chart as a day-scale timeline: tasks under their sections, a bar
492 * each (`▒` done, `◆` milestone). Dates must be `YYYY-MM-DD`; a task's
493 * `:[tags,][id,][start,]end` follows Mermaid's forms (start a date or
494 * `after id`, end a date or a length in d, w or h).
495 */
496export function ganttChart(source: string, width: number): string | null {
497 const parts = diagramParts(source)
498 let title = parts.title
499 let section: string | undefined
500 const tasks: { section: string | undefined; name: string; start: number; end: number; tags: Set<string> }[] = []
501 const ends = new Map<string, number>()
502 for (const line of parts.lines.slice(1)) {
503 const setting = GANTT_SETTINGS.exec(line)
504 if (setting) {
505 if (setting[1] === 'title') title = setting[2]?.trim() || title
506 if (setting[1] === 'dateFormat' && setting[2]?.trim() !== 'YYYY-MM-DD') return null
507 continue
508 }
509 const header = /^section\s+(.+)$/.exec(line)
510 if (header) {
511 section = header[1]?.trim()
512 continue
513 }
514 const task = /^(.+?)\s*:\s*(.+)$/.exec(line)
515 if (!task) return null
516 const items = (task[2] ?? '').split(',').map(item => item.trim()).filter(item => item !== '')
517 const tags = new Set<string>()
518 while (items.length > 0 && GANTT_TAGS.has(items[0] ?? '')) tags.add(items.shift() ?? '')
519 if (items.length === 0 || items.length > 3) return null
520 const [id, startText, endText] =
521 items.length === 3 ? items : items.length === 2 ? [undefined, ...items] : [undefined, undefined, ...items]
522 const start = startText === undefined ? tasks[tasks.length - 1]?.end : startOf(startText, ends)
523 if (start === undefined || start === null || endText === undefined) return null
524 const length = parseLength(endText)
525 const end = parseDay(endText) ?? (length === null ? null : start + length)
526 if (end === null || end < start) return null
527 tasks.push({ section, name: task[1]?.trim() ?? '', start, end, tags })
528 if (id !== undefined) ends.set(id, end)
529 }
530 if (tasks.length === 0) return null
531
532 const first = Math.min(...tasks.map(t => t.start))
533 const last = Math.max(...tasks.map(t => t.end))
534 const nameWidth = Math.min(Math.max(...tasks.map(t => widthOf(t.name))) + 2, Math.max(10, Math.floor(width / 3)))
535 const chartWidth = Math.max(10, width - nameWidth - 1)
536 const scale = chartWidth / Math.max(1, last - first)
537 const [from, to] = [formatDay(first), formatDay(last)]
538 const axis = ' '.repeat(nameWidth + 1) + (chartWidth >= from.length + to.length + 1 ? from + to.padStart(chartWidth - from.length) : from)
539 const out = [...(title ? [title, ''] : []), axis]
540 let shown: string | undefined | null = null
541 for (const t of tasks) {
542 if (t.section !== shown) {
543 if (t.section !== undefined) out.push(t.section)
544 shown = t.section
545 }
546 const left = Math.min(chartWidth - 1, Math.floor((t.start - first) * scale))
547 const right = Math.max(left + 1, Math.min(chartWidth, Math.round((t.end - first) * scale)))
548 const bar = t.tags.has('milestone') || t.end === t.start ? '◆' : (t.tags.has('done') ? '▒' : '█').repeat(right - left)
549 out.push(`${fit(` ${t.name}`, nameWidth)} ${' '.repeat(left)}${bar}`)
550 }
551
552 return out.join('\n')
553}
554
555/** Text safe inside a flowchart node or edge label: no brackets, braces, pipes or quotes. */
556const flowText = (text: string): string =>
557 text
558 .replace(/[[\]{}()|"<>]/g, ' ')
559 .replace(/\s+/g, ' ')
560 .trim()
561const flowId = (name: string): string => name.replace(/~[^~]*~/g, '').replace(/\W/g, '_')
562/** A `direction` line's flowchart direction (mermaid-ascii draws LR and TD), or null for another line. */
563const flowDirection = (line: string): 'LR' | 'TD' | null => {
564 const turn = /^direction\s+(LR|RL|TB|TD|BT)$/.exec(line)?.[1]
565 if (turn === undefined) return null
566 return turn === 'LR' || turn === 'RL' ? 'LR' : 'TD'
567}
568const flowEdge = (from: string, to: string, label: string): string =>
569 label === '' ? ` ${from} --> ${to}` : ` ${from} -->|${label}| ${to}`
570const flowchart = (direction: string, labels: Map<string, string>, edges: string[]): string =>
571 [`flowchart ${direction}`, ...[...labels].map(([id, label]) => ` ${id}[${flowText(label) || id}]`), ...edges].join('\n')
572
573/**
574 * A state diagram as a flowchart: states become boxes (`[*]` a start or end
575 * box), transitions become edges with their labels. Null for composite
576 * states, forks, choices and concurrency, which a flat flowchart can't hold.
577 */
578export function stateToFlowchart(source: string): string | null {
579 const labels = new Map<string, string>()
580 const edges: string[] = []
581 let direction = 'LR'
582 let inNote = false
583 const state = (name: string, side: 'from' | 'to'): string => {
584 if (name === '[*]') {
585 const id = side === 'from' ? 'START' : 'END'
586 labels.set(id, side === 'from' ? 'start' : 'end')
587 return id
588 }
589 const id = flowId(name)
590 if (!labels.has(id)) labels.set(id, name)
591 return id
592 }
593 for (const line of diagramParts(source).lines.slice(1)) {
594 if (inNote) {
595 if (/^end note$/i.test(line)) inNote = false
596 continue
597 }
598 if (/^note\b/i.test(line)) {
599 inNote = !line.includes(':')
600 continue
601 }
602 const turn = flowDirection(line)
603 if (turn !== null) {
604 direction = turn
605 continue
606 }
607 if (/[{}]|<<|^--$/.test(line)) return null
608 const named = /^state\s+"([^"]+)"\s+as\s+([\w.-]+)$/.exec(line)
609 const edge = /^(\[\*\]|[\w.-]+)\s*-->\s*(\[\*\]|[\w.-]+)\s*(?::\s*(.+))?$/.exec(line)
610 const described = /^([\w.-]+)\s*:\s*(.+)$/.exec(line)
611 if (named) labels.set(flowId(named[2] ?? ''), named[1] ?? '')
612 else if (edge) edges.push(flowEdge(state(edge[1] ?? '', 'from'), state(edge[2] ?? '', 'to'), flowText(edge[3] ?? '')))
613 else if (described) labels.set(flowId(described[1] ?? ''), described[2] ?? '')
614 else if (/^[\w.-]+$/.test(line)) state(line, 'from')
615 else return null
616 }
617
618 return edges.length === 0 ? null : flowchart(direction, labels, edges)
619}
620
621/** Class relationship arrows: whether the edge points from right to left, and its label when the line has none. */
622const RELATIONS: Record<string, { isReversed: boolean; label: string }> = {
623 '<|--': { isReversed: true, label: 'extends' },
624 '--|>': { isReversed: false, label: 'extends' },
625 '<|..': { isReversed: true, label: 'implements' },
626 '..|>': { isReversed: false, label: 'implements' },
627 '*--': { isReversed: false, label: 'has' },
628 '--*': { isReversed: true, label: 'has' },
629 'o--': { isReversed: false, label: 'has' },
630 '--o': { isReversed: true, label: 'has' },
631 '<--': { isReversed: true, label: '' },
632 '-->': { isReversed: false, label: '' },
633 '<..': { isReversed: true, label: '' },
634 '..>': { isReversed: false, label: '' },
635 '--': { isReversed: false, label: '' },
636 '..': { isReversed: false, label: '' },
637}
638const RELATION =
639 /^([\w~]+)\s*(?:"[^"]*"\s*)?(<\|--|--\|>|<\|\.\.|\.\.\|>|\*--|--\*|o--|--o|<--|-->|<\.\.|\.\.>|--|\.\.)\s*(?:"[^"]*"\s*)?([\w~]+)\s*(?::\s*(.+))?$/
640const CLASS_IGNORED = /^(note|cssClass|style|classDef|click|link|callback|<<|namespace\b|}$)/
641
642/**
643 * A class diagram as a flowchart: classes become boxes and relationships
644 * edges (inheritance as `extends`, composition and aggregation as `has`
645 * unless labelled). Members are dropped: a flowchart box holds one line.
646 */
647export function classToFlowchart(source: string): string | null {
648 const labels = new Map<string, string>()
649 const edges: string[] = []
650 let direction = 'LR'
651 let inBody = false
652 const klass = (name: string): string => {
653 const id = flowId(name)
654 if (!labels.has(id)) labels.set(id, name.replace(/~[^~]*~/g, ''))
655 return id
656 }
657 for (const line of diagramParts(source).lines.slice(1)) {
658 if (inBody) {
659 if (line.startsWith('}')) inBody = false
660 continue
661 }
662 const turn = flowDirection(line)
663 const declared = /^class\s+([\w~]+)(?:\s*\[[^\]]*\])?\s*(\{)?\s*$/.exec(line)
664 const relation = RELATION.exec(line)
665 const member = /^([\w~]+)\s*:\s*.+$/.exec(line)
666 if (turn !== null) direction = turn
667 else if (declared) {
668 klass(declared[1] ?? '')
669 inBody = declared[2] !== undefined
670 } else if (relation) {
671 const [left, right] = [klass(relation[1] ?? ''), klass(relation[3] ?? '')]
672 const kind = RELATIONS[relation[2] ?? ''] ?? { isReversed: false, label: '' }
673 const [from, to] = kind.isReversed ? [right, left] : [left, right]
674 edges.push(flowEdge(from, to, flowText(relation[4] ?? '') || kind.label))
675 } else if (member) klass(member[1] ?? '')
676 else if (!CLASS_IGNORED.test(line)) return null
677 }
678
679 return labels.size === 0 ? null : flowchart(direction, labels, edges)
680}
681
682/** Drops ANSI escapes and every control character but tab and newline. */
683export const stripAnsi = (text: string): string =>
684 text
685 .replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '')
686 .replace(/\x1b\][^\x07\x1b]*(\x07|\x1b\\)/g, '')
687 .replace(/[\x00-\x08\x0b-\x1f\x7f]/g, '')
688
689/** A tool's output as its first non-blank line, ANSI stripped. */
690export const firstLine = (text: string): string =>
691 stripAnsi(text).split('\n').map(line => line.trim()).find(line => line !== '') ?? ''
692
693/**
694 * A renderer's failure as one readable line: a logrus `msg="…"` unwrapped,
695 * and mermaid-ascii's "unsupported graph type" said as which kind it can't draw.
696 */
697export function rendererError(output: string, kind: string): string {
698 const line = firstLine(output)
699 const message = /msg="((?:[^"\\]|\\.)*)"/.exec(line)?.[1]?.replace(/\\"/g, '"') ?? line
700
701 return /unsupported graph type/i.test(message) ? `mermaid-ascii can't draw ${kind} diagrams` : message
702}
703
704/** Width and height from a base64 PNG's IHDR chunk; null when it is no PNG. */
705export function pngSize(base64: string): { width: number; height: number } | null {
706 let bytes: number[]
707 try {
708 bytes = [...atob(base64.slice(0, 32))].map(c => c.charCodeAt(0))
709 } catch {
710 return null
711 }
712 const at = (i: number) => bytes[i] ?? 0
713 const isPng = at(0) === 137 && at(1) === 80 && at(2) === 78 && at(3) === 71
714 if (!isPng || bytes.length < 24) return null
715 const u32 = (i: number) => ((at(i) << 24) | (at(i + 1) << 16) | (at(i + 2) << 8) | at(i + 3)) >>> 0
716
717 return { width: u32(16), height: u32(20) }
718}
719
720/** Terminal cells for a picture: about 16 px a column at the renderers' 2x scale, cells twice as tall as wide. */
721export function imageBox(
722 size: { width: number; height: number },
723 maxColumns: number,
724): { columns: number; rows: number } {
725 const columns = Math.max(8, Math.min(maxColumns, 255, Math.round(size.width / 16)))
726 const rows = Math.round((columns * size.height) / Math.max(1, size.width) / 2)
727
728 return { columns, rows: Math.max(2, Math.min(255, rows)) }
729}
730
731/**
732 * Folders tools are installed to that an app started from the desktop, such as
733 * VS Code, may leave off its PATH: Go's and Cargo's bins, pipx and npm prefixes, Homebrew.
734 */
735export function toolDirs(home: string | undefined, gopath: string | undefined): string[] {
736 const goBin = gopath ? [`${gopath.split(':')[0]}/bin`] : []
737 const own = home ? [`${home}/go/bin`, `${home}/.cargo/bin`, `${home}/.local/bin`, `${home}/.npm-global/bin`] : []
738
739 return [...new Set([...goBin, ...own, '/opt/homebrew/bin', '/home/linuxbrew/.linuxbrew/bin', '/usr/local/bin'])]
740}
741
742/** The variables a terminal is told apart by; any of them may be unset. */
743export type TerminalEnv = Partial<Record<'term' | 'program' | 'kittyWindow' | 'ghostty' | 'forced', string>>
744
745/**
746 * Whether the terminal draws kitty's placeholder images: kitty or Ghostty.
747 * `TERM` and `TERM_PROGRAM` are set by the terminal Claude Code runs in, while
748 * `KITTY_WINDOW_ID` and `GHOSTTY_RESOURCES_DIR` leak into terminals started
749 * from one (VS Code opened from Ghostty), so they count only when no other
750 * terminal names itself. `DOC_PREVIEW_IMAGES` (`1` or `0`) overrides.
751 */
752export function drawsImagesIn({ term, program, kittyWindow, ghostty, forced }: TerminalEnv): boolean {
753 if (forced === '1' || forced === '0') return forced === '1'
754 const isKittyOrGhostty = (name: string | undefined) => /kitty|ghostty/i.test(name ?? '')
755 if (isKittyOrGhostty(term) || isKittyOrGhostty(program)) return true
756
757 return !program && (kittyWindow !== undefined || ghostty !== undefined)
758}
759
760/**
761 * Which inline format a surface gets, or null to show the diagram's source.
762 * The desktop and mobile apps always get SVG: pele draws it inside the mod.
763 * VS Code declares Svg but its panel draws only the alt text (2.1.304), so it
764 * gets text like a terminal. The terminal gets a PNG where it draws pixels and
765 * something can rasterize.
766 */
767export function formatFor(surface: string, renderers: Renderers | null): InlineFormat | null {
768 if (surface !== 'terminal' && surface !== 'vscode') return 'svg'
769 if (renderers === null) return null
770 if (surface === 'terminal' && renderers.drawsImages && (renderers.rasterizer !== null || renderers.mmdc)) return 'png'
771
772 return renderers.ascii ? 'ascii' : null
773}
774
775/** The pele build vendored in `vendor/pele.js`; cached drawings are named with it. */
776export const PELE_VERSION = '1.6.0'
777
778/** Pele's `--pele-*` colors, by the name after the prefix. */
779type Palette = Record<'bg' | 'fg' | 'muted' | 'line' | 'surface' | 'surface-alt' | 'border' | 'accent', string>
780
781/** Pele's palette per scheme: light is its own defaults, dark the browser page's (GitHub dark). */
782export const PELE_THEMES: Record<Scheme, Palette> = {
783 light: {
784 bg: '#ffffff',
785 fg: '#1f1f1f',
786 muted: '#6e6e6e',
787 line: '#1f1f1f',
788 surface: '#f3f3f3',
789 'surface-alt': '#e6e6e6',
790 border: '#8a8a8a',
791 accent: '#5b7bd5',
792 },
793 dark: {
794 bg: '#0d1117',
795 fg: '#e6edf3',
796 muted: '#9198a1',
797 line: '#d1d9e0',
798 surface: '#151b23',
799 'surface-alt': '#212830',
800 border: '#3d444d',
801 accent: '#4493f8',
802 },
803}
804
805/** The dark palette as `--pele-*` declarations, set under `prefers-color-scheme: dark`. */
806const PELE_DARK_VARS = Object.entries(PELE_THEMES.dark)
807 .map(([key, value]) => `--pele-${key}:${value}`)
808 .join(';')
809
810/**
811 * Light or dark, from Claude Code's `theme` setting (`dark`, `light-ansi`,
812 * `dark-daltonized`, …). `auto` and custom themes follow the terminal's
813 * `COLORFGBG` (`fg;bg`, a background of 7 or 15 is light), else dark.
814 */
815export function schemeFor(theme: unknown, colorfgbg: string | undefined): Scheme {
816 if (typeof theme === 'string') {
817 if (theme.startsWith('light')) return 'light'
818 if (theme.startsWith('dark')) return 'dark'
819 }
820 const bg = Number(colorfgbg?.split(';').pop())
821
822 return bg === 7 || bg === 15 ? 'light' : 'dark'
823}
824
825/**
826 * Pele's SVG with its CSS variables resolved: it themes through
827 * `--_x: var(--pele-x, fallback)` on the root and `var(--_x)` below, which
828 * resvg and librsvg don't follow and an image's host page can't set anyway.
829 * Only tags are rewritten: a label's text (pele escapes `<` and `>` in it)
830 * is drawn as written, even when it reads like a variable.
831 */
832export function flattenPeleSvg(svg: string, theme: Partial<Record<string, string>> = PELE_THEMES.light): string {
833 const inTags = (text: string, edit: (tag: string) => string) => text.replace(/<[^>]*>/g, edit)
834 const local = new Map<string, string>()
835 const declared = inTags(svg, tag =>
836 tag.replace(/--(_[\w-]+):var\(--pele-([\w-]+),([^)]*)\);?/g, (_, name: string, key: string, fallback: string) => {
837 local.set(name, theme[key] ?? fallback)
838 return ''
839 }),
840 )
841
842 return inTags(declared, tag =>
843 tag
844 .replace(/var\(--(_[\w-]+)\)/g, (whole, name: string) => local.get(name) ?? whole)
845 .replace(/var\(--pele-[\w-]+,([^)]*)\)/g, '$1'),
846 )
847}
848
849/**
850 * Named families before the generic one: resvg maps `sans-serif` to Arial and
851 * draws no text where Arial is missing (most Linux), so it takes the first
852 * family here that is installed.
853 */
854const PELE_FONTS = "Helvetica, Arial, 'Segoe UI', 'DejaVu Sans', 'Liberation Sans', 'Noto Sans', sans-serif"
855
856const drawPele = (source: string, fontFamily?: string): string =>
857 peleRender(source, { fontFamily, links: false, images: false })
858 // The initial values, which resvg warns it can't parse.
859 .svg.replace(/(letter|word)-spacing:normal;?/g, '')
860
861/** Markup put first inside the root `<svg>`. */
862const prependToSvg = (svg: string, markup: string): string => svg.replace(/^(<svg\b[^>]*>)/, `$1${markup}`)
863
864/** A ground painted first, so it sits under the drawing. */
865const withGround = (svg: string, fill: string): string =>
866 prependToSvg(svg, `<rect width="100%" height="100%" fill="${fill}"/>`)
867
868/**
869 * A Mermaid diagram as a standalone SVG by pele in one scheme's colors, its
870 * variables resolved, for a rasterizer; throws on syntax pele can't read.
871 */
872export function peleSvg(source: string, scheme: Scheme): string {
873 return withGround(flattenPeleSvg(drawPele(source, PELE_FONTS), PELE_THEMES[scheme]), PELE_THEMES[scheme].bg)
874}
875
876/**
877 * The same, for a surface that shows SVG (the desktop and mobile apps): light colors,
878 * turned dark by a `prefers-color-scheme` rule, so the image follows the
879 * app's own theme as it changes; throws on syntax pele can't read.
880 */
881export function peleSvgAdaptive(source: string): string {
882 const style = `<style>@media (prefers-color-scheme: dark){svg{${PELE_DARK_VARS}}}</style>`
883
884 return prependToSvg(withGround(drawPele(source), 'var(--_bg)'), style)
885}
886
887/** The command that turns an SVG file into a PNG at twice its size, by the rasterizer found. */
888export function rasterArgv(tool: Rasterizer, input: string, output: string): string[] {
889 return tool === 'resvg'
890 ? ['resvg', '--zoom', '2', input, output]
891 : ['rsvg-convert', '--zoom', '2', '--output', output, input]
892}
893
894/**
895 * A render's cache key: a hash of what the renderer is given (for ASCII the
896 * flowchart a state or class diagram becomes), so a converter change makes
897 * new keys by itself, and for a PNG the scheme it is colored in, so both
898 * schemes' drawings are kept as the theme flips.
899 */
900export const renderKey = (source: string, format: InlineFormat, scheme: Scheme): string =>
901 `${hashText(format === 'ascii' ? asciiSource(source) : source)}.${format}${format === 'png' ? `.${scheme}` : ''}`
902
903const escapeHtml = (text: string): string =>
904 text.replace(/[&<>"']/g, c => `&#${c.charCodeAt(0)};`)
905
906/** JSON safe to embed in a <script>: no `</script>`, no line separators. */
907const scriptJson = (value: unknown): string =>
908 JSON.stringify(value)
909 .replace(/</g, '\\u003c')
910 .replace(/\u2028/g, '\\u2028')
911 .replace(/\u2029/g, '\\u2029')
912
913/**
914 * A standalone page that renders the document in the browser: Markdown through
915 * marked + DOMPurify, ```mermaid blocks and .mmd files through pele (the
916 * build the pane uses), all from jsDelivr. A strict CSP, DOMPurify and pele's
917 * own escaping keep the document's own HTML from running script.
918 */
919export function previewHtml(doc: {
920 title: string
921 source: string
922 isMermaid: boolean
923 baseDir?: string
924}): string {
925 const base =
926 doc.baseDir === undefined
927 ? ''
928 : `<base href="${escapeHtml(`file://${encodeURI(`${doc.baseDir}/`)}`)}">`
929
930 return `<!doctype html>
931<html lang="en">
932<head>
933<meta charset="utf-8">
934<meta name="viewport" content="width=device-width, initial-scale=1">
935<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline' https://cdn.jsdelivr.net; style-src 'unsafe-inline'; img-src * data: file:; font-src data:">
936${base}
937<title>${escapeHtml(doc.title)}</title>
938<style>
939 :root { color-scheme: light dark; --fg: #1f2328; --muted: #59636e; --bg: #ffffff; --code: #f6f8fa; --line: #d1d9e0; --link: #0969da; }
940 @media (prefers-color-scheme: dark) {
941 :root { --fg: #e6edf3; --muted: #9198a1; --bg: #0d1117; --code: #151b23; --line: #3d444d; --link: #4493f8; }
942 }
943 body { margin: 0; background: var(--bg); color: var(--fg); font: 16px/1.6 -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif; }
944 main { max-width: 900px; margin: 0 auto; padding: 32px 16px 64px; }
945 header { color: var(--muted); font-size: 13px; border-bottom: 1px solid var(--line); padding-bottom: 8px; margin-bottom: 24px; }
946 a { color: var(--link); }
947 h1, h2 { border-bottom: 1px solid var(--line); padding-bottom: .3em; }
948 code, pre { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 85%; }
949 code { background: var(--code); padding: .2em .4em; border-radius: 6px; }
950 pre { background: var(--code); padding: 16px; border-radius: 6px; overflow: auto; }
951 pre code { background: none; padding: 0; font-size: 100%; }
952 figure.mermaid { margin: 0 0 16px; text-align: center; overflow: auto; }
953 @media (prefers-color-scheme: dark) {
954 figure.mermaid { ${PELE_DARK_VARS}; }
955 }
956 table { border-collapse: collapse; display: block; overflow: auto; }
957 th, td { border: 1px solid var(--line); padding: 6px 13px; }
958 blockquote { margin: 0; padding: 0 1em; color: var(--muted); border-left: .25em solid var(--line); }
959 img { max-width: 100%; }
960</style>
961<script src="https://cdn.jsdelivr.net/npm/marked@15.0.12/marked.min.js" integrity="sha384-948ahk4ZmxYVYOc+rxN1H2gM1EJ2Duhp7uHtZ4WSLkV4Vtx5MUqnV+l7u9B+jFv+" crossorigin="anonymous"></script>
962<script src="https://cdn.jsdelivr.net/npm/dompurify@3.4.16/dist/purify.min.js" integrity="sha384-a7SzOxErzJ3ZpQz0zJ32d67dSitNzPcbfybc/ykU9KJhMgZkwqfSxlhhdJRS+XGL" crossorigin="anonymous"></script>
963<script src="https://cdn.jsdelivr.net/npm/pele@${PELE_VERSION}/dist/pele.global.js" integrity="sha384-4lHoXtKDt+x/E+htiTc83bpFWyREQzJCMudNQHirqKiCTW7Mx790I/5Q7criNZ1G" crossorigin="anonymous"></script>
964</head>
965<body>
966<main>
967<header>${escapeHtml(doc.title)}</header>
968<article id="doc"></article>
969</main>
970<script>
971(async () => {
972 const source = ${scriptJson(doc.source)};
973 const isMermaid = ${doc.isMermaid ? 'true' : 'false'};
974 const article = document.getElementById('doc');
975 const raw = () => {
976 const pre = document.createElement('pre');
977 pre.textContent = source;
978 article.replaceChildren(pre);
979 };
980 if (isMermaid) {
981 const pre = document.createElement('pre');
982 pre.className = 'mermaid';
983 pre.textContent = source;
984 article.replaceChildren(pre);
985 } else if (window.marked && window.DOMPurify) {
986 const escape = text => text.replace(/[&<>]/g, c => ({ '&': '&', '<': '<', '>': '>' })[c]);
987 marked.use({
988 gfm: true,
989 renderer: {
990 code(token) {
991 const lang = (token.lang || '').trim().split(/\\s+/)[0].toLowerCase();
992 return lang === 'mermaid' ? '<pre class="mermaid">' + escape(token.text) + '</pre>' : false;
993 },
994 },
995 });
996 article.innerHTML = DOMPurify.sanitize(marked.parse(source));
997 } else {
998 raw();
999 return;
1000 }
1001 if (!window.pele || !window.DOMPurify) return;
1002 for (const pre of article.querySelectorAll('pre.mermaid')) {
1003 try {
1004 const { svg } = pele.render(pre.textContent, { links: false, images: false });
1005 const figure = document.createElement('figure');
1006 figure.className = 'mermaid';
1007 figure.innerHTML = DOMPurify.sanitize(svg, { USE_PROFILES: { svg: true, svgFilters: true } });
1008 pre.replaceWith(figure);
1009 } catch (err) {
1010 console.error(err);
1011 }
1012 }
1013})();
1014</script>
1015</body>
1016</html>
1017`
1018}
1019types/index.d.ts 51 lines1/** What the preview pane shows. `rev` bumps when the file changes, so the pane re-reads it. */
2export type DocView =
3 | { kind: 'file'; path: string; rev: number }
4 | { kind: 'diagram'; id: string }
5 | { kind: 'picker'; dir: string }
6
7/** A Markdown or Mermaid file Claude wrote or edited this session (absolute path). */
8export type GeneratedDoc = { path: string; at: number }
9
10/** A ```mermaid block from one of Claude's replies, keyed by a hash of its source. */
11export type ReplyDiagram = { id: string; source: string; title: string; at: number }
12
13/** One diagram drawn for inline display; svg and png stay on disk, named by path. */
14export type DiagramRender =
15 | { format: 'ascii'; text: string }
16 | { format: 'svg'; file: string }
17 | { format: 'png'; file: string; width: number; height: number }
18 | { format: 'error'; message: string }
19
20/** The pane size asked for: body columns (null, the engine's default) or the whole screen. */
21export type PaneSize = { columns: number | null; isFull: boolean }
22
23/** A command that turns pele's SVG into a PNG for the terminal. */
24export type Rasterizer = 'resvg' | 'rsvg-convert'
25
26/**
27 * Which inline renderers this machine has, whether the terminal draws images
28 * (kitty, Ghostty, or `DOC_PREVIEW_IMAGES=1`; see `drawsImagesIn`), and the colors to draw them in.
29 * Pele, vendored in the mod, draws SVG everywhere; `rasterizer` makes PNGs of
30 * it in `scheme`'s colors, and `mmdc` is the fallback when there is none.
31 */
32export type Renderers = { ascii: boolean; mmdc: boolean; rasterizer: Rasterizer | null; drawsImages: boolean; scheme: Scheme }
33
34/** Which colors the terminal's PNGs are drawn in, from Claude Code's theme. */
35export type Scheme = 'light' | 'dark'
36
37declare module 'claude-code' {
38 interface PluginState {
39 'doc-preview': {
40 view: DocView | null
41 generated: GeneratedDoc[]
42 diagrams: ReplyDiagram[]
43 seenAt: number
44 renders: Record<string, DiagramRender>
45 renderers: Renderers | null
46 notice: string | null
47 size: PaneSize
48 }
49 }
50}
51