SLOPSHOPPER

idea-shell

Captures ideas per folder with /idea while Claude keeps working, and hands them to Claude later

panespinnerguardcommandtoasttool
★ 2v0.1.0MITupdated 2026-10-16MichaelP17/claude-mods/idea-shell
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · idea-shell
│ ┃ New idea ✕ › fix the failing auth test and add an audit log call │ ┃ New idea ⏎ save │ ┃ 0 ideas for this folder · Shift+Enter adds a ⏺ Read(src/auth.ts) │ ┃ line · Esc closes ⎿ Read 6 lines │ ⏺ 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 │ │ › /idea │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · New idea
New idea ⏎ save 0 ideas for this folder · Shift+Enter adds a line · Esc closes
Pane · Ideas
No ideas for this folder. /idea captures one.
README

idea-shell

Captures ideas while Claude is busy, without interrupting it. Type /idea mid-turn, write the thought down, and Claude keeps working on its task; later you hand the idea to Claude or let it work through the list.

Ideas belong to the folder Claude Code was started in. Every folder has its own list, whether it is a git repository or not.

WhenWhat you see
/idea <text>, also while Claude is workingthe idea is saved, a toast confirms it; Claude sees nothing
/ideaa pane with one text field: Enter saves and empties it for the next idea, Shift+Enter adds a line in the terminal, Esc closes
Ideas exist for this folder💡 3 in the footer under the prompt, terminal and desktop app
Desktop app/idea, /ideas, the 💡 in the footer and the hub open one Ideas pane: the field for a new idea, laid over a card beside its label, above the waiting ideas, each a numbered card with its Markdown and Work on it and ✕ laid over its right edge; the footer and the hub open it at once, also while Claude is working
/ideasa pane listing the folder's ideas: pressing one puts it into the prompt and removes it from the list, delete drops it
You ask Claude to work through the ideasClaude reads them with its ideas_list tool and removes each with idea_remove once it is done

No setup needed.

Where ideas are kept

One Markdown file per folder under ~/.claude/ideas/, mirroring the folder's path: ideas for ~/Projects/app live in ~/.claude/ideas/home/Projects/app.md, ideas for a folder outside your home directory under ~/.claude/ideas/root/…. A file holds nothing but the ideas, one bullet each, so reading it costs Claude only the ideas themselves. The file is deleted when its last idea is gone.

config-snapshots records ~/.claude/ideas/ with every snapshot, which carries the ideas to other machines that share the snapshot repository.

Details and limits

  • In the terminal, /idea and /ideas run at once, even while a turn is in flight, and leave no row in the conversation: neither the command nor the idea reaches Claude's context. A pressed idea only goes into the prompt box and reaches Claude when you send it.
  • The desktop app holds a slash command typed mid-turn until the turn ends, whatever the mod declares. The 💡 in the footer is the way in there while Claude works.
  • The folder is the one the session started in; a cd inside a shell command does not change it, /cd does. A subfolder or a worktree has a list of its own.
  • Every change re-reads the file first, so two sessions in the same folder do not overwrite each other's ideas.
  • The desktop app's text field is a single line: Shift+Enter saves there like Enter.
  • The mobile app draws no text field; /idea <text> works there.
  • With mod-hub loaded, the desktop footer leaves the 💡 to its 🧰, whose Ideas row opens the Ideas pane.

Uninstall

Remove the mod from CLAUDE_CODE_PLUGIN_DIRS. Captured ideas stay in ~/.claude/ideas/ until you delete them.

