SLOPSHOPPER

config-snapshots

Snapshot and roll back the Claude Code configuration through claude-config

panecommandtoastprocess
★ 2v0.2.0MITupdated 2026-10-16MichaelP17/claude-mods/config-snapshots
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · config-snapshots
│ ┃ Config snapshots ✕ › fix the failing auth test and add an audit log call │ ┃ No snapshots yet. /snapshot <name> records │ ┃ one. ⏺ Read(src/auth.ts) │ ┃ ⎿ Read 6 lines │ ┃ [ Close ] ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /snapshot │ ⎿ config-snapshots: Usage: /snapshot <name> │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Config snapshots
No snapshots yet. /snapshot <name> records one. [ Close ]
README

config-snapshots

Puts ~/.claude under version control, so trying a plugin, mod or skill is reversible: take a snapshot, experiment, roll back if you do not like the result.

It consists of a shell script, bin/claude-config, and a mod that exposes the script inside Claude Code. Both do the same thing; use whichever is at hand.

What a snapshot holds

The snapshot repository is a bare git repository at ~/.claude-config.git whose work tree is ~/.claude. Nothing inside ~/.claude changes except one file, ~/.claude/.gitignore, which is an allowlist: everything is ignored unless listed.

RecordedNot recorded
settings.json, CLAUDE.md, rules/, skills/, agents/, commands/, hooks/, keybindings.json, statusline.py, ideas/transcripts (projects/), history.jsonl, caches, sessions
plugins/installed_plugins.json, plugins/known_marketplaces.jsonplugin caches and marketplace clones
inventory/<machine>/

inventory/<machine>/ lists what is installed on the machine at snapshot time: Homebrew (Brewfile), global npm, cargo, mise, dotnet tool, uv tool, pipx and winget packages — each only if the tool exists — the MCP servers from ~/.claude.json, and the commit of every mod loaded through CLAUDE_CODE_PLUGIN_DIRS. Each machine writes only its own folder, so several machines can share one snapshot repository.

Setup

  1. Initialise the repository and record the first snapshot, baseline. Pass a remote URL to push snapshots there (an empty, private repository is the right target):
   ~/claude-mods/config-snapshots/bin/claude-config init git@github.com:<you>/claude-config.git

Without a URL, snapshots stay local. An existing ~/.claude/.gitignore is kept as the allowlist.

  1. Optional — use the script by name in a terminal by adding its folder to PATH in your shell profile:
   export PATH="$HOME/claude-mods/config-snapshots/bin:$PATH"
  1. Optional — let Claude take snapshots and roll back without a permission prompt: run /permissions in Claude Code and add the allow rules Bash(claude-config snapshot:*) and Bash(claude-config rollback:*) to the user settings. This needs step 2.

To keep the repository elsewhere, set CLAUDE_CONFIG_GIT_DIR to its path — in the shell profile for the terminal, and in the env block of ~/.claude/settings.json for the mod.

Use

CommandEffect
claude-config snapshot <name> [message]Record the current state as <name>; spaces become dashes
claude-config listAll snapshots with date
claude-config statusChanges since the last snapshot, plus new entries in ~/.claude the allowlist does not cover
claude-config diff <name> [--full]Changed files since <name> and packages installed since then
claude-config rollback <name>Restore the config of <name>
claude-config brew-cleanup <name>Uninstall Homebrew packages added since <name>, after confirmation
claude-config pruneDelete caches of plugins and marketplaces that are no longer installed, after confirmation

Inside Claude Code:

CommandEffect
/snapshot <name>Same as claude-config snapshot
/snapshotsA pane with all snapshots; selecting one shows its diff, a button rolls back after a second confirming press
/rollback <name>Opens the pane on that snapshot

In the desktop app the pane also says whether the config changed since the last snapshot and has a field, laid over a card beside its label, that takes a snapshot: what you type becomes its message, and the name is derived from it as on the command line. Each snapshot is a card with Compare laid over its right edge; Compare shows the changed files in a card beneath it, Show full diff, in the bar above it, every changed line, added ones green and removed ones red. Roll back… asks once more in a red card, its buttons laid over it, before it replaces anything.

At session start a toast reports when the config changed since the last snapshot. Changes under ideas/, which idea-shell writes, do not count on their own; they are recorded with the next snapshot.

A rollback never rewrites history: it commits the current state first, then commits the restored one, so a rollback can itself be undone. It never uninstalls packages; it lists them and leaves the decision to you. snapshot and rollback push to origin when a remote is set; CLAUDE_CONFIG_NO_PUSH=1 skips the push. Restart Claude Code after a rollback.

Limits

  • MCP servers added with claude mcp add --scope user live in ~/.claude.json, which also holds login data and runtime state. Only its mcpServers section is recorded, and a rollback reports differences there instead of rewriting the file.
  • plugins/installed_plugins.json contains absolute paths, so plugins are best installed per machine rather than shared across operating systems.
  • lastUpdated in plugins/known_marketplaces.json is not recorded, because Claude Code rewrites it on every background marketplace refresh. A rollback restores that file without the field.
  • Homebrew's auto-update is disabled while the script reads the inventory; otherwise taking a snapshot could migrate formulae.
  • With mod-hub loaded, its 🧰 has a Config snapshots row that says whether the config changed since the last snapshot and opens the pane.

Uninstall

Remove the mod from CLAUDE_CODE_PLUGIN_DIRS. The snapshot repository ~/.claude-config.git and ~/.claude/.gitignore stay until you delete them.

