Diagram and image viewer pane: Claude renders Mermaid, Graphviz, TikZ, Typst, PDF, SVG and images, shows them beside the transcript, and looks at every render.

A Claude Code mod that shows diagrams and images in a side pane, and makes Claude look at every render.
show with Mermaid or Graphviz source, or a file (.tex .typ .pdf .svg .png .jpg …). iris renders it to PNG, opens the pane, and tells Claude to read the image back before claiming anything about it.id adds versions (v2, v3 …); watched files re-render when they change on disk.o open the vector original, s source, z/x zoom, h j k l pan, 0 fit, p/n versions, b/f PDF pages./show [n | path] opens the pane, selects a figure, or shows a file.Needs: Claude Code ≥ 2.1.287; ImageMagick (magick), Graphviz (dot), poppler (pdftoppm, pdfinfo); optionally mmdc (Mermaid CLI), pdflatex, typst.
hooks/register.tsx 605 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, ImageSource, Register } from 'claude-code'
3
4import type { IrisFigure, IrisImages, IrisVersion, IrisZoom } from '../types'
5import { basename, convert, crop, dimsOf, dirname, embeddedSvg, extOf, fitCells, rasterize, renderPdfPage, SVG_LIMIT, TEXT_EXTS, vectorSource } from './render'
6import type { RasterCells } from './raster'
7
8const PANE = 'iris'
9const TOOL = 'mcp__iris__show'
10
11const figures = atom({ plugin: 'iris', key: 'figures' } as const, [])
12const sel = atom({ plugin: 'iris', key: 'sel' } as const, null)
13const view = atom({ plugin: 'iris', key: 'view' } as const, 'preview')
14const FIT: IrisZoom = { z: 1, cx: 0.5, cy: 0.5 }
15const zoom = atom({ plugin: 'iris', key: 'zoom' } as const, FIT)
16
17const SHOW_DESCRIPTION = [
18 'Show a diagram or image to the user in the iris side pane, and get back a PNG of what they see.',
19 'Use it whenever a picture helps the user follow along: architecture or data flow (mermaid), graphs (dot),',
20 'figures you compiled (.tex, .typ, .pdf, .svg), plots and sample data (.png, .jpg).',
21 'Reuse an `id` to add a new version of the same figure while iterating on it.',
22 'The pane is a narrow sidebar: prefer top-down layouts (flowchart TB, rankdir=TB) over long left-to-right ones.',
23 'After every call, Read the returned PNG and say what is actually visible (layout, labels, anything off)',
24 'before claiming anything about the figure.',
25].join(' ')
26
27const SHOW_SCHEMA = {
28 type: 'object',
29 properties: {
30 title: { type: 'string', description: 'Short title for the pane header.' },
31 caption: { type: 'string', description: 'One line saying what to look at.' },
32 mermaid: { type: 'string', description: 'Mermaid source to render.' },
33 dot: { type: 'string', description: 'Graphviz dot source to render.' },
34 path: {
35 type: 'string',
36 description: 'File to show: .mmd .dot .gv .tex .typ .pdf .svg .png .jpg .jpeg .gif .webp .bmp. Watched for changes.',
37 },
38 id: { type: 'string', description: 'Stable figure id. Reusing it adds a version (v2, v3, ...).' },
39 page: { type: 'integer', minimum: 1, description: 'PDF page to show (default 1).' },
40 page_titles: {
41 type: 'array',
42 items: { type: 'string' },
43 description: 'Title for each PDF page, in order; the header shows only the current page\'s title.',
44 },
45 save_to: { type: 'string', description: 'Also copy the rendered PNG to this path.' },
46 },
47 additionalProperties: false,
48}
49
50type ShowArgs = {
51 title?: string
52 caption?: string
53 mermaid?: string
54 dot?: string
55 path?: string
56 id?: string
57 page?: number
58 page_titles?: string[]
59 save_to?: string
60}
61
62type Shown = { fig: IrisFigure; version: IrisVersion; png: string }
63
64// Module variables are rebuilt on every (re)load: session.start fills them again.
65let cwd = '.'
66let base = '/tmp/iris'
67let watch: { cancel: () => void } | undefined
68let isPolling = false
69// Debug trace of pane redraws while probing, written to <base>/render-log.jsonl (last 40 entries).
70const renderLog: string[] = []
71// /show probe: draw the image as a file source and as PNG bytes, to compare how the terminal scales each.
72let isProbe = false
73// When the renderer was last asked how an Image came out, and the viewport it was asked for.
74let probedAt = 0
75// What the viewer showed, kept outside $.state: a render may not set state, and asking again after a reload is cheap.
76let images: IrisImages = 'unknown'
77let probedViewport = ''
78const failedMtime = new Map<number, number>()
79const rasters = new Map<string, RasterCells | string>()
80const dims = new Map<string, { w: number; h: number }>()
81
82const abs = (path: string) => (path.startsWith('/') ? path : `${cwd}/${path}`.replace(/\/\.\//g, '/'))
83const figDir = (n: number) => `${base}/${n}`
84const pngOf = (version: IrisVersion, page: number) => version.png[String(page)]
85
86async function sh($: EngineInterface, argv: string[]) {
87 return $.process.run(argv, { timeoutMs: 30_000 })
88}
89
90/** Opens a file in VS Code (inside its terminal) or the desktop viewer, detached. */
91async function openExternal($: EngineInterface, file: string) {
92 const isVscode = (await $.env.get('TERM_PROGRAM')) === 'vscode'
93 const opener = isVscode ? 'code -r "$1"' : 'xdg-open "$1"'
94 await sh($, ['sh', '-c', `${opener} >/dev/null 2>&1 &`, 'iris', file])
95}
96
97/** The working folder and mmdc's config; recreated whenever missing. */
98async function ensureBase($: EngineInterface) {
99 const config = `${base}/puppeteer.json`
100 if (!(await $.fs.exists(config))) await $.fs.write(config, '{"args":["--no-sandbox"]}\n')
101}
102
103async function show($: EngineInterface, args: ShowArgs, isFromWatch = false): Promise<Shown> {
104 await ensureBase($)
105 const list = await read($, figures)
106 const existing = args.id === undefined ? undefined : list.find(f => f.id === args.id)
107 const n = existing?.n ?? list.length + 1
108 const dir = figDir(n)
109 const v = (existing?.versions.length ?? 0) + 1
110
111 let path: string
112 let isWatched: boolean
113 if (args.mermaid !== undefined || args.dot !== undefined) {
114 path = `${dir}/v${v}.${args.mermaid !== undefined ? 'mmd' : 'dot'}`
115 await $.fs.write(path, args.mermaid ?? args.dot ?? '')
116 isWatched = false
117 } else if (args.path !== undefined) {
118 path = abs(args.path)
119 isWatched = true
120 } else if (existing) {
121 path = existing.path
122 isWatched = existing.isWatched
123 } else {
124 throw new Error('iris needs one of: mermaid, dot, path')
125 }
126
127 const page = args.page ?? existing?.page ?? 1
128 const rendered = await convert($, path, dir, v, page, `${base}/puppeteer.json`)
129 await sh($, ['cp', rendered.png, `${dir}/current.png`])
130 const mtime = isWatched ? (await $.fs.stat(path)).mtimeMs : undefined
131
132 const version: IrisVersion = {
133 v,
134 at: await $.clock.now(),
135 pdf: rendered.pdf,
136 vector: rendered.vector,
137 pages: rendered.pages,
138 png: { [String(rendered.page)]: rendered.png },
139 }
140 const fig: IrisFigure = {
141 n,
142 id: existing?.id ?? args.id ?? `fig${n}`,
143 title: args.title ?? existing?.title ?? basename(path),
144 caption: args.caption ?? existing?.caption,
145 path,
146 isWatched,
147 page: rendered.page,
148 pageTitles: args.page_titles ?? existing?.pageTitles,
149 mtime,
150 versions: [...(existing?.versions ?? []), version],
151 }
152 await update($, figures, all => [...all.filter(f => f.n !== n), fig].sort((a, b) => a.n - b.n))
153 await update($, sel, () => ({ n, v }))
154 await update($, view, () => 'preview')
155 await update($, zoom, () => FIT)
156 failedMtime.delete(n)
157
158 if (args.save_to !== undefined) {
159 const target = abs(args.save_to)
160 await sh($, ['sh', '-c', 'mkdir -p "$(dirname "$2")" && cp "$1" "$2"', 'iris', rendered.png, target])
161 }
162
163 const opened = await $.ui.open({ id: PANE, title: 'iris' })
164 if (!opened.isPlaced) {
165 $.ui.toast(`iris: #${n} ${fig.title} v${v} ready. /show to view`)
166 }
167 // Where the pane shows real pixels the full image is already in view; elsewhere open it once per figure.
168 if (v === 1 && !isFromWatch && images === 'none') {
169 await openExternal($, `${dir}/current.png`)
170 }
171 return { fig, version, png: rendered.png }
172}
173
174function describe(shown: Shown): string {
175 const { fig, version, png } = shown
176 const pages = version.pages > 1 ? `, page ${fig.page}/${version.pages}` : ''
177 return [
178 `Shown in the iris pane as #${fig.n} "${fig.title}" v${version.v}${pages}.`,
179 `PNG: ${png}`,
180 'Now Read that PNG and tell the user what is actually visible before relying on it.',
181 ].join('\n')
182}
183
184async function select($: EngineInterface, n: number, v?: number) {
185 const fig = (await read($, figures)).find(f => f.n === n)
186 if (!fig) return false
187 const last = fig.versions.length
188 await update($, sel, () => ({ n, v: Math.min(Math.max(1, v ?? last), last) }))
189 await update($, zoom, () => FIT)
190 return true
191}
192
193/** Shows another page of the selected version, rendering it on first use. */
194async function flipPage($: EngineInterface, delta: number) {
195 const s = await read($, sel)
196 const fig = (await read($, figures)).find(f => f.n === s?.n)
197 if (fig) await gotoPage($, fig.page + delta)
198}
199
200async function gotoPage($: EngineInterface, target: number) {
201 const s = await read($, sel)
202 const fig = (await read($, figures)).find(f => f.n === s?.n)
203 const version = fig?.versions[(s?.v ?? 1) - 1]
204 if (!fig || !version?.pdf) return
205 const page = Math.min(Math.max(1, target), version.pages)
206 if (page === fig.page) return
207 let png = pngOf(version, page)
208 if (png === undefined) {
209 png = (await renderPdfPage($, version.pdf, page, `${figDir(fig.n)}/v${version.v}-p${page}`)).png
210 }
211 const updated: IrisVersion = { ...version, png: { ...version.png, [String(page)]: png } }
212 await update($, figures, all =>
213 all.map(f =>
214 f.n === fig.n
215 ? { ...f, page, versions: f.versions.map(one => (one.v === version.v ? updated : one)) }
216 : f,
217 ),
218 )
219}
220
221/** Re-renders watched files whose modification time moved. */
222async function poll($: EngineInterface) {
223 if (isPolling) return
224 isPolling = true
225 try {
226 for (const fig of await read($, figures)) {
227 if (!fig.isWatched) continue
228 const stat = await $.fs.stat(fig.path).catch(() => undefined)
229 if (!stat || stat.mtimeMs === fig.mtime || stat.mtimeMs === failedMtime.get(fig.n)) continue
230 try {
231 await show($, { id: fig.id }, true)
232 } catch (err) {
233 failedMtime.set(fig.n, stat.mtimeMs)
234 $.ui.toast(`iris: #${fig.n} changed but failed to render: ${String(err).slice(0, 160)}`)
235 }
236 }
237 } finally {
238 isPolling = false
239 }
240}
241
242async function rasterFor($: EngineInterface, png: string, columns: number, maxRows: number) {
243 const key = `${png}|${columns}|${maxRows}`
244 let cached = rasters.get(key)
245 if (cached === undefined) {
246 cached = await rasterize($, png, columns, maxRows).catch(err => `preview failed: ${String(err).slice(0, 200)}`)
247 rasters.set(key, cached)
248 }
249 return cached
250}
251
252/** Terminals that draw real pixels (kitty graphics protocol). */
253/**
254 * Asks the renderer how the Image just drawn came out, and switches to what the viewing terminal can show.
255 * The session's own environment says nothing about this: a background session is viewed from another terminal.
256 */
257async function probeImages($: EngineInterface, key: string, source: ImageSource, box: { columns: number; rows: number }) {
258 const now = await $.clock.now()
259 if (now - probedAt < 2000) return
260 probedAt = now
261 await $.clock.sleep(300) // let the frame holding the Image land first
262 const r = await $.ui.blit({ requestId: PANE, key, source, columns: box.columns, rows: box.rows }).catch(() => ({ deny: 'failed' }))
263 const deny = r.deny ?? ''
264 const was = images
265 let next = was
266 if (deny === '') next = 'png' in source ? 'bytes' : 'file'
267 // "this terminal cannot read files on this machine ... bytes still draw"
268 else if (/cannot read files/.test(deny)) next = 'bytes'
269 // "the terminal draws no placeholder images"; not "every image id is in use", which passes
270 else if (/draws its alt|not drawn under a terminal/.test(deny) && !/in use/.test(deny)) next = 'none'
271 // "has not yet said whether it reads files ... asked now, blit again"
272 else if (/blit again/.test(deny)) probedAt = 0
273 if (next !== was) {
274 images = next
275 $.ui.invalidate('ui.render')
276 // One line per change, so how a viewer was judged can be checked afterwards.
277 await sh($, ['sh', '-c', 'printf "%s %s -> %s (%s)\\n" "$(date -Is)" "$1" "$2" "$3" >> "$4"', 'iris', was, next, deny || 'drawn', `${base}/images.log`]).catch(() => undefined)
278 }
279}
280
281/** Whether to draw an Image: yes unless this viewer showed none. A new viewport may be a new viewer, so ask again. */
282async function imagesFor($: EngineInterface, viewport: { columns: number; rows: number } | undefined): Promise<boolean> {
283 const vp = `${viewport?.columns}x${viewport?.rows}`
284 if (vp !== probedViewport) {
285 probedViewport = vp
286 if (images === 'none') images = 'unknown'
287 }
288 return images !== 'none'
289}
290
291async function cachedDims($: EngineInterface, file: string) {
292 let found = dims.get(file)
293 if (found === undefined) {
294 found = await dimsOf($, file)
295 dims.set(file, found)
296 }
297 return found
298}
299
300/** The file the pane shows for the current zoom: the whole render, or a cropped window of it. */
301async function zoomed($: EngineInterface, png: string, z: IrisZoom) {
302 const full = await cachedDims($, png)
303 if (z.z <= 1) return { file: png, ...full }
304 return crop($, png, full.w, full.h, z.z, z.cx, z.cy)
305}
306
307// Raster sizes tried for the desktop, largest first: PNG keeps diagrams sharp; JPEG fits photos and big pages.
308const DESKTOP_TRIES = [
309 [1600, 'png'],
310 [1200, 'png'],
311 [1600, 'jpg'],
312 [1200, 'jpg'],
313 [900, 'jpg'],
314 [600, 'jpg'],
315] as const
316const desktopDocs = new Map<string, string>()
317
318/**
319 * The picture as an SVG document for the desktop surface. A Graphviz figure keeps its own vector (it needs
320 * no stylesheet). Anything else is its PNG embedded at the largest size that fits the Svg limit.
321 */
322async function desktopSvg($: EngineInterface, file: string, w: number, h: number, vector?: string): Promise<string | undefined> {
323 const own = vector?.endsWith('.svg') ? vectorSource(await $.fs.read(vector).catch(() => undefined)) : undefined
324 if (own !== undefined) return own
325 const cacheKey = `${file}:${w}x${h}`
326 const known = desktopDocs.get(cacheKey)
327 if (known !== undefined) return known
328 for (const [width, kind] of DESKTOP_TRIES) {
329 const out = `${file}.desktop-${width}.${kind}`
330 const flatten = kind === 'jpg' ? ['-background', 'white', '-flatten', '-quality', '82'] : []
331 await sh($, ['magick', file, '-resize', `${width}x>`, ...flatten, out]).catch(() => undefined)
332 const bytes = await $.fs.read(out, { as: 'bytes' }).catch(() => undefined)
333 if (bytes === undefined || bytes.base64.length + 300 > SVG_LIMIT) continue
334 const doc = embeddedSvg(bytes.base64, kind === 'jpg' ? 'image/jpeg' : 'image/png', w, h, width)
335 desktopDocs.set(cacheKey, doc)
336 return doc
337 }
338 return undefined
339}
340
341const ZOOM_STEP = 1.5
342const MAX_ZOOM = 12
343
344function zoomBy(factor: number) {
345 return (z: IrisZoom): IrisZoom => {
346 const next = Math.min(MAX_ZOOM, Math.max(1, z.z * factor))
347 return next <= 1.01 ? FIT : { ...z, z: next }
348 }
349}
350
351/** Moves the view by a quarter of its own size. */
352function panBy(dx: number, dy: number) {
353 return (z: IrisZoom): IrisZoom => {
354 const half = 0.5 / z.z
355 const clamp = (c: number) => Math.min(1 - half, Math.max(half, c))
356 return { ...z, cx: clamp(z.cx + (dx * 0.25) / z.z), cy: clamp(z.cy + (dy * 0.25) / z.z) }
357 }
358}
359
360async function sourceText($: EngineInterface, fig: IrisFigure) {
361 if (!TEXT_EXTS.includes(extOf(fig.path))) return `${fig.path}\n(binary file: no source to show)`
362 const text = await $.fs.read(fig.path).catch(() => '(source file no longer readable)')
363 const lines = text.split('\n')
364 return lines.length > 200 ? `${lines.slice(0, 200).join('\n')}\n… ${lines.length - 200} more lines` : text
365}
366
367export const register: Register = on => {
368 on('session.start', async ($, e, next) => {
369 cwd = e.cwd
370 base = `${(await $.env.get('TMPDIR')) ?? '/tmp'}/iris-${await $.session.id()}`
371 await ensureBase($)
372 // Renders outlive the process so a resumed session keeps its figures; old ones are pruned here.
373 await sh($, ['sh', '-c', 'find "$1" -maxdepth 1 -name "iris-*" -mtime +7 -exec rm -rf {} +', 'iris', dirname(base)]).catch(
374 () => undefined,
375 )
376 await $.tool.register({ name: 'show', description: SHOW_DESCRIPTION, inputSchema: SHOW_SCHEMA, isDeferred: false })
377 await $.command.register({
378 name: 'show',
379 description: 'Open the iris pane. /show <n> selects figure n; /show <path> shows a file.',
380 argumentHint: '[n | path]',
381 })
382 watch?.cancel()
383 watch = $.clock.every(1000, () => void poll($))
384
385 return next(e)
386 })
387
388 on('tool.call', { tool: TOOL }, async ($, e) => {
389 const { tool: _tool, tool_use_id: _id, ...args } = e as unknown as ShowArgs & { tool: string; tool_use_id: string }
390 try {
391 return { result: describe(await show($, args)) }
392 } catch (err) {
393 return { deny: `iris could not render it: ${err instanceof Error ? err.message : String(err)}` }
394 }
395 }).catch(() => ({ deny: 'iris failed while handling the call.' }))
396
397 on('command.run', { command: 'show' }, async ($, e) => {
398 const arg = e.args.trim()
399 let text = 'iris pane opened.'
400 if (arg === 'probe') {
401 isProbe = !isProbe
402 $.ui.invalidate('ui.render')
403 text = `iris probe ${isProbe ? 'on' : 'off'}.`
404 } else if (/^#?\d+$/.test(arg)) {
405 text = (await select($, Number(arg.replace('#', '')))) ? `Showing #${arg.replace('#', '')}.` : `No figure ${arg}.`
406 } else if (arg !== '') {
407 try {
408 const shown = await show($, { path: arg })
409 text = `Showing #${shown.fig.n} ${shown.fig.title}.`
410 } catch (err) {
411 text = `iris could not render ${arg}: ${err instanceof Error ? err.message : String(err)}`
412 }
413 }
414 await $.ui.open({ id: PANE, title: 'iris' })
415
416 return { text }
417 })
418
419 on('prompt.submit', async ($, e, next) => {
420 const result = await next(e)
421 const s = await read($, sel)
422 const fig = (await read($, figures)).find(f => f.n === s?.n)
423 const version = fig?.versions[(s?.v ?? 1) - 1]
424 if (result.drop !== undefined || !fig || !version) return result
425 const line = `iris pane shows #${fig.n} "${fig.title}" v${version.v}/${fig.versions.length} (png: ${pngOf(version, fig.page) ?? ''})`
426
427 return { ...result, context: [...(result.context ?? []), line] }
428 }).catch(($, e, next) => next(e))
429
430 on('ui.render', { component: 'ToolUse' }, async ($, e, next) => {
431 if (e.props.tool !== TOOL) return next(e)
432 const { Box, Text } = $.ui.resolve(e)
433 const a = (e.props.input ?? {}) as ShowArgs
434 const what = a.title ?? (a.path !== undefined ? basename(a.path) : a.mermaid !== undefined ? 'Mermaid diagram' : a.dot !== undefined ? 'Graphviz diagram' : a.id ?? 'figure')
435 const extra = [a.id !== undefined ? `id ${a.id}` : '', a.page !== undefined ? `page ${a.page}` : ''].filter(Boolean).join(' · ')
436 return (
437 <Box flexDirection="row">
438 <Text bold color="#4E79A7">iris</Text>
439 <Text dimColor> · Show {what}{extra !== '' ? ` · ${extra}` : ''}</Text>
440 </Box>
441 )
442 }).catch(($, e, next) => next(e))
443
444 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
445 const { Box, Text, Button, Code } = $.ui.resolve(e)
446 const list = await read($, figures)
447 const s = await read($, sel)
448 const mode = await read($, view)
449 const fig = list.find(f => f.n === s?.n)
450 const version = fig?.versions[(s?.v ?? 1) - 1]
451
452 if (!fig || !version) {
453 return (
454 <Box flexDirection="column">
455 <Text dimColor>No figures yet. Claude adds them with the show tool; you can type /show path/to/file.</Text>
456 </Box>
457 )
458 }
459
460 const z = await read($, zoom)
461 const columns = Math.max(10, e.props.bodyColumns)
462 const png = pngOf(version, fig.page) ?? ''
463 const count = fig.versions.length
464 // Fit the picture into what the pane shows at once: its body less the header and button rows.
465 const chrome = 3 + (fig.caption === undefined ? 0 : 1) + (z.z > 1 ? 1 : 0) + (version.pages > 1 ? 1 : 0)
466 const fitRows = Math.max(4, e.props.scroll.bodyRows - chrome)
467 const zoomLabel = z.z > 1 ? ` · ${z.z.toFixed(1)}×` : ''
468
469 let body
470 let indent = 0
471 if (mode === 'source') {
472 body = <Code source={await sourceText($, fig)} language={extOf(fig.path)} />
473 } else if (e.surface === 'terminal') {
474 const shown = await zoomed($, png, z).catch(() => undefined)
475 if (!shown) {
476 body = <Text dimColor>Preview failed. Press o to open the file.</Text>
477 } else if (await imagesFor($, e.viewport)) {
478 const how = images
479 const { Image } = $.ui.resolve(e)
480 const box = fitCells(shown.w, shown.h, columns, fitRows)
481 indent = Math.max(0, Math.floor((columns - box.columns) / 2))
482 if (isProbe) renderLog.push(
483 JSON.stringify({
484 t: await $.clock.now(),
485 bodyColumns: e.props.bodyColumns,
486 bodyRows: e.props.scroll.bodyRows,
487 scrollOffset: e.props.scroll.offset,
488 placement: e.props.placement,
489 viewport: e.viewport,
490 image: { w: shown.w, h: shown.h },
491 box,
492 indent,
493 fitRows,
494 }),
495 )
496 if (renderLog.length > 40) renderLog.shift()
497 if (isProbe) void $.fs.write(`${base}/render-log.jsonl`, renderLog.join('\n') + '\n')
498 // A keyed Image keeps its first placement size; a new key per box size makes a resize re-place it.
499 const key = `preview-${box.columns}x${box.rows}`
500 // Same file at a new size must be re-sent: a source equal to the last one sends nothing.
501 const source: ImageSource =
502 how === 'bytes' ? { png: (await $.fs.read(shown.file, { as: 'bytes' })).base64 } : { file: shown.file, format: 'png', generation: box.columns * 1000 + box.rows }
503 body = <Image key={key} source={source} columns={box.columns} rows={box.rows} alt={`#${fig.n} ${fig.title} (press o to open)`} />
504 void probeImages($, key, source, box).catch(() => undefined)
505 if (isProbe) {
506 const half = fitCells(shown.w, shown.h, columns, Math.max(4, Math.floor(fitRows / 2) - 2))
507 const { base64 } = await $.fs.read(shown.file, { as: 'bytes' })
508 body = (
509 <Box flexDirection="column">
510 <Text dimColor>Probe A: file source {half.columns}x{half.rows}</Text>
511 <Image key="probe-file" source={{ file: shown.file, format: 'png', generation: half.columns * 1000 + half.rows }} columns={half.columns} rows={half.rows} alt="file" />
512 <Text dimColor>Probe B: PNG bytes {half.columns}x{half.rows}</Text>
513 <Image key="probe-png" source={{ png: base64 }} columns={half.columns} rows={half.rows} alt="png" />
514 </Box>
515 )
516 }
517 } else {
518 const { Raster } = $.ui.resolve(e)
519 const raster = await rasterFor($, shown.file, columns, fitRows)
520 body =
521 typeof raster === 'string' ? (
522 <Text dimColor>{raster}</Text>
523 ) : (
524 <Raster key="preview" columns={raster.columns} rows={raster.rows} cells={raster.cells} />
525 )
526 }
527 } else if (e.surface === 'desktop') {
528 const { Svg } = $.ui.resolve(e)
529 const shown = await zoomed($, png, z).catch(() => undefined)
530 // The vector only for the whole picture: a zoomed view is a crop of the PNG.
531 const doc = shown ? await desktopSvg($, shown.file, shown.w, shown.h, z.z <= 1 ? version.vector : undefined) : undefined
532 body = doc ? (
533 <Svg source={doc} alt={`#${fig.n} ${fig.title}`} />
534 ) : (
535 <Text dimColor>Preview failed. Press Open for the full image.</Text>
536 )
537 } else {
538 body = <Text dimColor>This surface shows no pictures. Press Open for the full image.</Text>
539 }
540
541 const recent = list.slice(-8).reverse()
542 const target = version.vector ?? `${figDir(fig.n)}/current.png`
543
544 return (
545 <Box flexDirection="column">
546 <Text bold>
547 #{fig.n} {fig.title}{' '}
548 <Text dimColor>
549 v{version.v}/{count}
550 {version.pages > 1 ? ` · page ${fig.page}/${version.pages}` : ''}
551 {fig.pageTitles?.[fig.page - 1] !== undefined ? ` · ${fig.pageTitles[fig.page - 1]}` : ''}
552 {zoomLabel}
553 </Text>
554 </Text>
555 {fig.caption !== undefined && <Text dimColor>{fig.caption}</Text>}
556 <Box flexDirection="row" flexWrap="wrap" columnGap={1}>
557 <Button key="open" hotkey="o" label="Open" onPress={() => openExternal($, target)} />
558 <Button
559 key="source"
560 hotkey="s"
561 label={mode === 'source' ? 'Preview' : 'Source'}
562 onPress={() => update($, view, m => (m === 'source' ? 'preview' : 'source'))}
563 />
564 <Button key="zoomin" hotkey="z" label="Zoom +" onPress={() => update($, zoom, zoomBy(ZOOM_STEP))} />
565 {z.z > 1 && <Button key="zoomout" hotkey="x" label="Zoom −" onPress={() => update($, zoom, zoomBy(1 / ZOOM_STEP))} />}
566 {z.z > 1 && <Button key="fit" hotkey="0" label="Fit" onPress={() => update($, zoom, () => FIT)} />}
567 {count > 1 && <Button key="prev" hotkey="p" label="‹ Older" onPress={() => select($, fig.n, version.v - 1)} />}
568 {count > 1 && <Button key="next" hotkey="n" label="Newer ›" onPress={() => select($, fig.n, version.v + 1)} />}
569 {version.pages > 1 && <Button key="pageup" hotkey="b" label="‹ Page" onPress={() => flipPage($, -1)} />}
570 {version.pages > 1 && <Button key="pagedown" hotkey="f" label="Page ›" onPress={() => flipPage($, 1)} />}
571 </Box>
572 {version.pages > 1 && version.pages <= 40 && (
573 // One click per page: rapid repeated clicks read as a double-click and select text.
574 <Box flexDirection="row" flexWrap="wrap" columnGap={1}>
575 {Array.from({ length: version.pages }, (_, i) => i + 1).map(p => (
576 <Button key={`page-${p}`} plain dimColor={p !== fig.page} onPress={() => gotoPage($, p)}>
577 {p === fig.page ? `[${p}]` : String(p)}
578 </Button>
579 ))}
580 </Box>
581 )}
582 {z.z > 1 && (
583 <Box flexDirection="row" columnGap={1}>
584 <Text dimColor>Pan</Text>
585 <Button key="left" hotkey="h" label="←" onPress={() => update($, zoom, panBy(-1, 0))} />
586 <Button key="down" hotkey="j" label="↓" onPress={() => update($, zoom, panBy(0, 1))} />
587 <Button key="up" hotkey="k" label="↑" onPress={() => update($, zoom, panBy(0, -1))} />
588 <Button key="right" hotkey="l" label="→" onPress={() => update($, zoom, panBy(1, 0))} />
589 </Box>
590 )}
591 <Box flexDirection="row" paddingLeft={indent}>
592 {body}
593 </Box>
594 {recent.length > 1 && <Text dimColor>History</Text>}
595 {recent.length > 1 &&
596 recent.map(one => (
597 <Button key={`fig-${one.n}`} plain dimColor={one.n !== fig.n} onPress={() => select($, one.n)}>
598 #{one.n} {one.title} <Text dimColor>v{one.versions.length}</Text>
599 </Button>
600 ))}
601 </Box>
602 )
603 })
604}
605hooks/render.ts 195 lines1// Turns a source file into a PNG with the converters installed on this machine.
2// Every converter writes its output to a file: $.process hands stdout back as text.
3
4import type { EngineInterface } from 'claude-code'
5
6import { packHalfBlocks, type RasterCells } from './raster'
7
8export const SOURCE_EXTS = ['mmd', 'dot', 'gv', 'tex', 'typ', 'pdf', 'svg', 'png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp'] as const
9export const TEXT_EXTS = ['mmd', 'dot', 'gv', 'tex', 'typ', 'svg']
10
11export function extOf(path: string): string {
12 const dot = path.lastIndexOf('.')
13 return dot < 0 ? '' : path.slice(dot + 1).toLowerCase()
14}
15
16export function basename(path: string): string {
17 return path.slice(path.lastIndexOf('/') + 1)
18}
19
20export function dirname(path: string): string {
21 const slash = path.lastIndexOf('/')
22 return slash <= 0 ? '/' : path.slice(0, slash)
23}
24
25export function parsePages(pdfinfo: string): number {
26 const m = /^Pages:\s+(\d+)/m.exec(pdfinfo)
27 return m ? Number(m[1]) : 1
28}
29
30/** Last lines of a failed command's output, enough to see the error. */
31export function tail(text: string, lines = 25): string {
32 return text.trimEnd().split('\n').slice(-lines).join('\n')
33}
34
35async function run($: EngineInterface, argv: string[], cwd?: string, timeoutMs = 120_000) {
36 const out = await $.process.run(argv, { cwd, timeoutMs })
37 if (out.exitCode !== 0) {
38 throw new Error(`${argv[0]} failed (exit ${out.exitCode}):\n${tail(out.stderr || out.stdout)}`)
39 }
40 return out
41}
42
43export type Rendered = { pdf?: string; vector?: string; pages: number; page: number; png: string }
44
45/** Renders page `page` of a PDF to `<base>.png`. */
46export async function renderPdfPage($: EngineInterface, pdf: string, page: number, base: string): Promise<Rendered> {
47 const pages = parsePages((await run($, ['pdfinfo', pdf])).stdout)
48 const p = Math.min(Math.max(1, page), pages)
49 await run($, ['pdftoppm', '-png', '-r', '200', '-f', String(p), '-l', String(p), '-singlefile', pdf, base])
50 return { pdf, vector: pdf, pages, page: p, png: `${base}.png` }
51}
52
53/**
54 * Renders `src` into `dir` as version `v`. `puppeteer` is the config file
55 * mmdc needs on this machine (Chrome's sandbox is blocked by AppArmor).
56 */
57export async function convert(
58 $: EngineInterface,
59 src: string,
60 dir: string,
61 v: number,
62 page: number,
63 puppeteer: string,
64): Promise<Rendered> {
65 await run($, ['mkdir', '-p', dir])
66 const png = `${dir}/v${v}-p1.png`
67 const one = (vector?: string): Rendered => ({ pages: 1, page: 1, png, vector })
68 const svg = `${dir}/v${v}.svg`
69 const pdf = `${dir}/v${v}.pdf`
70 const ext = extOf(src)
71
72 switch (ext) {
73 case 'mmd':
74 await run($, ['mmdc', '-p', puppeteer, '-i', src, '-o', png, '-b', 'white', '-s', '3', '-q'])
75 await run($, ['mmdc', '-p', puppeteer, '-i', src, '-o', svg, '-b', 'white', '-q'])
76 return one(svg)
77 case 'dot':
78 case 'gv':
79 await run($, ['dot', '-Tpng', '-Gdpi=200', src, '-o', png])
80 await run($, ['dot', '-Tsvg', src, '-o', svg])
81 return one(svg)
82 case 'svg':
83 await run($, ['magick', '-density', '200', '-background', 'white', src, '-flatten', png])
84 await run($, ['cp', src, svg])
85 return one(svg)
86 case 'png':
87 await run($, ['cp', src, png])
88 return one()
89 case 'jpg':
90 case 'jpeg':
91 case 'gif':
92 case 'webp':
93 case 'bmp':
94 await run($, ['magick', `${src}[0]`, png])
95 return one()
96 case 'pdf':
97 await run($, ['cp', src, pdf])
98 break
99 case 'tex': {
100 const out = `${dir}/tex`
101 await run($, ['mkdir', '-p', out])
102 await run(
103 $,
104 ['pdflatex', '-interaction=nonstopmode', '-halt-on-error', `-output-directory=${out}`, basename(src)],
105 dirname(src),
106 )
107 await run($, ['cp', `${out}/${basename(src).replace(/\.tex$/i, '.pdf')}`, pdf])
108 break
109 }
110 case 'typ':
111 await run($, ['typst', 'compile', src, pdf])
112 break
113 default:
114 throw new Error(`iris can't show .${ext} files (supported: ${SOURCE_EXTS.join(', ')})`)
115 }
116 return renderPdfPage($, pdf, page, `${dir}/v${v}-p${page}`)
117}
118
119/** Pixel width and height of an image file. */
120export async function dimsOf($: EngineInterface, file: string): Promise<{ w: number; h: number }> {
121 const out = await run($, ['magick', 'identify', '-format', '%w %h', `${file}[0]`])
122 const [w, h] = out.stdout.trim().split(/\s+/).map(Number)
123 return { w: w || 1, h: h || 1 }
124}
125
126/** The window of a zoomed view, in pixels, kept inside the image. */
127export function cropWindow(w: number, h: number, z: number, cx: number, cy: number) {
128 const cw = Math.max(1, Math.round(w / z))
129 const ch = Math.max(1, Math.round(h / z))
130 const x = Math.min(Math.max(0, Math.round(cx * w - cw / 2)), w - cw)
131 const y = Math.min(Math.max(0, Math.round(cy * h - ch / 2)), h - ch)
132 return { cw, ch, x, y }
133}
134
135/** Crops `png` to the zoomed window, caching the result beside it. */
136export async function crop($: EngineInterface, png: string, w: number, h: number, z: number, cx: number, cy: number) {
137 const { cw, ch, x, y } = cropWindow(w, h, z, cx, cy)
138 const out = `${png}.crop-${cw}x${ch}+${x}+${y}.png`
139 if (!(await $.fs.exists(out))) await run($, ['magick', png, '-crop', `${cw}x${ch}+${x}+${y}`, '+repage', out])
140 return { file: out, w: cw, h: ch }
141}
142
143/** Cells that show a w x h picture whole inside columns x maxRows; a cell is about twice as tall as wide. */
144export function fitCells(w: number, h: number, columns: number, maxRows: number) {
145 const aspect = h / w
146 let cols = Math.min(columns, 255)
147 let rows = Math.max(1, Math.round((cols * aspect) / 2))
148 if (rows > maxRows) {
149 rows = Math.max(1, maxRows)
150 cols = Math.max(1, Math.min(cols, Math.round((rows * 2) / aspect)))
151 }
152 return { columns: cols, rows: Math.min(rows, 255) }
153}
154
155/** Shrinks a PNG to fit `columns` x `maxRows` cells and packs it as half blocks. */
156export async function rasterize(
157 $: EngineInterface,
158 png: string,
159 columns: number,
160 maxRows: number,
161): Promise<RasterCells> {
162 const raw = `${png}.${columns}x${maxRows}.rgb`
163 const out = await run($, [
164 'magick', png,
165 '-background', 'white', '-alpha', 'remove', '-alpha', 'off',
166 '-resize', `${columns}x${maxRows * 2}`,
167 '-dither', 'None', '-colors', '128',
168 '-print', '%w %h\n',
169 '-depth', '8', `rgb:${raw}`,
170 ])
171 const [w, h] = out.stdout.trim().split(/\s+/).map(Number)
172 const { base64 } = await $.fs.read(raw, { as: 'bytes' })
173 return packHalfBlocks(Uint8Array.fromBase64(base64), w ?? columns, h ?? 1)
174}
175
176/** The desktop surface draws pictures as Svg, whose source may be at most this many characters. */
177export const SVG_LIMIT = 131_072
178
179/**
180 * An SVG file's text as an Svg element's source, or undefined when it cannot be one: too long, or styled by a
181 * <style> block (mermaid's are), which a surface that scrubs stylesheets would draw unstyled.
182 */
183export function vectorSource(text: string | undefined): string | undefined {
184 const at = text?.indexOf('<svg') ?? -1
185 const doc = text !== undefined && at >= 0 ? text.slice(at) : undefined
186 return doc !== undefined && doc.length <= SVG_LIMIT && !doc.includes('<style') ? doc : undefined
187}
188
189/** A raster embedded in an SVG document of the picture's own size, at most `width` pixels across. */
190export function embeddedSvg(base64: string, mime: string, w: number, h: number, width: number): string {
191 const ww = Math.min(width, w)
192 const hh = Math.max(1, Math.round((h * ww) / w))
193 return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${ww} ${hh}" width="${ww}" height="${hh}"><image href="data:${mime};base64,${base64}" width="${ww}" height="${hh}"/></svg>`
194}
195hooks/raster.ts 27 lines1// Packs raw RGB pixels into Raster cells: one upper-half-block glyph per cell,
2// its foreground the top pixel and its background the bottom one.
3
4export const UPPER_HALF = 0x2580
5export const TERMINAL_DEFAULT = 0x01000000
6
7export type RasterCells = { cells: string; columns: number; rows: number }
8
9export function packHalfBlocks(rgb: Uint8Array, width: number, height: number): RasterCells {
10 const rows = Math.ceil(height / 2)
11 const words = new Uint32Array(width * rows * 3)
12 const pixel = (x: number, y: number) => {
13 if (y >= height) return TERMINAL_DEFAULT
14 const i = (y * width + x) * 3
15 return ((rgb[i] ?? 0) << 16) | ((rgb[i + 1] ?? 0) << 8) | (rgb[i + 2] ?? 0)
16 }
17 for (let r = 0; r < rows; r++) {
18 for (let x = 0; x < width; x++) {
19 const w = (r * width + x) * 3
20 words[w] = UPPER_HALF
21 words[w + 1] = pixel(x, 2 * r)
22 words[w + 2] = pixel(x, 2 * r + 1)
23 }
24 }
25 return { cells: new Uint8Array(words.buffer).toBase64(), columns: width, rows }
26}
27types/index.d.ts 55 lines1/** One render of a figure. PDFs keep a snapshot so pages can be flipped later. */
2export type IrisVersion = {
3 v: number
4 at: number
5 /** Snapshot of the PDF this version came from (pdf, tex, typ sources). */
6 pdf?: string
7 pages: number
8 /** The vector original Open shows (svg or pdf), zoomable in a viewer. */
9 vector?: string
10 /** Rendered PNG per page, keyed by page number as a string. */
11 png: Record<string, string>
12}
13
14export type IrisFigure = {
15 /** Display number, #1, #2, ... in order of creation. */
16 n: number
17 /** Stable id; showing the same id again adds a version. */
18 id: string
19 title: string
20 caption?: string
21 /** Absolute path of the source file (inline mermaid/dot is written to one). */
22 path: string
23 /** True when the source is the user's file, so iris watches it for changes. */
24 isWatched: boolean
25 page: number
26 /** Optional title per PDF page, shown in the header for the current page. */
27 pageTitles?: string[]
28 mtime?: number
29 versions: IrisVersion[]
30}
31
32export type IrisSelection = { n: number; v: number } | null
33
34/** In-pane zoom: z = 1 fits the whole image; cx, cy are the view's centre as fractions. */
35export type IrisZoom = { z: number; cx: number; cy: number }
36
37/**
38 * How the terminal that views the session shows an Image, learned by asking the renderer (not from the
39 * environment: a background session's environment is not its viewer's). file: pixels from a path;
40 * bytes: pixels only when sent as PNG bytes (the viewer cannot read this machine's files); none: no
41 * pixels, so draw half-block cells; unknown: not asked yet.
42 */
43export type IrisImages = 'unknown' | 'file' | 'bytes' | 'none'
44
45declare module 'claude-code' {
46 interface PluginState {
47 iris: {
48 figures: IrisFigure[]
49 sel: IrisSelection
50 view: 'preview' | 'source'
51 zoom: IrisZoom
52 }
53 }
54}
55