Pasted images shown as a scrollable shelf above the prompt, even in iTerm2 + tmux; click one to mark it up

繁體中文 | English

Claude Code 的 mod(外掛)。貼上的圖片會排在輸入框左上方,顯示成真正的縮圖;點一下就能畫圈、加箭頭、寫字、裁切,Claude 收到的是標註過的版本。
在終端機裡,貼上的圖片只會顯示成 [Image #3],貼了幾張之後就分不清哪張是哪張。Claude Code 內建的圖片元件只在 Ghostty、kitty 這類終端機畫得出來,iTerm2 和 tmux 裡看不到。image-shelf 在那種環境改用一個浮在終端機上方的透明小視窗來顯示圖片,像桌寵一樣。
在 Claude Code 的輸入框打:
/plugin install image-shelf --marketplace olilllioli287/claude-code-image-shelf
問要不要加入來源時按 y,範圍選 user。第一次貼圖會花幾秒編譯浮動視窗和編輯器。
/plugin uninstall image-shelf@image-shelf
想連來源一起移除:/plugin marketplace remove image-shelf。之後要再裝,照上面的安裝指令再打一次就好,可以重複。
不會留下東西在你的設定裡:編譯出來的程式放在 /private/tmp/image-shelf/(重開機會自動清掉);只有你自己建立了 ~/.config/image-shelf.json 才需要手動刪。
xcode-select --install),用來編譯浮動視窗.heic / .heif 轉成 PNG,一樣排在架子上(標成「HEIC 1」),可以點開標註;送出時 Claude 會被告知去讀轉好的 PNGpanel/shelf.swift)把圖片蓋在那些列上[-];列從視窗頂端開始的位移,用截一條細長畫面、找兩條白線量出來[-](收合按鈕)用一塊終端機背景色的小視窗蓋住,滑鼠可穿透~/.config/image-shelf.json:
{ "dx": 0, "dy": -5.5 }
dy 是圖片相對白線的上下位移(點,負數往上)。預設值是在 Noto Sans Mono CJK TC 20、行高 0.96 下調的,字型不同可能要微調。
目前只支援 macOS,最需要 Windows 和 Linux 的幫手。運作原理看 ARCHITECTURE.md,怎麼參與看 CONTRIBUTING.md。
標註編輯器(editor/)取自 alan890104/claude-code-paste-preview(MIT),未修改。
MIT
A Claude Code mod that shows the images you paste as real thumbnails above the prompt, on the left, and lets you mark one up with a click.
Claude Code's own Image element draws only in terminals with the kitty graphics protocol (Ghostty, kitty), and never through tmux. image-shelf draws there when it can, and in iTerm2 (with or without tmux) it floats a transparent borderless window over blank rows it reserves above the prompt.
Install (in Claude Code): /plugin install image-shelf --marketplace olilllioli287/claude-code-image-shelf
Needs: macOS, Xcode Command Line Tools, iTerm2 with Screen Recording permission (to measure where rows start), or Ghostty/kitty outside tmux.
Use: paste as usual (no popup); swipe or Shift+wheel to scroll a long row; click a picture to annotate it (pen, ellipse, box, arrow, text, crop, rotate). An edited picture gets an orange border; on send, Claude is told to read the edited file. HEIC photos, which Claude Code does not attach (a path to one stays text), are converted to PNG, shown on the shelf as "HEIC 1", and Claude is told to read the PNG.
Uninstall: /plugin uninstall image-shelf@image-shelf (and /plugin marketplace remove image-shelf); reinstall with the install line above.
Tuning: ~/.config/image-shelf.json → { "dx": 0, "dy": -5.5 } (points; negative moves up).
Contributing: macOS only for now; Windows and Linux help wanted. See ARCHITECTURE.md and CONTRIBUTING.md.
The markup editor (editor/) is from alan890104/claude-code-paste-preview (MIT), unmodified.
hooks/register.tsx 511 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Shot } from '../types'
5
6// image-shelf: each [Image #N] in the prompt box shows on a shelf at the left above the
7// prompt. Nothing opens on paste. Pressing an image opens a copy of it in Preview, whose
8// Markup tools draw on it; once Preview saves (Cmd+S, or on close), the shelf marks it
9// edited and, at Enter, Claude is told to read the edited copy.
10//
11// Claude Code writes each paste to /private/tmp/claude-<uid>/<project>/<session>/images/
12// <N>.png; that is its internal layout, not an API. The picture itself is drawn only
13// where the terminal can (Ghostty, kitty, WezTerm, outside tmux); elsewhere the shelf
14// shows a button per image, and a floating window of our own (panel/shelf.swift, as a
15// desktop pet sits over the screen) shows the pictures over blank rows the band holds.
16
17const shots = atom({ plugin: 'image-shelf', key: 'shots' } as const, [])
18const inBox = atom({ plugin: 'image-shelf', key: 'inBox' } as const, [])
19// Rows the floating window's grid takes; the band holds that many blank rows.
20const roomRows = atom({ plugin: 'image-shelf', key: 'roomRows' } as const, 4)
21
22const PLACEHOLDER = /\[Image #(\d+)\]/g
23// A terminal cell is about twice as tall as it is wide.
24const CELL = 2
25const ROWS = 6
26
27type Setup = { edits: string; tmp: string; session: string; canDraw: boolean; tmuxPane: string; home: string }
28
29// Rows the floating window's pictures take, and what sits under the band down to the
30// pane's bottom (the buttons sit above the pictures): a spacer, the prompt between its two rules,
31// and the status lines. ~/.config/image-shelf.json may say otherwise (dx, dy in points).
32const PANEL_ROWS = 4
33type Tuning = { dx: number; dy: number; statusLines: number; spacer: number }
34const TUNING: Tuning = { dx: 0, dy: -5.5, statusLines: 1, spacer: 0 }
35
36// Module variables start over on a hot reload; everything a drawing reads is in $.state.
37let setup: Promise<Setup> | undefined
38let images: string | undefined
39let isTicking = false
40let panel: Promise<string | undefined> | undefined
41let isPanelUp = false
42let lastShelf = ''
43// What the band last drew with, so the tick can keep the floating window in step as
44// the prompt grows or shrinks between draws.
45let lastColumns = 80
46let lastMaxRows = 0
47let lastShown = false
48const capturing = new Set<number>()
49const thumbs = new Map<string, string>()
50
51// What went wrong, for a session whose shelf stays empty: `claude --debug` shows it in the
52// debug log, and this file has it either way. A failure is not kept: the next look tries again.
53const ERRORS = '/private/tmp/image-shelf/errors.log'
54// A Swift build that failed is tried again this long after, not at every tick.
55const RETRY_MS = 30_000
56const reported = new Map<string, string>()
57let writing = Promise.resolve()
58let setupFailures = 0
59
60const report = ($: EngineInterface, where: string, err: unknown) => {
61 const text = err instanceof Error ? err.message : String(err)
62 // The tick comes every 0.7 s: a failure that keeps happening is written once.
63 if (reported.get(where) === text) return
64 reported.set(where, text)
65 $.ui.log(`image-shelf ${where}: ${text}`, { to: 'debug' })
66 writing = writing.then(async () => {
67 const session = await $.session.id().catch(() => '-')
68 const old = await $.fs.read(ERRORS).catch(() => '')
69 const lines = [...old.split('\n').filter(line => line !== ''), `${new Date().toISOString()} ${session.slice(0, 8)} ${where}: ${text}`]
70 await $.fs.write(ERRORS, `${lines.slice(-200).join('\n')}\n`)
71 }).catch(() => undefined)
72}
73
74// Working again: the same failure, should it come back, is written again.
75const recovered = (where: string) => void reported.delete(where)
76
77const numbersIn = (text: string) => [...new Set([...text.matchAll(PLACEHOLDER)].map(m => Number(m[1])))]
78
79// HEIC / HEIF photos (what an iPhone takes): Claude Code does not take them as images, so a
80// path to one stays text in the box. Such a path, typed, pasted or dragged in (quoted, or with
81// spaces escaped), gets a converted PNG on the shelf like a paste, under a number of its own
82// below zero so it never meets an [Image #N].
83const HEIC_PATH = /'([^'\n]+\.hei[cf])'|"([^"\n]+\.hei[cf])"|((?:~|\/)(?:\\.|[^\s'"\\])+\.hei[cf])(?![\w.])/gi
84const heicIds = new Map<string, number>()
85const heicPaths = new Map<number, string>()
86
87// The HEIC paths a prompt names, as files: quotes taken off, escapes undone, ~ made home.
88export const heicPathsIn = (text: string, home: string) => [...new Set([...text.matchAll(HEIC_PATH)].map(m => {
89 const raw = m[1] ?? m[2] ?? (m[3] ?? '').replace(/\\(.)/g, '$1')
90 return raw.startsWith('~/') ? `${home}${raw.slice(1)}` : raw
91}))]
92
93const heicsIn = async ($: EngineInterface, text: string) => {
94 const { home } = await setUp($)
95 const found: { n: number; path: string }[] = []
96 for (const path of heicPathsIn(text, home)) {
97 if (!(await $.fs.exists(path).catch(() => false))) continue
98 let n = heicIds.get(path)
99 if (n === undefined) {
100 n = -(heicIds.size + 1)
101 heicIds.set(path, n)
102 heicPaths.set(n, path)
103 }
104 found.push({ n, path })
105 }
106 return found
107}
108
109const isSame = (a: readonly number[], b: readonly number[]) => a.length === b.length && a.every((n, i) => n === b[i])
110
111// Claude Code can move a session into its background host, which starts it again without
112// the terminal's environment (no TMUX, TMUX_PANE, TERM_PROGRAM). The host still runs under
113// the claude the pane started, so the pane is the one whose shell is among our ancestors.
114const paneOfAncestors = async ($: EngineInterface) => {
115 const tmux = ['/opt/homebrew/bin/tmux', '/usr/local/bin/tmux', '/usr/bin/tmux']
116 let bin = 'tmux'
117 for (const path of tmux) if (await $.fs.exists(path).catch(() => false)) { bin = path; break }
118 const [panes, tree, me] = await Promise.all([
119 $.process.run([bin, 'list-panes', '-a', '-F', '#{pane_pid} #{pane_id}']),
120 $.process.run(['ps', '-A', '-o', 'pid=,ppid=']),
121 $.process.run(['sh', '-c', 'echo $PPID']),
122 ])
123 if (panes.exitCode !== 0 || tree.exitCode !== 0) return ''
124 const paneOf = new Map(panes.stdout.trim().split('\n').map(l => l.trim().split(' ') as [string, string]))
125 const parentOf = new Map(tree.stdout.trim().split('\n').map(l => l.trim().split(/\s+/) as [string, string]))
126 let pid = me.stdout.trim()
127 for (let i = 0; i < 40 && pid !== '' && pid !== '0' && pid !== '1'; i++) {
128 const pane = paneOf.get(pid)
129 if (pane !== undefined) return pane
130 pid = parentOf.get(pid) ?? ''
131 }
132 return ''
133}
134
135const setUp = ($: EngineInterface) => {
136 if (setup !== undefined) return setup
137 const attempt = (async () => {
138 const session = await $.session.id()
139 const uid = (await $.process.run(['id', '-u'])).stdout.trim()
140 const edits = `/private/tmp/image-shelf/${session.slice(0, 8)}`
141 await $.process.run(['mkdir', '-p', edits])
142 const [program, term, tmux, envPane, home] = await Promise.all([$.env.get('TERM_PROGRAM'), $.env.get('TERM'), $.env.get('TMUX'), $.env.get('TMUX_PANE'), $.env.get('HOME')])
143 const tmuxPane = tmux ? (envPane ?? '') : await paneOfAncestors($).catch(() => '')
144 const canDraw = !tmux && tmuxPane === '' && (/^(ghostty|wezterm)$/i.test(program ?? '') || /kitty|ghostty/i.test(term ?? ''))
145 return { edits, tmp: `/private/tmp/claude-${uid}`, session, canDraw, tmuxPane, home: home ?? '' }
146 })()
147 setup = attempt
148 attempt.then(() => {
149 setupFailures = 0
150 recovered('setup')
151 }, err => {
152 if (setup === attempt) setup = undefined
153 setupFailures += 1
154 report($, 'setup', err)
155 if (setupFailures === 5) $.ui.toast(`image-shelf 啟動失敗,還在重試(記錄在 ${ERRORS})`)
156 })
157 return attempt
158}
159
160// A /clear (or a resume into another conversation) goes on under a new session id, and
161// Claude Code puts the pastes in that session's folder: what was tied to the old one starts over.
162const forget = async ($: EngineInterface) => {
163 const was = await setup?.catch(() => undefined)
164 setup = undefined
165 images = undefined
166 lastShelf = ''
167 capturing.clear()
168 thumbs.clear()
169 await update($, shots, () => [])
170 await update($, inBox, () => [])
171 // The old floating window reads the old shelf.json; the next paste starts one for the new.
172 if (was !== undefined) await $.process.run(['pkill', '-f', `image-shelf/bin/shelf-[0-9a-f]+ ${was.edits}/shelf.json`]).catch(() => undefined)
173}
174
175// <tmp>/<project>/<session>/images, whichever project folder holds this session.
176const imagesOf = async ($: EngineInterface, tmp: string, session: string) => {
177 for (const entry of await $.fs.list(tmp).catch(() => [])) {
178 if (entry.kind === 'file') continue
179 const at = `${tmp}/${entry.name}/${session}/images`
180 if (await $.fs.exists(at).catch(() => false)) return at
181 }
182 return undefined
183}
184
185// Claude Code's copy lands a moment after the placeholder does.
186const engineCopy = async ($: EngineInterface, n: number) => {
187 const { tmp, session } = await setUp($)
188 for (let attempt = 0; attempt < 120; attempt++) {
189 images ??= await imagesOf($, tmp, session)
190 if (images !== undefined) {
191 const entry = (await $.fs.list(images).catch(() => [])).find(e => new RegExp(`^${n}\\.[a-z]+$`).test(e.name))
192 if (entry !== undefined) return `${images}/${entry.name}`
193 }
194 await $.clock.sleep(50)
195 }
196 return undefined
197}
198
199// Size and a small PNG for the shelf: a screenshot can be 10 MB, the shelf needs 480 px.
200const look = async ($: EngineInterface, n: number, file: string, gen: number) => {
201 const { edits } = await setUp($)
202 const info = await $.process.run(['sips', '-g', 'pixelWidth', '-g', 'pixelHeight', file])
203 const width = Number(/pixelWidth: (\d+)/.exec(info.stdout)?.[1] ?? 0)
204 const height = Number(/pixelHeight: (\d+)/.exec(info.stdout)?.[1] ?? 0)
205 const thumb = `${edits}/${n}.thumb-${gen}.png`
206 const made = await $.process.run(['sips', '-s', 'format', 'png', '-Z', '480', file, '--out', thumb])
207 return made.exitCode === 0 && width > 0 && height > 0 ? { width, height, thumb } : undefined
208}
209
210const mtimeOf = async ($: EngineInterface, file: string) => (await $.fs.stat(file).catch(() => undefined))?.mtimeMs ?? 0
211
212// A new paste: copy it where Preview may write, so the original stays as pasted.
213// A HEIC path: a PNG of it where Preview may write (at most 2400 px, a phone photo is 4000).
214const captureHeic = async ($: EngineInterface, n: number, source: string) => {
215 const { edits } = await setUp($)
216 const copy = `${edits}/heic${-n}.png`
217 const made = await $.process.run(['sips', '-s', 'format', 'png', '-Z', '2400', source, '--out', copy])
218 if (made.exitCode !== 0) return
219 const seen = await look($, n, copy, 0)
220 const shot: Shot = { n, copy, thumb: seen?.thumb ?? '', madeAt: await mtimeOf($, copy), isEdited: false, gen: 0, width: seen?.width ?? 0, height: seen?.height ?? 0, label: `HEIC ${-n}`, source }
221 await update($, shots, list => [...list.filter(s => s.n !== n), shot])
222}
223
224const nameOf = (n: number, shot?: Shot) => shot?.label ?? (n < 0 ? `HEIC ${-n}` : `#${n}`)
225
226const capture = async ($: EngineInterface, n: number) => {
227 const found = await engineCopy($, n)
228 if (found === undefined) return
229 const { edits } = await setUp($)
230 const copy = `${edits}/${n}.png`
231 const made = await $.process.run(['sips', '-s', 'format', 'png', found, '--out', copy])
232 if (made.exitCode !== 0) return
233 const seen = await look($, n, copy, 0)
234 const shot: Shot = { n, copy, thumb: seen?.thumb ?? '', madeAt: await mtimeOf($, copy), isEdited: false, gen: 0, width: seen?.width ?? 0, height: seen?.height ?? 0 }
235 await update($, shots, list => [...list.filter(s => s.n !== n), shot])
236}
237
238// Preview saved: the copy's mtime moved on. Remake the thumbnail and mark it edited.
239const watchEdits = async ($: EngineInterface) => {
240 for (const shot of await read($, shots)) {
241 if (shot.copy === '') continue
242 const at = await mtimeOf($, shot.copy)
243 const last = shot.madeAt
244 if (at === 0 || at === last) continue
245 const gen = shot.gen + 1
246 const seen = await look($, shot.n, shot.copy, gen).catch(() => undefined)
247 await update($, shots, list => list.map(s => (s.n === shot.n ? { ...s, madeAt: at, isEdited: true, gen, thumb: seen?.thumb ?? s.thumb, width: seen?.width ?? s.width, height: seen?.height ?? s.height } : s)))
248 }
249}
250
251// Numbers run up through a session, so only an unknown N is a new paste.
252const sync = async ($: EngineInterface, text: string) => {
253 // No session.start fires after a /clear, so the id is checked on every look at the box.
254 if (setup !== undefined && (await setup).session !== (await $.session.id())) await forget($)
255 await setUp($)
256 const ns = [...numbersIn(text), ...(await heicsIn($, text)).map(h => h.n)]
257 if (!isSame(ns, await read($, inBox))) await update($, inBox, () => ns)
258 const known = await read($, shots)
259 for (const n of ns) {
260 if (capturing.has(n) || known.some(s => s.n === n)) continue
261 capturing.add(n)
262 const source = heicPaths.get(n)
263 void (n < 0 && source !== undefined ? captureHeic($, n, source) : capture($, n)).finally(() => capturing.delete(n))
264 }
265}
266
267const tick = async ($: EngineInterface) => {
268 if (isTicking) return
269 isTicking = true
270 try {
271 await sync($, (await $.prompt.read()).text)
272 await watchEdits($)
273 const { canDraw } = await setUp($)
274 if (!canDraw) {
275 const ns = await read($, inBox)
276 // In the prompt's order, as the band writes it: shots is in the order copies finished.
277 const all = await read($, shots)
278 await writeShelf($, ns.flatMap(n => all.filter(s => s.n === n)), lastShown && ns.length > 0, lastColumns)
279 const { edits } = await setUp($)
280 const told = Number(/"rows":(\d+)/.exec(await $.fs.read(`${edits}/layout.json`).catch(() => ''))?.[1] ?? PANEL_ROWS)
281 if (told !== (await read($, roomRows))) await update($, roomRows, () => told)
282 }
283 recovered('tick')
284 } finally {
285 isTicking = false
286 }
287}
288
289const open = async ($: EngineInterface, n: number) => {
290 const shot = (await read($, shots)).find(s => s.n === n)
291 if (shot === undefined || shot.copy === '') {
292 $.ui.toast(`${n < 0 ? nameOf(n, shot) : `Image #${n}`} 還在準備,等一下再點`)
293 return
294 }
295 // The editor writes the edit over the copy; its new mtime marks it edited.
296 const binary = await buildEditor($)
297 if (binary === undefined) {
298 await $.process.run(['open', '-a', 'Preview', shot.copy])
299 return
300 }
301 await $.process.run([binary, `${$.plugin.root}/editor/editor.html`, shot.copy, shot.copy, shot.label ?? `Image #${n}`, 'zh-Hant'], { timeoutMs: 3_600_000 }).catch(() => undefined)
302}
303
304const pictureOf = async ($: EngineInterface, shot: Shot) => {
305 const held = thumbs.get(shot.thumb)
306 if (held !== undefined) return held
307 const { base64 } = await $.fs.read(shot.thumb, { as: 'bytes' })
308 thumbs.set(shot.thumb, base64)
309 return base64
310}
311
312// What a failed command said: its error lines, or its last lines when it marked none.
313const tail = (text: string) => {
314 const lines = text.trim().split('\n').map(line => line.trim())
315 const errors = lines.filter(line => line.includes('error:'))
316 return (errors.length > 0 ? errors : lines).slice(-3).join(' / ')
317}
318
319// A Swift program of the mod's, compiled once per version of its source and named by it.
320const build = async ($: EngineInterface, source: string, name: string) => {
321 const text = await $.fs.read(source)
322 const digest = [...new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)))].slice(0, 6).map(b => b.toString(16).padStart(2, '0')).join('')
323 const binary = `/private/tmp/image-shelf/bin/${name}-${digest}`
324 if (await $.fs.exists(binary).catch(() => false)) return binary
325 await $.process.run(['mkdir', '-p', '/private/tmp/image-shelf/bin'])
326 const part = `${binary}.${crypto.randomUUID().slice(0, 8)}`
327 const made = await $.process.run(['xcrun', 'swiftc', '-O', source, '-o', part], { timeoutMs: 180_000 })
328 if (made.exitCode !== 0) throw new Error(`swiftc ${name}.swift: ${tail(made.stderr)}`)
329 const moved = await $.process.run(['mv', '-f', part, binary])
330 if (moved.exitCode !== 0) throw new Error(`mv ${name}: ${tail(moved.stderr)}`)
331 return binary
332}
333
334// The floating window, and the markup editor (editor/, from paste-preview, MIT).
335const buildPanel = ($: EngineInterface) => build($, `${$.plugin.root}/panel/shelf.swift`, 'shelf')
336let editor: Promise<string | undefined> | undefined
337let editorRetryAt = 0
338const buildEditor = ($: EngineInterface) => {
339 if (editor === undefined && Date.now() < editorRetryAt) return Promise.resolve(undefined)
340 editor ??= build($, `${$.plugin.root}/editor/editor.swift`, 'editor').catch(err => {
341 report($, 'editor', err)
342 editorRetryAt = Date.now() + RETRY_MS
343 editor = undefined
344 return undefined
345 })
346 return editor
347}
348
349const tuningOf = async ($: EngineInterface, home: string): Promise<Tuning> => {
350 const text = await $.fs.read(`${home}/.config/image-shelf.json`).catch(() => '')
351 try {
352 return { ...TUNING, ...(text === '' ? {} : JSON.parse(text)) }
353 } catch {
354 return TUNING
355 }
356}
357
358// Started the first time there is something to show; it quits with Claude Code.
359let panelRetryAt = 0
360let isPanelFailureShown = false
361const startPanel = ($: EngineInterface, shelfFile: string) => {
362 if (panel === undefined && Date.now() < panelRetryAt) return Promise.resolve(undefined)
363 panel ??= (async () => {
364 const binary = await buildPanel($)
365 isPanelUp = true
366 const startedAt = Date.now()
367 void (async () => {
368 const child = $.process.spawn({ argv: [binary, shelfFile] })
369 try {
370 for await (const _ of child) { /* it says nothing */ }
371 const { code, signal } = await child.result
372 // pkill, on a reload or a /clear, ends it with SIGTERM; it quits by itself with 0.
373 const isCrash = signal === null ? code !== 0 : !['SIGTERM', 'SIGKILL', 'SIGHUP', 'SIGINT'].includes(signal)
374 if (isCrash) {
375 report($, 'panel', `shelf ended with ${signal ?? `code ${code}`}`)
376 // One that dies right away waits before it starts again, not 0.7 s.
377 if (Date.now() - startedAt < 5_000) panelRetryAt = Date.now() + RETRY_MS
378 } else if (Date.now() - startedAt >= 5_000) {
379 recovered('panel')
380 }
381 } catch (err) {
382 report($, 'panel', err)
383 panelRetryAt = Date.now() + RETRY_MS
384 }
385 isPanelUp = false
386 panel = undefined
387 })()
388 return binary
389 })().catch(err => {
390 report($, 'panel', err)
391 if (!isPanelFailureShown) $.ui.toast('image-shelf:浮動視窗編譯失敗(需要 Xcode Command Line Tools)')
392 isPanelFailureShown = true
393 panelRetryAt = Date.now() + RETRY_MS
394 panel = undefined
395 return undefined
396 })
397 return panel
398}
399
400// Display width in cells: CJK and emoji take two.
401const widthOf = (text: string) => [...text].reduce((sum, ch) => sum + ((ch.codePointAt(0) ?? 0) >= 0x1100 ? 2 : 1), 0)
402
403const promptRows = (text: string, columns: number) => text.split('\n').reduce((sum, line) => sum + Math.max(1, Math.ceil((widthOf(line) + 2) / Math.max(10, columns))), 0)
404
405// What the floating window reads: the pictures, and where the band's blank rows are.
406const writeShelf = async ($: EngineInterface, list: Shot[], isVisible: boolean, columns: number) => {
407 const { edits, tmuxPane, home } = await setUp($)
408 const tuning = await tuningOf($, home)
409 const text = isVisible ? (await $.prompt.read().catch(() => ({ text: '' }))).text : ''
410 const rowsBelow = tuning.spacer + 2 + promptRows(text, columns) + tuning.statusLines
411 const items = list.filter(s => s.thumb !== '').map(s => ({ n: s.n, thumb: s.thumb, copy: s.copy, edited: s.isEdited, ...(s.label === undefined ? {} : { label: s.label }) }))
412 const editorBinary = items.length > 0 ? ((await buildEditor($)) ?? '') : ''
413 const shelf = JSON.stringify({ visible: isVisible && items.length > 0, items, rows: PANEL_ROWS, rowsBelow, editor: editorBinary, page: `${$.plugin.root}/editor/editor.html`, tmuxPane, maxRows: lastMaxRows, dx: tuning.dx, dy: tuning.dy })
414 const file = `${edits}/shelf.json`
415 if (shelf !== lastShelf) {
416 lastShelf = shelf
417 await $.fs.write(file, shelf)
418 }
419 // Started again if it quit (or was stopped) while there are pictures to show.
420 if (items.length > 0 && !isPanelUp) void startPanel($, file)
421}
422
423// Same height for all, `rows` tall, as wide as the picture's shape asks.
424const columnsOf = (shot: Shot, rows: number) => Math.max(4, Math.min(48, Math.round((rows * CELL * shot.width) / shot.height)))
425
426export const register: Register = on => {
427 on('session.start', async ($, e, next) => {
428 // A reload (or a new version of the mod) brings a fresh panel: the one an earlier load
429 // started for this session goes, so an edited panel/shelf.swift takes effect.
430 void setUp($).then(({ edits }) => $.process.run(['pkill', '-f', `image-shelf/bin/shelf-[0-9a-f]+ ${edits}/shelf.json`])).catch(() => undefined)
431 $.clock.every(700, () => void tick($).catch(err => report($, 'tick', err)))
432 return next(e)
433 })
434
435 on('prompt.edit', async ($, e, next) => {
436 const box = await next(e)
437 await sync($, box.text).catch(err => report($, 'sync', err))
438 return box
439 })
440
441 // At Enter: Claude is pointed at each edited copy. The original paste still goes along;
442 // the note says which one to trust. A HEIC photo is not attached at all, so Claude is
443 // pointed at its PNG (made now if Enter came before the shelf had it).
444 on('prompt.submit', async ($, e, next) => {
445 await watchEdits($).catch(() => undefined)
446 const ns = numbersIn(e.text)
447 const heics = await heicsIn($, e.text).catch(() => [] as { n: number; path: string }[])
448 for (const h of heics) {
449 if (!(await read($, shots).catch(() => [] as Shot[])).some(s => s.n === h.n && s.copy !== '')) await captureHeic($, h.n, h.path).catch(() => undefined)
450 }
451 const all = await read($, shots).catch(() => [] as Shot[])
452 const notes = all.filter(s => s.isEdited && ns.includes(s.n)).map(s => `The person edited [Image #${s.n}] in Preview before sending (drew on, cropped or annotated it). The attached original is the unedited paste; the edited picture is ${s.copy}. Read that file and work from the edited version.`)
453 for (const h of heics) {
454 const s = all.find(x => x.n === h.n)
455 if (s === undefined || s.copy === '') continue
456 notes.push(`The person attached the HEIC photo ${h.path}. Claude Code cannot read HEIC files, so image-shelf converted it to PNG${s.isEdited ? ' and the person then drew on or annotated it' : ''}: ${s.copy}. Read that file to see the photo.`)
457 }
458 if (notes.length === 0) return next(e)
459 return next({ ...e, context: [...(e.context ?? []), ...notes] })
460 })
461
462 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
463 // Not set up yet (setUp has written why, and tries again): the band is left as it is.
464 const ready = await setUp($).catch(() => undefined)
465 if (ready === undefined) return next(e)
466 const { canDraw } = ready
467 const ns = await read($, inBox)
468 const all = await read($, shots)
469 const isShown = e.surface === 'terminal' && !e.props.hasSurvey && ns.length > 0
470 lastColumns = e.props.bodyColumns
471 lastMaxRows = e.props.maxRows
472 lastShown = isShown
473 if (!canDraw) void writeShelf($, ns.flatMap(n => all.filter(s => s.n === n)), isShown, e.props.bodyColumns).catch(err => report($, 'shelf', err))
474 if (e.surface !== 'terminal' || e.props.hasSurvey || ns.length === 0) return next(e)
475 const { Box, Text, Button, Image } = $.ui.resolve(e)
476 const rows = Math.max(3, Math.min(ROWS, e.props.maxRows - 2))
477
478 // Where the terminal cannot draw, blank rows for the floating window to cover.
479 const room = !canDraw && all.some(s => ns.includes(s.n) && s.thumb !== '')
480 ? <Box key="room" height={Math.max(1, Math.min(PANEL_ROWS, e.props.maxRows))} />
481 : null
482
483 // Here the floating window shows the pictures and takes the clicks: only its room.
484 if (!canDraw) return room === null ? next(e) : <Box flexDirection="column">{room}</Box>
485
486 return (
487 <Box flexDirection="column">
488 <Box flexDirection="row" flexWrap="wrap" columnGap={2} justifyContent="flex-start">
489 {await Promise.all(ns.map(async (n, i) => {
490 const shot = all.find(s => s.n === n)
491 const label = `${nameOf(n, shot)}${shot?.isEdited ? ' 已編輯' : ''}`
492 const hotkey = i < 9 ? { hotkey: String(i + 1) } : {}
493 const png = canDraw && shot !== undefined && shot.thumb !== '' ? await pictureOf($, shot).catch(() => undefined) : undefined
494 return (
495 <Box key={`shot-${n}`} flexDirection="column">
496 {png !== undefined && shot !== undefined && (
497 <Image key={`img-${n}`} source={{ png }} columns={columnsOf(shot, rows)} rows={rows} alt={nameOf(n, shot)} />
498 )}
499 {shot === undefined
500 ? <Text key={`wait-${n}`} dimColor>{nameOf(n)} …</Text>
501 : <Button key={`open-${n}`} label={`🖼 ${label}`} plain {...hotkey} onPress={() => void open($, n)} />}
502 </Box>
503 )
504 }))}
505 </Box>
506 {room}
507 </Box>
508 )
509 })
510}
511types/index.d.ts 25 lines1// One pasted image: the N of its [Image #N], the editable copy Preview opens, and the
2// small PNG the band draws where the terminal can draw pictures.
3export type Shot = {
4 n: number
5 // The copy in our own folder; '' until Claude Code's copy of the paste is found.
6 copy: string
7 thumb: string
8 // The copy's mtime when it was made; a later one means Preview saved an edit.
9 madeAt: number
10 isEdited: boolean
11 // Bumped each time the picture changes, so the thumbnail is read again.
12 gen: number
13 width: number
14 height: number
15 // A HEIC photo's: what its badge says ("HEIC 1"), and the photo it was converted from.
16 label?: string
17 source?: string
18}
19
20declare module 'claude-code' {
21 interface PluginState {
22 'image-shelf': { shots: Shot[]; inBox: number[]; roomRows: number }
23 }
24}
25