SLOPSHOPPER

quick-actions

A band above the prompt with buttons that run saved prompts, skills and shell commands

panebandcommandtoastprocesstimer
★ 1v0.1.4MITupdated 2026-10-23zirkelc/claude-quick-actions
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · quick-actions
│ ┃ Quick actions ✕ › fix the failing auth test and add an audit log call │ ┃ ╭────────────────────────────────────────╮ │ ┃ │ ◆ Quick actions ✕ Close │ ⏺ Read(src/auth.ts) │ ┃ │ 0 actions · 0 on the band │ ⎿ Read 6 lines │ ┃ ╰────────────────────────────────────────╯ ⏺ Update(src/auth.ts) │ ┃ ⎿ Added 2 lines, removed 1 line │ ┃ Actions ⏺ Bash(bun test) │ ┃ + Add action ⎿ 3 pass, 1 fail │ ┃ │ ┃ Band ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ Nothing on the band yet: press ☆ on an acti │ ┃ ✻ Worked for 42s · done 4:20 PM │ ┃ / skill · > prompt · $ shell · [1] hotkey │ ┃ · ★ on the band · ▶ run · ✕ delete › /quick-actions │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Quick actions
╭────────────────────────────────────────────────────────╮ │ ◆ Quick actions ✕ Close │ │ 0 actions · 0 on the band │ ╰────────────────────────────────────────────────────────╯ Actions 0 + Add action Band 0 Nothing on the band yet: press ☆ on an action. / skill · > prompt · $ shell · [1] hotkey · ★ on the band · ▶ run · ✕ delete
README

<h1 align="center">Quick Actions </h1>

<img src="assets/quick-actions-light.gif" alt="A Claude Code session with the quick actions band above the prompt: hotkey 1 runs git fetch, hotkey 3 fills the prompt box with a saved prompt, hotkey 2 runs the /code-review skill and Claude reviews the diff, then /quick-actions opens the pane beside the chat" />

Why

git pull, "review the diff", /commit: things you type ten times a day become one click. Save an action once, pin it to the band, and press it. Actions you use less often stay in a list, one click away from the band.

quick-actions is a Claude Code mod: a plugin of function hooks that draws its own UI inside Claude Code.

Features

  • Four types of action: call a skill or slash command, send a prompt, fill the prompt box to edit before sending, or run a shell command.
  • A band you arrange: pin the actions you want, set their order, and split them over several rows.
  • Colors and hotkeys: give an action a color, and a digit that presses it from an empty prompt box.
  • More actions than the band shows: unpinned actions stay in the list, where ▶ runs them.
  • Plays well with other mods: the band draws above the bands of other mods, and draws nothing when no action is pinned.
  • Same actions everywhere: actions are kept in the mod's store, so every project and session shows them.

Requirements

Claude Code 2.1.287 or later, where mods load by default.

Install

Type these commands at the prompt of a Claude Code terminal session:

/plugin marketplace add zirkelc/agent-plugins
/plugin install quick-actions@zirkelc

Select a scope (user scope is the default).

To try it for one session without installing:

git clone https://github.com/zirkelc/claude-quick-actions.git
claude --plugin-dir ./claude-quick-actions

To uninstall: /plugin uninstall quick-actions@zirkelc.

Usage

<img src="assets/quick-actions-pane-light.png" alt="The quick actions pane beside a finished code review: the Actions list and the Band list with git fetch, /code-review, write tests and explain diff, and the band of colored buttons above the prompt" />

Type /quick-actions to open the pane, and again to close it. The head of the pane counts your actions, the actions on the band and its rows. The pane has two lists. When the pane is 90 columns or wider, the Band list is next to the Actions list; otherwise it is under it. A line at the bottom tells what each symbol means.

Actions lists every saved action:

ControlWhat it does
labelOpens the action's form
☆ / ★Pins the action to the band, or takes it off
▶Runs the action now
✕Deletes the action (press twice)
+ Add actionOpens the form for a new action. A new action is not on the band until you press its ☆

Band lists what the band shows, in order. Each entry has ↑ ↓ to move it and - to take it off the band. Once an action is on the band, + Add new line adds a ↵ new line entry: the entries after it go on the next row of the band.

The form sets the action's type (Call Skill, Fill Prompt, Send Prompt or Run Shell), its color, its hotkey, its label and its text. The preview shows the button as the band draws it. ← Back and Esc go back one step; ✕ Close closes the pane.

TypeWhat a press does
Call SkillRuns /name args at once, as if typed
Fill PromptPuts the text in the prompt box, to edit before sending
Send PromptSends the text to Claude at once
Run ShellRuns the command with sh -c in the session's directory, without Claude; the output goes to the transcript

Skills and prompts wait until Claude is idle. Shell commands run at once.

Options

Set them in /config, or in ~/.claude/settings.json under pluginConfigs["quick-actions@zirkelc"].options:

OptionDefaultWhat it does
columnsthe engine's widthColumns to ask for when the pane docks beside the transcript in the fullscreen layout (24 or more). The engine gives a docked pane at most 45% of the terminal, and a width you drag the pane to wins

What it can access

The mod does only what you set up in the pane. It builds no command, prompt or slash command of its own, and it adds nothing to the text you save.

What it runs, and when. An action runs only when you press its button or its hotkey (a digit, typed while the prompt box is empty), or press ▶ in the pane:

TypeWhat the mod doesEngine call
Call SkillRuns the slash command you saved, for example /commit, with the arguments you saved$.command.run
Fill PromptPuts the text you saved in the prompt box; nothing is sent until you send it$.prompt.fill
Send PromptSends the text you saved to Claude, unchanged, as your own prompt$.prompt.submit
Run ShellRuns the command you saved as sh -c "<your command>" in the session's directory, with a 2 minute time limit. The output goes to the transcript and nowhere else$.process.run

The mod runs no other program, no other slash command and no other prompt. The command text in the shell call comes from your saved action, which is why the directory cannot read it as fixed text.

What it reads. Only its own saved data: your actions and the band order, kept with $.store under the mod's own keys. The text of an action is the only stored data that goes into a command or a prompt, and only into the one you pressed. It reads no files, no conversation, no environment variables and no credentials.

What it sends. The mod itself makes no network calls. A Send Prompt action sends its text to Claude, as if you typed it. A Run Shell command can do anything the command you wrote does, so save only commands you trust.

Other calls. It draws the band, the pane, toasts and transcript lines ($.ui), keeps what the pane shows in session state ($.state), adds the /quick-actions command ($.command.register), and reads the saved actions again every 15 seconds so that actions saved in another session show up ($.clock).

Limits

These come from the mod API:

  • A button label is one plain string, so a colored button keeps the terminal's text color. Light colors (yellow, white) read best with a light terminal theme.
  • A digit hotkey only works for an action on the band, and the band shows it before the label (1: commit).
  • Text inputs are single-line. In the text field, Enter adds a line break, and Save saves.
  • A filled ! text stays a normal prompt; the prompt box cannot be put into shell mode. Use Run Shell instead.

Development

claude plugin validate .
claude plugin test .

To load your checkout in every session, add it to the env block of ~/.claude/settings.json:

{
  "env": {
    "CLAUDE_CODE_PLUGIN_DIRS": "~/Developer/claude-quick-actions"
  }
}

Claude Code writes the API types to .claude-plugin/types/ when it loads the mod, and tsconfig.json extends them, so tsc -p . type-checks the mod after the first load.

