SLOPSHOPPER

cache-watch

Shows how long the prompt cache stays warm and suggests compacting a large context at the right moment

bandspinnerguardtoastprompttimer
★ 2v0.1.0MITupdated 2026-10-16MichaelP17/claude-mods/cache-watch
A shopper browsing a rack in a slop shop
README

cache-watch

Shows how long the prompt cache stays warm and suggests compacting a large context at the moments where it pays off.

Every model request re-sends the whole conversation. The prompt cache makes that cheap, but it expires a fixed time after the last request — one hour in Claude Code, five minutes under usage overage. A request on an expired cache re-reads the entire context at the cache write price, which on a large context is the most expensive single request of a session. This mod keeps that moment visible and offers to shrink the context before it happens.

Countdown

ShownMeaning
⏳ 42mWarm for another 42 minutes
⏳ 8m, yellowExpires within warnMinutes
🧊 coldExpired; the next request rebuilds the cache over the whole context

The countdown sits in the footer under the prompt: beside the model picker in the desktop app, among the mode labels in the terminal. It shares that footer with status-band and idea-shell.

It only appears when there is something to decide: from statusFromTokens of context on, or while the cache is about to expire. A small context on a cold cache shows nothing, and neither does the time right after a compaction, when the next request rebuilds the cache anyway.

The timer starts over with every model request of the main conversation, including the steps Claude takes on its own between tool calls. Subagents have a cache of their own and do not count.

With mod-hub loaded, the desktop footer leaves the countdown to its 🧰: the Cache row always says how long the cache stays warm and how large the context is, the button turns yellow while it is about to expire, and Compact now appears between turns when compacting pays off.

Suggestions

From largeContextTokens of context on, a band above the prompt offers Compact, Write handoff and Dismiss:

WhenWhy then
The cache expires in warnMinutes and you are idleCompacting on a warm cache reads the context at the cache read price
A turn committed or ran tests greenA unit of work ended; nothing in flight gets lost

A running turn is never interrupted. In the desktop app the band is a card with a ring for the time the cache has left and a bar at its foot that runs out with it, the buttons laid over its right edge.

Write handoff sends a prompt that asks Claude to write HANDOFF.md at the repository root: goal, state, decisions with their reasons, rejected approaches, open points and the exact next step.

When a conversation starts in a repository that has a HANDOFF.md, a toast names it and Claude is told where it lies, so asking it to continue is enough for the next session. Only the path is added to the context, not the file's content.

When you send a prompt on a cold cache with a large context, a dialog asks whether to compact first. The rebuild is paid either way; compacting first pays it on the smaller remainder.

Lifetime learned from the server

The server reports with every response how much of the prompt came from the cache. When a request finds nothing cached although the timer still ran, the mod switches to a five-minute lifetime; when a request is served from the cache after more than five minutes, it switches back. Prompts under 20k tokens teach nothing, since they may be too short to be cached at all.

Configuration

OptionDefaultMeaning
ttlMinutes60Cache lifetime Claude Code uses
warnMinutes10How early before expiry to suggest compacting
statusFromTokens300000Context size from which the countdown shows
largeContextTokens300000Context size from which the mod suggests compacting

Change them in /config, or in ~/.claude/settings.json under pluginConfigs["cache-watch"].options.

Works with compact-shaper

Compact runs a normal compaction. With compact-shaper loaded, its summary follows the structure of a handoff.

Uninstall

Remove the mod from CLAUDE_CODE_PLUGIN_DIRS. Its options in pluginConfigs can be deleted.

