/music: what macOS Music.app is playing, in one line above the prompt. A pressable play/pause glyph, track · artist · album, a progress bar with the clocks…

<h1>music-mod</h1>
╭─ MUSIC ──────────────────────────────────────────────────╮
│ ▶ Tipsy WANUKA / Greenhorn ━━━━━━━━━━━━──────── 2:43 / 3:39 ⏭ │
╰──────────────────────────────────────────────────────────╯
Long sessions have a soundtrack, and a switch to Music.app to see the track breaks your focus. music-mod puts the track, its progress and 2 buttons in the terminal that you already look at.
⏭ for the next track.osascript call every 5 seconds, for any number of open sessions. The clock updates every second.Function hooks are in early access. Turn them on in your shell profile:
export CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1
Then install the mod in Claude Code:
/plugin marketplace add zyx1121/music-mod
/plugin install music-mod@music-mod
Start a new session and play a song. The line appears above the prompt. On the first read, macOS can ask you to let your terminal control Music.
/music hides the line or shows it again. The mod remembers your choice between sessions.
| Part | Shows |
|---|---|
▶ ⏸ » « | The player state. Click to play or pause |
| Title | Track, artist and album, cut with an ellipsis when the line is narrow |
| Bar | Progress in the width that the title leaves (6 cells at least), then position and duration |
⏭ | Click for the next track |
When Music.app is not running or has stopped, the line says so. When osascript fails, the line shows the reason and the mod tries again.
| Setting | Default | Does |
|---|---|---|
refreshMs | 5000 | time between reads of Music.app, 1000 at least |
showOnStart | true | show the line when a session starts. /music wins after first use |
Set them with /config, or as music-mod.refreshMs in settings.
hooks/register.tsx registers /music on session.start and starts a 1-second tick. The tick draws the clock from the last read and reads again after refreshMs.hooks/now-playing.ts holds the JXA script for osascript -l JavaScript and the parser. The script asks only for what the line shows. It does not read the system volume, because that wakes coreaudiod.hooks/shared-read.ts keeps the shared read in $TMPDIR/music-mod/now.json. While one session reads, the others wait for its result.hooks/views/band-view.tsx draws the line with Box, Text and Button in the AbovePrompt band.Facts for coding agents and LLM tools. The rules for changing the code are in AGENTS.md.
/music (toggle), AbovePrompt UI line with buttons/plugin marketplace add zyx1121/music-mod, then /plugin install music-mod@music-modCLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1 claude --plugin-dir .bunx -p typescript tsc -p tsconfig.json && CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1 claude plugin test .refreshMs, showOnStartbunx -p typescript tsc -p tsconfig.json # typecheck
CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1 claude plugin test . # the engine's test harness
types/claude-code.d.ts is the engine contract from anthropics/claude-code/mods/types. When the engine changes, copy the new version and let the typecheck show what moved.
hooks/register.tsx 290 lines1/* @jsxRuntime classic */
2/* @jsx h */
3/* @jsxFrag Fragment */
4import type { EngineInterface, On, PluginOptions, Timer } from 'claude-code'
5
6import { ARGV, controlArgvOf, hasEnded, modelAt, modelOf, READ_TIMEOUT_MS, type Control, type Model } from './now-playing'
7import { cachePathOf, entryOf, isFresh, type Entry } from './shared-read'
8import { bandView } from './views/band-view'
9import { rowOf } from './views/panel'
10
11export const COMMAND_NAME = 'music'
12export const DEFAULT_REFRESH_MS = 5000
13export const MIN_REFRESH_MS = 1000
14
15/** How often the band redraws its clock while playing; no read happens on a tick. */
16export const TICK_MS = 1000
17
18/** At a track's end, a reading this recent (another session's) is still taken. */
19export const END_MAX_AGE_MS = 1000
20
21export const SHOWN_TEXT = 'Music shown above the prompt'
22export const HIDDEN_TEXT = 'Music hidden'
23
24/** The store key under which the last /music choice is kept between sessions. */
25export const STORE_SHOWN_KEY = 'shown'
26
27/**
28 * The refresh interval the options ask for, floored at MIN_REFRESH_MS.
29 *
30 * @param options the plugin's userConfig values
31 * @returns milliseconds between reads
32 */
33export function refreshMsOf(options: PluginOptions): number {
34 const value = options.refreshMs
35
36 return typeof value === 'number' && Number.isFinite(value)
37 ? Math.max(MIN_REFRESH_MS, Math.floor(value))
38 : DEFAULT_REFRESH_MS
39}
40
41type Host = {
42 run: (
43 argv: readonly string[],
44 init: { timeoutMs: number },
45 ) => Promise<{ exitCode: number; stdout: string; stderr: string }>
46 invalidate: () => void
47 every: (ms: number, fn: () => void) => Timer
48 now: () => Promise<number>
49 readShared: () => Promise<Entry | null>
50 writeShared: (entry: Entry) => Promise<void>
51 storeGet: (key: string) => Promise<unknown>
52 storeSet: (key: string, value: unknown) => Promise<void>
53}
54
55/**
56 * Whether the band shows at a session's start: the last /music choice the
57 * store kept, else the `showOnStart` option (true unless set false).
58 *
59 * @param kept what the store holds under STORE_SHOWN_KEY
60 * @param options the plugin's userConfig values
61 * @returns whether to show
62 */
63export function isShownAtStart(kept: unknown, options: PluginOptions): boolean {
64 if (typeof kept === 'boolean') {
65 return kept
66 }
67
68 return options.showOnStart !== false
69}
70
71/**
72 * The engine calls the band needs, taken off `$`. The shared reading lives
73 * under `TMPDIR`; a file the engine cannot read or write counts as absent.
74 *
75 * @param $ the engine
76 * @returns the host
77 */
78async function hostOf($: EngineInterface): Promise<Host> {
79 const path = cachePathOf(await $.env.get('TMPDIR').catch(() => undefined))
80
81 return {
82 run: (argv, init) => $.process.run(argv, init),
83 invalidate: () => $.ui.invalidate('ui.render'),
84 every: (ms, fn) => $.clock.every(ms, fn),
85 now: () => $.clock.now(),
86 readShared: () =>
87 $.fs.read(path).then(
88 text => (typeof text === 'string' ? entryOf(text) : null),
89 () => null,
90 ),
91 writeShared: entry => $.fs.write(path, JSON.stringify(entry)).catch(() => undefined),
92 storeGet: key => $.store.get(key),
93 storeSet: (key, value) => $.store.set(key, value),
94 }
95}
96
97/**
98 * The Music band: one line above the prompt, shown from the session's start
99 * (the last /music choice, else `showOnStart`) and toggled by /music. While
100 * it shows, a one-second tick redraws the clock from the last reading and,
101 * once `refreshMs` has passed, takes a new one: another session's from the
102 * shared file when it is recent enough, else its own from osascript. A press
103 * on a glyph sends its control and reads at once.
104 *
105 * @param on the engine's hook registrar
106 * @param options the plugin's userConfig values
107 */
108export function register(on: On, options: PluginOptions): void {
109 const refreshMs = refreshMsOf(options)
110
111 let model: Model = { kind: 'idle' }
112 let timer: Timer | null = null
113 let isShown = false
114 let isReading = false
115 let checkedAt = 0
116 let host: Host | null = null
117
118 /**
119 * Takes a reading no older than `maxAgeMs`: the shared one when it is,
120 * else a new osascript run, claimed in the shared file first so the other
121 * sessions wait for it instead of running their own.
122 */
123 async function read(host: Host, maxAgeMs: number): Promise<void> {
124 if (isReading) {
125 return
126 }
127
128 isReading = true
129
130 try {
131 const at = await host.now()
132 const shared = await host.readShared()
133
134 if (isFresh(shared, at, maxAgeMs)) {
135 if (!shared.run) {
136 // another session's read is under way: look again on the next tick
137 checkedAt = Number.NEGATIVE_INFINITY
138
139 return
140 }
141
142 checkedAt = at
143
144 if (model.kind !== 'ok' || model.readAt !== shared.readAt) {
145 model = modelOf(shared.run, shared.readAt)
146 }
147
148 return
149 }
150
151 checkedAt = at
152
153 await host.writeShared({ readAt: at, run: null })
154
155 const run = await host.run(ARGV, { timeoutMs: READ_TIMEOUT_MS })
156 const readAt = await host.now()
157
158 model = modelOf(run, readAt)
159 await host.writeShared({ readAt, run })
160 } catch (error) {
161 model = { kind: 'error', text: error instanceof Error ? error.message : String(error) }
162 } finally {
163 isReading = false
164 host.invalidate()
165 }
166 }
167
168 async function tick(host: Host): Promise<void> {
169 const at = await host.now().catch(() => null)
170
171 if (at === null) {
172 return
173 }
174
175 // a reading that already stood at the end (the track outruns its
176 // metadata) waits for the usual refresh instead of re-reading each tick
177 const isEndDue = hasEnded(model, at) && model.kind === 'ok' && !hasEnded(model, model.readAt)
178
179 if (isEndDue) {
180 await read(host, END_MAX_AGE_MS)
181 } else if (at < checkedAt || at - checkedAt >= refreshMs) {
182 await read(host, refreshMs)
183 } else if (model.kind === 'ok' && model.now.state === 'playing') {
184 host.invalidate()
185 }
186 }
187
188 async function control(which: Control): Promise<void> {
189 if (!host) {
190 return
191 }
192
193 const run = await host.run(controlArgvOf(which), { timeoutMs: READ_TIMEOUT_MS }).catch(() => null)
194
195 if (run && run.exitCode !== 0) {
196 model = { kind: 'error', text: `osascript exited ${run.exitCode}: ${run.stderr.trim()}` }
197 host.invalidate()
198
199 return
200 }
201
202 await read(host, 0)
203 }
204
205 const actions = {
206 playpause: () => void control('playpause'),
207 next: () => void control('next'),
208 }
209
210 function stop(): void {
211 timer?.cancel()
212 timer = null
213 isShown = false
214 }
215
216 async function show(engine: Host): Promise<void> {
217 host = engine
218 isShown = true
219 model = { kind: 'idle' }
220 await read(engine, refreshMs)
221
222 timer?.cancel()
223 timer = engine.every(TICK_MS, () => {
224 void tick(engine)
225 })
226 }
227
228 function hide(engine: Host): void {
229 stop()
230 engine.invalidate()
231 }
232
233 on('session.start', async ($, e, next) => {
234 try {
235 await $.command.register({
236 name: COMMAND_NAME,
237 description: 'What Music.app is playing, one line above the prompt',
238 })
239 } catch (error) {
240 $.ui.log(
241 `/${COMMAND_NAME} did not register: ${error instanceof Error ? error.message : String(error)}`,
242 )
243 }
244
245 if (e.isInteractive && e.surface === 'terminal') {
246 const engine = await hostOf($)
247 const kept = await engine.storeGet(STORE_SHOWN_KEY).catch(() => undefined)
248
249 if (isShownAtStart(kept, options)) {
250 await show(engine)
251 }
252 }
253
254 return next(e)
255 })
256
257 on('command.run', { command: COMMAND_NAME }, async $ => {
258 const engine = await hostOf($)
259 const isHiding = isShown
260
261 if (isHiding) {
262 hide(engine)
263 } else {
264 await show(engine)
265 }
266
267 await engine.storeSet(STORE_SHOWN_KEY, !isHiding).catch(() => undefined)
268
269 return { text: isHiding ? HIDDEN_TEXT : SHOWN_TEXT }
270 })
271
272 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
273 if (!isShown || e.props.hasSurvey) {
274 return next(e)
275 }
276
277 const { Box, Text, Button } = $.ui.resolve(e)
278 const at = await $.clock.now()
279 const beneath = await next(e)
280
281 return rowOf({ Box, Text }, bandView({ Box, Text, Button }, modelAt(model, at), e.props.bodyColumns, actions), beneath)
282 })
283
284 on('session.end', ($, e, next) => {
285 stop()
286
287 return next(e)
288 })
289}
290hooks/now-playing.ts 236 lines1/**
2 * What Music.app reports, read with one `osascript -l JavaScript` run and
3 * parsed from the JSON it prints: only what the band draws.
4 */
5export type NowPlaying = {
6 state: 'closed' | 'stopped' | 'playing' | 'paused' | 'fast forwarding' | 'rewinding'
7 track: { name: string; artist: string; album: string; duration: number } | null
8 position: number | null
9}
10
11/**
12 * The pane's state: nothing read yet, a reading taken at `readAt`
13 * (milliseconds since the epoch), or why the read failed.
14 */
15export type Model =
16 | { kind: 'idle' }
17 | { kind: 'ok'; now: NowPlaying; readAt: number }
18 | { kind: 'error'; text: string }
19
20/**
21 * The JXA script osascript runs. One IIFE whose value is the JSON text
22 * (osascript prints the top-level expression's value). It asks Music.app for
23 * the fewest properties the band draws: no system volume (each read of it
24 * wakes coreaudiod) and no playlist walk (`tracks.length` is slow on a
25 * long playlist).
26 *
27 * It never launches Music.app. `Application('Music')` relaunches the app
28 * when a read lands while it quits, so the script finds the running process
29 * through NSRunningApplication (no Apple event) and sends each get as a raw
30 * Apple event to that process ID. An event to a process that has gone fails
31 * (-600, -609) and the read reports closed.
32 */
33export const SCRIPT = `(() => {
34 ObjC.import('AppKit')
35 const D = $.NSAppleEventDescriptor
36 const code = s => ((s.charCodeAt(0) << 24) | (s.charCodeAt(1) << 16) | (s.charCodeAt(2) << 8) | s.charCodeAt(3)) >>> 0
37 const text = n => String.fromCharCode((n >>> 24) & 255, (n >>> 16) & 255, (n >>> 8) & 255, n & 255)
38 const STATES = { kPSS: 'stopped', kPSP: 'playing', kPSp: 'paused', kPSF: 'fast forwarding', kPSR: 'rewinding' }
39 const GONE = [-600, -609]
40 const WHY = { '-1712': 'Music.app did not answer in time', '-1743': 'not allowed to send Apple events to Music.app' }
41 const SEND = 0x3 | 0x10 | 0x80 // wait for the reply, never interact, never reconnect
42 const DEADLINE = Date.now() + 4000 // the whole read, a second inside READ_TIMEOUT_MS
43 const MISSING = code('msng') // missing value: a typeType descriptor holding 'msng'
44 const out = { state: 'closed', track: null, position: null }
45 const found = $.NSRunningApplication.runningApplicationsWithBundleIdentifier('com.apple.Music').js
46 if (found.length === 0) return JSON.stringify(out)
47 const target = D.descriptorWithProcessIdentifier(found[0].processIdentifier)
48 const property = (id, of) => {
49 const spec = D.recordDescriptor
50 spec.setDescriptorForKeyword(D.descriptorWithTypeCode(code('prop')), code('want'))
51 spec.setDescriptorForKeyword(D.descriptorWithEnumCode(code('prop')), code('form'))
52 spec.setDescriptorForKeyword(D.descriptorWithTypeCode(code(id)), code('seld'))
53 spec.setDescriptorForKeyword(of || D.nullDescriptor, code('from'))
54 return spec.coerceToDescriptorType(code('obj '))
55 }
56 const get = spec => {
57 const event = D.appleEventWithEventClassEventIDTargetDescriptorReturnIDTransactionID(code('core'), code('getd'), target, -1, 0)
58 event.setParamDescriptorForKeyword(spec, code('----'))
59 const error = $()
60 const reply = event.sendEventWithOptionsTimeoutError(SEND, Math.max(0.1, (DEADLINE - Date.now()) / 1000), error)
61 if (reply.isNil()) throw { errorNumber: Number(error.code) }
62 const errn = reply.paramDescriptorForKeyword(code('errn'))
63 if (!errn.isNil() && errn.int32Value !== 0) throw { errorNumber: errn.int32Value }
64 return reply.paramDescriptorForKeyword(code('----'))
65 }
66 try {
67 const state = text(get(property('pPlS')).enumCodeValue)
68 out.state = STATES[state] || state
69 if (out.state === 'stopped') return JSON.stringify(out)
70 const track = property('pTrk')
71 const string = id => ObjC.unwrap(get(property(id, track)).stringValue)
72 const number = d => (d.descriptorType === code('type') && d.typeCodeValue === MISSING ? null : d.doubleValue)
73 out.track = { name: string('pnam'), artist: string('pArt'), album: string('pAlb'), duration: number(get(property('pDur', track))) }
74 try { out.position = number(get(property('pPos'))) } catch (e) { out.position = null }
75 return JSON.stringify(out)
76 } catch (e) {
77 if (e instanceof Error) throw e
78 if (GONE.includes(e.errorNumber)) return JSON.stringify({ state: 'closed', track: null, position: null })
79 throw new Error((WHY[e.errorNumber] || 'Music.app answered error') + ' (' + e.errorNumber + ')')
80 }
81})()`
82
83/** The argv that reads Music.app. */
84export const ARGV: readonly string[] = ['osascript', '-l', 'JavaScript', '-e', SCRIPT]
85
86/** How long one read may take before it counts as failed. */
87export const READ_TIMEOUT_MS = 5000
88
89const STATES = new Set(['closed', 'stopped', 'playing', 'paused', 'fast forwarding', 'rewinding'])
90
91function isRecord(value: unknown): value is Record<string, unknown> {
92 return typeof value === 'object' && value !== null && !Array.isArray(value)
93}
94
95function numberOr(value: unknown, fallback: number): number {
96 return typeof value === 'number' && Number.isFinite(value) ? value : fallback
97}
98
99function stringOr(value: unknown, fallback: string): string {
100 return typeof value === 'string' ? value : fallback
101}
102
103/**
104 * The reading a finished osascript run stands for.
105 *
106 * @param run the process result
107 * @param readAt when the run was taken, milliseconds since the epoch
108 * @returns the reading, or the error the pane should show
109 */
110export function modelOf(run: { exitCode: number; stdout: string; stderr: string }, readAt: number): Model {
111 if (run.exitCode !== 0) {
112 const reason = run.stderr.trim().split('\n').at(-1) ?? ''
113
114 return { kind: 'error', text: `osascript exited ${run.exitCode}${reason ? `: ${reason}` : ''}` }
115 }
116
117 let parsed: unknown
118
119 try {
120 parsed = JSON.parse(run.stdout)
121 } catch {
122 return { kind: 'error', text: 'Music.app answered something that is not JSON' }
123 }
124
125 if (!isRecord(parsed) || typeof parsed.state !== 'string' || !STATES.has(parsed.state)) {
126 return { kind: 'error', text: 'Music.app answered an unknown player state' }
127 }
128
129 const track = isRecord(parsed.track) ? parsed.track : null
130
131 return {
132 kind: 'ok',
133 readAt,
134 now: {
135 state: parsed.state as NowPlaying['state'],
136 track: track
137 ? {
138 name: stringOr(track.name, ''),
139 artist: stringOr(track.artist, ''),
140 album: stringOr(track.album, ''),
141 duration: numberOr(track.duration, 0),
142 }
143 : null,
144 position: typeof parsed.position === 'number' ? parsed.position : null,
145 },
146 }
147}
148
149/**
150 * The reading as it stands at `at`: while playing, the position runs on from
151 * where it was read, so the clock ticks without asking Music.app again.
152 *
153 * @param model what was last read
154 * @param at now, milliseconds since the epoch
155 * @returns the model with the position carried forward, capped at the track's end
156 */
157export function modelAt(model: Model, at: number): Model {
158 if (model.kind !== 'ok' || model.now.state !== 'playing' || !model.now.track || model.now.position === null) {
159 return model
160 }
161
162 const elapsed = Math.max(0, at - model.readAt) / 1000
163 const { duration } = model.now.track
164 const position = model.now.position + elapsed
165
166 return { ...model, now: { ...model.now, position: duration > 0 ? Math.min(duration, position) : position } }
167}
168
169/**
170 * Whether the playing track has run out by `at`, so the next one is due.
171 *
172 * @param model what was last read
173 * @param at now, milliseconds since the epoch
174 * @returns true once the carried-forward position reaches the duration
175 */
176export function hasEnded(model: Model, at: number): boolean {
177 const shown = modelAt(model, at)
178
179 return (
180 shown.kind === 'ok' &&
181 shown.now.state === 'playing' &&
182 shown.now.track !== null &&
183 shown.now.track.duration > 0 &&
184 (shown.now.position ?? 0) >= shown.now.track.duration
185 )
186}
187
188/**
189 * Seconds as m:ss (or h:mm:ss past an hour).
190 *
191 * @param seconds a non-negative duration
192 * @returns the clock text
193 */
194export function clockOf(seconds: number): string {
195 const whole = Math.max(0, Math.floor(seconds))
196 const h = Math.floor(whole / 3600)
197 const m = Math.floor((whole % 3600) / 60)
198 const s = whole % 60
199 const mm = h > 0 ? String(m).padStart(2, '0') : String(m)
200
201 return `${h > 0 ? `${h}:` : ''}${mm}:${String(s).padStart(2, '0')}`
202}
203
204/**
205 * A progress bar of `width` cells, filled to `ratio`.
206 *
207 * @param ratio 0 to 1; out of range is clamped
208 * @param width the bar's cells, at least 1
209 * @returns the bar
210 */
211export function barOf(ratio: number, width: number): string {
212 const cells = Math.max(1, Math.floor(width))
213 const filled = Math.round(Math.min(1, Math.max(0, Number.isFinite(ratio) ? ratio : 0)) * cells)
214
215 return `${'█'.repeat(filled)}${'░'.repeat(cells - filled)}`
216}
217
218
219/** The transport controls the band offers. */
220export type Control = 'playpause' | 'next'
221
222const CONTROL_SCRIPT: Record<Control, string> = {
223 playpause: 'tell application "Music" to playpause',
224 next: 'tell application "Music" to next track',
225}
226
227/**
228 * The argv that sends one transport control to Music.app.
229 *
230 * @param control which control
231 * @returns the argv
232 */
233export function controlArgvOf(control: Control): readonly string[] {
234 return ['osascript', '-e', CONTROL_SCRIPT[control]]
235}
236hooks/shared-read.ts 83 lines1/**
2 * One reading of Music.app shared by every session on the machine: each
3 * session looks at a small file under the temporary directory first and runs
4 * osascript only when the reading there is older than it can use, so five
5 * open sessions cost one read per interval, not five.
6 */
7
8/** A finished osascript run, as `$.process.run` resolves it. */
9export type Run = { exitCode: number; stdout: string; stderr: string }
10
11/**
12 * What the shared file holds: when the reading was taken (milliseconds since
13 * the epoch) and the run it came from, or null while the first read is
14 * still under way.
15 */
16export type Entry = { readAt: number; run: Run | null }
17
18/** The shared file's name under the temporary directory. */
19export const CACHE_NAME = 'music-mod/now.json'
20
21/**
22 * The shared file's path.
23 *
24 * @param tmpdir `TMPDIR`, when set
25 * @returns the path under it, else under /tmp
26 */
27export function cachePathOf(tmpdir: string | undefined): string {
28 const dir = tmpdir && tmpdir !== '' ? tmpdir : '/tmp'
29
30 return `${dir.replace(/\/+$/, '')}/${CACHE_NAME}`
31}
32
33function isRun(value: unknown): value is Run {
34 if (typeof value !== 'object' || value === null) {
35 return false
36 }
37
38 const run = value as Record<string, unknown>
39
40 return typeof run.exitCode === 'number' && typeof run.stdout === 'string' && typeof run.stderr === 'string'
41}
42
43/**
44 * The entry a shared file's text stands for.
45 *
46 * @param text the file's content
47 * @returns the entry, or null when the text is not one
48 */
49export function entryOf(text: string): Entry | null {
50 let parsed: unknown
51
52 try {
53 parsed = JSON.parse(text)
54 } catch {
55 return null
56 }
57
58 if (typeof parsed !== 'object' || parsed === null) {
59 return null
60 }
61
62 const { readAt, run } = parsed as Record<string, unknown>
63
64 if (typeof readAt !== 'number' || !Number.isFinite(readAt)) {
65 return null
66 }
67
68 return { readAt, run: isRun(run) ? run : null }
69}
70
71/**
72 * Whether an entry is recent enough to use instead of a new read. An entry
73 * from the future (a clock set back) is never fresh.
74 *
75 * @param entry what the shared file holds
76 * @param at now, milliseconds since the epoch
77 * @param maxAgeMs the oldest reading the caller takes
78 * @returns whether to use it
79 */
80export function isFresh(entry: Entry | null, at: number, maxAgeMs: number): entry is Entry {
81 return entry !== null && entry.readAt <= at && at - entry.readAt < maxAgeMs
82}
83hooks/views/band-view.tsx 192 lines1/* @jsxRuntime classic */
2/* @jsx h */
3/* @jsxFrag Fragment */
4import type { Elements, RenderElement } from 'claude-code'
5
6import { barOf, clockOf, type Control, type Model, type NowPlaying } from '../now-playing'
7import { COLOR, FRAME_CELLS, cellsOf, lineOf, panelOf, type Seg } from './panel'
8
9/** The tags the band draws with. */
10export type Kit = Pick<Elements['terminal'], 'Box' | 'Text' | 'Button'>
11
12/** What a press on each control runs. */
13export type Actions = Record<Control, () => void>
14
15/** The panel's title. */
16export const TITLE = 'MUSIC'
17
18/** The fewest cells the bar keeps; below that the title gives way. */
19export const BAR_MIN_CELLS = 6
20
21/** The share of the band a playing track's panel takes. */
22export const PLAYING_SHARE = 0.4
23
24/** The fewest columns a playing track's panel takes. */
25export const PLAYING_MIN_COLUMNS = 36
26
27/** The state glyph, a pressable play/pause. */
28export const STATE_MARK: Record<Exclude<NowPlaying['state'], 'closed'>, string> = {
29 stopped: '▶',
30 playing: '▶',
31 paused: '⏸',
32 'fast forwarding': '»',
33 rewinding: '«',
34}
35
36/** The next-track glyph. */
37export const NEXT_MARK = '⏭'
38
39const WIDE =
40 /[ᄀ-ᅟ⺀-가-힣豈-︰-﹏-⦆¢-₩\u{1F300}-\u{1FAFF}]/u
41
42/**
43 * The columns `text` takes on the terminal, a CJK or emoji character two.
44 *
45 * @param text the string
46 * @returns its cells
47 */
48export function widthOf(text: string): number {
49 let width = 0
50
51 for (const char of text) {
52 width += WIDE.test(char) ? 2 : 1
53 }
54
55 return width
56}
57
58/**
59 * `text` cut to `cells` columns with an ellipsis when it does not fit.
60 *
61 * @param text the string
62 * @param cells the columns to fit
63 * @returns the fitted string
64 */
65export function fitOf(text: string, cells: number): string {
66 if (widthOf(text) <= cells) {
67 return text
68 }
69
70 let width = 0
71 let out = ''
72
73 for (const char of text) {
74 const w = WIDE.test(char) ? 2 : 1
75
76 if (width + w > cells - 1) {
77 return `${out}…`
78 }
79
80 width += w
81 out += char
82 }
83
84 return out
85}
86
87/**
88 * A panel sized to one line of segments.
89 *
90 * @param kit Box, Text and Button
91 * @param segs the line
92 * @param tone the border's tone
93 * @returns the tree
94 */
95function textPanelOf(kit: Kit, segs: readonly Seg[], tone: 'normal' | 'error' = 'normal'): RenderElement {
96 const width = Math.max(cellsOf(segs), TITLE.length + 2) + FRAME_CELLS
97
98 return panelOf(kit, { title: TITLE, tone, width }, lineOf(kit, segs))
99}
100
101/**
102 * The band's panel for one `ui.render`: the track, a bar that takes what the
103 * title leaves, and the two pressable glyphs.
104 *
105 * @param kit Box, Text and Button
106 * @param model what was last read
107 * @param columns the band's body columns
108 * @param actions what the glyphs run
109 * @returns the tree
110 */
111export function bandView(kit: Kit, model: Model, columns: number, actions: Actions): RenderElement {
112 const { Box, Text, Button } = kit
113
114 if (model.kind === 'idle') {
115 return textPanelOf(kit, [{ text: 'reading Music.app…', color: COLOR.muted }])
116 }
117
118 if (model.kind === 'error') {
119 return panelOf(
120 kit,
121 { title: TITLE, tone: 'error', width: Math.max(PLAYING_MIN_COLUMNS, Math.floor(columns * PLAYING_SHARE)) },
122 lineOf(kit, [
123 { text: 'could not read Music.app', color: COLOR.error },
124 { text: ` ${model.text}`, color: COLOR.muted },
125 ]),
126 )
127 }
128
129 const { now } = model
130
131 if (now.state === 'closed') {
132 return textPanelOf(kit, [{ text: 'not running', color: COLOR.muted }])
133 }
134
135 if (now.state === 'stopped' || !now.track) {
136 const text = 'nothing playing'
137 const width = 1 + 1 + text.length + FRAME_CELLS
138
139 return panelOf(
140 kit,
141 { title: TITLE, width },
142 <Box flexDirection="row" gap={1}>
143 <Button key="playpause" plain onPress={actions.playpause}>
144 {STATE_MARK.stopped}
145 </Button>
146 <Text color={COLOR.muted}>{text}</Text>
147 </Box>,
148 )
149 }
150
151 const { track } = now
152 const position = now.position ?? 0
153 const clocks = `${clockOf(position)} / ${clockOf(track.duration)}`
154 const name = track.name
155 const rest = [track.artist, track.album].filter(part => part !== '').join(' / ')
156 const title = rest ? `${name} ${rest}` : name
157 const width = Math.min(columns, Math.max(PLAYING_MIN_COLUMNS, Math.floor(columns * PLAYING_SHARE)))
158 // Glyph, title, bar, clocks and glyph, a space between each.
159 const fixed = 1 + 1 + 1 + 1 + clocks.length + 1 + 1
160 const spare = Math.max(BAR_MIN_CELLS + 4, width - FRAME_CELLS - fixed)
161 const isWhole = widthOf(title) + BAR_MIN_CELLS <= spare
162 const titleCells = isWhole ? widthOf(title) : spare - BAR_MIN_CELLS
163 const shown = fitOf(title, titleCells)
164 const shownName = [...shown].slice(0, [...name].length).join('')
165 const bar = barOf(track.duration > 0 ? position / track.duration : 0, spare - titleCells)
166 const filled = bar.replace(/░/g, '').length
167
168 return panelOf(
169 kit,
170 { title: TITLE, width },
171 <Box flexDirection="row" gap={1}>
172 <Button key="playpause" plain onPress={actions.playpause}>
173 {STATE_MARK[now.state]}
174 </Button>
175 <Text>
176 <Text color={COLOR.text} bold>
177 {shownName}
178 </Text>
179 <Text color={COLOR.muted}>{shown.slice(shownName.length)}</Text>
180 </Text>
181 <Text>
182 <Text color={COLOR.title}>{'━'.repeat(filled)}</Text>
183 <Text color={COLOR.line}>{'─'.repeat(bar.length - filled)}</Text>
184 <Text color={COLOR.muted}> {clocks}</Text>
185 </Text>
186 <Button key="next" plain onPress={actions.next}>
187 {NEXT_MARK}
188 </Button>
189 </Box>,
190 )
191}
192hooks/views/panel.tsx 147 lines1/* @jsxRuntime classic */
2/* @jsx h */
3/* @jsxFrag Fragment */
4import type { Elements, RenderChildren, RenderElement } from 'claude-code'
5
6// One panel of the band, drawn the way Textual draws a widget with a border
7// title: a round border, the title over its top edge, an optional subtitle
8// over its bottom edge. Music, today and hum each draw their panels with a
9// copy of this file and lay them in one row: each passes `next(e)` into the
10// row's remaining space, so the three share the band from left to right.
11
12/** The tags a panel draws with. */
13export type PanelKit = Pick<Elements['terminal'], 'Box' | 'Text'>
14
15/**
16 * The ditto statusline's palette, shared by the three mods: its lavender body
17 * for titles, its highlight for text, darker lavenders for the quiet parts.
18 * Warnings and errors follow the person's theme, like the statusline's.
19 */
20export const COLOR = {
21 text: '#ece0fa',
22 label: '#8e7ba8',
23 muted: '#9a8fad',
24 line: '#5e4f70',
25 title: '#c3a1e6',
26 warn: 'warning',
27 error: 'error',
28} as const
29
30/** What the panel says: quiet, a value worth a look, or a failure (the only tone that colors the border). */
31export type Tone = 'normal' | 'warn' | 'error' | 'dim'
32
33/** The cells the border and its padding take across a panel. */
34export const FRAME_CELLS = 4
35
36/** A run of text in one color: the body of a panel is a list of these. */
37export type Seg = { text: string; color: string; bold?: boolean }
38
39export type PanelSpec = {
40 title: string
41 subtitle?: string
42 tone?: Tone
43 /** Fixed columns, frame included; without it the panel grows into the free space. */
44 width?: number
45}
46
47/**
48 * One panel: the round border around `body`, the title and subtitle over it.
49 *
50 * @param kit Box and Text
51 * @param spec title, subtitle, tone and width
52 * @param body the tree inside the border
53 * @returns the tree
54 */
55export function panelOf(kit: PanelKit, spec: PanelSpec, body: RenderChildren): RenderElement {
56 const { Box, Text } = kit
57 const tone = spec.tone ?? 'normal'
58 // A value worth a look colors only that value; the border changes for a failure alone.
59 const border = tone === 'error' ? COLOR.error : COLOR.line
60 const size = spec.width === undefined ? { flexGrow: 1, flexShrink: 1 } : { width: spec.width, flexShrink: 0 }
61
62 return (
63 <Box flexDirection="column" {...size}>
64 <Box key="body" flexDirection="column" borderStyle="round" borderColor={border} paddingX={1}>
65 {body}
66 </Box>
67 <Box position="absolute" top={0} left={2}>
68 <Text color={tone === 'dim' ? COLOR.muted : COLOR.title} bold>
69 {` ${spec.title} `}
70 </Text>
71 </Box>
72 {spec.subtitle ? (
73 <Box position="absolute" top={2} right={2}>
74 <Text color={COLOR.muted}>{` ${spec.subtitle} `}</Text>
75 </Box>
76 ) : null}
77 </Box>
78 )
79}
80
81/**
82 * Segments as one line of Text, cut at the end when the panel is narrower.
83 *
84 * @param kit Box and Text
85 * @param segs the runs
86 * @returns the tree
87 */
88export function lineOf(kit: PanelKit, segs: readonly Seg[]): RenderElement {
89 const { Text } = kit
90
91 return (
92 <Text wrap="truncate-end">
93 {segs.map(seg => (
94 <Text color={seg.color} bold={seg.bold ?? false}>
95 {seg.text}
96 </Text>
97 ))}
98 </Text>
99 )
100}
101
102/**
103 * The cells segments take, a CJK or emoji character two.
104 *
105 * @param segs the runs
106 * @returns the cells
107 */
108export function cellsOf(segs: readonly Seg[]): number {
109 let cells = 0
110
111 for (const seg of segs) {
112 for (const char of seg.text) {
113 cells += WIDE.test(char) ? 2 : 1
114 }
115 }
116
117 return cells
118}
119
120const WIDE =
121 /[ᄀ-ᅟ⺀-가-힣豈-︰-﹏-⦆¢-₩\u{1F300}-\u{1FAFF}]/u
122
123/**
124 * This mod's panels, then what the plugins beneath draw, in one row.
125 *
126 * A mod whose panels grow into the free space passes `isLast`: the space for
127 * what is beneath then keeps to its content instead of taking a share.
128 *
129 * @param kit Box and Text
130 * @param mine this mod's panels
131 * @param beneath `next(e)`'s tree
132 * @param isLast true when this mod's panels fill the rest of the row
133 * @returns the tree
134 */
135export function rowOf(kit: PanelKit, mine: RenderChildren, beneath: RenderChildren, isLast = false): RenderElement {
136 const { Box } = kit
137
138 return (
139 <Box flexDirection="row" flexGrow={1}>
140 {mine}
141 <Box flexDirection="row" flexGrow={isLast ? 0 : 1}>
142 {beneath}
143 </Box>
144 </Box>
145 )
146}
147