Source 6 files
hooks/register.tsx 383 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderElement } from 'claude-code'
3
4import type { Comparison, Snapshot } from '../types'
5import type { HubCall, HubEntry } from './hub'
6import { buttonWidthOf, diffCards, headerCard, noticeCard, snapshotCard, spinnerSvg } from './look'
7import type { Card } from './look'
8import { ROOMY_WIDTH, barCard, cardWidthOf, columnsOf, fieldCard } from './svg'
9import { hasConfigChanges } from './status'
10
11const PANE = 'config-snapshots'
12const SCRIPT_TIMEOUT_MS = 180_000
13
14const snapshots = atom({ plugin: 'config-snapshots', key: 'snapshots' } as const, [])
15const selected = atom({ plugin: 'config-snapshots', key: 'selected' } as const, null)
16const output = atom({ plugin: 'config-snapshots', key: 'output' } as const, '')
17const isArmed = atom({ plugin: 'config-snapshots', key: 'isArmed' } as const, false)
18const isBusy = atom({ plugin: 'config-snapshots', key: 'isBusy' } as const, false)
19const comparison = atom({ plugin: 'config-snapshots', key: 'comparison' } as const, null)
20const notice = atom({ plugin: 'config-snapshots', key: 'notice' } as const, '')
21const isChanged = atom({ plugin: 'config-snapshots', key: 'isChanged' } as const, null)
22
23async function runScript($: EngineInterface, args: readonly string[]): Promise<string> {
24  const home = (await $.env.get('HOME')) ?? (await $.env.get('USERPROFILE'))
25  // The script ships inside this mod, so the mod works from wherever it was cloned.
26  const pluginRoot = $.plugin.root.replace(/[\\/]\.claude-plugin[\\/]?$/, '')
27  const script = `${pluginRoot}/bin/claude-config`
28  // Windows cannot execute a shell script directly; Git Bash's bash runs it.
29  const isWindows = (await $.env.get('OS')) === 'Windows_NT'
30  const argv = isWindows ? ['bash', script, ...args] : [script, ...args]
31  const result = await $.process.run(argv, {
32    cwd: home,
33    timeoutMs: SCRIPT_TIMEOUT_MS,
34  })
35  const text = [result.stdout.trim(), result.stderr.trim()].filter(i => i.length > 0).join('\n')
36
37  return result.exitCode === 0 ? text : `Failed (exit ${result.exitCode}):\n${text}`
38}
39
40async function refreshSnapshots($: EngineInterface): Promise<Snapshot[]> {
41  const listing = await runScript($, ['list', '--tsv'])
42  const list = listing
43    .split('\n')
44    .filter(i => i.includes('\t'))
45    .map(i => {
46      const [createdAt = '', name = '', message = ''] = i.split('\t')
47
48      return { createdAt, name, message }
49    })
50  await update($, snapshots, () => list)
51
52  return list
53}
54
55// Every script call goes through here so the pane shows one call at a time and
56// a second press cannot start a rollback while a snapshot is still being written.
57async function busy($: EngineInterface, work: () => Promise<string>): Promise<string> {
58  if (await read($, isBusy)) {
59    return 'claude-config is still running.'
60  }
61  await update($, isBusy, () => true)
62  try {
63    const text = await work()
64    await update($, output, () => text)
65
66    return text
67  } finally {
68    await update($, isBusy, () => false)
69  }
70}
71
72async function selectSnapshot($: EngineInterface, name: string): Promise<void> {
73  await compare($, name, false)
74}
75
76async function compare($: EngineInterface, name: string, isFull: boolean): Promise<void> {
77  await update($, selected, () => name)
78  await update($, isArmed, () => false)
79  await update($, comparison, () => null)
80  const text = await busy($, () => runScript($, isFull ? ['diff', name, '--full'] : ['diff', name]))
81  const value: Comparison = { name, text, isFull }
82  await update($, comparison, () => value)
83}
84
85async function rollBack($: EngineInterface, name: string): Promise<void> {
86  await update($, isArmed, () => false)
87  const text = await busy($, () => runScript($, ['rollback', name]))
88  await update($, notice, () => text)
89  await refreshSnapshots($)
90  await reportStatus($)
91  $.ui.toast(`Config rolled back to ${name}. Restart Claude Code to load it.`)
92}
93
94async function takeSnapshot($: EngineInterface, label: string): Promise<string> {
95  const text = await busy($, () => runScript($, ['snapshot', label]))
96  await update($, notice, () => text)
97  await refreshSnapshots($)
98  await reportStatus($)
99
100  return text
101}
102
103// Without mod-hub the call throws; the snapshots stay reachable by command.
104async function publish($: EngineInterface, entry: HubEntry): Promise<void> {
105  try {
106    await ($ as unknown as HubCall).hub.set({ id: 'config-snapshots', ...entry })
107  } catch {
108    // mod-hub is not loaded.
109  }
110}
111
112async function reportStatus($: EngineInterface): Promise<boolean> {
113  const changed = hasConfigChanges(await runScript($, ['status']))
114  await update($, isChanged, () => changed)
115  await publish($, {
116    icon: '📸',
117    title: 'Config snapshots',
118    status: changed ? 'Config changed since the last snapshot' : 'Config matches the last snapshot',
119    attention: changed ? 'info' : 'none',
120    actions: [{ key: 'open', label: 'Open' }],
121  })
122
123  return changed
124}
125
126async function openSnapshots($: EngineInterface): Promise<void> {
127  await update($, notice, () => '')
128  await refreshSnapshots($)
129  await $.ui.open({ id: PANE, title: 'Config snapshots', focus: true })
130  void reportStatus($)
131}
132
133const FIELD_LABEL_WIDTH = 176
134
135export const register: Register = on => {
136  on('session.start', async ($, e, next) => {
137    await $.command.register({
138      name: 'snapshot',
139      description: 'Record the Claude Code config as a named snapshot',
140      argumentHint: '<name>',
141    })
142    await $.command.register({
143      name: 'snapshots',
144      description: 'Browse config snapshots, show diffs and roll back',
145    })
146    await $.command.register({
147      name: 'rollback',
148      description: 'Show what rolling back to a snapshot changes, then confirm',
149      argumentHint: '<name>',
150    })
151
152    if (await reportStatus($)) {
153      $.ui.toast('Claude config changed since the last snapshot. /snapshot <name> records it.')
154    }
155
156    return next(e)
157  })
158
159  on('command.run', { command: 'snapshot' }, async ($, e) => {
160    const label = e.args.trim()
161    if (label.length === 0) {
162      return { text: 'Usage: /snapshot <name>' }
163    }
164    const text = await takeSnapshot($, label)
165
166    return { text }
167  })
168
169  on('command.run', { command: 'snapshots' }, async $ => {
170    await openSnapshots($)
171
172    return {}
173  })
174
175  on('ui.press', { plugin: 'mod-hub', element: 'config-snapshots:open' }, async ($, e, next) => {
176    await openSnapshots($)
177
178    return next(e)
179  })
180
181  on('command.run', { command: 'rollback' }, async ($, e) => {
182    const label = e.args.trim()
183    const list = await refreshSnapshots($)
184    if (label.length === 0) {
185      await $.ui.open({ id: PANE, title: 'Config snapshots', focus: true })
186
187      return {}
188    }
189    const snapshot = list.find(i => i.name === label || i.message === label)
190    if (snapshot === undefined) {
191      return { text: `Unknown snapshot: ${label}. /snapshots lists them.` }
192    }
193    await $.ui.open({ id: PANE, title: 'Config snapshots', focus: true })
194    await selectSnapshot($, snapshot.name)
195
196    return {}
197  })
198
199  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
200    const { Box, Text, Button } = $.ui.resolve(e)
201    const list = await read($, snapshots)
202    const current = await read($, selected)
203    const text = await read($, output)
204    const armed = await read($, isArmed)
205    const running = await read($, isBusy)
206    if (e.surface !== 'terminal' && e.surface !== 'mobile') {
207      const { Input, Svg } = $.ui.resolve(e)
208      const width = cardWidthOf(e.props.bodyColumns)
209      const newest = [...list].reverse()
210      const compared = await read($, comparison)
211      const message = await read($, notice)
212      const changed = await read($, isChanged)
213      const drawCards = (cards: readonly Card[]) => cards.map(card => <Svg source={card.source} alt={card.alt} width={width} height={card.height} />)
214      const spinner = (label: string) => (
215        <Box flexDirection="row" columnGap={1} alignItems="center">
216          <Svg source={spinnerSvg()} alt={label} width={16} height={16} />
217          <Text dimColor>{label}</Text>
218        </Box>
219      )
220      const header = headerCard({
221        width,
222        eyebrow: '📸 CONFIG SNAPSHOTS',
223        title: changed === null ? 'Snapshots of ~/.claude' : changed ? 'Changed since the last snapshot' : 'Matches the last snapshot',
224        counter: `${list.length} ${list.length === 1 ? 'snapshot' : 'snapshots'}`,
225      })
226
227      const isRoomy = width >= ROOMY_WIDTH
228      const fieldLabel = 'TAKE A SNAPSHOT'
229      const fieldHint = changed === true ? 'Something changed · Enter records it' : 'What it captures · Enter records it'
230      const input = (
231        <Input
232          key="snapshot-name"
233          value=""
234          placeholder="e.g. Before trying the new plugin"
235          submitLabel="Snapshot"
236          autoFocus
237          onSubmit={label => {
238            if (label.trim().length > 0) {
239              void takeSnapshot($, label.trim())
240            }
241          }}
242        />
243      )
244      // The field and the buttons lie over the cards, centered on their height:
245      // the pictures take no presses. A narrow pane keeps them beneath.
246      const layered = (key: string, list: readonly Card[], buttons: RenderElement[]) =>
247        isRoomy ? (
248          <Box key={key} flexDirection="column">
249            {drawCards(list)}
250            <Box position="absolute" top={0} bottom={0} right={2} flexDirection="row" alignItems="center" columnGap={1}>
251              {buttons}
252            </Box>
253          </Box>
254        ) : (
255          <Box key={key} flexDirection="column" rowGap={1}>
256            {drawCards(list)}
257            <Box flexDirection="row" columnGap={1}>
258              {buttons}
259            </Box>
260          </Box>
261        )
262
263      return (
264        <Box flexDirection="column" rowGap={1}>
265          {drawCards([header])}
266          <Box flexDirection="column" rowGap={isRoomy ? 1 : 0}>
267            {isRoomy ? (
268              <Box key="take" flexDirection="column">
269                {drawCards([fieldCard(width, fieldLabel, fieldHint, FIELD_LABEL_WIDTH)])}
270                <Box position="absolute" top={0} bottom={0} left={columnsOf(FIELD_LABEL_WIDTH)} right={2} flexDirection="column" justifyContent="center">
271                  {input}
272                </Box>
273              </Box>
274            ) : (
275              <Box flexDirection="column">
276                <Text bold dimColor>
277                  {changed === true ? 'TAKE A SNAPSHOT · SOMETHING CHANGED' : fieldLabel}
278                </Text>
279                {input}
280              </Box>
281            )}
282            {running && current === null ? spinner('Recording…') : message.length > 0 && <Text dimColor>{message}</Text>}
283          </Box>
284
285          {newest.length > 0 && (
286            <Text dimColor bold>
287              HISTORY · NEWEST FIRST
288            </Text>
289          )}
290          {newest.map(snapshot => {
291            const isSelected = snapshot.name === current
292            const result = isSelected && compared?.name === snapshot.name ? compared : null
293            const labels = isSelected && !armed ? ['⇄ Compare', '↶ Roll back…'] : ['⇄ Compare']
294            const card = snapshotCard(width, snapshot, { isSelected, isArmed: armed, reserve: buttonWidthOf(labels) })
295
296            return (
297              <Box key={`card-${snapshot.name}`} flexDirection="column" rowGap={1}>
298                {layered(`snapshot-${snapshot.name}`, [card], [
299                  <Button key={`select-${snapshot.name}`} {...(isSelected ? {} : { dimColor: true })} label="⇄ Compare" onPress={() => selectSnapshot($, snapshot.name)} />,
300                  ...(isSelected && !armed ? [<Button key="arm" hover={{ color: 'error' }} label="↶ Roll back…" onPress={() => update($, isArmed, () => true)} />] : []),
301                ])}
302                {isSelected && running && spinner('Comparing with the current config…')}
303                {result !== null &&
304                  !running &&
305                  (result.text.trim().length === 0 ? (
306                    <Text color="success">✓ Nothing changed since this snapshot</Text>
307                  ) : (
308                    <Box flexDirection="column" rowGap={1}>
309                      {layered('diff-bar', [barCard(width, 'What changed', result.isFull ? 'EVERY CHANGE SINCE THIS SNAPSHOT' : 'CHANGED SINCE THIS SNAPSHOT')], [
310                        <Button key="full-diff" dimColor label={result.isFull ? 'Show summary' : 'Show full diff'} onPress={() => compare($, snapshot.name, !result.isFull)} />,
311                      ])}
312                      {drawCards(diffCards(width, result.text, result.text))}
313                    </Box>
314                  ))}
315                {isSelected &&
316                  armed &&
317                  layered(
318                    'rollback',
319                    noticeCard(width, 'card-error', `Roll back to ${snapshot.name}?`, 'The current config is replaced by this snapshot. Claude Code loads it after a restart.', isRoomy ? buttonWidthOf(['↶ Roll back', 'Cancel']) : 0),
320                    [
321                      <Button key="confirm" variant="primary" label="↶ Roll back" onPress={() => rollBack($, snapshot.name)} />,
322                      <Button key="cancel" label="Cancel" onPress={() => update($, isArmed, () => false)} />,
323                    ],
324                  )}
325              </Box>
326            )
327          })}
328        </Box>
329      )
330    }
331
332    return (
333      <Box flexDirection="column">
334        {list.length === 0 && <Text dimColor>No snapshots yet. /snapshot &lt;name&gt; records one.</Text>}
335        {[...list].reverse().map(snapshot => (
336          <Box key={`row-${snapshot.name}`}>
337            <Button
338              key={`select-${snapshot.name}`}
339              plain
340              dimColor={snapshot.name !== current}
341              label={`${snapshot.name === current ? '▸' : ' '} ${snapshot.createdAt}  ${snapshot.message}`}
342              onPress={() => selectSnapshot($, snapshot.name)}
343            />
344          </Box>
345        ))}
346
347        {current !== null && (
348          <Box marginTop={1}>
349            {armed ? (
350              <Box>
351                <Button
352                  key="confirm"
353                  variant="primary"
354                  label={`Confirm rollback to ${current}`}
355                  onPress={() => rollBack($, current)}
356                />
357                <Button key="cancel" label="Cancel" onPress={() => update($, isArmed, () => false)} />
358              </Box>
359            ) : (
360              <Button
361                key="arm"
362                label={`Roll back to ${current}`}
363                onPress={() => update($, isArmed, () => true)}
364              />
365            )}
366          </Box>
367        )}
368
369        {running && <Text dimColor>Running claude-config…</Text>}
370        {!running && text.length > 0 && (
371          <Box marginTop={1} flexDirection="column">
372            <Text>{text}</Text>
373          </Box>
374        )}
375
376        <Box marginTop={1}>
377          <Button key="close" role="dismiss" dimColor label="Close" onPress={() => $.ui.close({ id: PANE })} />
378        </Box>
379      </Box>
380    )
381  })
382}
383
hooks/hub.ts 12 lines
1// mod-hub's contract, restated: listed under dependencies, it would keep this
2// mod from loading where mod-hub is not installed.
3export type HubEntry = {
4  icon: string
5  title: string
6  status: string
7  attention: 'none' | 'info' | 'warning'
8  actions: { key: string; label: string }[]
9}
10
11export type HubCall = { hub: { set: (entry: HubEntry & { id: string }) => Promise<void> } }
12
hooks/look.ts 35 lines
1import type { Snapshot } from '../types'
2import { PAD, escape, fitText, frame, svgDocument } from './svg'
3import type { Card } from './svg'
4
5export { buttonWidthOf, diffCards, headerCard, noticeCard } from './svg'
6export type { Card } from './svg'
7
8const HEIGHT = 64
9
10// One snapshot: what it captures and when; the selected one in the accent
11// color, red once a roll back to it is asked for. `reserve` keeps the text
12// clear of the native buttons laid over the card's right edge.
13export function snapshotCard(width: number, snapshot: Snapshot, state: { isSelected: boolean; isArmed: boolean; reserve: number }): Card {
14  const textX = PAD + 26
15  const maxWidth = width - textX - PAD - state.reserve
16  const middle = HEIGHT / 2
17  const title = snapshot.message.length > 0 ? snapshot.message : snapshot.name
18  const meta = `${snapshot.createdAt} · ${snapshot.name}`
19  const variant = state.isSelected ? (state.isArmed ? 'card-error' : 'card-accent') : 'card'
20  const dot = state.isSelected ? (state.isArmed ? 'error' : 'accent') : 'muted'
21  const body = [
22    frame(width, HEIGHT, variant),
23    `<circle class="${dot}" cx="${PAD + 6}" cy="${middle}" r="${state.isSelected ? 6 : 4.5}"/>`,
24    state.isSelected ? `<circle class="on-accent" cx="${PAD + 6}" cy="${middle}" r="2.2"/>` : '',
25    `<text class="t" x="${textX}" y="${middle - 4}" font-size="14" font-weight="650">${escape(fitText(title, maxWidth, 14, true))}</text>`,
26    `<text class="muted" x="${textX}" y="${middle + 15}" font-size="12.5">${escape(fitText(meta, maxWidth, 12.5))}</text>`,
27  ]
28
29  return { height: HEIGHT, alt: `${title}: ${meta}${state.isSelected ? ' (selected)' : ''}`, source: svgDocument(width, HEIGHT, body.join('')) }
30}
31
32export function spinnerSvg(): string {
33  return svgDocument(16, 16, '<circle cx="8" cy="8" r="6" fill="none" stroke="#8b8b8b" stroke-opacity="0.3" stroke-width="2"/><circle cx="8" cy="8" r="6" fill="none" stroke="#d97757" stroke-width="2" stroke-dasharray="9 40" stroke-linecap="round" class="spin"/>')
34}
35
hooks/svg.ts 603 lines
1// An SVG drawn as an image cannot lay out text: no wrapping, no Markdown, no
2// measuring. This module does that by estimate and stacks the result into
3// cards. Every mod with desktop cards carries the same copy of this file.
4
5export type Run = { text: string; isBold?: boolean; isItalic?: boolean; isCode?: boolean; isLink?: boolean }
6
7export type Block =
8  | { kind: 'paragraph'; runs: Run[] }
9  | { kind: 'heading'; runs: Run[] }
10  | { kind: 'quote'; runs: Run[] }
11  | { kind: 'item'; marker: string; runs: Run[] }
12  | { kind: 'code'; lines: string[] }
13
14export const SANS = '-apple-system,BlinkMacSystemFont,&quot;Segoe UI&quot;,system-ui,sans-serif'
15export const MONO = 'ui-monospace,SFMono-Regular,Menlo,monospace'
16
17// Classes rather than colors: drawn as an image the SVG follows the light or
18// dark color scheme by itself, which a color handed in from the hook could not.
19export const STYLE = `<style>
20text{font-family:${SANS};white-space:pre}.mono{font-family:${MONO}}
21.card{fill:#f7f6f3;stroke:#e5e3de}.card-accent{fill:#fbf1ec;stroke:#e7b49c}.card-success{fill:#f1f8f3;stroke:#a9d6b8}
22.card-warning{fill:#fcf6e6;stroke:#e6cf8a}.card-error{fill:#fcefee;stroke:#e8aaa6}
23.tile{fill:#ffffff;stroke:#e5e3de}.tile-accent{fill:#ffffff;stroke:#d97757}.tile-success{fill:#ffffff;stroke:#2e9e5b}
24.t{fill:#1f1e1d}.muted{fill:#77756f}.eyebrow{fill:#c9643f}.code{fill:#a2482a}.link{fill:#c9643f}
25.success{fill:#2e9e5b}.warning{fill:#a87a06}.error{fill:#c0392b}.accent{fill:#d97757}.on-accent{fill:#ffffff}
26.badge{fill:#ecebe7}.badge-t{fill:#4a4844}.codebg{fill:#efede8}.rule{fill:#dad7d0}.pill{fill:#f6e1d7}.pill-success{fill:#dcefe2}
27.open{fill:#e4e2dc}.answered{fill:#2e9e5b}.skipped{fill:#d4a017}.current{fill:#d97757}
28.current,.pulse{animation:pulse 1.8s ease-in-out infinite}@keyframes pulse{50%{opacity:.5}}
29.ripple{transform-box:fill-box;transform-origin:center;animation:ripple 2.4s ease-out infinite}@keyframes ripple{0%{transform:scale(1);opacity:.45}100%{transform:scale(2.8);opacity:0}}
30.spin{transform-box:fill-box;transform-origin:center;animation:spin .9s linear infinite}@keyframes spin{to{transform:rotate(360deg)}}
31.dot{animation:dot 1.2s ease-in-out infinite}.dot2{animation-delay:.2s}.dot3{animation-delay:.4s}@keyframes dot{0%,80%,100%{opacity:.25}40%{opacity:1}}
32@media (prefers-color-scheme: dark){
33.card{fill:#262625;stroke:#363632}.card-accent{fill:#2e2420;stroke:#7a4a36}.card-success{fill:#1f2a23;stroke:#2f5a3d}
34.card-warning{fill:#2c2717;stroke:#6a5a24}.card-error{fill:#2e1f1e;stroke:#6e3430}
35.tile{fill:#1e1e1d;stroke:#3a3a36}.tile-accent{fill:#1e1e1d;stroke:#e08a6a}.tile-success{fill:#1e1e1d;stroke:#3fb36b}
36.t{fill:#ecebe8}.muted{fill:#a5a39d}.eyebrow{fill:#e8916f}.code{fill:#f0a283}.link{fill:#e8916f}
37.success{fill:#4cc27a}.warning{fill:#e2b33c}.error{fill:#e8746a}.accent{fill:#e08a6a}.on-accent{fill:#1f1e1d}
38.badge{fill:#34342f}.badge-t{fill:#d6d4cf}.codebg{fill:#1c1c1b}.rule{fill:#45443f}.pill{fill:#4a3328}.pill-success{fill:#24432f}
39.open{fill:#3a3a37}.answered{fill:#3fb36b}.skipped{fill:#d4a017}.current{fill:#e08a6a}}
40@media (prefers-reduced-motion: reduce){.current,.pulse,.dot,.ripple,.spin{animation:none}}
41</style>`
42
43// Widths are estimated from the font size, on the wide side: a line then ends
44// a little early rather than past the card's edge.
45export function textWidth(text: string, size: number, isBold = false, isMono = false): number {
46  if (isMono) {
47    return Array.from(text).length * size * 0.62
48  }
49  let units = 0
50  for (const char of text) {
51    if (/[\s.,:;'|!ijlI]/u.test(char)) {
52      units += 0.3
53    } else if (/[A-Z@%&MWmw]/u.test(char)) {
54      units += 0.74
55    } else if (/\p{Extended_Pictographic}/u.test(char)) {
56      units += 1.15
57    } else {
58      units += 0.53
59    }
60  }
61
62  return units * size * (isBold ? 1.04 : 1)
63}
64
65function runWidth(run: Run, size: number): number {
66  return textWidth(run.text, size, run.isBold === true, run.isCode === true)
67}
68
69export function fitText(text: string, maxWidth: number, size: number, isBold = false): string {
70  if (textWidth(text, size, isBold) <= maxWidth) {
71    return text
72  }
73  const chars = Array.from(text)
74  while (chars.length > 0 && textWidth(`${chars.join('')}…`, size, isBold) > maxWidth) {
75    chars.pop()
76  }
77
78  return `${chars.join('').trimEnd()}…`
79}
80
81export function escape(text: string): string {
82  return text.replace(/&/gu, '&amp;').replace(/</gu, '&lt;').replace(/>/gu, '&gt;').replace(/"/gu, '&quot;')
83}
84
85const INLINE = /(\*\*[^*]+?\*\*|__[^_]+?__|`[^`]+`|\[[^\]]+\]\([^)\s]+\)|(?<![\w*])\*(?!\s)[^*]+?(?<!\s)\*(?!\w))/gu
86
87export function parseInline(text: string): Run[] {
88  const runs: Run[] = []
89  let last = 0
90  for (const match of text.matchAll(INLINE)) {
91    const [token] = match
92    if (match.index > last) {
93      runs.push({ text: text.slice(last, match.index) })
94    }
95    if (token.startsWith('**') || token.startsWith('__')) {
96      runs.push(...parseInline(token.slice(2, -2)).map(i => ({ ...i, isBold: true })))
97    } else if (token.startsWith('`')) {
98      runs.push({ text: token.slice(1, -1), isCode: true })
99    } else if (token.startsWith('[')) {
100      runs.push({ text: token.slice(1, token.indexOf('](')), isLink: true })
101    } else {
102      runs.push(...parseInline(token.slice(1, -1)).map(i => ({ ...i, isItalic: true })))
103    }
104    last = match.index + token.length
105  }
106  if (last < text.length) {
107    runs.push({ text: text.slice(last) })
108  }
109
110  return runs.filter(i => i.text.length > 0)
111}
112
113export function plainOf(text: string): string {
114  return parseInline(text)
115    .map(i => i.text)
116    .join('')
117}
118
119const ITEM = /^\s*([-*•+]|\d{1,3}[.)])\s+(.*)$/u
120const HEADING = /^\s{0,3}#{1,6}\s+(.*)$/u
121const QUOTE = /^\s*>\s?(.*)$/u
122const FENCE = /^\s*(```|~~~)/u
123
124// Single line breaks join a paragraph, as Markdown reads them; a list item,
125// heading, quote or code fence starts a block of its own.
126export function parseBlocks(markdown: string): Block[] {
127  const blocks: Block[] = []
128  let paragraph: string[] = []
129  let item: { marker: string; text: string[] } | null = null
130  let quote: string[] = []
131  const flush = () => {
132    if (paragraph.length > 0) {
133      blocks.push({ kind: 'paragraph', runs: parseInline(paragraph.join(' ')) })
134    }
135    if (item !== null) {
136      blocks.push({ kind: 'item', marker: item.marker, runs: parseInline(item.text.join(' ')) })
137    }
138    if (quote.length > 0) {
139      blocks.push({ kind: 'quote', runs: parseInline(quote.join(' ')) })
140    }
141    paragraph = []
142    item = null
143    quote = []
144  }
145  const lines = markdown.replace(/\r\n?/gu, '\n').split('\n')
146  for (let index = 0; index < lines.length; index++) {
147    const line = lines[index] ?? ''
148    if (FENCE.test(line)) {
149      flush()
150      const code: string[] = []
151      index += 1
152      while (index < lines.length && !FENCE.test(lines[index] ?? '')) {
153        code.push(lines[index] ?? '')
154        index += 1
155      }
156      blocks.push({ kind: 'code', lines: code })
157      continue
158    }
159    if (line.trim().length === 0) {
160      flush()
161      continue
162    }
163    const heading = HEADING.exec(line)
164    if (heading !== null) {
165      flush()
166      blocks.push({ kind: 'heading', runs: parseInline(heading[1] ?? '') })
167      continue
168    }
169    const listed = ITEM.exec(line)
170    if (listed !== null) {
171      flush()
172      const marker = listed[1] ?? '-'
173      item = { marker: /\d/u.test(marker) ? marker : '•', text: [listed[2] ?? ''] }
174      continue
175    }
176    const quoted = QUOTE.exec(line)
177    if (quoted !== null) {
178      if (quote.length === 0) {
179        flush()
180      }
181      quote.push(quoted[1] ?? '')
182      continue
183    }
184    if (item !== null && /^\s+\S/u.test(line)) {
185      item.text.push(line.trim())
186      continue
187    }
188    if (item !== null || quote.length > 0) {
189      flush()
190    }
191    paragraph.push(line.trim())
192  }
193  flush()
194
195  return blocks
196}
197
198type Word = Run & { hasSpace: boolean }
199
200function wordsOf(runs: readonly Run[]): Word[] {
201  const words: Word[] = []
202  for (const run of runs) {
203    for (const piece of run.text.split(/(\s+)/u)) {
204      if (piece.length === 0) {
205        continue
206      }
207      if (/^\s+$/u.test(piece)) {
208        const previous = words.at(-1)
209        if (previous !== undefined) {
210          previous.hasSpace = true
211        }
212        continue
213      }
214      words.push({ ...run, text: piece, hasSpace: false })
215    }
216  }
217
218  return words
219}
220
221function sameStyle(first: Run, second: Run): boolean {
222  return first.isBold === second.isBold && first.isItalic === second.isItalic && first.isCode === second.isCode && first.isLink === second.isLink
223}
224
225function breakWord(word: Word, maxWidth: number, size: number): Word[] {
226  const pieces: Word[] = []
227  let current = ''
228  for (const char of word.text) {
229    if (current.length > 0 && runWidth({ ...word, text: current + char }, size) > maxWidth) {
230      pieces.push({ ...word, text: current, hasSpace: false })
231      current = ''
232    }
233    current += char
234  }
235  pieces.push({ ...word, text: current })
236
237  return pieces
238}
239
240// Greedy, word by word; a word wider than the line is broken by characters.
241// `firstWidth` keeps the first line clear of a badge drawn at its end.
242export function wrapRuns(runs: readonly Run[], maxWidth: number, size: number, firstWidth = maxWidth): Run[][] {
243  const lines: Word[][] = []
244  let line: Word[] = []
245  let width = 0
246  const space = textWidth(' ', size)
247  const words = wordsOf(runs).flatMap(i => (runWidth(i, size) > maxWidth ? breakWord(i, maxWidth, size) : [i]))
248  for (const word of words) {
249    const previous = line.at(-1)
250    const gap = previous?.hasSpace === true ? space : 0
251    const wordWidth = runWidth(word, size)
252    if (line.length > 0 && width + gap + wordWidth > (lines.length === 0 ? firstWidth : maxWidth)) {
253      lines.push(line)
254      line = []
255      width = 0
256    }
257    width += (line.length > 0 ? gap : 0) + wordWidth
258    line.push(word)
259  }
260  if (line.length > 0) {
261    lines.push(line)
262  }
263
264  // The space after a code span is drawn in the text's font, not the code's
265  // wider one.
266  return lines.map(words => {
267    const merged: Run[] = []
268    const append = (run: Run) => {
269      const previous = merged.at(-1)
270      if (previous !== undefined && sameStyle(previous, run)) {
271        previous.text += run.text
272      } else {
273        merged.push({ ...run })
274      }
275    }
276    words.forEach((word, index) => {
277      const { hasSpace, ...run } = word
278      const hasGap = hasSpace && index < words.length - 1
279      if (run.isCode === true) {
280        append(run)
281        if (hasGap) {
282          append({ text: ' ' })
283        }
284      } else {
285        append({ ...run, text: run.text + (hasGap ? ' ' : '') })
286      }
287    })
288
289    return merged
290  })
291}
292
293// Cuts wrapped lines to `maxLines`, the last one ending in an ellipsis.
294export function clampLines(lines: Run[][], maxLines: number, maxWidth: number, size: number): Run[][] {
295  if (lines.length <= maxLines) {
296    return lines
297  }
298  const kept = lines.slice(0, maxLines)
299  const last = kept[maxLines - 1] ?? []
300  const text = last.map(i => i.text).join('')
301  kept[maxLines - 1] = [{ ...(last[0] ?? { text: '' }), text: fitText(`${text}…`, maxWidth, size, last[0]?.isBold === true) }]
302
303  return kept
304}
305
306export function lineSvg(runs: readonly Run[], x: number, y: number, size: number, tone = 't', weight?: number): string {
307  const spans = runs.map(run => {
308    const classes = run.isCode ? 'code' : run.isLink ? 'link' : tone
309    const attributes = [
310      `class="${classes}"`,
311      run.isBold === true || weight !== undefined ? `font-weight="${run.isBold === true ? 650 : weight}"` : '',
312      run.isItalic === true ? 'font-style="italic"' : '',
313      run.isCode === true ? `font-family="${MONO}" font-size="${(size * 0.92).toFixed(1)}"` : '',
314      run.isLink === true ? 'text-decoration="underline"' : '',
315    ].filter(i => i.length > 0)
316
317    return `<tspan ${attributes.join(' ')}>${escape(run.text)}</tspan>`
318  })
319
320  return `<text x="${x}" y="${y.toFixed(1)}" font-size="${size}">${spans.join('')}</text>`
321}
322
323// A pane reports its width in columns only; about 8 CSS pixels each, as
324// savvy-progress measures it, minus the pane's own inset.
325export function cardWidthOf(columns: number): number {
326  return Math.max(240, Math.min(900, (columns || 40) * 8 - 8))
327}
328
329// The columns a native control laid over a card is pushed in by to clear
330// `pixels` of the card, at the same 8 pixels per column.
331export function columnsOf(pixels: number): number {
332  return Math.ceil(pixels / 8)
333}
334
335// About how wide the desktop draws a row of native buttons with these labels,
336// for text that has to keep clear of buttons laid over a card.
337export function buttonWidthOf(labels: readonly string[]): number {
338  return labels.reduce((sum, label) => sum + textWidth(label, 13) + 30, 0) + Math.max(0, labels.length - 1) * 8
339}
340
341export function svgDocument(width: number, height: number, body: string): string {
342  return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">${STYLE}${body}</svg>`
343}
344
345export type Segment = 'answered' | 'skipped' | 'current' | 'open'
346
347export type Card = { source: string; height: number; alt: string }
348
349export type Variant = 'card' | 'card-accent' | 'card-success' | 'card-warning' | 'card-error'
350
351export type Section = { height: number; draw: (y: number) => string }
352
353export const PAD = 18
354export const SIZE = 14
355export const LINE = 21
356export const EYEBROW = 11
357export const RADIUS = 14
358
359// The engine refuses an Svg taller than 4096 pixels; a longer card is cut
360// between sections into several cards of the same look.
361export const MAX_HEIGHT = 4000
362
363export function baseline(y: number, line: number, lineHeight = LINE): number {
364  return y + line * lineHeight + lineHeight * 0.72
365}
366
367export function frame(width: number, height: number, variant: Variant): string {
368  return `<rect class="${variant}" x="0.5" y="0.5" width="${width - 1}" height="${height - 1}" rx="${RADIUS}"/>`
369}
370
371export function eyebrowSvg(text: string, x: number, y: number, tone = 'eyebrow', anchor = 'start'): string {
372  return `<text class="${tone}" x="${x}" y="${y}" font-size="${EYEBROW}" font-weight="700" letter-spacing="1.1" text-anchor="${anchor}">${escape(text)}</text>`
373}
374
375export function eyebrowWidth(text: string): number {
376  return textWidth(text, EYEBROW, true) + text.length * 1.1
377}
378
379export function textSection(
380  runs: readonly Run[],
381  x: number,
382  maxWidth: number,
383  options: { tone?: string; size?: number; maxLines?: number; weight?: number; firstWidth?: number } = {},
384): Section {
385  const size = options.size ?? SIZE
386  const lineHeight = Math.round(size * 1.5)
387  const wrapped = wrapRuns(runs, maxWidth, size, options.firstWidth)
388  const lines = options.maxLines === undefined ? wrapped : clampLines(wrapped, options.maxLines, maxWidth, size)
389
390  return {
391    height: lines.length * lineHeight,
392    draw: y => lines.map((line, index) => lineSvg(line, x, baseline(y, index, lineHeight), size, options.tone, options.weight)).join(''),
393  }
394}
395
396export function codeSection(lines: readonly string[], x: number, maxWidth: number): Section {
397  const size = 12.5
398  const lineHeight = 18
399  const perLine = Math.max(8, Math.floor((maxWidth - 24) / (size * 0.62)))
400  const rows = lines.flatMap(line => {
401    const chars = Array.from(line)
402    const pieces: string[] = []
403    for (let index = 0; index < Math.max(1, chars.length); index += perLine) {
404      pieces.push(chars.slice(index, index + perLine).join(''))
405    }
406
407    return pieces
408  })
409
410  return {
411    height: rows.length * lineHeight + 20,
412    draw: y =>
413      `<rect class="codebg" x="${x}" y="${y}" width="${maxWidth}" height="${rows.length * lineHeight + 20}" rx="8"/>` +
414      rows.map((row, index) => lineSvg([{ text: row, isCode: true }], x + 12, baseline(y + 10, index, lineHeight), size / 0.92)).join(''),
415  }
416}
417
418export function blockSection(block: Block, x: number, maxWidth: number): Section {
419  switch (block.kind) {
420    case 'code':
421      return codeSection(block.lines, x, maxWidth)
422    case 'heading':
423      return textSection(block.runs, x, maxWidth, { size: SIZE + 1.5, weight: 650 })
424    case 'quote': {
425      const text = textSection(block.runs, x + 14, maxWidth - 14, { tone: 'muted' })
426
427      return { height: text.height, draw: y => `<rect class="rule" x="${x}" y="${y + 2}" width="3" height="${text.height - 4}" rx="1.5"/>${text.draw(y)}` }
428    }
429    case 'item': {
430      const indent = block.marker === '•' ? 16 : textWidth(block.marker, SIZE) + 8
431      const text = textSection(block.runs, x + indent, maxWidth - indent)
432
433      return {
434        height: text.height,
435        draw: y => `<text class="muted" x="${x + (block.marker === '•' ? 3 : 0)}" y="${baseline(y, 0).toFixed(1)}" font-size="${SIZE}">${escape(block.marker)}</text>${text.draw(y)}`,
436      }
437    }
438    default:
439      return textSection(block.runs, x, maxWidth)
440  }
441}
442
443// Paragraphs sit further apart than the items of one list.
444export function blockSections(blocks: readonly Block[], x: number, maxWidth: number): Section[] {
445  return blocks.map((block, index) => {
446    const section = blockSection(block, x, maxWidth)
447    const previous = blocks[index - 1]
448    const spacing = index === 0 ? 0 : previous?.kind === 'item' && block.kind === 'item' ? 4 : 10
449
450    return { height: section.height + spacing, draw: y => section.draw(y + spacing) }
451  })
452}
453
454// Stacks sections inside one frame; past MAX_HEIGHT the rest go on in a next one.
455// `minHeight` keeps a short card tall enough for native controls laid over it.
456export function cards(width: number, variant: Variant, sections: readonly Section[], alt: string, decoration = '', minHeight = 0): Card[] {
457  const result: Card[] = []
458  let pending: Section[] = []
459  let used = 2 * PAD
460  const close = () => {
461    if (pending.length === 0) {
462      return
463    }
464    let y = PAD
465    const body = pending.map(section => {
466      const drawn = section.draw(y)
467      y += section.height
468
469      return drawn
470    })
471    const natural = Math.ceil(y + PAD)
472    const height = result.length === 0 ? Math.max(natural, minHeight) : natural
473    result.push({ height, alt, source: svgDocument(width, height, frame(width, height, variant) + (result.length === 0 ? decoration : '') + body.join('')) })
474    pending = []
475    used = 2 * PAD
476  }
477  for (const section of sections) {
478    if (pending.length > 0 && used + section.height > MAX_HEIGHT) {
479      close()
480    }
481    pending.push(section)
482    used += section.height
483  }
484  close()
485
486  return result
487}
488
489export const GLOW =
490  '<defs><linearGradient id="glow" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#d97757" stop-opacity="0.14"/><stop offset="0.55" stop-color="#d97757" stop-opacity="0"/></linearGradient></defs>'
491
492// The card heading a pane: an eyebrow, a count at the right, a title of up
493// to two lines and, given segments, a bar with one segment per step.
494// `reserve` keeps the title clear of native buttons laid over the right side;
495// a card without a bar is too low for them beside the count at its top right,
496// so the count then goes beneath the title.
497export function headerCard(card: { width: number; eyebrow: string; title: string; counter: string; segments?: readonly Segment[]; reserve?: number }): Card {
498  const { width } = card
499  const segments = card.segments ?? []
500  const inner = width - 2 * PAD
501  const reserve = card.reserve ?? 0
502  const isCountBelow = reserve > 0 && segments.length === 0
503  const counterWidth = isCountBelow ? 0 : textWidth(card.counter, 12)
504  const eyebrow = fitText(card.eyebrow, inner - counterWidth - 16 - (isCountBelow ? reserve : 0), EYEBROW, true)
505  const title = textSection(parseInline(card.title).map(i => ({ ...i, isBold: true })), PAD, inner - reserve, { size: 17, maxLines: 2 })
506  const titleTop = PAD + EYEBROW + 8
507  const countY = titleTop + title.height + 14
508  const barY = titleTop + title.height + 12
509  const height = isCountBelow ? countY + PAD - 2 : segments.length === 0 ? titleTop + title.height + PAD - 4 : barY + 6 + PAD
510  const count = Math.max(1, segments.length)
511  const segmentWidth = (inner - 4 * (count - 1)) / count
512  const bars = segments.map(
513    (segment, index) => `<rect class="${segment}" x="${(PAD + index * (segmentWidth + 4)).toFixed(1)}" y="${barY}" width="${segmentWidth.toFixed(1)}" height="6" rx="3"/>`,
514  )
515  const body = [
516    frame(width, height, 'card'),
517    GLOW,
518    `<rect x="0.5" y="0.5" width="${width - 1}" height="${height - 1}" rx="${RADIUS}" fill="url(#glow)"/>`,
519    eyebrowSvg(eyebrow, PAD, PAD + EYEBROW),
520    isCountBelow
521      ? `<text class="muted" x="${PAD}" y="${countY}" font-size="12.5">${escape(fitText(card.counter, inner - reserve, 12.5))}</text>`
522      : `<text class="muted" x="${width - PAD}" y="${PAD + EYEBROW}" font-size="12" text-anchor="end">${escape(card.counter)}</text>`,
523    title.draw(titleTop),
524    ...bars,
525  ]
526
527  return { height, alt: `${card.eyebrow}: ${plainOf(card.title)}, ${card.counter}`, source: svgDocument(width, height, body.join('')) }
528}
529
530export function noticeCard(width: number, variant: 'card-warning' | 'card-error', title: string, text: string, reserve = 0): Card[] {
531  const inner = width - 2 * PAD - reserve
532  const body = textSection([{ text }], PAD, inner, { tone: 'muted' })
533  const sections = [textSection([{ text: title, isBold: true }], PAD, inner, { size: 15 }), { height: body.height + 6, draw: (y: number) => body.draw(y + 6) }]
534
535  return cards(width, variant, sections, `${title} ${text}`, '', reserve > 0 ? 72 : 0)
536}
537
538const FIELD_HEIGHT = 72
539
540// A card holding a native text field: its label and a hint in a column at the
541// left, the rest left free for the field laid over it. `labelWidth` is that
542// column's width; the field starts past it.
543export function fieldCard(width: number, label: string, hint: string, labelWidth: number): Card {
544  const maxWidth = labelWidth - PAD - 12
545  const hints = wrapRuns([{ text: hint }], maxWidth, 12).slice(0, 2)
546  const top = FIELD_HEIGHT / 2 - (hints.length * 16 + EYEBROW + 6) / 2 + EYEBROW
547  const body = [
548    frame(width, FIELD_HEIGHT, 'card'),
549    eyebrowSvg(fitText(label, maxWidth, EYEBROW, true), PAD, top),
550    ...hints.map((line, index) => lineSvg(line, PAD, top + 18 + index * 16, 12, 'muted')),
551    `<rect class="rule" x="${labelWidth - 6}" y="16" width="1" height="${FIELD_HEIGHT - 32}"/>`,
552  ]
553
554  return { height: FIELD_HEIGHT, alt: `${label}: ${hint}`, source: svgDocument(width, FIELD_HEIGHT, body.join('')) }
555}
556
557// Below this width a card leaves too little room beside native controls, so
558// they go beneath it instead of over it.
559export const ROOMY_WIDTH = 420
560
561// A slim card for a row of native buttons laid over it; given a label, that
562// heads the bar at its left, as a section title with its actions beside it.
563export function barCard(width: number, alt: string, label = '', variant: Variant = 'card', reserve = 0): Card {
564  const height = 56
565  const text = label.length === 0 ? '' : eyebrowSvg(fitText(label, width - 2 * PAD - reserve - 12, EYEBROW, true), PAD, height / 2 + EYEBROW / 2 - 1)
566
567  return { height, alt, source: svgDocument(width, height, frame(width, height, variant) + text) }
568}
569
570// A diff or a list of changes in the code font: added lines green, removed
571// ones red, hunk heads in the accent color. Long lines are cut, not wrapped,
572// so the columns stay aligned.
573export function diffCards(width: number, text: string, alt: string): Card[] {
574  const size = 12
575  const lineHeight = 17
576  const maxWidth = width - 2 * PAD
577  const rows = text.replace(/\s+$/u, '').split('\n')
578  const toneOf = (row: string) =>
579    /^\+(?!\+\+)/u.test(row) ? 'success' : /^-(?!--)/u.test(row) ? 'error' : /^@@/u.test(row) ? 'accent' : /^(diff |index |\+\+\+|---)/u.test(row) ? 'muted' : 't'
580  const sections: Section[] = rows.map(row => ({
581    height: lineHeight,
582    draw: y =>
583      `<text class="${toneOf(row)} mono" x="${PAD}" y="${(y + lineHeight * 0.75).toFixed(1)}" font-size="${size}">${escape(fitMono(row, maxWidth, size))}</text>`,
584  }))
585
586  return cards(width, 'card', sections, alt)
587}
588
589function fitMono(text: string, maxWidth: number, size: number): string {
590  const chars = Array.from(text.replace(/\t/gu, '  '))
591  const fits = Math.floor(maxWidth / (size * 0.62))
592
593  return chars.length <= fits ? chars.join('') : `${chars.slice(0, Math.max(1, fits - 1)).join('')}…`
594}
595
596// An eyebrow line heading a card, with an optional second one at its right.
597export function eyebrowSection(left: string, right: string | null, rightTone: string, width: number): Section {
598  return {
599    height: EYEBROW + 10,
600    draw: y => eyebrowSvg(left, PAD, y + EYEBROW) + (right === null ? '' : eyebrowSvg(right, width - PAD, y + EYEBROW, rightTone, 'end')),
601  }
602}
603
hooks/status.ts 22 lines
1// idea-shell rewrites ~/.claude/ideas/ whenever an idea is captured or done.
2// Those changes travel with the next snapshot without a toast for each of them.
3const QUIET_PREFIXES = ['ideas/']
4
5export function hasConfigChanges(status: string): boolean {
6  const [changes = ''] = status.split('\n\n')
7  if (changes.startsWith('No config changes')) {
8    return false
9  }
10
11  return changes
12    .split('\n')
13    .filter(i => i.trim().length > 0)
14    .some(line => !QUIET_PREFIXES.some(prefix => pathOf(line).startsWith(prefix)))
15}
16
17// `git status --short` lines are two status letters, a space and the path,
18// quoted when it holds unusual characters.
19function pathOf(line: string): string {
20  return line.slice(3).replace(/^"/, '')
21}
22
types/index.d.ts 19 lines
1export type Snapshot = { createdAt: string; name: string; message: string }
2
3export type Comparison = { name: string; text: string; isFull: boolean }
4
5declare module 'claude-code' {
6  interface PluginState {
7    'config-snapshots': {
8      snapshots: Snapshot[]
9      selected: string | null
10      output: string
11      isArmed: boolean
12      isBusy: boolean
13      comparison: Comparison | null
14      notice: string
15      isChanged: boolean | null
16    }
17  }
18}
19