Shows Xcode RenderPreview snapshots of SwiftUI previews in a Claude Code pane

A Claude Code mod that shows SwiftUI previews right in the terminal, rendered by Xcode itself.

Claude calls Xcode's RenderPreview MCP tool on a #Preview; the mod shows the snapshot in a SwiftUI Preview pane — components 1:1 in points like Xcode's canvas at 100%, whole screens fit to the pane. Variants (dark mode, Dynamic Type, orientation), localizations and #Preview(arguments:) come from RenderPreview itself.
sudo xcrun mcp-server enable)claude mcp add xcode -s user -- xcrun mcpbridge
then, at a Claude Code prompt:
/plugin install swiftui-preview --marketplace degterev/swiftui-preview-mod
Answer y to add the marketplace, then pick a scope.
Ask Claude in plain words; if the file has no #Preview, Claude adds one.
The pane opens with each render, labelled with the preview, device and variant (Settings · iPhone 18 Pro · Dark Appearance). When the terminal is too narrow to place it, a toast says so; /swiftui-preview reopens the pane with the last render.
[ − ] [ 100% ] [ + ] beside the label zoom from 50% to 400%; click the percentage to reset. With the pane focused (click it), i zooms in, o out, 0 resets. Zoomed in, the picture can outgrow the pane's height, which scrolls, but never its width. The terminal passes no pinch to apps, so a trackpad scrolls the pane but does not zoom it.
python3 (with ps), once per render, through $.process, to measure the terminal's cell in pixels so a view shows at its real size. Claude Code's SDK has no other way to learn it.$.fs, and pads it in memory; writes no files.claude plugin validate .
claude plugin test .
MIT
hooks/register.tsx 102 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Shot } from '../types'
5import { CELL_SCRIPT, fitImage, fromBase64, padTop, parseRendered, pngInfo, stepZoom, toBase64, variantLabel } from './lib'
6import type { Cell } from './lib'
7
8const PANE = 'swiftui-preview'
9const TITLE = 'SwiftUI Preview'
10const shot = atom({ plugin: 'swiftui-preview', key: 'shot' } as const, null)
11const zoom = atom({ plugin: 'swiftui-preview', key: 'zoom' } as const, 1)
12
13// The terminal's cell in screen points; a guess until measured.
14let cell: Cell = { width: 8, height: 17 }
15async function measureCell($: EngineInterface) {
16 const run = await $.process.run(['python3', '-c', CELL_SCRIPT]).catch(() => undefined)
17 const [x, y] = (run?.stdout ?? '').split(' ').map(Number)
18 // ponytail: assumes a 2x (Retina) display; read the backing scale if a 1x screen shows up
19 if (x && y) cell = { width: x / 2, height: y / 2 }
20}
21
22// The snapshot with rows on top to fill the pane box, base64, kept for the renders that follow.
23let padded: { key: string; png?: string } = { key: '' }
24async function pad($: EngineInterface, current: Shot, rows: number) {
25 const key = `${current.path}@${current.generation}+${rows}`
26 if (padded.key !== key) {
27 const read = await $.fs.read(current.path, { as: 'bytes' }).catch(() => undefined)
28 const png = read && padTop(fromBase64(read.base64), rows)
29 // `{ png }` takes at most 2 MiB; past it, or unpadded, the box stretches the snapshot a little.
30 padded = { key, png: png && png.length <= 2 * 1024 * 1024 ? toBase64(png) : undefined }
31 }
32
33 return padded.png
34}
35
36export const register: Register = on => {
37 on('session.start', async ($, e, next) => {
38 await $.command.register({ name: 'swiftui-preview', description: 'Show the last SwiftUI preview' })
39
40 return next(e)
41 })
42
43 on('command.run', { command: 'swiftui-preview' }, async $ => {
44 await $.ui.open({ id: PANE, title: TITLE })
45
46 return { text: 'SwiftUI preview pane opened.' }
47 })
48
49 // Xcode MCP's RenderPreview (`claude mcp add xcode -- xcrun mcpbridge`), whatever the server is named.
50 on('tool.call', async ($, e, next) => {
51 const ran = await next(e)
52 if (!e.tool.endsWith('__RenderPreview') || ran.isError) return ran
53 const rendered = parseRendered(ran.text)
54 if (!rendered) return ran
55 try {
56 const size = pngInfo(fromBase64((await $.fs.read(rendered.path, { as: 'bytes' })).base64))
57 if (!size) throw new Error(`no PNG at ${rendered.path}`)
58 await measureCell($)
59 const label = [rendered.label, ...variantLabel(e)].filter(Boolean).join(' · ')
60 await update($, shot, () => ({ ...rendered, ...size, label, generation: Date.now() }) satisfies Shot)
61 // Opened unasked, the pane waits for a wide enough terminal: say where the preview is.
62 const { isPlaced } = await $.ui.open({ id: PANE, title: TITLE })
63 if (!isPlaced) $.ui.toast('SwiftUI preview ready: /swiftui-preview to show it')
64 } catch (err) {
65 // The pane is a bonus: never fail the model's call over it, but say the pane is stale.
66 $.ui.toast(`SwiftUI Preview not updated: ${err instanceof Error ? err.message : String(err)}`)
67 }
68
69 return ran
70 })
71
72 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
73 const current = await read($, shot)
74 if (e.surface !== 'terminal') {
75 const { Text } = $.ui.resolve(e)
76 return <Text>{current ? `Preview saved to ${current.path}` : 'No preview yet.'}</Text>
77 }
78 const { Box, Button, Text, Image } = $.ui.resolve(e)
79 if (!current) return <Text dimColor>No preview yet. Ask Claude to preview a view.</Text>
80 const z = await read($, zoom)
81 const fit = fitImage(current.width, current.height, current.scale, cell, e.props.bodyColumns, e.props.scroll.bodyRows - 1, z)
82 const png = fit.height > current.height ? await pad($, current, fit.height - current.height) : undefined
83
84 return (
85 <Box flexDirection="column" alignItems="center">
86 <Box gap={1}>
87 <Text dimColor wrap="truncate">{current.label}</Text>
88 <Button hotkey="o" onPress={() => void update($, zoom, v => stepZoom(v, -1))}>−</Button>
89 <Button key="zoom" hotkey="0" onPress={() => void update($, zoom, () => 1)}>{`${z * 100}%`}</Button>
90 <Button hotkey="i" onPress={() => void update($, zoom, v => stepZoom(v, 1))}>+</Button>
91 </Box>
92 <Image
93 source={png ? { png } : { file: current.path, format: 'png', generation: current.generation }}
94 columns={fit.columns}
95 rows={fit.rows}
96 alt={`SwiftUI preview: ${current.path}`}
97 />
98 </Box>
99 )
100 })
101}
102hooks/lib.ts 192 lines1// Pure helpers: reading Xcode's RenderPreview answer and sizing the pane.
2
3export type Rendered = { path: string; label: string }
4
5// Xcode MCP's RenderPreview answers JSON text; undefined when it rendered nothing.
6export function parseRendered(text: string | undefined): Rendered | undefined {
7 try {
8 const out = JSON.parse(text ?? '') as {
9 previewSnapshotPath?: string
10 displayName?: string
11 renderedDestination?: { deviceModelName?: string }
12 }
13 if (!out.previewSnapshotPath) return undefined
14 const device = out.renderedDestination?.deviceModelName
15
16 return { path: out.previewSnapshotPath, label: [out.displayName, device].filter(Boolean).join(' · ') }
17 } catch {
18 return undefined
19 }
20}
21
22// The RenderPreview arguments that change the picture, for the label: `Dark Appearance · AX 3 · uk`.
23// Takes the whole `tool.call` input, whose type knows nothing of an MCP tool's arguments.
24export function variantLabel(input: object): string[] {
25 const args = input as { previewVariantOverrides?: Record<string, unknown>; previewLocalizationOverride?: unknown }
26
27 return [...Object.values(args.previewVariantOverrides ?? {}), args.previewLocalizationOverride]
28 .filter((v): v is string => typeof v === 'string' && v !== '')
29}
30
31// PNG is read and padded here, so the mod needs no image tool.
32type Chunk = { type: string; data: Uint8Array }
33
34const view = (d: Uint8Array) => new DataView(d.buffer, d.byteOffset, d.byteLength)
35
36function chunks(png: Uint8Array): Chunk[] {
37 const out: Chunk[] = []
38 for (let i = 8; i + 12 <= png.length; i += 12 + view(png).getUint32(i)) {
39 const n = view(png).getUint32(i)
40 out.push({ type: String.fromCharCode(...png.subarray(i + 4, i + 8)), data: png.subarray(i + 8, i + 8 + n) })
41 }
42
43 return out
44}
45
46// Width, height and pixels per point (Xcode tags @3x as 216 dpi, @2x as 144, in pHYs as pixels
47// per metre); @3x when untagged or tagged 72 dpi; undefined when it is no PNG.
48export function pngInfo(png: Uint8Array): { width: number; height: number; scale: number } | undefined {
49 if (String.fromCharCode(...png.subarray(1, 4)) !== 'PNG') return undefined
50 const all = chunks(png)
51 const ihdr = all.find(c => c.type === 'IHDR')?.data
52 if (!ihdr || ihdr.length < 13) return undefined
53 const phys = all.find(c => c.type === 'pHYs')?.data
54 const scale = phys?.length === 9 && phys[8] === 1 ? Math.round((view(phys).getUint32(0) * 0.0254) / 72) : 0
55
56 return { width: view(ihdr).getUint32(0), height: view(ihdr).getUint32(4), scale: scale > 1 ? scale : 3 }
57}
58
59const concat = (parts: Uint8Array[]) => {
60 const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0))
61 parts.reduce((at, p) => (out.set(p, at), at + p.length), 0)
62
63 return out
64}
65
66const u32 = (n: number) => {
67 const out = new Uint8Array(4)
68 view(out).setUint32(0, n)
69
70 return out
71}
72
73const CRC = Array.from({ length: 256 }, (_, n) => {
74 for (let k = 0; k < 8; k++) n = n & 1 ? 0xedb88320 ^ (n >>> 1) : n >>> 1
75
76 return n >>> 0
77})
78
79function chunk(type: string, data: Uint8Array) {
80 const body = concat([Uint8Array.from(type, c => c.charCodeAt(0)), data])
81 let crc = 0xffffffff
82 for (const b of body) crc = CRC[(crc ^ b) & 255]! ^ (crc >>> 8)
83
84 return concat([u32(data.length), body, u32((crc ^ 0xffffffff) >>> 0)])
85}
86
87// zlib's adler32_combine: the Adler-32 of A then B from each one's and B's length.
88function adlerCombine(a: number, b: number, lengthB: number) {
89 const BASE = 65521
90 const rem = lengthB % BASE
91 const s1 = (a & 0xffff) + (b & 0xffff) + BASE - 1
92 const s2 = ((rem * (a & 0xffff)) % BASE) + (a >>> 16) + (b >>> 16) + BASE - rem
93
94 return ((s2 % BASE) * 65536 + (s1 % BASE)) >>> 0
95}
96
97// The PNG with `rows` transparent rows on top; undefined unless 8-bit RGBA, not interlaced, as
98// Xcode writes. Nothing is decoded: the rows go in as stored deflate blocks ahead of Xcode's own,
99// and a transparent row is zeros, which the first row's filters already assume above it.
100export function padTop(png: Uint8Array, rows: number): Uint8Array | undefined {
101 const info = pngInfo(png)
102 const all = chunks(png)
103 const ihdr = all.find(c => c.type === 'IHDR')?.data
104 if (!info || !ihdr || ihdr[8] !== 8 || ihdr[9] !== 6 || ihdr[12] !== 0) return undefined
105 const zlib = concat(all.filter(c => c.type === 'IDAT').map(c => c.data))
106 // A preset dictionary (FDICT) would sit before the deflate data.
107 if (zlib.length < 6 || zlib[1]! & 0x20) return undefined
108 const rowBytes = 1 + info.width * 4
109 const length = rows * rowBytes
110 const blocks: Uint8Array[] = []
111 for (let at = 0; at < length; at += 65535) {
112 const n = Math.min(65535, length - at)
113 // Not final, stored: a zero header byte, then LEN and its complement, little-endian.
114 const block = new Uint8Array(5 + n)
115 block.set([0, n & 255, n >> 8, (n ^ 0xffff) & 255, (n ^ 0xffff) >> 8])
116 blocks.push(block)
117 }
118 // The Adler-32 of `length` zeros is 1, with its second sum `length`.
119 const adler = adlerCombine(((length % 65521) * 65536 + 1) >>> 0, view(zlib).getUint32(zlib.length - 4), info.height * rowBytes)
120 const idat = concat([zlib.subarray(0, 2), ...blocks, zlib.subarray(2, -4), u32(adler)])
121 const header = ihdr.slice()
122 view(header).setUint32(4, info.height + rows)
123 const isIdat = (c: Chunk) => c.type === 'IDAT'
124 const first = all.findIndex(isIdat)
125
126 return concat([
127 png.subarray(0, 8),
128 ...all.map((c, i) =>
129 i === first ? chunk('IDAT', idat) : isIdat(c) ? new Uint8Array() : chunk(c.type, c.type === 'IHDR' ? header : c.data)),
130 ])
131}
132
133export const fromBase64 = (text: string) => Uint8Array.from(atob(text), c => c.charCodeAt(0))
134
135export function toBase64(bytes: Uint8Array) {
136 let text = ''
137 for (let i = 0; i < bytes.length; i += 0x8000) text += String.fromCharCode(...bytes.subarray(i, i + 0x8000))
138
139 return btoa(text)
140}
141
142const clamp = (n: number) => Math.max(1, Math.min(255, n))
143
144// A terminal cell in screen points: what `CELL_SCRIPT` prints, halved for a 2x display.
145export type Cell = { width: number; height: number }
146
147// Prints a cell's size in device pixels (`x y`) from the tty of the nearest ancestor that has one.
148export const CELL_SCRIPT = `
149import fcntl, os, struct, subprocess, termios
150p = os.getppid()
151while p > 1:
152 tty, ppid = (subprocess.run(['ps', '-o', 'tty=,ppid=', '-p', str(p)], capture_output=True, text=True).stdout.split() + ['', '1'])[:2]
153 if tty not in ('', '??'): break
154 p = int(ppid)
155rows, cols, x, y = struct.unpack('HHHH', fcntl.ioctl(os.open('/dev/' + tty, os.O_RDONLY | os.O_NOCTTY), termios.TIOCGWINSZ, bytes(8)))
156print(x / cols, y / rows)
157`
158
159// At 100% the view's own size in points is pixels / scale, shown 1:1 in screen points like
160// Xcode's canvas, shrunk to fit the pane and never enlarged (that pixelates).
161// ponytail: Xcode caps a snapshot's long side at 1500 px (a whole device screen), so a capped one
162// is only fit to the pane, enlarged on a tall one; read the real scale from the device model if that ever matters.
163// Zoomed in, the picture may outgrow the pane's height, which scrolls; never its width.
164// `Image` fills its columns×rows box, so `height` is the snapshot's padded to the box's aspect; rows
165// are rounded up, so only ever the height.
166export function fitImage(width: number, height: number, scale: number, cell: Cell, columns: number, rows: number, zoom = 1) {
167 const isCapped = Math.max(width, height) >= 1500
168 const rowsPerColumn = (height / width) * (cell.width / cell.height)
169 const natural = isCapped ? Math.min(columns, rows / rowsPerColumn) : width / scale / cell.width
170 const maxRows = zoom > 1 ? 255 : rows
171 // Floored to the pane, so the rows derived from it never exceed `maxRows`.
172 const c = clamp(Math.min(Math.round(natural * zoom), Math.floor(columns), Math.floor(maxRows / rowsPerColumn)))
173 // Capped too: in floating point `c * rowsPerColumn` can land a hair above `maxRows`.
174 const r = clamp(Math.min(Math.ceil(c * rowsPerColumn), Math.floor(maxRows)))
175 const aspect = (c * cell.width) / (r * cell.height)
176
177 return {
178 columns: c,
179 rows: r,
180 height: Math.max(height, Math.round(width / aspect)),
181 }
182}
183
184export const ZOOMS = [0.5, 0.75, 1, 1.5, 2, 3, 4]
185
186// The next zoom step in or out from `zoom`, held at the ends.
187export function stepZoom(zoom: number, by: 1 | -1): number {
188 const next = by > 0 ? ZOOMS.find(z => z > zoom) : [...ZOOMS].reverse().find(z => z < zoom)
189
190 return next ?? zoom
191}
192types/index.d.ts 16 lines1export type Shot = {
2 path: string
3 width: number
4 height: number
5 /** Pixels per point: 3 for an iPhone, 2 for an iPad. */
6 scale: number
7 label: string
8 generation: number
9}
10
11declare module 'claude-code' {
12 interface PluginState {
13 'swiftui-preview': { shot: Shot | null; zoom: number }
14 }
15}
16