Source 6 files
hooks/register.tsx 390 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, Timer } from 'claude-code'
3
4import type { CacheReading } from '../types'
5import {
6  HANDOFF_FILE,
7  HANDOFF_PROMPT,
8  contextTokensOf,
9  footerOf,
10  formatRemaining,
11  formatTokens,
12  handoffContextOf,
13  hubStatusOf,
14  isCold,
15  isMilestoneCommand,
16  learnTtl,
17  remainingMs,
18} from './cache'
19import type { HubCall, HubEntry } from './hub'
20import { buttonWidthOf, cacheBandCard } from './look'
21
22const COMPACT_FIRST = 'Compact first'
23const SEND_AS_IS = 'Send as is'
24const EXPIRING_COLOR = '#d4a017'
25
26const BAND_LABELS = ['Compact', 'Write handoff', 'Dismiss']
27
28const BAND_TEXT = {
29  expiring: { title: '⏳ Cache expires soon', hint: 'compacting now is cheaper than after it expires' },
30  milestone: { title: '🏁 Milestone reached', hint: 'a good moment to compact' },
31}
32
33const INITIAL: CacheReading = { lastRequestAt: null, ttlMs: 60 * 60 * 1000, contextTokens: 0, isRebuildPending: false }
34
35const reading = atom({ plugin: 'cache-watch', key: 'reading' } as const, INITIAL)
36const suggestion = atom({ plugin: 'cache-watch', key: 'suggestion' } as const, null)
37const warnedFor = atom({ plugin: 'cache-watch', key: 'warnedFor' } as const, null)
38const isWorking = atom({ plugin: 'cache-watch', key: 'isWorking' } as const, false)
39const footer = atom({ plugin: 'cache-watch', key: 'footer' } as const, null)
40const isHubbed = atom({ plugin: 'cache-watch', key: 'isHubbed' } as const, false)
41
42// Set from the plugin's options when the module registers.
43let settings = { ttlMs: 60 * 60 * 1000, warnMs: 10 * 60 * 1000, largeContextTokens: 300_000, statusFromTokens: 300_000 }
44let hadMilestone = false
45let ticker: Timer | undefined
46let published: string | null = null
47
48// Without mod-hub the call throws, and the mod keeps its own footer countdown.
49async function publish($: EngineInterface, entry: HubEntry): Promise<void> {
50  const text = JSON.stringify(entry)
51  if (text === published) {
52    return
53  }
54  let isReached = true
55  try {
56    await ($ as unknown as HubCall).hub.set({ id: 'cache-watch', ...entry })
57  } catch {
58    isReached = false
59  }
60  published = isReached ? text : null
61  if ((await read($, isHubbed)) !== isReached) {
62    await update($, isHubbed, () => isReached)
63  }
64}
65
66// Written only on a change, so the ticker does not redraw the footer every
67// fifteen seconds for a minute count that stayed the same.
68async function refreshFooter($: EngineInterface): Promise<void> {
69  const now = await $.clock.now()
70  const visibility = { fromTokens: settings.statusFromTokens, warnMs: settings.warnMs }
71  const next = footerOf(await read($, reading), now, visibility)
72  const current = await read($, footer)
73  if (next?.label !== current?.label || next?.isExpiring !== current?.isExpiring) {
74    await update($, footer, () => next)
75  }
76  const canCompact = (await read($, suggestion)) !== null && !(await read($, isWorking))
77  await publish($, {
78    icon: '⏳',
79    title: 'Cache',
80    status: hubStatusOf(await read($, reading), now),
81    attention: next?.isExpiring === true ? 'warning' : 'none',
82    actions: canCompact ? [{ key: 'compact', label: 'Compact now' }] : [],
83  })
84}
85
86async function checkExpiring($: EngineInterface): Promise<void> {
87  if (await read($, isWorking)) {
88    return
89  }
90  const now = await $.clock.now()
91  const current = await read($, reading)
92  const remaining = remainingMs(current, now)
93  if (remaining === null || remaining === 0 || remaining > settings.warnMs || current.isRebuildPending) {
94    return
95  }
96  if (current.contextTokens < settings.largeContextTokens) {
97    return
98  }
99  if ((await read($, warnedFor)) === current.lastRequestAt) {
100    return
101  }
102  await update($, warnedFor, () => current.lastRequestAt)
103  await update($, suggestion, () => ({ kind: 'expiring', contextTokens: current.contextTokens }))
104  $.ui.toast(`Prompt cache expires in ${formatRemaining(remaining)} · context ${formatTokens(current.contextTokens)}`, {
105    timeoutMs: 10_000,
106  })
107}
108
109async function tick($: EngineInterface): Promise<void> {
110  await refreshFooter($)
111  await checkExpiring($)
112}
113
114async function markCompacted($: EngineInterface, tokensAfter: number | undefined): Promise<void> {
115  await update($, reading, current => ({
116    ...current,
117    contextTokens: tokensAfter ?? current.contextTokens,
118    isRebuildPending: true,
119  }))
120  await update($, suggestion, () => null)
121  await refreshFooter($)
122}
123
124async function compactNow($: EngineInterface): Promise<void> {
125  await update($, suggestion, () => null)
126  const result = await $.session.compact()
127  if (result.skip === undefined) {
128    await markCompacted($, result.tokensAfter)
129  }
130}
131
132// The handoff sits at the repository root, so a session started in a
133// subfolder still finds it.
134async function handoffPathOf($: EngineInterface): Promise<string | null> {
135  let directory = await $.session.cwd()
136  while (true) {
137    const candidate = `${directory}/${HANDOFF_FILE}`
138    if (await $.fs.exists(candidate)) {
139      return candidate
140    }
141    const parent = directory.slice(0, directory.lastIndexOf('/'))
142    if ((await $.fs.exists(`${directory}/.git`)) || parent.length === 0 || parent === directory) {
143      return null
144    }
145    directory = parent
146  }
147}
148
149export const register: Register = (on, options) => {
150  settings = {
151    ttlMs: Number(options.ttlMinutes ?? 60) * 60_000,
152    warnMs: Number(options.warnMinutes ?? 10) * 60_000,
153    largeContextTokens: Number(options.largeContextTokens ?? 300_000),
154    statusFromTokens: Number(options.statusFromTokens ?? 300_000),
155  }
156
157  on('session.start', async ($, e, next) => {
158    ticker?.cancel()
159    ticker = $.clock.every(15_000, () => {
160      void tick($)
161    })
162    await refreshFooter($)
163
164    return next(e)
165  })
166
167  on('prompt.context', async ($, e, next) => {
168    const result = await next(e)
169    const path = await handoffPathOf($)
170    if (path === null) {
171      return result
172    }
173    $.ui.toast(`Handoff ready: ${path}`, { timeoutMs: 10_000 })
174
175    return { ...result, blocks: [...result.blocks, { name: 'handoff', text: handoffContextOf(path) }] }
176  })
177
178  // Every model request of the main conversation reads the cache and starts
179  // its lifetime over. The lifetime counts from the request's start.
180  on('turn.step', async function* ($, e, next) {
181    if (e.agentId !== undefined) {
182      return yield* next(e)
183    }
184    const startedAt = await $.clock.now()
185    const result = yield* next(e)
186    const usage = result.usage
187    if (usage !== null) {
188      await update($, reading, current => ({
189        lastRequestAt: startedAt,
190        ttlMs: learnTtl(current, startedAt, usage, settings.ttlMs),
191        contextTokens: contextTokensOf(usage),
192        isRebuildPending: false,
193      }))
194      await refreshFooter($)
195    }
196
197    return result
198  })
199
200  on('turn.start', async ($, e, next) => {
201    hadMilestone = false
202    await update($, isWorking, () => true)
203
204    return next(e)
205  })
206
207  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
208    const ran = await next(e)
209    if (ran.deny === undefined && ran.isError !== true && typeof e.command === 'string' && isMilestoneCommand(e.command)) {
210      hadMilestone = true
211    }
212
213    return ran
214  })
215
216  on('turn.complete', async ($, e, next) => {
217    const result = await next(e)
218    await update($, isWorking, () => false)
219    const current = await read($, reading)
220    const now = await $.clock.now()
221    if (hadMilestone && current.contextTokens >= settings.largeContextTokens && !isCold(current, now)) {
222      await update($, suggestion, () => ({ kind: 'milestone', contextTokens: current.contextTokens }))
223    }
224    hadMilestone = false
225    await refreshFooter($)
226
227    return result
228  })
229
230  // On a cold cache the next request re-reads the whole context at the write
231  // price anyway. Compacting first means paying that price on the small
232  // remainder instead.
233  on('prompt.submit', async ($, e, next) => {
234    if (e.origin.kind !== 'composer' || e.turnId !== undefined || e.text.trimStart().startsWith('/')) {
235      return next(e)
236    }
237    await update($, suggestion, () => null)
238    const current = await read($, reading)
239    const now = await $.clock.now()
240    if (current.isRebuildPending || !isCold(current, now) || current.contextTokens < settings.largeContextTokens) {
241      return next(e)
242    }
243    let answer: string
244    try {
245      answer = await $.ui.ask(
246        `The prompt cache has expired and the context holds ${formatTokens(current.contextTokens)} tokens. Sending now re-reads all of it at the cache write price. Compact before sending?`,
247        { options: [COMPACT_FIRST, SEND_AS_IS], header: 'Cache' },
248      )
249    } catch {
250      answer = SEND_AS_IS
251    }
252    if (answer === COMPACT_FIRST) {
253      try {
254        await compactNow($)
255      } catch (error) {
256        $.ui.toast(`Compaction failed, sending as is: ${error instanceof Error ? error.message : String(error)}`)
257      }
258    }
259
260    return next(e)
261  })
262
263  // Catches /compact and automatic compactions. A compaction another plugin
264  // answers without passing on is not seen here; the next request's usage
265  // corrects the reading then.
266  on('session.compact', async ($, e, next) => {
267    const result = await next(e)
268    if (e.agentId === undefined && e.trigger !== 'precompute' && result.skip === undefined) {
269      await markCompacted($, result.tokensAfter)
270    }
271
272    return result
273  })
274
275  on('session.end', async ($, e, next) => {
276    if (e.reason === 'clear') {
277      await update($, reading, current => ({ ...INITIAL, ttlMs: current.ttlMs }))
278      await update($, suggestion, () => null)
279      await update($, warnedFor, () => null)
280      await update($, footer, () => null)
281    }
282
283    return next(e)
284  })
285
286  // The terminal draws the mode labels itself, so the countdown joins them
287  // there. On the desktop, status-band draws the footer from the labels it was
288  // handed, whichever order the mods load in; only a drawn tree survives that.
289  // Offered only between turns, as the band above the prompt does.
290  on('ui.press', { plugin: 'mod-hub', element: 'cache-watch:compact' }, async ($, e, next) => {
291    if (await read($, isWorking)) {
292      $.ui.toast('Claude is working; compact once the turn is done.')
293    } else {
294      void compactNow($)
295    }
296
297    return next(e)
298  })
299
300  on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
301    const current = await read($, footer)
302    if (current === null) {
303      return next(e)
304    }
305    if (e.surface === 'terminal') {
306      return next({ ...e, props: { ...e.props, modes: [...e.props.modes, current.label] } })
307    }
308    if (await read($, isHubbed)) {
309      return next(e)
310    }
311    const below = await next(e)
312    const { Box, Text } = $.ui.resolve(e)
313    const rest = below.type !== 'engine' ? below : e.props.modes.length === 0 ? null : <Text dimColor>{e.props.modes.join(' & ')}</Text>
314    const tone = current.isExpiring ? { color: EXPIRING_COLOR } : { dimColor: true }
315
316    return (
317      <Box flexDirection="row">
318        <Text {...tone}>{current.label}</Text>
319        {rest !== null && <Text dimColor> · </Text>}
320        {rest}
321      </Box>
322    )
323  })
324
325  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
326    const current = await read($, suggestion)
327    if (current === null || e.props.hasSurvey || e.props.isWorking) {
328      return next(e)
329    }
330    // Another mod's band (session-relay) may be drawn beneath; it stays under
331    // this one. An `engine` element means none was, and it cannot be nested.
332    const below = await next(e)
333    const beneath = below.type === 'engine' ? null : below
334    const { Box, Button, Text } = $.ui.resolve(e)
335    const text = BAND_TEXT[current.kind]
336    const writeHandoff = async () => {
337      await update($, suggestion, () => null)
338      await $.prompt.submit({ text: HANDOFF_PROMPT })
339    }
340    if (e.surface !== 'terminal' && e.surface !== 'mobile') {
341      const { Svg } = $.ui.resolve(e)
342      const now = await $.clock.now()
343      const cache = await read($, reading)
344      const remaining = remainingMs(cache, now) ?? 0
345      const width = Math.max(240, Math.min(1600, (e.props.bodyColumns || 100) * 8 - 8))
346      const card = cacheBandCard(width, {
347        isExpiring: current.kind === 'expiring',
348        title: text.title,
349        hint: `${formatTokens(current.contextTokens)} context · ${text.hint}`,
350        ring: remaining === 0 ? 'cold' : formatRemaining(remaining),
351        remainingMs: remaining,
352        ttlMs: cache.ttlMs,
353        reserve: buttonWidthOf(BAND_LABELS),
354      })
355
356      // The buttons lie over the card's right edge: the picture takes no presses.
357      return (
358        <Box flexDirection="column">
359          <Box key="cache-band" flexDirection="column">
360            <Svg source={card.source} alt={card.alt} width={width} height={card.height} />
361            <Box position="absolute" top={0} bottom={0} right={2} flexDirection="row" alignItems="center" columnGap={1}>
362              <Button key="compact" label="Compact" hotkey="c" variant="primary" onPress={() => compactNow($)} />
363              <Button key="handoff" label="Write handoff" hotkey="h" onPress={writeHandoff} />
364              <Button key="dismiss" label="Dismiss" hotkey="d" role="dismiss" onPress={() => update($, suggestion, () => null)} />
365            </Box>
366          </Box>
367          {beneath}
368        </Box>
369      )
370    }
371
372    return (
373      <Box flexDirection="column">
374        <Box flexDirection="row" flexWrap="wrap" alignItems="center" columnGap={3}>
375          <Text>
376            <Text bold>{text.title}</Text>
377            <Text dimColor>{` · ${formatTokens(current.contextTokens)} context · ${text.hint}`}</Text>
378          </Text>
379          <Box flexDirection="row" columnGap={1}>
380            <Button key="compact" label="Compact" hotkey="c" variant="primary" onPress={() => compactNow($)} />
381            <Button key="handoff" label="Write handoff" hotkey="h" onPress={writeHandoff} />
382            <Button key="dismiss" label="Dismiss" hotkey="d" role="dismiss" onPress={() => update($, suggestion, () => null)} />
383          </Box>
384        </Box>
385        {beneath}
386      </Box>
387    )
388  })
389}
390
hooks/cache.ts 128 lines
1import type { CacheReading, Footer } from '../types'
2
3export const SHORT_TTL_MS = 5 * 60 * 1000
4
5// Below this prompt size a cache miss says nothing about the TTL: the prefix
6// may simply be too short to be cached at all.
7const MIN_LEARNING_TOKENS = 20_000
8
9export type Usage = {
10  input_tokens: number
11  output_tokens: number
12  cache_read_input_tokens: number
13  cache_creation_input_tokens: number
14}
15
16export function promptTokensOf(usage: Usage): number {
17  return usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens
18}
19
20export function contextTokensOf(usage: Usage): number {
21  return promptTokensOf(usage) + usage.output_tokens
22}
23
24export function remainingMs(reading: CacheReading, now: number): number | null {
25  if (reading.lastRequestAt === null) {
26    return null
27  }
28
29  return Math.max(0, reading.lastRequestAt + reading.ttlMs - now)
30}
31
32export function isCold(reading: CacheReading, now: number): boolean {
33  return remainingMs(reading, now) === 0
34}
35
36// The server is the only one who knows the real TTL. A request that found
37// nothing cached although the timer still ran means a shorter lifetime (usage
38// overage drops it to five minutes); one served after more than five minutes
39// means the configured lifetime holds again.
40export function learnTtl(reading: CacheReading, startedAt: number, usage: Usage, configuredTtlMs: number): number {
41  if (reading.lastRequestAt === null || reading.isRebuildPending) {
42    return reading.ttlMs
43  }
44  const prompt = promptTokensOf(usage)
45  if (prompt < MIN_LEARNING_TOKENS) {
46    return reading.ttlMs
47  }
48  const gap = startedAt - reading.lastRequestAt
49  const wasServed = usage.cache_read_input_tokens >= prompt * 0.5
50  if (!wasServed && gap > SHORT_TTL_MS && gap < reading.ttlMs) {
51    return SHORT_TTL_MS
52  }
53  if (wasServed && gap > reading.ttlMs) {
54    return configuredTtlMs
55  }
56
57  return reading.ttlMs
58}
59
60export function formatTokens(tokens: number): string {
61  if (tokens >= 1_000_000) {
62    return `${(tokens / 1_000_000).toFixed(1)}M`
63  }
64  if (tokens >= 1000) {
65    return `${Math.round(tokens / 1000)}k`
66  }
67
68  return String(tokens)
69}
70
71export function formatRemaining(ms: number): string {
72  return ms < 60_000 ? '<1m' : `${Math.floor(ms / 60_000)}m`
73}
74
75export type Visibility = { fromTokens: number; warnMs: number }
76
77// The countdown only earns its place when there is something to decide: a
78// large context, or a cache about to go cold. After a compaction the next
79// request rebuilds the cache anyway, so there is nothing to count down.
80export function footerOf(reading: CacheReading, now: number, visibility: Visibility): Footer | null {
81  const remaining = remainingMs(reading, now)
82  if (remaining === null || reading.isRebuildPending) {
83    return null
84  }
85  const isExpiring = remaining > 0 && remaining <= visibility.warnMs
86  if (reading.contextTokens < visibility.fromTokens && !isExpiring) {
87    return null
88  }
89  if (remaining === 0) {
90    return { label: '🧊 cold', isExpiring: false }
91  }
92
93  return { label: `⏳ ${formatRemaining(remaining)}`, isExpiring }
94}
95
96// The hub always says where the cache stands, unlike the footer, which stays
97// quiet for a small context.
98export function hubStatusOf(reading: CacheReading, now: number): string {
99  const remaining = remainingMs(reading, now)
100  if (remaining === null) {
101    return 'No request yet'
102  }
103  if (reading.isRebuildPending) {
104    return 'Rebuilt by the next request'
105  }
106  const context = `${formatTokens(reading.contextTokens)} context`
107
108  return remaining === 0 ? `Cold · ${context}` : `Warm for ${formatRemaining(remaining)} · ${context}`
109}
110
111const COMMIT = /\bgit\s+(?:-C\s+\S+\s+)?commit\b/
112const TESTS = /\b(?:dotnet\s+test|(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test|pytest|go\s+test|cargo\s+test|vitest|jest|mvn\s+test|gradle\s+test|claude\s+plugin\s+test)\b/
113
114// A turn that committed or ran tests green ends a unit of work: compacting
115// there loses nothing that is still in flight.
116export function isMilestoneCommand(command: string): boolean {
117  return COMMIT.test(command) || TESTS.test(command)
118}
119
120export const HANDOFF_FILE = 'HANDOFF.md'
121
122export const HANDOFF_PROMPT =
123  'Write HANDOFF.md at the repository root so a new session can continue from it alone: date and branch, the goal, the current state, decisions and their reasons, approaches that were rejected and why, open points, the exact next step and which files to read first. Replace what an older handoff says. Leave out anything that can be re-read from the code.'
124
125export function handoffContextOf(path: string): string {
126  return `The previous session left a handoff in ${path}. When the person asks to continue without saying with what, read it first and check that branch and recent commits still match it.`
127}
128
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 44 lines
1import { PAD, escape, fitText, frame, svgDocument } from './svg'
2import type { Card } from './svg'
3
4export { buttonWidthOf } from './svg'
5export type { Card } from './svg'
6
7const HEIGHT = 68
8const RING = 40
9
10// The band is drawn once per suggestion, not on every second, so the bar at
11// its foot runs out by itself: a CSS animation as long as the cache has left.
12export function cacheBandCard(
13  width: number,
14  band: { isExpiring: boolean; title: string; hint: string; ring: string; remainingMs: number; ttlMs: number; reserve: number },
15): Card {
16  const tone = band.isExpiring ? 'warning' : 'accent'
17  const fraction = band.ttlMs === 0 ? 0 : Math.max(0, Math.min(1, band.remainingMs / band.ttlMs))
18  const radius = (RING - 4) / 2
19  const center = { x: PAD + RING / 2, y: HEIGHT / 2 - 3 }
20  const circumference = 2 * Math.PI * radius
21  const textX = PAD + RING + 14
22  const maxWidth = width - textX - PAD - band.reserve
23  const barWidth = width - 2 * PAD
24  const seconds = Math.max(1, Math.round(band.remainingMs / 1000))
25  const drain =
26    fraction === 0
27      ? ''
28      : `<style>.drain{transform-box:fill-box;transform-origin:left;animation:drain ${seconds}s linear forwards}@keyframes drain{from{transform:scaleX(1)}to{transform:scaleX(0)}}@media (prefers-reduced-motion: reduce){.drain{animation:none}}</style><rect class="${tone} drain" x="${PAD}" y="${HEIGHT - 9}" width="${(barWidth * fraction).toFixed(1)}" height="3" rx="1.5"/>`
29  const body = [
30    frame(width, HEIGHT, band.isExpiring ? 'card-warning' : 'card-accent'),
31    `<circle cx="${center.x}" cy="${center.y}" r="${radius}" fill="none" stroke="#8b8b8b" stroke-opacity="0.25" stroke-width="4"/>`,
32    fraction === 0
33      ? ''
34      : `<circle cx="${center.x}" cy="${center.y}" r="${radius}" fill="none" stroke="${band.isExpiring ? '#d4a017' : '#d97757'}" stroke-width="4" stroke-linecap="round" stroke-dasharray="${(circumference * fraction).toFixed(2)} ${circumference.toFixed(2)}" transform="rotate(-90 ${center.x} ${center.y})"/>`,
35    `<text class="${tone}" x="${center.x}" y="${center.y + 4}" font-size="11.5" font-weight="700" text-anchor="middle">${escape(band.ring)}</text>`,
36    `<text class="t" x="${textX}" y="${center.y - 3}" font-size="14" font-weight="650">${escape(fitText(band.title, maxWidth, 14, true))}</text>`,
37    `<text class="muted" x="${textX}" y="${center.y + 15}" font-size="12.5">${escape(fitText(band.hint, maxWidth, 12.5))}</text>`,
38    `<rect class="open" x="${PAD}" y="${HEIGHT - 9}" width="${barWidth}" height="3" rx="1.5"/>`,
39    drain,
40  ]
41
42  return { height: HEIGHT, alt: `${band.title}: ${band.hint}`, source: svgDocument(width, HEIGHT, body.join('')) }
43}
44
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 24 lines
1export type CacheReading = {
2  lastRequestAt: number | null
3  ttlMs: number
4  contextTokens: number
5  isRebuildPending: boolean
6}
7
8export type Footer = { label: string; isExpiring: boolean }
9
10export type Suggestion = { kind: 'expiring' | 'milestone'; contextTokens: number } | null
11
12declare module 'claude-code' {
13  interface PluginState {
14    'cache-watch': {
15      reading: CacheReading
16      suggestion: Suggestion
17      warnedFor: number | null
18      footer: Footer | null
19      isWorking: boolean
20      isHubbed: boolean
21    }
22  }
23}
24