Claude's answers, rendered: Markdown, math, charts and diagrams drawn in the Claude Code terminal. Independent project, not affiliated with Anthropic.
TypeScript claude-code-mod
Add /md-preview height for images
razorback1651be50998883
diff --git a/README.md b/README.mdindex bb15a2e..673006b 100644--- a/README.md+++ b/README.md@@ -26,7 +26,7 @@ Only the drawing changes. The saved answer stays Markdown.Other files stay as the normal row. JPEG images, WebP images and Markdown files need Typst.- Images that you paste into the prompt (`[Image #N]`). The mod draws each image under your prompt.- These pictures are not larger than the image. They are not wider than the transcript, and not taller than 24 rows or half the screen. The mod draws PNG, JPEG and WebP images only. Other image types (for example GIF and SVG) stay as the normal row.+ These pictures are not larger than the image. They are not wider than the transcript. The height setting (`/md-preview height`) sets the most rows that they can use: by default, half the screen and not more than 24 rows. The mod draws PNG, JPEG and WebP images only. Other image types (for example GIF and SVG) stay as the normal row.- The plan in plan mode (the ExitPlanMode tool). The mod draws the plan as a picture in the transcript, the same as an answer. Then the mod asks you to approve the plan. Refer to [Plan approval](#plan-approval).## Requirements@@ -69,13 +69,17 @@ To try it from a clone without installing: `claude --plugin-dir /path/to/claude-| Command | What it does ||---|---|-| `/md-preview` | Shows the state, the text size, the width and the terminal font that the mod found |+| `/md-preview` | Shows the state, the text size, the width, the image height and the terminal font that the mod found || `/md-preview on` / `off` | Turns the pictures on or off (kept for later sessions) || `/md-preview setup` / `setup remove` | iTerm2: adds or removes the shell line that turns pictures on (then close the tab and open a new one) || `/md-preview size <80–200>` | Text size in percent. 100 is the same visual size as your terminal text. || `/md-preview width` | Shows the width: the most columns that a picture can use || `/md-preview width <40–400>` | Sets the most columns that a picture can use (kept for later sessions) || `/md-preview width full` | Pictures use the full width of the terminal, the same as the text of Claude Code (kept for later sessions). This is the default. A picture is never wider than 255 columns. |+| `/md-preview height` | Shows the image height: the most rows that an image can use. This applies to images that Claude sends and to images that you paste, not to answers. |+| `/md-preview height half` | An image uses half the terminal height, from 6 to 24 rows (kept for later sessions). This is the default. |+| `/md-preview height full` | An image uses the terminal height less 16 rows (kept for later sessions). The 16 rows are for the row of the file, the text around it and the prompt. |+| `/md-preview height <6–200>` | Sets the most rows that an image can use (kept for later sessions). An image is never taller than with `full`. || `/md-preview theme` | Lists the themes, shows which one is in use, and shows the folder for your own themes || `/md-preview theme <name>` | Changes to that theme (kept for later sessions) |diff --git a/hooks/lib/command.ts b/hooks/lib/command.tsindex 5b4981f..0e9642a 100644--- a/hooks/lib/command.ts+++ b/hooks/lib/command.ts@@ -2,15 +2,20 @@// its registration.import type { EngineInterface } from 'claude-code'-import { DEFAULT_SIZE, DEFAULT_WIDTH, IMAGE_MAX_COLUMNS, MAX_SIZE, MAX_WIDTH, MIN_SIZE, MIN_WIDTH, type Width } from './settings'+import {+ DEFAULT_HEIGHT, DEFAULT_SIZE, DEFAULT_WIDTH, IMAGE_MAX_COLUMNS, MAX_HEIGHT, MAX_SIZE, MAX_WIDTH, MIN_HEIGHT, MIN_SIZE, MIN_WIDTH, PICTURE_ROOM_ROWS,+ type Height, type Width,+} from './settings'import { isThemeName, type ThemeInfo } from './themes'-// `/md-preview` arguments: on, off, size <80-200>, width [40-400|full], or-// nothing (show state). A `width` with no value shows the width.+// `/md-preview` arguments: on, off, size <80-200>, width [40-400|full],+// height [6-200|half|full], or nothing (show state). A `width` or `height`+// with no value shows it.export type Command =| { kind: 'on' | 'off' | 'show' | 'probe' }| { kind: 'size'; percent: number }| { kind: 'width'; width?: Width }+ | { kind: 'height'; height?: Height }| { kind: 'theme'; name?: string }| { kind: 'setup'; remove: boolean }| { kind: 'bad' }@@ -36,30 +41,38 @@ export function parseCommand(args: string): Command {const width = Number.parseInt(words[1]!, 10)if (width >= MIN_WIDTH && width <= MAX_WIDTH) return { kind: 'width', width }}+ if (words[0] === 'height' && words.length === 1) return { kind: 'height' }+ if (words[0] === 'height' && words.length === 2 && (words[1] === 'half' || words[1] === 'full')) return { kind: 'height', height: words[1] }+ if (words[0] === 'height' && words.length === 2 && /^\d+$/.test(words[1]!)) {+ const height = Number.parseInt(words[1]!, 10)+ if (height >= MIN_HEIGHT && height <= MAX_HEIGHT) return { kind: 'height', height }+ }return { kind: 'bad' }}-// The /md-preview arguments, and the sizes and widths the typeahead offers.+// The /md-preview arguments, and the sizes, widths and heights the typeahead offers.const SUBCOMMANDS = [{ name: 'on', description: 'draw answers as pictures' },{ name: 'off', description: 'show answers as text' },{ name: 'size', description: `text size, ${MIN_SIZE}-${MAX_SIZE}%` },{ name: 'width', description: `the most columns a picture takes, ${MIN_WIDTH}-${MAX_WIDTH} or full` },+ { name: 'height', description: `the most rows an image takes, ${MIN_HEIGHT}-${MAX_HEIGHT}, half or full` },{ name: 'theme', description: 'list the themes, or switch to one' },{ name: 'setup', description: 'iTerm2: add the shell line that turns pictures on' },] as constconst SIZES = [80, 90, 100, 110, 120, 125, 150, 175, 200]const WIDTHS: readonly Width[] = [80, 100, 120, 160, 200, 'full']+const HEIGHTS: readonly Height[] = ['half', 'full', 12, 24, 36]// Typeahead rows for `/md-preview` arguments: the word at the cursor (`token`,// starting at `start` in `text`) completed as a subcommand, a theme name, a-// size or a width. Right after `theme`, `size` or `width`, rows hold the word-// and its argument, since the typeahead asks only while a word is at the-// cursor.+// size, a width or a height. Right after `theme`, `size`, `width` or+// `height`, rows hold the word and its argument, since the typeahead asks+// only while a word is at the cursor.export type Suggestion = { text: string; label?: string; description?: string }export function commandSuggestions(text: string, token: string, start: number,- o: { themes: readonly ThemeInfo[]; active: string; size: number; width?: Width },+ o: { themes: readonly ThemeInfo[]; active: string; size: number; width?: Width; height?: Height },): Suggestion[] {const head = /^\s*\/md-preview\s+/.exec(text)if (!head || start < head[0].length) return []@@ -84,8 +97,18 @@ export function commandSuggestions(label: w === 'full' ? 'full' : `${w} columns`,description: w === width ? 'current' : w === DEFAULT_WIDTH ? 'the default' : w === 'full' ? `the terminal width (${IMAGE_MAX_COLUMNS} at most)` : undefined,}))+ const height = o.height ?? DEFAULT_HEIGHT+ const heightRows = (prefix: string, lead: string) => HEIGHTS+ .filter(h => String(h).startsWith(prefix))+ .map(h => ({+ text: `${lead}${h}`,+ label: typeof h === 'number' ? `${h} rows` : h,+ description: h === height ? 'current' : h === DEFAULT_HEIGHT ? 'the default: half the terminal'+ : h === 'full' ? `the terminal height less ${PICTURE_ROOM_ROWS} rows` : undefined,+ }))if (before.length === 0) {if (word === 'theme') return themeRows('', 'theme ')+ if (word === 'height') return heightRows('', 'height ')if (word === 'size') return sizeRows('', 'size ')if (word === 'width') return widthRows('', 'width ')return SUBCOMMANDS.filter(c => c.name.startsWith(word)).map(c => ({ text: c.name, description: c.description }))@@ -93,6 +116,7 @@ export function commandSuggestions(if (before.length === 1 && before[0] === 'theme') return themeRows(word, '')if (before.length === 1 && before[0] === 'size') return sizeRows(word.replace(/%$/, ''), '')if (before.length === 1 && before[0] === 'width') return widthRows(word, '')+ if (before.length === 1 && before[0] === 'height') return heightRows(word, '')return []}@@ -101,7 +125,7 @@ export function commandSuggestions(export async function registerCommand($: EngineInterface) {await $.command.register({name: 'md-preview',- description: "Draw Claude's answers as rendered Markdown pictures: on, off, size <80-200> (text size in % of the terminal's), width [40-400|full] (the most columns a picture takes), theme [name] (list or switch themes)",- argumentHint: '[on|off|size <percent>|width [columns|full]|theme [name]]',+ description: "Draw Claude's answers as rendered Markdown pictures: on, off, size <80-200> (text size in % of the terminal's), width [40-400|full] (the most columns a picture takes), height [6-200|half|full] (the most rows an image takes), theme [name] (list or switch themes)",+ argumentHint: '[on|off|size <percent>|width [columns|full]|height [rows|half|full]|theme [name]]',}).catch(() => undefined)}diff --git a/hooks/lib/env.ts b/hooks/lib/env.tsindex 5d2fca5..a2cbb50 100644--- a/hooks/lib/env.ts+++ b/hooks/lib/env.ts@@ -4,7 +4,9 @@import { atom, update } from 'claude-code'import type { EngineInterface } from 'claude-code'-import { BASE_THEME, DEFAULT_SIZE, DEFAULT_THEME, DEFAULT_WIDTH, MAX_SIZE, MAX_WIDTH, MIN_SIZE, MIN_WIDTH, NO_TYPST } from './settings'+import {+ BASE_THEME, DEFAULT_HEIGHT, DEFAULT_SIZE, DEFAULT_THEME, DEFAULT_WIDTH, MAX_HEIGHT, MAX_SIZE, MAX_WIDTH, MIN_HEIGHT, MIN_SIZE, MIN_WIDTH, NO_TYPST,+} from './settings'import { DEFAULT_METRICS, refresh, S, type Env } from './state'import { resolveMode, settingOf } from './mode'import { isItermIn } from './terminals'@@ -75,6 +77,9 @@ export function setUp($: EngineInterface): Promise<Env> {S.size = kept >= MIN_SIZE && kept <= MAX_SIZE ? kept : DEFAULT_SIZEconst width = await $.store.get('width').catch(() => undefined)S.width = width === 'full' ? 'full' : Number.isInteger(width) && Number(width) >= MIN_WIDTH && Number(width) <= MAX_WIDTH ? Number(width) : DEFAULT_WIDTH+ const height = await $.store.get('height').catch(() => undefined)+ S.height = height === 'half' || height === 'full' ? height+ : Number.isInteger(height) && Number(height) >= MIN_HEIGHT && Number(height) <= MAX_HEIGHT ? Number(height) : DEFAULT_HEIGHTif ((await $.store.get('enabled').catch(() => undefined)) === false) await update($, isOn, () => false).catch(() => undefined)const isMac = os.trim() === 'Darwin'S.cell = await measureCell($)diff --git a/hooks/lib/images.ts b/hooks/lib/images.tsindex 82e08e5..bfc232a 100644--- a/hooks/lib/images.ts+++ b/hooks/lib/images.ts@@ -3,13 +3,18 @@// images, and the cells a picture takes. The drawing on the host is in// pictures.tsx.import type { Cell } from './state'-import { CONVERT_MAX_SIDE, MAX_IMAGE_ROWS, PICTURE_MAX_ROWS, PICTURE_MIN_ROWS } from './settings'+import { CONVERT_MAX_SIDE, MAX_IMAGE_ROWS, PICTURE_MAX_ROWS, PICTURE_MIN_ROWS, PICTURE_ROOM_ROWS, type Height } from './settings'import { hashOf } from './draw'-// The most rows a picture under a row takes: half the viewport, within-// PICTURE_MIN_ROWS to PICTURE_MAX_ROWS.-export function pictureRowsFor(viewportRows: number | undefined): number {- return Math.max(PICTURE_MIN_ROWS, Math.min(PICTURE_MAX_ROWS, Math.floor((viewportRows ?? 2 * PICTURE_MAX_ROWS) / 2)))+// The most rows a picture under a row takes, by `height` (/md-preview+// height): half the viewport within PICTURE_MIN_ROWS to PICTURE_MAX_ROWS+// (half); the viewport less PICTURE_ROOM_ROWS (full); or a number, at most+// as much as full. Never under PICTURE_MIN_ROWS or over MAX_IMAGE_ROWS.+export function pictureRowsFor(viewportRows: number | undefined, height: Height): number {+ const view = viewportRows ?? 2 * PICTURE_MAX_ROWS+ const full = view - PICTURE_ROOM_ROWS+ const rows = height === 'half' ? Math.min(PICTURE_MAX_ROWS, Math.floor(view / 2)) : height === 'full' ? full : Math.min(height, full)+ return Math.min(MAX_IMAGE_ROWS, Math.max(PICTURE_MIN_ROWS, rows))}// The cells a picture of `size` pixels takes: its own size or smaller (neverdiff --git a/hooks/lib/pictures.tsx b/hooks/lib/pictures.tsxindex 4e0ed8c..5356e3b 100644--- a/hooks/lib/pictures.tsx+++ b/hooks/lib/pictures.tsx@@ -74,7 +74,7 @@ export async function shownOf($: EngineInterface, e: RowInput, ready: Env, filesexport async function shownOne($: EngineInterface, e: RowInput, ready: Env, file: string, alt = nameOf(file)): Promise<Shown | null> {const p = await pictureOf($, file)if (!p) return null- const fit = pictureCells(p, columnsFor(e.viewport?.columns, S.width), pictureRowsFor(e.viewport?.rows), S.cell ?? DEFAULT_CELL)+ const fit = pictureCells(p, columnsFor(e.viewport?.columns, S.width), pictureRowsFor(e.viewport?.rows, S.height), S.cell ?? DEFAULT_CELL)if (ready.inline) {const png = await pictureBytes($, p)return png ? { source: { png }, ...fit, alt } : null@@ -106,7 +106,9 @@ export async function convertedOf($: EngineInterface, ready: Env, file: string,if (before && [...converting.keys()].some(k => k.startsWith(`${file}@${stamp}@`))) return beforerun = convertOnce($, ready, file, stamp, box, key).finally(() => converting.delete(key))converting.set(key, run)- if (before) void run.then(() => refresh($), () => undefined)+ // The refresh one tick later: a run that ends while this row still draws+ // must not be lost.+ if (before) void run.then(() => void $.clock.after(0, () => refresh($)), () => undefined)}return before ?? run}@@ -175,7 +177,7 @@ export async function sentOf(// Over ssh a Markdown file's page must stay INLINE_MAX_SIDE pixels wide at most.const columns = columnsFor(e.viewport?.columns, S.width, o.ready.inline ? (S.cell ?? DEFAULT_CELL) : null)// The space a picture takes (as in shownOne), which a JPEG or WebP is made to fit.- const box = convertBox(columns, pictureRowsFor(e.viewport?.rows), S.cell ?? DEFAULT_CELL)+ const box = convertBox(columns, pictureRowsFor(e.viewport?.rows, S.height), S.cell ?? DEFAULT_CELL)const under: Under[] = []for (const f of o.files) {const full = imagePathOf(f.path, o.ready.cwd)diff --git a/hooks/lib/settings.ts b/hooks/lib/settings.tsindex 4f20022..288fec4 100644--- a/hooks/lib/settings.ts+++ b/hooks/lib/settings.ts@@ -70,6 +70,22 @@ export const MODES = ['dark', 'light'] as const// at most this many rows tall, and at most half the viewport.export const PICTURE_MAX_ROWS = 24export const PICTURE_MIN_ROWS = 6+// `/md-preview height`: the most rows an image takes (sent or pasted; not a+// Markdown page). `half`, the default: as above. `full`: the viewport less+// PICTURE_ROOM_ROWS. A number: that many rows, at most as many as `full`.+// Never under PICTURE_MIN_ROWS.+export type Height = number | 'half' | 'full'+export const DEFAULT_HEIGHT: Height = 'half'+export const MIN_HEIGHT = PICTURE_MIN_ROWS+export const MAX_HEIGHT = 200+// The rows an image leaves free: the row of the file, the text around it+// and the prompt.+export const PICTURE_ROOM_ROWS = 16+// The height setting as words.+export const heightText = (height: Height) =>+ height === 'half' ? `half (half the terminal, ${PICTURE_MIN_ROWS} to ${PICTURE_MAX_ROWS} rows)`+ : height === 'full' ? `full (the terminal height less ${PICTURE_ROOM_ROWS} rows)`+ : `${height} rows`export const PICTURES_KEPT = 64// A Markdown file Claude sends (SendUserFile) draws when it is at most this// many bytes.diff --git a/hooks/lib/state.ts b/hooks/lib/state.tsindex 70675e5..a995069 100644--- a/hooks/lib/state.ts+++ b/hooks/lib/state.ts@@ -7,7 +7,7 @@ import type { MdPreviewTheme } from '../../types'import type { ThemeInfo } from './themes'import type { HostMode, ThemeSetting } from './mode'import type { PlanVerdict } from './plan'-import { DEFAULT_SIZE, DEFAULT_WIDTH, type Width } from './settings'+import { DEFAULT_HEIGHT, DEFAULT_SIZE, DEFAULT_WIDTH, type Height, type Width } from './settings'// The `done` atom (see types/index.d.ts) for refresh. The state scan of// `claude plugin validate` reads an atom only from a const in the file that@@ -75,6 +75,8 @@ export const S = {size: DEFAULT_SIZE,// `/md-preview width`: the most columns a picture takes, or full.width: DEFAULT_WIDTH as Width,+ // `/md-preview height`: the most rows an image takes (half, full or a number).+ height: DEFAULT_HEIGHT as Height,look: null as Look | null,// The usable themes the last scan found, for the typeahead.themeChoices: [] as ThemeInfo[],diff --git a/hooks/register.tsx b/hooks/register.tsxindex aec2ec4..763e6c2 100644--- a/hooks/register.tsx+++ b/hooks/register.tsx@@ -18,7 +18,9 @@import { atom, read, update } from 'claude-code'import type { EngineInterface, Register, RenderElement, RenderViewport } from 'claude-code'-import { DEFAULT_CELL, DEFAULT_THEME, IMAGE_MAX_COLUMNS, MAX_SIZE, MAX_WIDTH, MIN_SIZE, MIN_WIDTH, TYPST_PROMPT, widthText } from './lib/settings'+import {+ DEFAULT_CELL, DEFAULT_THEME, heightText, IMAGE_MAX_COLUMNS, MAX_HEIGHT, MAX_SIZE, MAX_WIDTH, MIN_HEIGHT, MIN_SIZE, MIN_WIDTH, TYPST_PROMPT, widthText,+} from './lib/settings'import { editedPlans, refresh, S, subagentPlans, writesLive, type Env } from './lib/state'import { columnsFor } from './lib/terminal'import { escapeControls, luminanceOf, modeLine, modeOfLuminance, parseOsc11, settingOf } from './lib/mode'@@ -40,8 +42,8 @@ import {// The names this module exported before the split (the tests import them).export {- BASE_THEME, DEFAULT_CELL, DEFAULT_SIZE, DEFAULT_THEME, DEFAULT_WIDTH, IMAGE_MAX_COLUMNS, MAX_SIZE, MAX_WIDTH, MIN_SIZE, MIN_WIDTH,- PICTURE_MAX_ROWS, SEGMENT_ROWS, TYPST_PROMPT, widthText, type Width,+ BASE_THEME, DEFAULT_CELL, DEFAULT_HEIGHT, DEFAULT_SIZE, DEFAULT_THEME, DEFAULT_WIDTH, heightText, IMAGE_MAX_COLUMNS, MAX_HEIGHT, MAX_SIZE, MAX_WIDTH,+ MIN_HEIGHT, MIN_SIZE, MIN_WIDTH, PICTURE_MAX_ROWS, PICTURE_MIN_ROWS, PICTURE_ROOM_ROWS, SEGMENT_ROWS, TYPST_PROMPT, widthText, type Height, type Width,} from './lib/settings'export { DEFAULT_METRICS, type Cell, type FontMetrics, type Look, type Metrics } from './lib/state'export {@@ -122,7 +124,7 @@ export const register: Register = on => {const got = await next(e)if (!/^\s*\/md-preview\s/.test(e.text)) return gotif (!S.themeChoices.length) await setUp($).catch(() => null)- const mine = commandSuggestions(e.text, e.token, e.start, { themes: S.themeChoices, active: S.look?.name ?? DEFAULT_THEME, size: S.size, width: S.width })+ const mine = commandSuggestions(e.text, e.token, e.start, { themes: S.themeChoices, active: S.look?.name ?? DEFAULT_THEME, size: S.size, width: S.width, height: S.height })return mine.length ? { suggestions: [...got.suggestions, ...mine] } : got})@@ -150,6 +152,16 @@ export const register: Register = on => {const head = asked.width === undefined ? 'The most columns a picture takes' : 'md-preview pictures now take at most'return { text: `${head}: ${widthText(S.width)}${most}. Use /md-preview width <${MIN_WIDTH}-${MAX_WIDTH}> for a cap, or /md-preview width full (the default) for no cap.` }}+ if (asked.kind === 'height') {+ if (asked.height === undefined) await setUp($).catch(() => null)+ else {+ S.height = asked.height+ await $.store.set('height', S.height)+ refresh($)+ }+ const head = asked.height === undefined ? 'The most rows an image takes' : 'md-preview images now take at most'+ return { text: `${head}: ${heightText(S.height)}. Use /md-preview height half (the default), /md-preview height full, or /md-preview height <${MIN_HEIGHT}-${MAX_HEIGHT}> (never more than full).` }+ }if (asked.kind === 'setup') {await setUp($).catch(() => null)return { text: await runSetup($, asked.remove) }@@ -193,9 +205,9 @@ export const register: Register = on => {? `this terminal draws pictures${ready.inline ? ' (over ssh, sent as bytes)' : ''}`: 'Claude Code draws no pictures here (it does in kitty and Ghostty, in iTerm2 3.6+ and Rio 0.5.27+ with CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1, over ssh when TERM names kitty or Ghostty or with that variable; never in tmux, screen or a background session; not in WezTerm, Warp, Konsole or others), so answers stay text'const tried = S.setupNeeded ? ' In iTerm2, run /md-preview setup once to show pictures.' : ''- const usage = `Use /md-preview on, /md-preview off, /md-preview size <${MIN_SIZE}-${MAX_SIZE}>, /md-preview width <${MIN_WIDTH}-${MAX_WIDTH}|full>, or /md-preview theme [name].`+ const usage = `Use /md-preview on, /md-preview off, /md-preview size <${MIN_SIZE}-${MAX_SIZE}>, /md-preview width <${MIN_WIDTH}-${MAX_WIDTH}|full>, /md-preview height <${MIN_HEIGHT}-${MAX_HEIGHT}|half|full>, or /md-preview theme [name].`const bad = asked.kind === 'bad' ? `Not understood: "${e.args.trim()}". ` : ''- return { text: `${bad}md-preview is ${state}, theme ${S.look?.name ?? DEFAULT_THEME}, ${modeLine(S.theme, S.setting, S.settingRaw, S.host)}, text size ${S.size}%, width ${widthText(S.width)}, ${font}. ${typst}; ${terminal}.${tried} ${usage}` }+ return { text: `${bad}md-preview is ${state}, theme ${S.look?.name ?? DEFAULT_THEME}, ${modeLine(S.theme, S.setting, S.settingRaw, S.host)}, text size ${S.size}%, width ${widthText(S.width)}, image height ${heightText(S.height)}, ${font}. ${typst}; ${terminal}.${tried} ${usage}` }})on('config.set', { key: 'theme' }, async ($, e, next) => {diff --git a/tests/command.test.ts b/tests/command.test.tsindex 2c17004..9e01ae7 100644--- a/tests/command.test.ts+++ b/tests/command.test.ts@@ -14,6 +14,7 @@ const at = (text: string) => {test('the first word completes as a subcommand', () => {expect(at('/md-preview t').map(r => r.text)).toEqual(['theme'])expect(at('/md-preview w').map(r => r.text)).toEqual(['width'])+ expect(at('/md-preview h').map(r => r.text)).toEqual(['height'])expect(at('/md-preview o').map(r => r.text)).toEqual(['on', 'off'])expect(at('/md-preview S').map(r => r.text)).toEqual(['size', 'setup'])expect(at('/md-preview x')).toEqual([])@@ -31,6 +32,12 @@ test('right after theme or size, rows hold the word and its argument', () => {expect(widths.map(r => r.text)).toEqual(['width 80', 'width 100', 'width 120', 'width 160', 'width 200', 'width full'])// full is the default; with no width given, it is current.expect(widths.at(-1)!.description).toBe('current')+ const heights = at('/md-preview height')+ expect(heights.map(r => r.text)).toEqual(['height half', 'height full', 'height 12', 'height 24', 'height 36'])+ expect(heights.map(r => r.label)).toEqual(['half', 'full', '12 rows', '24 rows', '36 rows'])+ // half is the default; with no height given, it is current.+ expect(heights[0]!.description).toBe('current')+ expect(heights[1]!.description).toBe('the terminal height less 16 rows')})test('a theme name or size completes after its word', () => {@@ -44,6 +51,11 @@ test('a theme name or size completes after its word', () => {const set = (text: string) => commandSuggestions(text, /\S+$/.exec(text)![0], text.lastIndexOf(' ') + 1, { ...o, width: 160 })expect(set('/md-preview width 16')[0]!.description).toBe('current')expect(set('/md-preview width f')[0]!.description).toBe('the default')+ expect(at('/md-preview height f').map(r => r.text)).toEqual(['full'])+ expect(at('/md-preview height 2').map(r => r.text)).toEqual(['24'])+ const tall = (text: string) => commandSuggestions(text, /\S+$/.exec(text)![0], text.lastIndexOf(' ') + 1, { ...o, height: 24 })+ expect(tall('/md-preview height 2')[0]!.description).toBe('current')+ expect(tall('/md-preview height h')[0]!.description).toBe('the default: half the terminal')})test('other prompts and the command name itself get no rows', () => {diff --git a/tests/images.test.ts b/tests/images.test.tsindex 5b89681..224ed8c 100644--- a/tests/images.test.ts+++ b/tests/images.test.ts@@ -2,7 +2,7 @@ import { expect, mock, test } from 'claude-code/testing'import {claudeTmpOf, convertBox, convertCall, convertedPath, DEFAULT_CELL, folderOf, imageKindOf, isMarkdownPath, pasteDirOf, pastedImagePath, pastedNumbers,- PICTURE_MAX_ROWS, pictureCells, pictureRowsFor, projectSlug, renderKey, sentFiles, sentImages,+ DEFAULT_HEIGHT, parseCommand, PICTURE_MAX_ROWS, PICTURE_ROOM_ROWS, pictureCells, pictureRowsFor, projectSlug, renderKey, sentFiles, sentImages,} from '../hooks/register'// ---- Pure helpers -----------------------------------------------------------@@ -20,10 +20,36 @@ test('a picture keeps its aspect, is never made larger, and fits the box', () =>})test('a picture takes at most half the viewport, within 6 and 24 rows', () => {- expect(pictureRowsFor(undefined)).toBe(PICTURE_MAX_ROWS)- expect(pictureRowsFor(100)).toBe(PICTURE_MAX_ROWS)- expect(pictureRowsFor(30)).toBe(15)- expect(pictureRowsFor(8)).toBe(6)+ expect(DEFAULT_HEIGHT).toBe('half')+ expect(pictureRowsFor(undefined, 'half')).toBe(PICTURE_MAX_ROWS)+ expect(pictureRowsFor(100, 'half')).toBe(PICTURE_MAX_ROWS)+ expect(pictureRowsFor(30, 'half')).toBe(15)+ expect(pictureRowsFor(8, 'half')).toBe(6)+})++test('height full: the viewport less 16 rows; a number: at most that, never under 6 or over 255', () => {+ expect(PICTURE_ROOM_ROWS).toBe(16)+ expect(pictureRowsFor(40, 'full')).toBe(24)+ expect(pictureRowsFor(100, 'full')).toBe(84)+ expect(pictureRowsFor(20, 'full')).toBe(6)+ expect(pictureRowsFor(undefined, 'full')).toBe(32)+ expect(pictureRowsFor(100, 12)).toBe(12)+ expect(pictureRowsFor(40, 36)).toBe(24)+ expect(pictureRowsFor(10, 12)).toBe(6)+ expect(pictureRowsFor(400, 200)).toBe(200)+ expect(pictureRowsFor(400, 'full')).toBe(255)+})++test('the height command: half, full, 6 to 200 rows, or nothing to show it', () => {+ expect(parseCommand('height')).toEqual({ kind: 'height' })+ expect(parseCommand('height half')).toEqual({ kind: 'height', height: 'half' })+ expect(parseCommand('HEIGHT Full')).toEqual({ kind: 'height', height: 'full' })+ expect(parseCommand('height 6')).toEqual({ kind: 'height', height: 6 })+ expect(parseCommand('height 200')).toEqual({ kind: 'height', height: 200 })+ expect(parseCommand('height 5')).toEqual({ kind: 'bad' })+ expect(parseCommand('height 201')).toEqual({ kind: 'bad' })+ expect(parseCommand('height tall')).toEqual({ kind: 'bad' })+ expect(parseCommand('height 12 rows')).toEqual({ kind: 'bad' })})test('only PNG, JPEG and WebP image attachments are drawn', () => {@@ -159,6 +185,8 @@ const JPEG = 'ff d8 ff e0 00 10 4a 46 49 46 00 01 01 00 00 01 00 01 00 00 ff dbconst PNG = 'iVBORw0KGgoAAAANSUhEUgAABkAAAABACAYAAAAAAAAA'const ENGINE = { type: 'Text', props: {}, children: ['engine drawing'] }const PASTED = '/private/tmp/claude-501/-w-app/sid-1/images'+// A tall PNG: 640 x 3200 px, 100 rows of 32 px at its own size.+const TALL = '89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 02 80 00 00 0c 80'// A Mac with kitty (pictures drawn), uid 501, session sid-1 in /w/app. `files`// are the files that exist, by path: their first bytes as od prints them.@@ -173,6 +201,8 @@ const PASTED = '/private/tmp/claude-501/-w-app/sid-1/images'// ends only when this settles.function world(on: any, o: {vars?: Record<string, string>+ // What md-preview kept in its store before (a setting).+ stored?: Record<string, unknown>files?: Record<string, string>texts?: Record<string, string>mtimes?: Record<string, number>@@ -186,7 +216,15 @@ function world(on: any, o: {holdRun?: { at: number; until: Promise<void> }holdCompile?: Promise<void>} = {}) {- mock.store(on)+ // md-preview's store in memory (as mock.store), and its writes by key.+ const store = new Map(Object.entries(o.stored ?? {}))+ const kept: Record<string, unknown> = {}+ on('store.get', async ($: any, e: any) => ({ value: store.get(e.key) }))+ on('store.set', async ($: any, e: any) => {+ store.set(e.key, e.value)+ kept[e.key] = e.value+ return { value: undefined }+ })const clock = mock.clock(on)mock.env(on, { HOME: '/h', TERM: 'xterm-kitty', ...o.vars })const files = o.files ?? {}@@ -280,7 +318,7 @@ function world(on: any, o: {})on('ui.toast', async () => ({ value: undefined }))on('ui.render', () => ENGINE as any)- return { clock, heads, reads, converts, moves, docs, logs, files, texts, mtimes, written }+ return { clock, heads, reads, converts, moves, docs, logs, files, texts, mtimes, written, kept }}const sent = (output: unknown, isErrored = false, id = 'tu-1') =>@@ -623,3 +661,76 @@ test('in a terminal that draws no pictures, rows stay as they are', async ($, onexpect(await (await $.ui.mount(sent(attach('/t/icon.png')))).drawn()).toMatchObject(ENGINE)expect(await (await $.ui.mount(prompt('[Image #5] hi'))).drawn()).toMatchObject(ENGINE)})++// ---- The height setting -------------------------------------------------------++test('a kept height caps sent and pasted images; height full draws them taller at once', async ($, on) => {+ const { kept } = world(on, { stored: { height: 12 }, files: { '/t/tall.png': TALL, [`${PASTED}/5.png`]: TALL }, dirs: [PASTED] })+ const ran = await ready($)+ expect(ran.text).toContain('image height 12 rows')+ const ui = await $.ui.mount(sent(attach('/t/tall.png')))+ expect(images(await ui.drawn())[0].props.rows).toBe(12)+ const pasted = await $.ui.mount(prompt('[Image #5] tall'))+ expect(images(await pasted.drawn())[0].props.rows).toBe(12)+ const set = await $.command.run({ command: 'md-preview', args: 'height full' } as any)+ expect(set.text).toContain('full (the terminal height less 16 rows)')+ expect(kept.height).toBe('full')+ // 40 rows less 16.+ await ui.redraw(sent(attach('/t/tall.png')).props)+ expect(images(await ui.drawn())[0].props.rows).toBe(24)+ await pasted.redraw(prompt('[Image #5] tall').props)+ expect(images(await pasted.drawn())[0].props.rows).toBe(24)+ // A number is never more than full.+ await $.command.run({ command: 'md-preview', args: 'height 36' } as any)+ expect(kept.height).toBe(36)+ await ui.redraw(sent(attach('/t/tall.png')).props)+ expect(images(await ui.drawn())[0].props.rows).toBe(24)+ // Half, the default: half of 40 rows.+ await $.command.run({ command: 'md-preview', args: 'height half' } as any)+ await ui.redraw(sent(attach('/t/tall.png')).props)+ expect(images(await ui.drawn())[0].props.rows).toBe(20)+})++test('a new height makes a new PNG of a JPEG in the background; the last one draws meanwhile', async ($, on) => {+ let release = () => {}+ const until = new Promise<void>(done => (release = done))+ const { clock, converts } = world(on, { typst: true, holdRun: { at: 2, until }, files: { '/t/photo.jpg': JPEG } })+ await ready($)+ const ui = await $.ui.mount(sent(attachAll('/t/photo.jpg')))+ const first = images(await ui.drawn())[0].props.source.file+ expect(converts[0]).toContain('maxh=640')+ await $.command.run({ command: 'md-preview', args: 'height full' } as any)+ await ui.redraw(sent(attachAll('/t/photo.jpg')).props)+ expect(images(await ui.drawn())[0].props.source.file).toBe(first)+ // 24 rows of 32 px.+ expect(converts[1]).toContain('maxh=768')+ // The run ends: its refresh draws the row again, with the new PNG.+ release()+ await clock.settle()+ expect(images(await ui.drawn())[0].props.source.file).toBe(convertedPath('/c', '/t/photo.jpg', '1:1000', { width: 1568, height: 768 }))+})++test('a background run that ends while the row draws still draws its PNG', async ($, on) => {+ const { clock, converts } = world(on, { typst: true, files: { '/t/photo.jpg': JPEG } })+ await ready($)+ const ui = await $.ui.mount(sent(attachAll('/t/photo.jpg')))+ const first = images(await ui.drawn())[0].props.source.file+ await $.command.run({ command: 'md-preview', args: 'height full' } as any)+ await ui.redraw(sent(attachAll('/t/photo.jpg')).props)+ expect(converts.length).toBe(2)+ await clock.settle()+ const now = images(await ui.drawn())[0].props.source.file+ expect(now).not.toBe(first)+ expect(now).toBe(convertedPath('/c', '/t/photo.jpg', '1:1000', { width: 1568, height: 768 }))+})++test('height with no value shows it; a bad value is refused; a bad kept value is the default', async ($, on) => {+ const { kept } = world(on, { stored: { height: 3 } })+ const shown = await $.command.run({ command: 'md-preview', args: 'height' } as any)+ expect(shown.text).toContain('The most rows an image takes: half (half the terminal, 6 to 24 rows)')+ const bad = await $.command.run({ command: 'md-preview', args: 'height 5' } as any)+ expect(bad.text).toContain('Not understood: "height 5"')+ expect(kept.height).toBe(undefined)+ await $.command.run({ command: 'md-preview', args: 'height 200' } as any)+ expect(kept.height).toBe(200)+})