Source 6 files
hooks/register.tsx 394 lines
1import { atom, read, update } from 'claude-code'
2import type { ElementTable, EngineInterface, Register, RenderElement } from 'claude-code'
3
4import type { HubCall, HubEntry } from './hub'
5import { formatIdeas, ideasFileOf, normalizeIdea, numberedList, parseIdeas, previewOf } from './ideas'
6import { buttonWidthOf, headerCard, ideaCards } from './look'
7import { ROOMY_WIDTH, cardWidthOf, columnsOf, fieldCard } from './svg'
8
9const CAPTURE_PANE = 'idea'
10const LIST_PANE = 'ideas'
11const LIST_TOOL = 'mcp__idea-shell__ideas_list'
12const REMOVE_TOOL = 'mcp__idea-shell__idea_remove'
13
14const ideas = atom({ plugin: 'idea-shell', key: 'ideas' } as const, [])
15const isHubbed = atom({ plugin: 'idea-shell', key: 'isHubbed' } as const, false)
16
17let published: string | null = null
18
19// Without mod-hub the call throws, and the mod keeps its own footer bulb.
20async function publish($: EngineInterface, entry: HubEntry): Promise<void> {
21  const text = JSON.stringify(entry)
22  if (text === published) {
23    return
24  }
25  let isReached = true
26  try {
27    await ($ as unknown as HubCall).hub.set({ id: 'idea-shell', ...entry })
28  } catch {
29    isReached = false
30  }
31  published = isReached ? text : null
32  if ((await read($, isHubbed)) !== isReached) {
33    await update($, isHubbed, () => isReached)
34  }
35}
36
37async function ideasFile($: EngineInterface): Promise<string> {
38  const home = (await $.env.get('HOME')) ?? (await $.env.get('USERPROFILE')) ?? ''
39  const configDirectory = (await $.env.get('CLAUDE_CONFIG_DIR')) ?? `${home}/.claude`
40  const folder = await $.session.root()
41
42  return ideasFileOf(folder, home, `${configDirectory}/ideas`)
43}
44
45// Every change starts from the file, not from the drawn list, so ideas another
46// session or Claude added in the meantime are never overwritten.
47async function load($: EngineInterface): Promise<string[]> {
48  const path = await ideasFile($)
49  const text = (await $.fs.exists(path)) ? await $.fs.read(path) : ''
50  const list = parseIdeas(text)
51  await update($, ideas, () => list)
52  await report($, list)
53
54  return list
55}
56
57async function save($: EngineInterface, list: string[]): Promise<void> {
58  const path = await ideasFile($)
59  if (list.length > 0) {
60    await $.fs.write(path, formatIdeas(list))
61  } else if (await $.fs.exists(path)) {
62    await $.process.run(['rm', '-f', path])
63  }
64  await update($, ideas, () => list)
65  await report($, list)
66}
67
68async function report($: EngineInterface, list: readonly string[]): Promise<void> {
69  await publish($, {
70    icon: '💡',
71    title: 'Ideas',
72    status: list.length === 0 ? 'None for this folder' : `${list.length} for this folder`,
73    attention: 'none',
74    actions: [{ key: 'open', label: 'Open' }],
75  })
76}
77
78async function addIdea($: EngineInterface, text: string): Promise<boolean> {
79  const idea = normalizeIdea(text)
80  if (idea.length === 0) {
81    return false
82  }
83  const list = await load($)
84  await save($, [...list, idea])
85
86  return true
87}
88
89async function removeIdea($: EngineInterface, idea: string): Promise<boolean> {
90  const list = await load($)
91  const index = list.indexOf(idea)
92  if (index === -1) {
93    return false
94  }
95  await save($, list.filter((_, position) => position !== index))
96
97  return true
98}
99
100async function workOn($: EngineInterface, idea: string): Promise<void> {
101  const draft = await $.prompt.read()
102  const isEmpty = draft.text.trim().length === 0
103  const filled = await $.prompt.fill({ text: isEmpty ? idea : `\n${idea}`, mode: isEmpty ? 'replace' : 'append' })
104  if (!filled.isFilled) {
105    $.ui.toast('The prompt box is busy; the idea stays in the list.')
106    return
107  }
108  await removeIdea($, idea)
109  await $.ui.close({ id: LIST_PANE })
110  if (await isDrawnRemotely($)) {
111    await $.ui.close({ id: CAPTURE_PANE })
112  }
113}
114
115// The desktop app and the editor draw one Ideas pane, the field above the list;
116// the terminal keeps the inline capture field apart from the list.
117async function isDrawnRemotely($: EngineInterface): Promise<boolean> {
118  const surfaces = await $.session.surfaces()
119
120  return surfaces.some(i => i !== 'terminal')
121}
122
123async function openCapture($: EngineInterface): Promise<void> {
124  await load($)
125  const isRemote = await isDrawnRemotely($)
126  await $.ui.open({ id: CAPTURE_PANE, title: isRemote ? 'Ideas' : 'New idea', focus: true, closeOnEscape: true, rows: 4 })
127}
128
129async function openList($: EngineInterface): Promise<void> {
130  if (await isDrawnRemotely($)) {
131    await openCapture($)
132    return
133  }
134  await load($)
135  await $.ui.open({ id: LIST_PANE, title: 'Ideas', focus: true, closeOnEscape: true })
136}
137
138type IdeasElements = Pick<ElementTable<'desktop'>, 'Box' | 'Button' | 'Svg' | 'Text'> & { Input: ElementTable<'desktop'>['Input'] | null }
139
140const IDEA_LABELS = ['➤ Work on it', '✕']
141
142const FIELD_LABEL_WIDTH = 176
143
144const FIELD_HINT = 'Enter saves it here · Claude sees an idea only once you hand it over'
145
146// The field and the buttons lie over the cards, centered on their height: the
147// pictures take no presses. A narrow pane keeps the field beneath its label.
148function drawIdeas($: EngineInterface, ui: IdeasElements, list: readonly string[], folder: string, width: number): RenderElement {
149  const { Box, Button, Input, Svg, Text } = ui
150  const header = headerCard({ width, eyebrow: '💡 IDEAS', title: list.length === 0 ? 'Nothing waiting' : `${list.length} waiting`, counter: folder })
151  const field = fieldCard(width, 'NEW IDEA', FIELD_HINT, FIELD_LABEL_WIDTH)
152  const drawInput = (Field: ElementTable<'desktop'>['Input']) => (
153    <Field
154      key="idea"
155      value=""
156      placeholder="Capture a new idea…"
157      submitLabel="Save"
158      autoFocus
159      onSubmit={value => {
160        void addIdea($, value)
161      }}
162    />
163  )
164
165  return (
166    <Box flexDirection="column" rowGap={1}>
167      <Svg source={header.source} alt={header.alt} width={width} height={header.height} />
168      {Input !== null &&
169        (width >= ROOMY_WIDTH ? (
170          <Box key="new-idea" flexDirection="column">
171            <Svg source={field.source} alt={field.alt} width={width} height={field.height} />
172            <Box position="absolute" top={0} bottom={0} left={columnsOf(FIELD_LABEL_WIDTH)} right={2} flexDirection="column" justifyContent="center">
173              {drawInput(Input)}
174            </Box>
175          </Box>
176        ) : (
177          <Box flexDirection="column">
178            <Text bold dimColor>
179              NEW IDEA
180            </Text>
181            {drawInput(Input)}
182            <Text dimColor>{FIELD_HINT}</Text>
183          </Box>
184        ))}
185      {list.length === 0 ? (
186        <Text dimColor>No ideas yet. The next one that crosses your mind goes in the field above.</Text>
187      ) : (
188        <Box flexDirection="column" rowGap={1}>
189          <Text dimColor bold>
190            WAITING
191          </Text>
192          {list.map((idea, index) => (
193            <Box key={`card-${index}`} flexDirection="column">
194              {ideaCards(width, idea, index, buttonWidthOf(IDEA_LABELS)).map(card => (
195                <Svg source={card.source} alt={card.alt} width={width} height={card.height} />
196              ))}
197              <Box position="absolute" top={0} bottom={0} right={2} flexDirection="row" alignItems="center" columnGap={1}>
198                <Button key={`work-${index}`} label={IDEA_LABELS[0]} onPress={() => workOn($, idea)} />
199                <Button key={`delete-${index}`} dimColor label={IDEA_LABELS[1]} onPress={() => removeIdea($, idea)} />
200              </Box>
201            </Box>
202          ))}
203          <Text dimColor>Work on it moves the idea into the prompt box and off this list.</Text>
204        </Box>
205      )}
206    </Box>
207  )
208}
209
210function folderNameOf(root: string): string {
211  return root.split('/').filter(i => i.length > 0).at(-1) ?? root
212}
213
214function textResult(text: string) {
215  return { result: text }
216}
217
218export const register: Register = on => {
219  on('session.start', async ($, e, next) => {
220    await $.command.register({
221      name: 'idea',
222      description: 'Capture an idea for this folder without interrupting Claude',
223      argumentHint: '[idea]',
224      immediate: true,
225    })
226    await $.command.register({
227      name: 'ideas',
228      description: 'Show the ideas captured for this folder and hand one to Claude',
229      immediate: true,
230    })
231    await $.tool.register({
232      name: 'ideas_list',
233      description:
234        'Lists the ideas the user captured with /idea for the folder this session runs in, numbered. Use it when the user asks to work through, review or pick from their ideas.',
235      inputSchema: { type: 'object', properties: {} },
236    })
237    await $.tool.register({
238      name: 'idea_remove',
239      description:
240        'Removes one idea from this folder\'s list. Call it only once the idea is done or the user dropped it. `number` comes from the latest ideas_list; list again before removing another, since the numbers shift.',
241      inputSchema: {
242        type: 'object',
243        properties: { number: { type: 'integer', minimum: 1 } },
244        required: ['number'],
245      },
246    })
247    await load($)
248
249    return next(e)
250  })
251
252  on('turn.complete', async ($, e, next) => {
253    const result = await next(e)
254    await load($)
255
256    return result
257  })
258
259  on('command.run', { command: 'idea' }, async ($, e) => {
260    if (e.args.trim().length > 0) {
261      if (await addIdea($, e.args)) {
262        $.ui.toast('Idea saved')
263      }
264
265      return {}
266    }
267    await openCapture($)
268
269    return {}
270  })
271
272  on('command.run', { command: 'ideas' }, async $ => {
273    await openList($)
274
275    return {}
276  })
277
278  on('ui.press', { plugin: 'mod-hub', element: 'idea-shell:open' }, async ($, e, next) => {
279    const list = await load($)
280    await (list.length === 0 ? openCapture($) : openList($))
281
282    return next(e)
283  })
284
285  on('tool.call', { tool: LIST_TOOL }, async $ => {
286    const list = await load($)
287
288    return textResult(list.length === 0 ? 'No ideas captured for this folder.' : numberedList(list))
289  }).catch(() => ({ deny: 'idea-shell could not read the ideas file.' }))
290
291  on('tool.call', { tool: REMOVE_TOOL }, async ($, e) => {
292    const number = (e as { number?: unknown }).number
293    const list = await load($)
294    const idea = typeof number === 'number' ? list[number - 1] : undefined
295    if (idea === undefined) {
296      return textResult(`No idea number ${String(number)}; the list has ${list.length}.`)
297    }
298    await removeIdea($, idea)
299
300    return textResult(`Removed: ${idea}`)
301  }).catch(() => ({ deny: 'idea-shell could not update the ideas file.' }))
302
303  on('ui.render', { component: 'Pane', requestId: CAPTURE_PANE }, async ($, e) => {
304    // Asked by surface, not by `'Input' in` the table: the mobile table carries an
305    // Input that draws nothing.
306    if (e.surface === 'mobile') {
307      const { Text } = $.ui.resolve(e)
308
309      return <Text dimColor>This app draws no text field. /idea followed by the idea saves it.</Text>
310    }
311    if (e.surface !== 'terminal') {
312      const { Box, Button, Input, Svg, Text } = $.ui.resolve(e)
313
314      // Reading the list makes every save redraw the pane, which empties the field.
315      return drawIdeas($, { Box, Button, Input, Svg, Text }, await read($, ideas), folderNameOf(await $.session.root()), cardWidthOf(e.props.bodyColumns))
316    }
317    // Reading the list makes every save redraw the pane, which empties the field.
318    const count = (await read($, ideas)).length
319    const { Box, Input, Text } = $.ui.resolve(e)
320    const hint = `${count} ${count === 1 ? 'idea' : 'ideas'} for this folder · Shift+Enter adds a line · Esc closes`
321
322    return (
323      <Box flexDirection="column">
324        <Input
325          key="idea"
326          value=""
327          placeholder="New idea"
328          submitLabel="save"
329          autoFocus
330          onSubmit={value => {
331            void addIdea($, value)
332          }}
333        />
334        <Text dimColor>{hint}</Text>
335      </Box>
336    )
337  })
338
339  on('ui.render', { component: 'Pane', requestId: LIST_PANE }, async ($, e) => {
340    const { Box, Text, Button } = $.ui.resolve(e)
341    const list = await read($, ideas)
342    if (e.surface !== 'terminal') {
343      const { Svg } = $.ui.resolve(e)
344
345      return drawIdeas($, { Box, Button, Input: null, Svg, Text }, list, folderNameOf(await $.session.root()), cardWidthOf(e.props.bodyColumns))
346    }
347    if (list.length === 0) {
348      return <Text dimColor>No ideas for this folder. /idea captures one.</Text>
349    }
350
351    return (
352      <Box flexDirection="column">
353        {list.map((idea, index) => (
354          <Box key={`row-${index}`}>
355            <Button key={`work-${index}`} plain label={previewOf(idea)} onPress={() => workOn($, idea)} />
356            <Button key={`delete-${index}`} plain dimColor label="delete" onPress={() => removeIdea($, idea)} />
357          </Box>
358        ))}
359        <Box marginTop={1}>
360          <Text dimColor>Pressing an idea puts it into the prompt and removes it from the list.</Text>
361        </Box>
362      </Box>
363    )
364  })
365
366  // The terminal draws the mode labels itself, so the count joins them there.
367  // On the desktop, status-band draws the footer from the labels it was handed,
368  // whichever order the mods load in; only a drawn tree survives that.
369  // The desktop app holds a slash command typed mid-turn until the turn ends,
370  // so the bulb is drawn even with no ideas: its press reaches the mod at once.
371  // With mod-hub loaded, its toolbox takes that place.
372  // The desktop draws a footer's buttons ahead of its text, so the bulb takes
373  // no separator; one would end up beside the next mod's.
374  on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
375    const count = (await read($, ideas)).length
376    if (e.surface === 'terminal') {
377      return count === 0 ? next(e) : next({ ...e, props: { ...e.props, modes: [...e.props.modes, `💡 ${count}`] } })
378    }
379    if (await read($, isHubbed)) {
380      return next(e)
381    }
382    const below = await next(e)
383    const { Box, Button, Text } = $.ui.resolve(e)
384    const rest = below.type !== 'engine' ? below : e.props.modes.length === 0 ? null : <Text dimColor>{e.props.modes.join(' & ')}</Text>
385
386    return (
387      <Box flexDirection="row" alignItems="center">
388        <Button key="capture-idea" plain dimColor label={count === 0 ? '💡' : `💡 ${count}`} onPress={() => openCapture($)} />
389        {rest}
390      </Box>
391    )
392  })
393}
394
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/ideas.ts 72 lines
1// One Markdown bullet per idea, continuation lines indented by two spaces.
2// Nothing else goes into the file, so reading it costs Claude only the ideas.
3export function parseIdeas(text: string): string[] {
4  const ideas: string[][] = []
5  for (const line of text.replace(/\r\n?/g, '\n').split('\n')) {
6    if (line.startsWith('- ')) {
7      ideas.push([line.slice(2)])
8      continue
9    }
10    const current = ideas.at(-1)
11    if (current !== undefined) {
12      current.push(line.startsWith('  ') ? line.slice(2) : line)
13      continue
14    }
15    // Text written by hand above the first bullet is kept as an idea of its own
16    // instead of being dropped on the next save.
17    if (line.trim().length > 0) {
18      ideas.push([line])
19    }
20  }
21
22  return ideas.map(i => i.join('\n').trim()).filter(i => i.length > 0)
23}
24
25export function formatIdeas(ideas: readonly string[]): string {
26  if (ideas.length === 0) {
27    return ''
28  }
29  const blocks = ideas.map(idea => {
30    const [first = '', ...rest] = idea.split('\n')
31    const continued = rest.map(line => (line.length === 0 ? '' : `  ${line}`))
32
33    return [`- ${first}`, ...continued].join('\n')
34  })
35
36  return `${blocks.join('\n')}\n`
37}
38
39export function normalizeIdea(text: string): string {
40  return text.replace(/\r\n?/g, '\n').trim()
41}
42
43// The file mirrors the folder's path, so every folder keeps its own list and the
44// same folder maps to the same file on every machine that shares the home layout.
45export function ideasFileOf(folder: string, home: string, ideasDirectory: string): string {
46  const path = trimSeparators(folder)
47  const homePath = trimSeparators(home)
48  if (homePath.length > 0 && path === homePath) {
49    return `${ideasDirectory}/home.md`
50  }
51  if (homePath.length > 0 && path.startsWith(`${homePath}/`)) {
52    return `${ideasDirectory}/home/${path.slice(homePath.length + 1)}.md`
53  }
54  const relative = path.replace(/^\/+/, '').replace(/:/g, '')
55
56  return relative.length === 0 ? `${ideasDirectory}/root.md` : `${ideasDirectory}/root/${relative}.md`
57}
58
59function trimSeparators(path: string): string {
60  return path.replace(/\\/g, '/').replace(/\/+$/, '')
61}
62
63export function previewOf(idea: string): string {
64  const [first = ''] = idea.split('\n')
65
66  return idea.includes('\n') ? `${first} …` : first
67}
68
69export function numberedList(ideas: readonly string[]): string {
70  return ideas.map((idea, index) => `${index + 1}. ${idea.split('\n').join('\n   ')}`).join('\n')
71}
72
hooks/look.ts 21 lines
1import { LINE, PAD, blockSections, cards, parseBlocks, plainOf } from './svg'
2import type { Card } from './svg'
3
4export { buttonWidthOf, headerCard } from './svg'
5export type { Card } from './svg'
6
7const BADGE = 22
8
9// One idea, numbered, its Markdown drawn as written; `reserve` keeps the text
10// clear of the native buttons laid over the card's right edge.
11export function ideaCards(width: number, idea: string, index: number, reserve: number): Card[] {
12  const textX = PAD + BADGE + 14
13  const center = PAD + LINE / 2
14  const badge = [
15    `<circle class="badge" cx="${PAD + BADGE / 2}" cy="${center}" r="${BADGE / 2}"/>`,
16    `<text class="badge-t" x="${PAD + BADGE / 2}" y="${center + 4.5}" font-size="12" font-weight="700" text-anchor="middle">${index + 1}</text>`,
17  ].join('')
18
19  return cards(width, 'card', blockSections(parseBlocks(idea), textX, width - textX - PAD - reserve), `${index + 1}. ${plainOf(idea.replace(/\s+/gu, ' '))}`, badge)
20}
21
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
types/index.d.ts 11 lines
1export type Idea = string
2
3declare module 'claude-code' {
4  interface PluginState {
5    'idea-shell': {
6      ideas: Idea[]
7      isHubbed: boolean
8    }
9  }
10}
11