hooks/register.tsx holds the hooks, the state and every call on the engine, because the mod API follows the engine interface only into functions of the same file. The rest is pure: hooks/actions.ts (the action model and the band order) and hooks/views/ (the band, the list and the form). Each file under tests/ covers the file of the same name under hooks/.

License

MIT

Source 15 files
hooks/register.tsx 338 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, PluginOptions, Register, Timer } from 'claude-code'
3
4import type { CustomAction, Draft } from '../types'
5import {
6  type Action,
7  arrangeOrder,
8  checkDraft,
9  moveEntry,
10  newlineEntry,
11  newDraft,
12  normalizeText,
13  rowsOf,
14  toAction,
15  togglePin,
16} from './actions'
17import { POLL_MS, SHELL_TIMEOUT_MS } from './limits'
18import { COMMAND, LEGACY_PANES, PANE, PANE_IN_BAND_TEXT, PANE_OPTIONS, STEP_BACK_REASON, STORE_ACTIONS, STORE_ORDER } from './names'
19import { bandView } from './views/band-view'
20import type { BandHandlers, PaneHandlers } from './views/kit'
21import { type PaneModel, paneView } from './views/pane/pane-view'
22
23const customState = atom({ plugin: 'quick-actions', key: 'custom' } as const, [])
24const orderState = atom({ plugin: 'quick-actions', key: 'order' } as const, [])
25const draftState = atom({ plugin: 'quick-actions', key: 'draft' } as const, null)
26const pendingDeleteState = atom({ plugin: 'quick-actions', key: 'pendingDelete' } as const, null)
27const paneOpenState = atom({ plugin: 'quick-actions', key: 'isPaneOpen' } as const, false)
28const paneInBandState = atom({ plugin: 'quick-actions', key: 'isPaneInBand' } as const, false)
29
30/** Reads the saved actions and their order from the store, so changes from other sessions show up. */
31export async function loadStore($: EngineInterface) {
32  const stored = await $.store.get(STORE_ACTIONS)
33  const custom = Array.isArray(stored) ? (stored as Array<CustomAction>) : []
34  await update($, customState, () => custom)
35  const order = arrangeOrder(await $.store.get(STORE_ORDER), custom.map(action => action.id))
36  await update($, orderState, () => order)
37}
38
39/** Saves the actions; a deleted one leaves the band too. */
40async function writeCustom($: EngineInterface, custom: Array<CustomAction>) {
41  await $.store.set(STORE_ACTIONS, custom)
42  await update($, customState, () => custom)
43  await writeOrder($, arrangeOrder(await read($, orderState), custom.map(action => action.id)))
44}
45
46/** Saves the band: its actions and new lines, in order. */
47async function writeOrder($: EngineInterface, order: Array<string>) {
48  await $.store.set(STORE_ORDER, order)
49  await update($, orderState, () => order)
50}
51
52/** The width to ask for when the pane docks, from the options; none leaves it to the engine. */
53let paneColumns: number | undefined
54
55/** The pane width from the options: a whole number of 24 or more, else none. */
56function paneColumnsOf(options: PluginOptions): number | undefined {
57  const columns = options.columns
58  return typeof columns === 'number' && Number.isFinite(columns) ? Math.max(24, Math.round(columns)) : undefined
59}
60
61/**
62 * Opens the pane. Called before any other await of a press, so the engine
63 * counts the open as the person's. A pane without room to draw would wait
64 * undrawn, so it is closed again and the band shows its views instead.
65 */
66async function openPane($: EngineInterface): Promise<boolean> {
67  const opened = await $.ui.open(paneColumns === undefined ? PANE_OPTIONS : { ...PANE_OPTIONS, columns: paneColumns })
68  if (!opened.isPlaced) {
69    await $.ui.close({ id: PANE }).catch(() => undefined)
70  }
71  await update($, paneOpenState, () => opened.isPlaced)
72  await update($, paneInBandState, () => !opened.isPlaced)
73  return opened.isPlaced
74}
75
76/**
77 * Closes the pane, or its views in the band. A close the mod makes itself
78 * does not always reach its own close hook, so the flags are cleared here.
79 */
80async function closePane($: EngineInterface) {
81  await $.ui.close({ id: PANE })
82  await update($, paneOpenState, () => false)
83  await update($, paneInBandState, () => false)
84}
85
86/** Runs a press's work, and says in the transcript when it fails; a press has no caller to report to. */
87function report($: EngineInterface, what: string, work: Promise<unknown>) {
88  work.catch(error => $.ui.log(`Quick actions: ${what} failed: ${error instanceof Error ? error.message : String(error)}`))
89}
90
91/** Opens the pane on the list of actions. */
92async function openList($: EngineInterface) {
93  const opened = openPane($)
94  await update($, draftState, () => null)
95  return opened
96}
97
98/** Opens the list, or closes the pane when it is open in any view, in the pane or in the band. */
99async function toggleList($: EngineInterface) {
100  const isOpen = (await read($, paneOpenState)) || (await read($, paneInBandState))
101  return isOpen ? closePane($).then(() => true) : openList($)
102}
103
104/** Opens the form for a new action in place of the list. */
105async function startAdd($: EngineInterface) {
106  await update($, draftState, () => newDraft())
107}
108
109async function startEdit($: EngineInterface, action: CustomAction) {
110  /** Actions saved before colors existed have no color. A command shows with its slash, as typed. */
111  await update($, draftState, () => ({
112    ...action,
113    text: action.kind === 'command' ? `/${action.text}` : action.text,
114    color: action.color ?? '',
115    error: null,
116    picking: null,
117  }))
118}
119
120/** Leaves the form, back to the list. */
121async function leaveForm($: EngineInterface) {
122  await update($, draftState, () => null)
123}
124
125/** Applies a change to the form; any change clears the last save error. */
126async function editDraft($: EngineInterface, change: Partial<Draft>) {
127  await update($, draftState, draft => (draft === null ? null : { ...draft, error: null, ...change }))
128}
129
130async function saveDraft($: EngineInterface) {
131  const draft = await read($, draftState)
132  if (draft === null) {
133    return
134  }
135  const custom = await read($, customState)
136  const usedHotkeys = custom.filter(action => action.id !== draft.id && action.hotkey !== '').map(action => action.hotkey)
137
138  /** Shown in the form: the pane holds toasts back while it is open, so a toast would stay unseen. */
139  const problem = checkDraft(draft, usedHotkeys)
140  if (problem !== null) {
141    await update($, draftState, current => (current === null ? null : { ...current, error: problem }))
142    return
143  }
144
145  const saved: CustomAction = {
146    id: draft.id ?? `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`,
147    label: draft.label.trim(),
148    hotkey: draft.hotkey,
149    color: draft.color,
150    kind: draft.kind,
151    text: normalizeText(draft.kind, draft.text),
152  }
153  await writeCustom($, draft.id === null ? [...custom, saved] : custom.map(action => (action.id === draft.id ? saved : action)))
154  await leaveForm($)
155  $.ui.toast(`Saved "${saved.label}"`)
156}
157
158/** Deletes on the second press, so one stray click cannot remove an action. */
159async function pressDelete($: EngineInterface, action: CustomAction) {
160  if ((await read($, pendingDeleteState)) !== action.id) {
161    await update($, pendingDeleteState, () => action.id)
162    return
163  }
164  await update($, pendingDeleteState, () => null)
165  await writeCustom($, (await read($, customState)).filter(one => one.id !== action.id))
166  $.ui.toast(`Deleted "${action.label}"`)
167}
168
169async function runShell($: EngineInterface, argv: Array<string>) {
170  const line = argv[0] === 'sh' && argv[1] === '-c' ? (argv[2] ?? '') : argv.join(' ')
171  $.ui.toast(`${line} …`)
172  try {
173    const { exitCode, stdout, stderr } = await $.process.run(argv, { timeoutMs: SHELL_TIMEOUT_MS })
174    const output = `${stdout}${stderr}`.trim()
175    $.ui.log(`$ ${line}${output === '' ? '' : `\n${output}`}${exitCode === 0 ? '' : `\nexit ${exitCode}`}`)
176    $.ui.toast(exitCode === 0 ? `${line}: done` : `${line}: failed (exit ${exitCode})`)
177  } catch (error) {
178    $.ui.log(`$ ${line}\n${error instanceof Error ? error.message : String(error)}`)
179    $.ui.toast(`${line}: did not run`)
180  }
181}
182
183async function run($: EngineInterface, action: Action) {
184  if (action.kind === 'command') {
185    await $.command.run({ command: action.command, args: action.args })
186  } else if (action.kind === 'submit') {
187    await $.prompt.submit({ text: action.text, asUser: true })
188  } else if (action.kind === 'shell') {
189    await runShell($, action.argv)
190  } else {
191    await $.prompt.fill({ text: action.text })
192  }
193}
194
195/** The pane's handlers, bound to one engine interface. */
196function paneHandlersOf($: EngineInterface, order: Array<string>): PaneHandlers {
197  return {
198    close: () => report($, 'closing the pane', closePane($)),
199    startAdd: () => report($, 'opening the form', startAdd($)),
200    startEdit: action => report($, 'opening the form', startEdit($, action)),
201    pressDelete: action => report($, 'deleting the action', pressDelete($, action)),
202    moveEntry: (entry, step) => report($, 'moving the entry', writeOrder($, moveEntry(order, entry, step))),
203    removeFromBand: entry => report($, 'removing from the band', writeOrder($, order.filter(one => one !== entry))),
204    togglePin: id => report($, 'changing the band', writeOrder($, togglePin(order, id))),
205    run: action => report($, `running "${action.label}"`, run($, toAction(action))),
206    addNewline: () => report($, 'adding a new line', writeOrder($, [...order, newlineEntry()])),
207    editDraft: change => editDraft($, change),
208    saveDraft: () => report($, 'saving the action', saveDraft($)),
209    leaveForm: () => report($, 'leaving the form', leaveForm($)),
210  }
211}
212
213async function paneModelOf($: EngineInterface, columns: number, surface: string): Promise<PaneModel> {
214  return {
215    draft: await read($, draftState),
216    custom: await read($, customState),
217    order: await read($, orderState),
218    pendingDelete: await read($, pendingDeleteState),
219    columns,
220    surface,
221  }
222}
223
224/** The poll that reads the saved actions again; a new session start replaces it. */
225let poll: Timer | undefined
226
227/** Reads the saved actions again, for changes from other sessions. Started from a timer without a caller, so a failure goes to the debug log. */
228async function reload($: EngineInterface) {
229  try {
230    await loadStore($)
231  } catch (error) {
232    $.ui.log(`reading the saved actions failed: ${error instanceof Error ? error.message : String(error)}`, { to: 'debug' })
233  }
234}
235
236export const register: Register = (on, options) => {
237  paneColumns = paneColumnsOf(options)
238
239  on('session.start', async ($, e, next) => {
240    const started = await next(e)
241    /**
242     * Earlier versions opened separate panes under these ids; nothing draws them
243     * any more, so they would stay empty. A failed close must not stop the start.
244     */
245    await Promise.all(LEGACY_PANES.map(id => $.ui.close({ id }).catch(() => undefined)))
246    /** A hot reload can find the pane still open. A failed read must not stop the start either. */
247    const panes = await $.ui.panes().catch(() => [])
248    await update($, paneOpenState, () => panes.some(pane => pane.id === PANE && pane.isPlaced))
249    await update($, paneInBandState, () => false)
250    try {
251      await $.command.register(COMMAND)
252    } catch (error) {
253      $.ui.log(`Quick actions: /${COMMAND.name} is not available: ${error instanceof Error ? error.message : String(error)}`)
254    }
255    await reload($)
256    /** A new start (a clear, a resume) replaces the poll of the one before. */
257    poll?.cancel()
258    poll = $.clock.every(POLL_MS, () => void reload($))
259    return started
260  })
261
262  on('command.run', { command: COMMAND.name }, async $ => {
263    const isShown = await toggleList($)
264    /** No text when the pane opened or closed, so the command leaves no line in the transcript. */
265    return isShown || !(await read($, paneInBandState)) ? {} : { text: PANE_IN_BAND_TEXT }
266  })
267
268  /**
269   * Esc steps back as the config menu does: from an option list to the form,
270   * from a form opened in the list back to the list; only then it closes.
271   */
272  on('ui.close', { id: PANE }, async ($, e, next) => {
273    /** Lets the close through and clears the open flag, for closes the mod did not make itself (Esc, the engine's mark). */
274    const close = async () => {
275      const closed = await next(e)
276      await update($, paneOpenState, () => false)
277      return closed
278    }
279    const draft = await read($, draftState)
280    if (e.origin.kind !== 'person' || draft === null) {
281      return close()
282    }
283    if (draft.picking !== null) {
284      await editDraft($, { picking: null })
285      return { deny: STEP_BACK_REASON }
286    }
287    await leaveForm($)
288    return { deny: STEP_BACK_REASON }
289  })
290
291  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
292    /** The engine raises the band on the terminal and the desktop only; the mobile app has no Input for the form. */
293    if (e.props.hasSurvey || e.surface === 'mobile') {
294      return next(e)
295    }
296    /**
297     * The band of the plugins beneath, drawn under this one. The engine's own
298     * drawing holds only the surveys, so without a survey it adds nothing.
299     */
300    const below = await next(e)
301    const ui = $.ui.resolve(e)
302
303    let band
304    if (await read($, paneInBandState)) {
305      band = paneView(ui, await paneModelOf($, e.props.bodyColumns, e.surface), paneHandlersOf($, await read($, orderState)))
306    } else {
307      const byId = new Map((await read($, customState)).map(action => [action.id, toAction(action)]))
308      const rows = rowsOf(await read($, orderState))
309        .map(row => row.flatMap(id => byId.get(id) ?? []))
310        .filter(row => row.length > 0)
311      /** With nothing on the band, the band is not drawn; the plugins beneath still draw theirs. */
312      if (rows.length === 0) {
313        return below
314      }
315      band = bandView(ui, { rows, surface: e.surface }, { run: action => report($, `running "${action.label}"`, run($, action)) })
316    }
317
318    if (below === null || below === undefined || below.type === 'engine') {
319      return band
320    }
321    const { Box } = ui
322    return (
323      <Box flexDirection="column">
324        {band}
325        {below}
326      </Box>
327    )
328  })
329
330  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
331    if (e.surface === 'mobile') {
332      const { Text } = $.ui.resolve(e)
333      return <Text dimColor>Manage quick actions in the terminal or the desktop app.</Text>
334    }
335    return paneView($.ui.resolve(e), await paneModelOf($, e.props.bodyColumns, e.surface), paneHandlersOf($, await read($, orderState)))
336  })
337}
338
hooks/actions.ts 223 lines
1import type { CustomAction, CustomKind, Draft } from '../types'
2
3type BaseAction = {
4  key: string
5  label: string
6  /** One digit that presses the button from an empty prompt box, or while the band has the focus. */
7  hotkey?: string
8  /** Color name of the button. */
9  color?: string
10}
11
12/**
13 * One button of the band.
14 *
15 * - `command` runs a slash command or skill at once, as if typed (`/commit`).
16 * - `submit` sends a prompt to Claude at once.
17 * - `fill` puts text in the prompt box to check before sending. The box stays
18 *   in prompt mode, so a leading `!` does not make it a shell command.
19 * - `shell` runs a command on the host in the session's directory, without
20 *   Claude, and shows its output in the transcript (Claude does not read it).
21 *
22 * Commands and prompts queue until the session is idle; shell commands run at once.
23 */
24export type Action =
25  | (BaseAction & { kind: 'command'; command: string; args: string })
26  | (BaseAction & { kind: 'submit' | 'fill'; text: string })
27  | (BaseAction & { kind: 'shell'; argv: Array<string> })
28
29/** Turns a saved action into a button. */
30export function toAction(custom: CustomAction): Action {
31  const base = {
32    key: `custom-${custom.id}`,
33    label: custom.label,
34    /** Only digits work from the prompt box; a letter saved by an older version is dropped. */
35    hotkey: /^[0-9]$/.test(custom.hotkey) ? custom.hotkey : undefined,
36    /** Actions saved before colors existed have no color. */
37    color: custom.color || undefined,
38  }
39  if (custom.kind === 'command') {
40    const [command = '', ...args] = custom.text.split(' ')
41    return { ...base, kind: 'command', command, args: args.join(' ') }
42  }
43  if (custom.kind === 'shell') {
44    return { ...base, kind: 'shell', argv: ['sh', '-c', custom.text] }
45  }
46  return { ...base, kind: custom.kind, text: custom.text }
47}
48
49/** An empty form for a new action: a prompt that is sent at once. */
50export function newDraft(): Draft {
51  return { id: null, error: null, picking: null, label: '', hotkey: '', color: '', kind: 'submit', text: '' }
52}
53
54/**
55 * The text as it is saved: trimmed, and without the prefix a person may type
56 * out of habit, `/` before a command and `!` before a shell command.
57 */
58export function normalizeText(kind: CustomKind, text: string): string {
59  const trimmed = text.trim()
60  if (kind === 'command') {
61    return trimmed.replace(/^\/+/, '')
62  }
63  if (kind === 'shell') {
64    return trimmed.replace(/^!\s*/, '')
65  }
66  return trimmed
67}
68
69/**
70 * Checks a draft before it is saved, and returns the reason it cannot be, or
71 * null. `usedHotkeys` are those of every other shown action.
72 */
73export function checkDraft(draft: Draft, usedHotkeys: Array<string>): string | null {
74  const text = normalizeText(draft.kind, draft.text)
75  if (draft.label.trim() === '') {
76    return 'The label is empty.'
77  }
78  if (text === '') {
79    return 'The action text is empty.'
80  }
81  if (draft.kind === 'command' && !/^[\w:.-]+/.test(text)) {
82    return 'A command starts with its name, e.g. "commit" or "pr --draft".'
83  }
84  if (draft.hotkey !== '' && !/^[0-9]$/.test(draft.hotkey)) {
85    return 'The hotkey must be one digit.'
86  }
87  if (draft.hotkey !== '' && usedHotkeys.includes(draft.hotkey)) {
88    return `The hotkey "${draft.hotkey}" is already in use.`
89  }
90  return null
91}
92
93/** Entries of the list that start a new row on the band carry this prefix before their own id. */
94export const NEWLINE_PREFIX = 'newline:'
95
96export function isNewline(entry: string): boolean {
97  return entry.startsWith(NEWLINE_PREFIX)
98}
99
100/** A new entry that starts a new row on the band. */
101export function newlineEntry(): string {
102  return `${NEWLINE_PREFIX}${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`
103}
104
105/**
106 * Makes the stored band order fit the saved actions: ids of deleted actions
107 * go, and an entry that shows twice keeps its first place. Actions in no
108 * place are not on the band, so with no order stored yet the band is empty.
109 */
110export function arrangeOrder(stored: unknown, ids: Array<string>): Array<string> {
111  if (!Array.isArray(stored)) {
112    return []
113  }
114  const known = new Set(ids)
115  const seen = new Set<string>()
116  return stored.filter((entry): entry is string => {
117    if (typeof entry !== 'string' || seen.has(entry) || (!known.has(entry) && !isNewline(entry))) {
118      return false
119    }
120    seen.add(entry)
121    return true
122  })
123}
124
125/** Puts an action on the band, at the end, or takes it off. */
126export function togglePin(order: Array<string>, id: string): Array<string> {
127  return order.includes(id) ? order.filter(entry => entry !== id) : [...order, id]
128}
129
130/** Moves an entry one place up (-1) or down (+1); unchanged at either end. */
131export function moveEntry(order: Array<string>, entry: string, step: -1 | 1): Array<string> {
132  const from = order.indexOf(entry)
133  const to = from + step
134  if (from === -1 || to < 0 || to >= order.length) {
135    return order
136  }
137  const next = [...order]
138  next[from] = order[to] as string
139  next[to] = entry
140  return next
141}
142
143/** The rows of the band: the order split at each new line entry, empty rows left out. */
144export function rowsOf(order: Array<string>): Array<Array<string>> {
145  const rows: Array<Array<string>> = [[]]
146  for (const entry of order) {
147    if (isNewline(entry)) {
148      rows.push([])
149    } else {
150      rows[rows.length - 1]?.push(entry)
151    }
152  }
153  return rows.filter(row => row.length > 0)
154}
155
156export type Section = 'commands' | 'prompts' | 'shell'
157
158/** The manage pane's section of a kind: commands run directly, prompts go to Claude, shell runs on the host. */
159export function sectionOf(kind: CustomKind): Section {
160  if (kind === 'command') {
161    return 'commands'
162  }
163  return kind === 'shell' ? 'shell' : 'prompts'
164}
165
166/** The colors the form offers. */
167export const COLORS = ['red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white']
168
169/** The RGB values of the named colors, as common terminal themes draw them. */
170const NAMED_RGB: Record<string, [number, number, number]> = {
171  black: [0, 0, 0],
172  red: [205, 49, 49],
173  green: [13, 188, 121],
174  yellow: [229, 229, 16],
175  blue: [36, 114, 200],
176  magenta: [188, 63, 188],
177  cyan: [17, 168, 205],
178  white: [229, 229, 229],
179  gray: [102, 102, 102],
180  grey: [102, 102, 102],
181}
182
183/** Reads a named color, `#rrggbb` or `rgb(r,g,b)`; null for anything else. */
184function rgbOf(color: string): [number, number, number] | null {
185  const name = color.toLowerCase().replace(/bright$/, '')
186  if (name in NAMED_RGB) {
187    return NAMED_RGB[name] ?? null
188  }
189  const hex = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(color)
190  if (hex !== null) {
191    return [parseInt(hex[1] ?? '', 16), parseInt(hex[2] ?? '', 16), parseInt(hex[3] ?? '', 16)]
192  }
193  const rgb = /^rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i.exec(color)
194  if (rgb !== null) {
195    return [Number(rgb[1]), Number(rgb[2]), Number(rgb[3])]
196  }
197  return null
198}
199
200/** The relative luminance of WCAG 2: 0 for black, 1 for white. */
201function luminanceOf([red, green, blue]: [number, number, number]): number {
202  const linear = (channel: number) => {
203    const value = channel / 255
204    return value <= 0.039_28 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4
205  }
206  return 0.2126 * linear(red) + 0.7152 * linear(green) + 0.0722 * linear(blue)
207}
208
209/**
210 * Black or white, whichever has the higher WCAG contrast ratio on the given
211 * background color; white for a color it cannot read.
212 */
213export function textColorOn(background: string): 'black' | 'white' {
214  const rgb = rgbOf(background)
215  if (rgb === null) {
216    return 'white'
217  }
218  const luminance = luminanceOf(rgb)
219  const onBlack = (luminance + 0.05) / 0.05
220  const onWhite = 1.05 / (luminance + 0.05)
221  return onBlack > onWhite ? 'black' : 'white'
222}
223
hooks/limits.ts 9 lines
1/** How often the saved actions are read again, for changes made in other sessions. */
2export const POLL_MS = 15_000
3
4/** How long a shell action may run before it is killed. */
5export const SHELL_TIMEOUT_MS = 120_000
6
7/** The longest label the band draws whole; a longer one is cut with an ellipsis. */
8export const LABEL_MAX_CHARS = 24
9
hooks/names.ts 21 lines
1/** One pane for the list of actions and the form that adds or edits one. */
2export const PANE = 'quick-actions'
3
4/** Panes that earlier versions opened; nothing draws them any more. */
5export const LEGACY_PANES = ['quick-actions-edit', 'quick-actions-manage']
6
7export const PANE_OPTIONS = { id: PANE, title: 'Quick actions', focus: true, closeOnEscape: true, holdToasts: true, rows: 20 } as const
8
9/** Keys in the store, which keeps the person's actions and their order across sessions. */
10export const STORE_ACTIONS = 'actions'
11export const STORE_ORDER = 'order'
12
13/** The slash command that opens or closes the pane, also when the band is hidden. */
14export const COMMAND = { name: 'quick-actions', description: 'Open or close the quick actions pane' } as const
15
16/** What a press or a command answers when the pane is open but not drawn; the band draws it instead. */
17export const PANE_IN_BAND_TEXT = 'The quick actions pane has no room here, so the band above the prompt shows it.'
18
19/** Why Esc did not close the pane: it stepped back one view instead. */
20export const STEP_BACK_REASON = 'back one view'
21
hooks/views/band-view.tsx 62 lines
1import type { RenderElement, RenderSurface } from 'claude-code'
2
3import type { Action } from '../actions'
4import type { BandHandlers, Ui } from './kit'
5import { shownLabel } from './label'
6
7export type BandModel = {
8  /** The band's rows of actions, top to bottom. */
9  rows: Array<Array<Action>>
10  surface: RenderSurface
11}
12
13/** The band above the prompt: the actions on it, in their rows. */
14export function bandView(ui: Ui, model: BandModel, handlers: BandHandlers): RenderElement {
15  const { Box, Button } = ui
16
17  /**
18   * One action. On the terminal a block in the action's color, or its plain
19   * label, underlined under the pointer, without one; both take one cell of
20   * room on each side, so colored and plain actions line up. Other surfaces
21   * draw their own button.
22   */
23  const item = (action: Action) => {
24    const label = shownLabel(action.label)
25    if (model.surface !== 'terminal') {
26      return <Button key={action.key} label={label} hotkey={action.hotkey} onPress={() => handlers.run(action)} />
27    }
28    return (
29      <Box
30        key={`block-${action.key}`}
31        flexDirection="row"
32        flexShrink={0}
33        paddingX={1}
34        {...(action.color !== undefined ? { backgroundColor: action.color } : {})}
35      >
36        <Button
37          key={action.key}
38          plain
39          label={label}
40          hotkey={action.hotkey}
41          {...(action.color === undefined ? { hover: { underline: true } } : {})}
42          onPress={() => handlers.run(action)}
43        />
44      </Box>
45    )
46  }
47
48  /** One row of the band. No wrapping: a wrapping row that may shrink reserves a second, empty line; room past the band's width is cut instead. */
49  const row = (key: string, actions: Array<Action>) => (
50    <Box key={key} flexDirection="row" columnGap={2} flexShrink={1} overflow="hidden">
51      {actions.map(item)}
52    </Box>
53  )
54
55  return (
56    <Box key="quick-actions" flexDirection="column" paddingLeft={1} paddingRight={3} marginTop={1}>
57      {/* The right padding keeps the last button off the band's own collapse control. */}
58      {model.rows.map((actions, index) => row(`row-${index}`, actions))}
59    </Box>
60  )
61}
62
hooks/views/kit.ts 36 lines
1import type { ElementTable } from 'claude-code'
2
3import type { CustomAction, Draft } from '../../types'
4import type { Action } from '../actions'
5
6/**
7 * The element constructors the views draw with, from the table the render
8 * hook resolves. The terminal and the desktop app have all of them; the
9 * mobile app has no Input, so the pane does not draw there.
10 */
11export type Ui = Pick<ElementTable<'terminal' | 'desktop'>, 'Box' | 'Text' | 'Button' | 'Input'>
12
13/** What the band's buttons do. */
14export type BandHandlers = {
15  run: (action: Action) => void
16}
17
18/** What the pane's buttons and inputs do. */
19export type PaneHandlers = {
20  close: () => void
21  startAdd: () => void
22  startEdit: (action: CustomAction) => void
23  pressDelete: (action: CustomAction) => void
24  moveEntry: (entry: string, step: -1 | 1) => void
25  /** Takes an action or a new line off the band; an action stays in the list of all actions. */
26  removeFromBand: (entry: string) => void
27  /** Puts an action on the band, or takes it off. */
28  togglePin: (id: string) => void
29  run: (action: CustomAction) => void
30  addNewline: () => void
31  /** Resolves once the change is in the form's state, so a save after it sees it. */
32  editDraft: (change: Partial<Draft>) => Promise<void>
33  saveDraft: () => void
34  leaveForm: () => void
35}
36
hooks/views/pane/pane-view.tsx 26 lines
1import type { RenderElement } from 'claude-code'
2
3import type { CustomAction, Draft } from '../../../types'
4import type { PaneHandlers, Ui } from '../kit'
5import { formView } from './form-view'
6import { listView } from './list-view'
7
8export type PaneModel = {
9  /** The form being filled in, or null for the list. */
10  draft: Draft | null
11  custom: Array<CustomAction>
12  order: Array<string>
13  pendingDelete: string | null
14  /** The pane's width in columns. */
15  columns: number
16  surface: string
17}
18
19/** The pane's current view: the form while one is filled in, the list otherwise. */
20export function paneView(ui: Ui, model: PaneModel, handlers: PaneHandlers): RenderElement {
21  if (model.draft !== null) {
22    return formView(ui, { draft: model.draft, custom: model.custom, columns: model.columns, surface: model.surface }, handlers)
23  }
24  return listView(ui, model, handlers)
25}
26
hooks/views/label.ts 12 lines
1import { LABEL_MAX_CHARS } from '../limits'
2
3/** Characters a label cannot draw: control characters, which would break the row. */
4const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f]/g
5
6/** A label as the band and the list draw it: on one line, without control characters, and cut with an ellipsis past the limit. */
7export function shownLabel(label: string, maxChars = LABEL_MAX_CHARS): string {
8  const clean = label.replace(/\s+/g, ' ').replace(CONTROL_CHARACTERS, '').trim()
9  const chars = [...clean]
10  return chars.length > maxChars ? `${chars.slice(0, maxChars - 1).join('')}…` : clean
11}
12
hooks/views/pane/form-view.tsx 227 lines
1import type { RenderElement } from 'claude-code'
2
3import type { CustomAction, Draft } from '../../../types'
4import { textColorOn } from '../../actions'
5import type { PaneHandlers, Ui } from '../kit'
6import { shownLabel } from '../label'
7import { keepSpaces } from '../theme'
8import { actionButton, ruleView } from './buttons'
9import { headerView } from './header-view'
10import { COLOR_OPTIONS, HOTKEYS, type Option, TEXT_FIELDS, TYPES } from './options'
11
12export type FormModel = {
13  draft: Draft
14  /** The saved actions, so a hotkey another action uses is not offered. */
15  custom: Array<CustomAction>
16  /** The pane's width in columns. */
17  columns: number
18  surface: string
19}
20
21type Setting = { id: 'color' | 'hotkey'; title: string; question: string; options: ReadonlyArray<Option> }
22
23/** The width of a setting's name, so the values of all settings start in one column. */
24const TITLE_WIDTH = 8
25
26/** The cells one option takes as a button: its label, or a one-cell swatch for a color, the ground's padding, and the gap before the next. */
27const optionCells = (setting: Setting, option: Option) => (setting.id === 'color' ? 1 : [...option.label].length) + 2 + 1
28
29/**
30 * The form that adds or edits an action. A setting shows its options as a row
31 * of buttons when they fit the pane; otherwise as its value, which opens the
32 * setting's option list in place of the form.
33 */
34export function formView(ui: Ui, model: FormModel, handlers: PaneHandlers): RenderElement {
35  const { Box, Button, Input, Text } = ui
36  const { draft, surface } = model
37  const keep = keepSpaces(surface)
38  const field = TEXT_FIELDS[draft.kind]
39
40  /** Digits another action already uses are left out, so a clash cannot be picked. */
41  const used = new Set(model.custom.filter(action => action.id !== draft.id).map(action => action.hotkey))
42  const hotkeyOptions = [{ value: '', label: '-' }, ...HOTKEYS.filter(digit => !used.has(digit)).map(digit => ({ value: digit, label: digit }))]
43
44  const settings: Array<Setting> = [
45    { id: 'color', title: 'Color', question: 'The color of the button', options: COLOR_OPTIONS },
46    { id: 'hotkey', title: 'Hotkey', question: 'The digit that presses the button from an empty prompt box', options: hotkeyOptions },
47  ]
48
49  /**
50   * One option as a button: blue when chosen, dim when not. On the terminal a
51   * color is a swatch in its own color without text, ticked when chosen, so
52   * the colors fit a narrow pane; the default color is a dash.
53   */
54  const optionButton = (setting: Setting, option: Option) => {
55    const key = `${setting.id}-${option.value || 'none'}`
56    const isChosen = draft[setting.id] === option.value
57    const pick = () => void handlers.editDraft({ [setting.id]: option.value, picking: null })
58    if (setting.id === 'color' && surface === 'terminal') {
59      return (
60        <Box
61          key={`box-${key}`}
62          flexDirection="row"
63          flexShrink={0}
64          paddingX={1}
65          {...(option.value !== '' ? { backgroundColor: option.value } : {})}
66        >
67          <Button key={key} label={isChosen ? '✔' : option.value === '' ? '-' : ' '} plain dimColor={option.value === '' && !isChosen} onPress={pick} />
68        </Box>
69      )
70    }
71    return actionButton(ui, surface, key, option.label, pick, isChosen)
72  }
73
74  const picking = settings.find(setting => setting.id === draft.picking)
75  if (picking !== undefined) {
76    return pickerView(ui, model, picking, handlers)
77  }
78
79  /**
80   * The type as one button for each kind. In a narrow pane the buttons wrap
81   * to a second line; the title keeps its width, and each button keeps the
82   * height of one line.
83   */
84  const typeRow = (
85    <Box key="setting-row-kind" flexDirection="row" columnGap={1} alignItems="flex-start">
86      <Box flexShrink={0}>
87        <Text>{keep('Type'.padEnd(TITLE_WIDTH))}</Text>
88      </Box>
89      <Box flexDirection="row" flexWrap="wrap" flexShrink={1} columnGap={1} rowGap={1} alignItems="flex-start">
90        {TYPES.map(type =>
91          actionButton(ui, surface, `kind-${type.kind}`, type.label, () => void handlers.editDraft({ kind: type.kind }), draft.kind === type.kind),
92        )}
93      </Box>
94    </Box>
95  )
96
97  /** A setting as a row of option buttons when they fit, or as its value that opens the option list. */
98  const settingRow = (setting: Setting) => {
99    const cells = TITLE_WIDTH + 1 + setting.options.reduce((sum, option) => sum + optionCells(setting, option), 0)
100    if (cells <= model.columns - 2) {
101      return (
102        <Box key={`setting-row-${setting.id}`} flexDirection="row" columnGap={1}>
103          <Text>{keep(setting.title.padEnd(TITLE_WIDTH))}</Text>
104          {setting.options.map(option => optionButton(setting, option))}
105        </Box>
106      )
107    }
108    const option = setting.options.find(one => one.value === draft[setting.id]) ?? setting.options[0]
109    return (
110      <Box key={`setting-row-${setting.id}`} flexDirection="row" columnGap={1}>
111        <Button
112          key={`setting-${setting.id}`}
113          label={keep(`${setting.title.padEnd(TITLE_WIDTH)}${option?.label ?? ''} ›`)}
114          plain
115          onPress={() => void handlers.editDraft({ picking: setting.id })}
116        />
117        {setting.id === 'color' && <Text color={draft.color || undefined}>■■■</Text>}
118      </Box>
119    )
120  }
121
122  /**
123   * The button as the band draws it: a block in the action's color with black or white text,
124   * whichever reads better on it, or the plain label without a color.
125   */
126  const label = shownLabel(draft.label) || '…'
127  const preview =
128    draft.color !== '' ? (
129      <Text backgroundColor={draft.color} color={textColorOn(draft.color)}>{` ${label} `}</Text>
130    ) : (
131      <Text>{` ${label} `}</Text>
132    )
133
134  return (
135    <Box flexDirection="column" paddingX={1}>
136      {headerView(ui, surface, handlers, handlers.leaveForm, draft.id === null ? 'New action' : 'Edit action')}
137      <Box flexDirection="column" rowGap={1}>
138        {typeRow}
139        {settings.map(settingRow)}
140      </Box>
141      <Box flexDirection="column" marginTop={1}>
142        <Text dimColor>Label</Text>
143        {ruleView(ui, 'rule-label-top', model.columns - 2)}
144        <Box flexDirection="row">
145          <Text bold>❯ </Text>
146          <Input
147            key="label"
148            placeholder="review diff"
149            value={draft.label}
150            submitLabel="save"
151            onInput={value => void handlers.editDraft({ label: value })}
152            onSubmit={value => void handlers.editDraft({ label: value }).then(handlers.saveDraft)}
153          />
154        </Box>
155        {ruleView(ui, 'rule-label-bottom', model.columns - 2)}
156      </Box>
157      <Box flexDirection="column" marginTop={1}>
158        <Box flexDirection="row" justifyContent="space-between">
159          <Text dimColor>{field.title}</Text>
160          <Text dimColor>Enter adds a line</Text>
161        </Box>
162        {ruleView(ui, 'rule-text-top', model.columns - 2)}
163        {/*
164          The input is one line and Enter submits it, so Enter appends a line break and Save saves.
165          Workaround for anthropics/claude-code#99616, tracked in zirkelc/issues#18. Remove both when the fix is adopted.
166        */}
167        <Box flexDirection="row" minHeight={3}>
168          <Text bold>❯ </Text>
169          <Input
170            key="text"
171            placeholder={field.placeholder}
172            value={draft.text}
173            autoFocus
174            submitLabel="new line"
175            onInput={value => void handlers.editDraft({ text: value })}
176            onSubmit={value => void handlers.editDraft({ text: `${value}\n` })}
177          />
178        </Box>
179        {ruleView(ui, 'rule-text-bottom', model.columns - 2)}
180      </Box>
181      {draft.error !== null && <Text color="red">{draft.error}</Text>}
182      <Box flexDirection="row" justifyContent="space-between" marginTop={1}>
183        {actionButton(ui, surface, 'save', 'Save', handlers.saveDraft)}
184        <Box flexDirection="row" columnGap={1}>
185          <Text dimColor>Preview:</Text>
186          {preview}
187        </Box>
188      </Box>
189      <Text key="hint" dimColor>
190        Esc goes back one step
191      </Text>
192    </Box>
193  )
194}
195
196/**
197 * The option list of one setting, for a pane too narrow for its row of
198 * buttons: the current option ticked and focused, a press picks it and returns
199 * to the form, Back or Esc returns without a change.
200 */
201function pickerView(ui: Ui, model: FormModel, setting: Setting, handlers: PaneHandlers): RenderElement {
202  const { Box, Button, Text } = ui
203  const keep = keepSpaces(model.surface)
204  const current = model.draft[setting.id]
205  /** Labels padded to the longest, so the swatches start in one column. */
206  const width = Math.max(...setting.options.map(option => option.label.length))
207  return (
208    <Box flexDirection="column" paddingX={1}>
209      {headerView(ui, model.surface, handlers, () => void handlers.editDraft({ picking: null }), setting.question)}
210      <Box flexDirection="column">
211        {setting.options.map(option => (
212          <Box key={`option-row-${option.value || 'none'}`} flexDirection="row" columnGap={2}>
213            <Button
214              key={`${setting.id}-${option.value || 'none'}`}
215              label={keep(`${option.value === current ? '✔' : ' '} ${option.label.padEnd(width)}`)}
216              plain
217              autoFocus={option.value === current ? true : undefined}
218              onPress={() => void handlers.editDraft({ [setting.id]: option.value, picking: null })}
219            />
220            {setting.id === 'color' && <Text color={option.value || undefined}>■■■</Text>}
221          </Box>
222        ))}
223      </Box>
224    </Box>
225  )
226}
227
hooks/views/pane/list-view.tsx 215 lines
1import type { RenderElement } from 'claude-code'
2
3import type { CustomAction } from '../../../types'
4import { isNewline, rowsOf, sectionOf } from '../../actions'
5import type { PaneHandlers, Ui } from '../kit'
6import { shownLabel } from '../label'
7import { keepSpaces } from '../theme'
8import { headerView, sectionBar } from './header-view'
9import { SECTION_MARKS } from './options'
10
11export type ListModel = {
12  /** Every saved action, in the order they were saved. */
13  custom: Array<CustomAction>
14  /** The band: the actions on it and its new lines, in order. */
15  order: Array<string>
16  /** The action whose delete button was pressed once and waits for the second press. */
17  pendingDelete: string | null
18  /** The pane's width in columns. */
19  columns: number
20  surface: string
21}
22
23/** The widest the label column gets; a longer label is cut. */
24const LABEL_WIDTH = 20
25
26/** From this width the band stands beside the list of actions; a narrower pane puts it under them. */
27const WIDE_COLUMNS = 90
28
29/** The band's column in a wide pane: a band row needs its symbol, the widest label and three controls. */
30const BAND_COLUMNS = 36
31
32/** The cells between the two columns. */
33const COLUMN_GAP = 2
34
35/** What the symbols of the list mean, under the lists. */
36const LEGEND = '/ skill · > prompt · $ shell · [1] hotkey · ★ on the band · ▶ run · ✕ delete'
37
38/** A count with its noun, in the plural unless it is one. */
39const counted = (count: number, noun: string) => `${count} ${noun}${count === 1 ? '' : 's'}`
40
41/** What an action does, on one line: the command with its slash, the shell command, or the prompt. */
42function whatOf(action: CustomAction): string {
43  const text = action.text.replace(/\s+/g, ' ').trim()
44  return action.kind === 'command' ? `/${text}` : text
45}
46
47/**
48 * Two lists, one action or new line per line: every action, each with a star
49 * that puts it on the band or takes it off, a button that runs it and a delete
50 * button; then the band in its order, with buttons that move an entry or take
51 * it off the band. A wide pane draws the two lists side by side.
52 */
53export function listView(ui: Ui, model: ListModel, handlers: PaneHandlers): RenderElement {
54  const { Box, Button, Text } = ui
55  const { order, pendingDelete, surface } = model
56  const keep = keepSpaces(surface)
57  const onBand = new Set(order)
58  const width = Math.min(Math.max(1, ...model.custom.map(action => [...shownLabel(action.label)].length)), LABEL_WIDTH)
59
60  /** The cells inside the pane's side padding, and the width of each list. */
61  const inner = Math.max(1, model.columns - 2)
62  const isWide = model.columns >= WIDE_COLUMNS
63  const bandWidth = isWide ? BAND_COLUMNS : inner
64  const actionsWidth = isWide ? inner - BAND_COLUMNS - COLUMN_GAP : inner
65
66  /**
67   * The section's symbol, dim, then the label in a column of one width; in
68   * its color the label is a block, as on the band.
69   */
70  const labelOf = (action: CustomAction, button: RenderElement) => [
71    <Box key={`mark-${action.id}`} flexShrink={0}>
72      <Text dimColor>{SECTION_MARKS[sectionOf(action.kind)]}</Text>
73    </Box>,
74    <Box
75      key={`block-${action.id}`}
76      flexDirection="row"
77      flexShrink={0}
78      paddingX={1}
79      {...(action.color ? { backgroundColor: action.color } : {})}
80    >
81      {button}
82    </Box>,
83  ]
84
85  const columnLabel = (action: CustomAction) => keep(shownLabel(action.label, width).padEnd(width))
86
87  /**
88   * A control at the end of a row. The spaces are part of the label, so the
89   * hover and the click cover them too and the target is three cells wide.
90   */
91  const control = (key: string, label: string, isDim: boolean, onPress: () => void) => (
92    <Button key={key} label={keep(` ${label} `)} plain dimColor={isDim} onPress={onPress} />
93  )
94
95  /** One action: its label opens the form, then its hotkey and what it does, dim and cut at the pane's edge. */
96  const actionRow = (action: CustomAction) => {
97    const isOnBand = onBand.has(action.id)
98    const edit = <Button key={`edit-${action.id}`} label={columnLabel(action)} plain onPress={() => handlers.startEdit(action)} />
99    return (
100      <Box key={`row-${action.id}`} flexDirection="row" columnGap={1}>
101        {labelOf(action, edit)}
102        <Box width={3} flexShrink={0}>
103          <Text dimColor>{action.hotkey !== '' ? `[${action.hotkey}]` : ''}</Text>
104        </Box>
105        {/** Width 0 and grow: only this cell takes the room left, so a long text cannot squeeze the cells beside it. */}
106        <Box width={0} flexGrow={1} overflow="hidden">
107          <Text dimColor wrap="truncate-end">
108            {whatOf(action)}
109          </Text>
110        </Box>
111        <Box flexDirection="row" flexShrink={0}>
112          {control(`pin-${action.id}`, isOnBand ? '★' : '☆', !isOnBand, () => handlers.togglePin(action.id))}
113          {control(`run-${action.id}`, '▶', true, () => handlers.run(action))}
114          {control(
115            `delete-${action.id}`,
116            pendingDelete === action.id ? 'delete? ✕' : '✕',
117            pendingDelete !== action.id,
118            () => handlers.pressDelete(action),
119          )}
120        </Box>
121      </Box>
122    )
123  }
124
125  /** Moves an entry of the band one place; across a new line it moves to the next or previous row. */
126  const bandControls = (entry: string, index: number) => (
127    <Box flexDirection="row" flexShrink={0}>
128      {control(`up-${entry}`, '↑', index > 0, () => handlers.moveEntry(entry, -1))}
129      {control(`down-${entry}`, '↓', index < order.length - 1, () => handlers.moveEntry(entry, 1))}
130      {control(`remove-${entry}`, '-', true, () => handlers.removeFromBand(entry))}
131    </Box>
132  )
133
134  /** A dim line at the end of a list that adds to it: a sign in the symbol column, the text in the label column. */
135  const addRow = (key: string, label: string, onPress: () => void) => (
136    <Box key={`row-${key}`} flexDirection="row" columnGap={1}>
137      <Text dimColor>+</Text>
138      <Box flexDirection="row" flexShrink={0} paddingX={1}>
139        <Button key={key} label={label} plain dimColor onPress={onPress} />
140      </Box>
141    </Box>
142  )
143
144  const byId = new Map(model.custom.map(action => [action.id, action]))
145  const bandActions = order.filter(entry => byId.has(entry)).length
146  const bandRowCount = rowsOf(order).filter(row => row.some(entry => byId.has(entry))).length
147  /** A new line splits rows of actions, so it is offered only once an action is on the band. */
148  const hasActionOnBand = bandActions > 0
149  const bandRows = order.flatMap((entry, index) => {
150    if (isNewline(entry)) {
151      return [
152        <Box key={`band-row-${entry}`} flexDirection="row" justifyContent="space-between" columnGap={1}>
153          <Box flexDirection="row" columnGap={1}>
154            <Text dimColor>↵</Text>
155            <Box flexDirection="row" paddingX={1}>
156              <Text dimColor>new line</Text>
157            </Box>
158          </Box>
159          {bandControls(entry, index)}
160        </Box>,
161      ]
162    }
163    const action = byId.get(entry)
164    if (action === undefined) {
165      return []
166    }
167    return [
168      <Box key={`band-row-${entry}`} flexDirection="row" justifyContent="space-between" columnGap={1}>
169        <Box flexDirection="row" columnGap={1} flexShrink={1}>
170          {labelOf(action, <Text key={`band-label-${entry}`}>{columnLabel(action)}</Text>)}
171        </Box>
172        {bandControls(entry, index)}
173      </Box>,
174    ]
175  })
176
177  const summary = [
178    counted(model.custom.length, 'action'),
179    `${bandActions} on the band`,
180    ...(bandRowCount > 1 ? [`${bandRowCount} rows`] : []),
181  ].join(' · ')
182
183  const actionsColumn = (
184    <Box key="column-actions" flexDirection="column" width={actionsWidth} flexShrink={0}>
185      {sectionBar(ui, surface, 'bar-actions', 'Actions', `${model.custom.length}`, actionsWidth)}
186      {model.custom.map(actionRow)}
187      {addRow('new', 'Add action', handlers.startAdd)}
188    </Box>
189  )
190
191  const bandColumn = (
192    <Box key="column-band" flexDirection="column" width={bandWidth} flexShrink={0}>
193      {sectionBar(ui, surface, 'bar-band', 'Band', `${bandActions}`, bandWidth)}
194      {bandRows}
195      {!hasActionOnBand && <Text dimColor>Nothing on the band yet: press ☆ on an action.</Text>}
196      {hasActionOnBand && addRow('newline', 'Add new line', handlers.addNewline)}
197    </Box>
198  )
199
200  return (
201    <Box flexDirection="column" paddingX={1}>
202      {headerView(ui, surface, handlers, null, summary)}
203      <Box key="columns" flexDirection={isWide ? 'row' : 'column'} {...(isWide ? { columnGap: COLUMN_GAP } : { rowGap: 1 })}>
204        {actionsColumn}
205        {bandColumn}
206      </Box>
207      <Box key="footer" marginTop={1}>
208        <Text dimColor wrap="wrap">
209          {LEGEND}
210        </Text>
211      </Box>
212    </Box>
213  )
214}
215
hooks/views/theme.ts 29 lines
1/**
2 * The pane's colors. Its own text stays in the terminal's colors (plain and
3 * dim), so it reads in a dark and a light theme, and the colors the person
4 * gives the actions are the only strong ones. One orange accent marks the
5 * title, the counts and the chosen option.
6 */
7
8/** The accent as text: the title mark and the counts. Orange reads on a dark and on a light ground. */
9export const ACCENT = '#d97757'
10
11/** The accent as the ground of a chosen option button: darker, so the text on it reads. */
12export const ACCENT_GROUND = '#c15f3c'
13
14/** A section's bar: a dark ground with light text. Both are set, so the bar reads in either theme. */
15export const BAR_GROUND = '#3d3d3a'
16export const BAR_TEXT = '#faf9f5'
17
18/** A non-breaking space, which no surface joins with the spaces next to it. */
19const NBSP = ' '
20
21/**
22 * Keeps the spaces of padded text. The desktop and remote surfaces join a run
23 * of spaces into one, which moves a padded column out of line; there every
24 * space becomes a non-breaking space. The terminal keeps spaces as they are.
25 */
26export function keepSpaces(surface: string): (text: string) => string {
27  return surface === 'terminal' ? text => text : text => text.replace(/ /g, NBSP)
28}
29
hooks/views/pane/buttons.tsx 48 lines
1import type { RenderElement } from 'claude-code'
2
3import type { Ui } from '../kit'
4import { ACCENT_GROUND } from '../theme'
5
6/**
7 * A button as an action: in the terminal a label on a colored ground, or the
8 * same label dimmed and without ground for an option not chosen; elsewhere the
9 * surface's own button, primary or not.
10 */
11export function actionButton(
12  ui: Ui,
13  surface: string,
14  id: string,
15  label: string,
16  onPress: () => void,
17  isChosen = true,
18): RenderElement {
19  const { Box, Button } = ui
20  if (surface !== 'terminal') {
21    return <Button key={id} label={label} variant={isChosen ? 'primary' : 'secondary'} onPress={onPress} />
22  }
23  return (
24    <Box key={`box-${id}`} flexDirection="row" flexShrink={0} paddingX={1} {...(isChosen ? { backgroundColor: ACCENT_GROUND } : {})}>
25      <Button key={id} label={label} plain {...(isChosen ? {} : { dimColor: true })} onPress={onPress} />
26    </Box>
27  )
28}
29
30/** A button that moves between views, as plain text in the terminal; elsewhere the surface's own button. */
31export function navButton(ui: Ui, surface: string, id: string, label: string, onPress: () => void): RenderElement {
32  const { Button } = ui
33  if (surface !== 'terminal') {
34    return <Button key={id} label={label} variant="secondary" onPress={onPress} />
35  }
36  return <Button key={id} label={label} plain onPress={onPress} />
37}
38
39/** A dim rule across the pane, to set one part of a view off from the next. */
40export function ruleView(ui: Ui, id: string, columns: number): RenderElement {
41  const { Text } = ui
42  return (
43    <Text key={id} dimColor>
44      {'─'.repeat(Math.max(columns, 1))}
45    </Text>
46  )
47}
48