/** * The command verbs the line knows. * * A table rather than a `switch`, because the table is what the readout reads: the * line shows what a word means while it is being typed and what `:help` lists, and * both of those questions want the same list the key press dispatches through. A * `switch` answers the second question by being read by a human. * * Every verb answers with the line it left on screen, including the ones that did * nothing: `:pause` on a paused track says `already paused` rather than staying * silent, because a command line that answers some presses and not others is * indistinguishable from one that dropped the press on the floor. One verb raises a * panel: `:timeaudit`, the load flamegraph. It raises the overlay the artwork zoom * already established (components/PlayerBar.tsx) — a full-screen layer with its own * keyboard — and the verb still does not build it: it writes one signal in * `lib/loadaudit.ts`, which the app root is watching, so the command table stays a table * of verbs and the renderer stays out of here. What a line beside the prompt is still * enough for is `volume 40%`. * * The verbs are the transport's and two the library's: what the command line controls * is what is playing, which is the player's state and lives outside the routed view * (see App.tsx for why the bar does too) — `:scan`, which asks the server to look * for new files before the minute-long poll does — and `:harvest`, which reads back what the last * crawl measured itself against and lets the reader ask for the index again from cold. Filtering is * not a verb here — that is what `/` is for. */ import { connection } from "../connection"; import { library } from "../harvest"; import { describeCrawlReceipt } from "../harvest/label"; import { copyAuditReport, saveAuditReport } from "../auditexport"; import { count } from "../print"; import { auditLength, audits, latestAudit, setAuditEnabled, showAudit, type LoadAudit, } from "../loadaudit"; import { player } from "../player"; import { lyrics } from "../lyrics"; import { clearLadderAudits, describeLadder, ladderAudits, latestLadder, setLadderAuditEnabled, showLadderAudit, } from "../lyrics/audit"; import { REPEAT_ORDER, type RepeatMode } from "../player/store"; import { formatClock, parseClock } from "../player/time"; import { keyWord, semitoneLabel, shiftSemitones, speedLabel, speedWord } from "../player/pitch"; import { SHIFT_QUALITIES, type ShiftQuality } from "../player/shift"; import { formatVolume } from "../player/volume"; import { cycleThemeMode, resolveTheme, setThemeMode, themeModes, type ThemeMode, } from "../theme/mode"; /** How much is in a report, said out loud: the number should match the file's own contents. */ const countSpans = (list: readonly LoadAudit[]): number => list.reduce((n, a) => n + a.raw().length, 0); /** What a press leaves on the line. `bad` is the only case that takes the danger ink. */ export interface CommandOutcome { text: string; bad: boolean; } /** * How the lyric is said back on the line. * * The setting and the answer are one sentence, because a listener typing `:lyrics` is asking the * first in order to find out about the second: `lyrics on · 42 lines · lrclib` says both what is * allowed and what came of it. Every state has its own words, including the two that are nobody's * fault — a track LRCLIB has never heard of, and a host that is throttling us — which the app must * not blur, since only one of them is worth asking about again. */ function lyricsLine(): string { const store = lyrics(); if (!store.peekEnabled()) return "lyrics off · nothing is asked of lrclib"; const state = store.peekCurrent(); if (!state) return "lyrics on · nothing on the bar to ask about"; switch (state.status) { case "found": { const n = state.lines.length; // Singular when it is one, because the line is read back at a person and "1 synced lines" is // the kind of sloppiness a command line is judged on. return `lyrics on · ${count(n, "synced line")} · lrclib`; } case "searching": return "lyrics on · asking lrclib"; case "none": return `lyrics on · nothing for this track${state.says ? ` · ${state.says}` : ""}`; case "unreachable": return `lyrics on · ${state.says ?? "lrclib did not answer"}`; default: // `off` with the setting on is a state between presses: switched off mid-track and back on // before the effect got there, so the honest line is that the next one will be asked about. return "lyrics on · the next track will be asked"; } } /** * What a verb hands back: a line, or — for the verbs whose answer is a round-trip — * a promise of one. A synchronous verb answers in the press; an asynchronous one * leaves `word…` beside the prompt until the server replies, and the promise then * replaces exactly that line (any key typed in between took it away, which is the * line's standing rule about feedback outliving its press). */ export type CommandRun = CommandOutcome | Promise; const ok = (text: string): CommandOutcome => ({ text, bad: false }); const bad = (text: string): CommandOutcome => ({ text, bad: true }); export interface Command { /** the word typed after the colon */ name: string; /** * How the arguments read, shown beside the description until somebody types them. * `[]` marks an optional argument, so `vol [n|up|down|mute]` says "and it may be * left out" without a second sentence saying it. */ usage: string; /** one line: what the verb does, in the imperative the reader can ignore */ says: string; /** the words that mean this verb as well */ also?: readonly string[]; run(args: readonly string[]): CommandRun; } /** The modes by the names the repeat button uses, plus the ones people type. */ const REPEAT_WORDS: Record = { off: "none", none: "none", all: "album", album: "album", record: "album", artist: "artist", track: "single", one: "single", }; /** The theme modes by the words that mean them, `auto` and the OS's own words included. */ const THEME_WORDS: Record = { system: "system", auto: "system", os: "system", light: "light", dark: "dark", }; /** * How the current theme is said back on the line. * * The mode and the theme it resolves to, because they can differ and the difference is the * whole idea of `system`: `theme system · painting light` tells a listener who just cycled * into `system` what they will actually see, which a bare `system` would not. */ function themeLine(mode: ThemeMode): string { return `theme ${mode} · painting ${resolveTheme()}`; } /** * `vol`'s argument, in the two forms it arrives in: a place on the slider, or a move * from where the slider is. A bare number is a *place* — `:vol 40` means forty per * cent, the way the slider says it — and only a leading sign or the two words make it * a move, because `:vol 40` followed by `:vol 4` should not be a riddle about which * one was meant relatively. */ function volumeStep(arg: string): number | null { if (arg === "up" || arg === "+") return 0.05; if (arg === "down" || arg === "-" || arg === "dn") return -0.05; const n = parseClock(arg); if (n === null) return null; // A signed number is a move, in slider points; an unsigned one is a place. return arg.startsWith("+") || arg.startsWith("-") ? n / 100 : null; } /** Parse a level out of `40`, `40%` or `0.4`; null for anything else. */ function volumeLevel(arg: string): number | null { const bare = arg.endsWith("%") ? arg.slice(0, -1) : arg; const n = Number(bare); if (!Number.isFinite(n) || n < 0) return null; // 0.4 and 40 are both a fifth of the way up the slider, and the reader who types // the first one is not wrong: the control is a percentage, the curve is not. return n > 1 ? n / 100 : n; } /** * How the deck's speed is said back on the line. * * The octave signed (`+1`, `-1`, `0`) because it is a displacement from the record rather than a * position on a dial, and the multiple beside it because the octave names only the pitch and the * line is reporting both halves of what the key did: the record is an octave up *and* takes half * as long. `×1` has no glyph to say it with, so the plainest sentence says it instead. */ /** * The speed as one line: the multiple, and what it has done to the record's own tempo. * * The percent is not in it even though it is what is stored: `×0.8` is the thing a listener is looking * at in the bar, and a line that printed both would be a line that admits it does not know which unit * the person asked for. */ function speedLine(rate: number): string { const glyph = speedLabel(rate); return `speed ${glyph || "\u00d71"} · ${rate === 1 ? "the record's own speed" : `the record plays at ${glyph}`}`; } /** What `:octave` says after a snap: the speed it landed on, and that it was a snap. */ function octaveLine(rate: number): string { return rate === 1 ? "octave off · the record's own speed" : `octave ${rate > 1 ? "up" : "down"} · ${speedLine(rate)}`; } /** The store every verb reaches for, named once rather than spelled at each helper's mouth. */ type Player = ReturnType; /** * How the pitch state is said back: the key the record is being heard in, and the fact that explains * it when the lock is involved — with the lock on, the key alone is not the whole of what somebody * asked for. */ function keyLine(p: Player, key = p.peekKey()): string { const label = semitoneLabel(shiftSemitones(key, p.peekLocked(), p.peekSpeed())); if (label === "") return "the record's own key"; return `key ${label}${p.peekLocked() ? " · pitch locked against the speed" : ""}`; } /** The lock as a sentence about what it does, because a bare "on" says nothing about the speed. */ function lockLine(p: Player, on = p.peekLocked()): string { if (!on) return "lock off · the speed moves the pitch with it"; const at = p.peekSpeed(); if (at === 1) return "lock on · nothing to hold yet — the speed is \u00d71"; // The correction stated rather than implied. The key readout shows the sum of what the listener // asked for and what the lock is undoing, and at 80 % the second half is 3.9 semitones that nobody // can compute at a prompt — so a line about the lock says what the lock is worth. const correction = semitoneLabel(-12 * Math.log2(at)); return `lock on · holding the pitch against ${speedLabel(at)} · ${correction} of correction`; } export const COMMANDS: readonly Command[] = [ { name: "play", usage: "", says: "let the music on", run: () => { const p = player(); if (p.peekState() === "playing") return ok("already playing"); // The transport's own front door: `toggle` re-issues the current track, which // is what resume means here, and it is the door the space bar uses — a second // way to start a source would be a second idea of what resuming costs. p.toggle(); return ok(p.peekState() === "idle" ? "nothing to play" : "playing"); }, }, { name: "pause", usage: "", says: "stop, and keep the place", run: () => { const p = player(); if (p.peekState() !== "playing") return ok("already stopped"); p.pause(); return ok(`paused at ${formatClock(p.peekLivePosition())}`); }, }, { name: "toggle", usage: "", says: "play, or stop", also: ["t"], run: () => { player().toggle(); return ok("toggled"); }, }, { name: "next", usage: "", says: "the track after this one", also: ["n"], run: () => { const p = player(); if (!p.peekCurrent()) return bad("nothing queued"); p.next(); return ok(p.peekCurrent()?.title ?? "next"); }, }, { name: "prev", usage: "", says: "the track before this one", also: ["previous", "p"], run: () => { const p = player(); if (!p.peekCurrent()) return bad("nothing queued"); p.previous(); return ok(p.peekCurrent()?.title ?? "previous"); }, }, { name: "seek", usage: " [+/-n]", says: "jump to a place in the track", also: ["s", "jump"], run: (args) => { const p = player(); if (!p.peekCurrent()) return bad("nothing queued"); const total = p.peekDuration(); if (total <= 0) return bad("no length to aim at yet"); const arg = args[0]; if (arg === undefined) { return ok(`at ${formatClock(p.peekLivePosition())} of ${formatClock(total)}`); } const at = parseClock(arg); if (at === null) return bad(`not a time: ${arg}`); // A signed argument is a move from where the clock is, which is the one case // `seek`'s own clamp cannot decide: `+10` is a distance, `10` is a place, and // the difference is the number the reader meant. const moved = arg.startsWith("+") || arg.startsWith("-") ? p.peekLivePosition() + at : at; p.seek(moved); return ok(`${formatClock(moved)} of ${formatClock(total)}`); }, }, { name: "vol", usage: "[n|up|down|mute]", says: "the master gain", also: ["volume", "v"], run: (args) => { const p = player(); const arg = args[0]; if (arg === undefined) { return ok(`${formatVolume(p.peekVolume())} · ${p.peekVolume() <= 0 ? "mute" : "on"}`); } if (arg === "mute") { p.setVolume(0); return ok("mute"); } const step = volumeStep(arg); if (step !== null) { p.setVolume(p.peekVolume() + step); return ok(formatVolume(p.peekVolume())); } const level = volumeLevel(arg); if (level === null) return bad(`not a level: ${arg}`); p.setVolume(level); return ok(formatVolume(p.peekVolume())); }, }, { name: "speed", usage: "[80|0.8|up|down|off]", says: "how fast the deck runs, in tens of a percent", also: ["varispeed", "tempo"], run: (args) => { const p = player(); const arg = args[0]; // A bare verb reports rather than stepping: `:vol`'s rule, and the reason is the same — the // person who typed the word without an argument is asking what it is, not asking for ten more // percent of it. `:octave`, which can only ever mean one of three speeds, is allowed to act. if (arg === undefined) return ok(speedLine(p.peekSpeed())); const word = speedWord(arg); if (word === "up" || word === "down") return ok(speedLine(p.stepSpeed(word))); if (word !== null) return ok(speedLine(p.setSpeed(word))); // Not a word, so a number: `80`, `0.8`, `1.25`, `65%` — all the same ask, and `clampSpeed` // decides which is which by size rather than by asking the person to remember the convention. const parsed = Number(arg.endsWith("%") ? arg.slice(0, -1) : arg); if (!Number.isFinite(parsed)) return bad(`not a speed: ${arg} · 80, 0.8, up, down, off`); return ok(speedLine(p.setSpeed(parsed))); }, }, { name: "octave", usage: "[up|down|off]", says: "snap the speed to half, normal or double", run: (args) => { const p = player(); const arg = (args[0] ?? "").toLowerCase(); // A bare verb snaps up, which is the one verb in this file that acts on a bare word: it has // three answers and no direction to lose, so reporting would be a line that says nothing about // anything the person could not already see in the bar. if (arg === "" || arg === "up" || arg === "fast" || arg === "faster" || arg === "double") return ok(octaveLine(p.snapOctave("up"))); if (arg === "off" || arg === "normal" || arg === "reset" || arg === "1" || arg === "100") return ok(octaveLine(p.setSpeed(1))); if (arg === "down" || arg === "dn" || arg === "slow" || arg === "slower" || arg === "half") return ok(octaveLine(p.snapOctave("down"))); return bad(`not an octave: ${arg} · up, down, off`); }, }, { name: "key", usage: "[n|up|down|off]", says: "the pitch, without the tempo", also: ["pitch", "transpose"], run: (args) => { const p = player(); const arg = args[0]; // Reports rather than moves, which is `:vol`'s rule and not `:repeat`'s: the ends here are a // press apart, and an accidental bare verb should not move the song a whole octave. if (arg === undefined) return ok(keyLine(p)); const next = keyWord(arg); if (next === null) return bad(`not a key: ${arg} · :key up, down, off, or a number of semitones`); // A word that names a *step* (`up`, `less`) moves from where we stand; a number or a word for // an interval (`-3`, `octave`) is the key itself. Both readings come out of the one table, so // the difference is made here, on the word the person actually typed. const word = arg.toLowerCase(); const step = word === "up" || word === "down" || word === "more" || word === "less"; return ok(keyLine(p, p.setKey(step ? p.peekKey() + next : next))); }, }, { name: "lock", usage: "[on|off]", says: "keep the pitch when the speed moves", also: ["keep-pitch"], run: (args) => { const p = player(); const arg = (args[0] ?? "").toLowerCase(); // A bare verb flips: on a two-state thing the word *is* the decision, and reading the state // back instead would cost a second press to say what the first one meant. if (arg === "") return ok(lockLine(p, p.toggleLock())); if (arg === "on" || arg === "true" || arg === "1") return ok(lockLine(p, p.setLock(true))); if (arg === "off" || arg === "false" || arg === "0") return ok(lockLine(p, p.setLock(false))); return bad(`not on or off: ${arg}`); }, }, { name: "shift", usage: "[crisp|balanced|smooth|off]", says: "how the pitch is moved, and what that costs", also: ["tuning"], run: (args) => { const p = player(); const arg = (args[0] ?? "").toLowerCase(); if (arg === "") { const label = semitoneLabel(shiftSemitones(p.peekKey(), p.peekLocked(), p.peekSpeed())); return ok(`shift ${p.peekShiftQuality()} · ${label || "the record as written"}`); } // `off` earns its place because it is what a listener reaches for when the effect is the // problem: not a different tuning, the pitch put back where the record was written. if (arg === "off" || arg === "reset") { p.putPitchAway(); return ok("the record as written"); } const next = SHIFT_QUALITIES.find((q: ShiftQuality) => q === arg); if (!next) return bad(`not a tuning: ${arg} · ${SHIFT_QUALITIES.join(", ")}`); return ok(`shift ${p.setShiftQuality(next)}`); }, }, { name: "repeat", usage: "[off|album|artist|one]", says: "how far the queue runs", also: ["r", "loop-mode"], run: (args) => { const p = player(); const arg = args[0]; if (arg === undefined) { p.cycleRepeat(); return ok(`repeat ${p.peekRepeat()}`); } const mode = REPEAT_WORDS[arg.toLowerCase()]; if (!mode) { return bad(`not a mode: ${arg} · ${REPEAT_ORDER.join(", ")}`); } p.setRepeat(mode); return ok(`repeat ${mode}`); }, }, { name: "loop", usage: "[a-b|off]", says: "the A–B region", run: (args) => { const p = player(); const arg = args[0]; if (arg === undefined || arg === "off") { // `off` and a bare `loop` are the same ask, and the bare form is the one a // person reaches for when the chip is on screen and they want it gone. p.setLoop(null); return ok("no A–B"); } const parts = arg.split(/[-–—]/); if (parts.length !== 2) return bad("want two times, as a-b"); const start = parseClock(parts[0]!); const end = parseClock(parts[1]!); if (start === null || end === null) return bad(`not a time: ${arg}`); // Refused on the store's terms and reported in the bar's words: no bytes yet, // or a span too short to hear, are both answers the reader can act on and // neither is a mistake in what they typed. if (!p.setLoop({ start, end })) { return bad(`no region in ${arg} — nothing decoded, or too short to hear`); } return ok(`A–B ${formatClock(start)}–${formatClock(end)}`); }, }, { name: "queue", usage: "[n]", says: "what is lined up", also: ["q"], run: (args) => { const p = player(); const arg = args[0]; if (arg === undefined) { const n = p.queueIds().length; if (!n) return ok("the queue is empty"); return ok(`${n} lined up · at ${p.peekCursor() + 1}`); } const at = Number(arg); if (!Number.isInteger(at) || at < 1) return bad(`not a row: ${arg}`); if (at > p.queueIds().length) return bad(`the queue has ${p.queueIds().length}`); p.playAt(at - 1); return ok(p.peekCurrent()?.title ?? `row ${at}`); }, }, { name: "stop", usage: "", says: "stop, and forget the queue", run: () => { player().stop(); return ok("stopped"); }, }, { name: "theme", usage: "[system|light|dark]", says: "light, dark, or follow the machine", also: ["appearance"], run: (args) => { const arg = args[0]; if (arg === undefined) { // No argument steps to the next mode rather than only reporting: cycling is how you // reach every state (and how you get back to `system` after pinning one), and the // line still says where it landed, so the press is never silent. return ok(themeLine(cycleThemeMode())); } const mode = THEME_WORDS[arg.toLowerCase()]; if (!mode) { return bad(`not a mode: ${arg} · ${themeModes().join(", ")}`); } return ok(themeLine(setThemeMode(mode))); }, }, { name: "lyrics", usage: "[on|off]", says: "whether the synced lyric is asked of LRCLIB, and what it said", also: ["lrc"], run: (args) => { const store = lyrics(); const arg = (args[0] ?? "").toLowerCase(); // A bare verb *reports* here, where `lock` and `theme` flip. The difference is what a press is // for: on a two-state setting with no readout anywhere else, cycling is the only way to see the // state at all, and the lyric has a readout (the column itself) and a second fact the reader // wants — what LRCLIB actually said about this track, which a flip would throw away. if (arg === "") return ok(lyricsLine()); if (arg === "on" || arg === "true" || arg === "1") { store.setEnabled(true); return ok("lyrics on \u00b7 the track on the bar is being asked"); } if (arg === "off" || arg === "false" || arg === "0") { store.setEnabled(false); // Said as the promise rather than the state, because it is the promise: nothing is on the // wire afterwards, and the column that was on screen is gone with the press. return ok("lyrics off \u00b7 nothing is asked of lrclib"); } return bad(`not on or off: ${arg}`); }, }, { name: "lyricsaudit", usage: "[n|on|off|clear]", says: "why the lyric was not found \u2014 every question the ladder asked, and what it refused", also: ["lrclibaudit", "ladder"], run: (args) => { const arg = (args[0] ?? "").toLowerCase(); // The switch first, as in `:timeaudit`: writing the ladder down is a few objects per track and // costs nothing worth naming, but a measurement tool that cannot be turned off is a tool that // gets removed rather than left running. if (arg === "on" || arg === "off") { setLadderAuditEnabled(arg === "on"); return ok( arg === "on" ? "writing the ladder down again" : "stopped writing it down \u00b7 the table keeps what it has already seen", ); } if (arg === "clear") { clearLadderAudits(); return ok("forgot every question asked this session"); } const all = ladderAudits(); if (!all.length) { // Not "nothing is playing": an attempt is made by a look-up, not by a press, and what is // missing here is a question rather than a track. return bad("nothing asked of lrclib yet \u00b7 play something, then ask again"); } // A bare verb asks about *this* track, which is the one whose missing lyric prompted the typing; // the newest attempt is usually the prefetch of the next song. let audit = latestLadder(player().peekCurrent()?.id ?? null) ?? all[0]!; if (arg !== "") { const at = Number(arg); if (!Number.isInteger(at) || at < 1) { return bad( `not an attempt: ${args[0]} \u00b7 :lyricsaudit, :lyricsaudit 2, :lyricsaudit off`, ); } if (at > all.length) { return bad(`only ${count(all.length, "attempt")} written down this session`); } audit = all[at - 1]!; } // The line the verb answers with is the verdict in one sentence; the table it raises is the // account of how it was reached, which is the part that can be argued with. showLadderAudit(audit); return ok(describeLadder(audit)); }, }, { name: "scan", usage: "[full]", says: "ask the server to look for new files, and re-harvest when it is done", also: ["rescan"], run: (args) => { const conn = connection(); if (!conn || conn.host === "") return bad("not connected"); const arg = args[0]; if (arg !== undefined && arg !== "quick" && arg !== "full") { return bad(`not a kind of scan: ${arg} · quick, full`); } // A full scan re-processes every file; quick is not just the shorter word, it // is the server's default — changed files only. Navidrome upgrades a quick // scan to a full one by itself when a previous full scan was interrupted, so // the verb does not second-guess that either. return library() .requestScan(conn, { fullScan: arg === "full" }) .then((r) => { if (!r.ok) return bad(`scan refused · ${r.error}`); // The server's own status, not a guess: startScan holds its response open // briefly and answers with whether the scan is running right now — false // means the fast pass finished on the spot, not that nothing happened. return ok(r.scanning ? "scanning · fresh rows shortly" : "scan done · rows on the way"); }); }, }, { name: "harvest", usage: "[n|rebuild]", says: "what the last crawl fetched, what the server counted against it, and whether anything was deleted", also: ["index", "lib"], run: (args) => { const arg = (args[0] ?? "").toLowerCase(); // The one argument that is not about *which* crawl to look at, and the only way back to a clean // index that does not involve the browser's storage settings. It asks for the word in full // because it spends a full crawl of the library, and `:harvest` beside a refusal is the press a // frustrated reader makes first. if (arg === "rebuild" || arg === "cold") { const conn = connection(); if (!conn || conn.host === "") return bad("not connected"); return library() .rebuild(conn) .then(() => { const rows = library().peekReceipt(); return ok( rows ? `index rebuilt from cold · ${describeCrawlReceipt(rows)}` : "index rebuilt from cold", ); }); } const all = library().peekReceipts(); if (!all.length) { // Not "not connected": a crawl can settle refused, abandoned, or never at all, and what the // reader wants to know is that there is no record to read rather than that the app is broken. return bad("no crawl written down yet · the library has not been harvested this session"); } let receipt = all[0]!; if (arg !== "") { const at = Number(arg); if (!Number.isInteger(at) || at < 1) { return bad(`not a crawl: ${args[0]} · :harvest, :harvest 2, :harvest rebuild`); } if (at > all.length) { return bad(`only ${count(all.length, "crawl")} written down this session`); } receipt = all[at - 1]!; } return ok(describeCrawlReceipt(receipt)); }, }, { name: "timeaudit", usage: "[n|on|off|save|json]", says: "where the time went loading a track — a flamegraph of the load", also: ["audit", "timing", "flame"], run: (args) => { const arg = (args[0] ?? "").toLowerCase(); // The switch first, because it is the one argument that is not about *which* load to look // at: recording costs the load path a boolean, and somebody taking a measurement should be // able to say it is not wanted without leaving the prompt. if (arg === "on" || arg === "off") { setAuditEnabled(arg === "on"); return ok( arg === "on" ? "measuring loads again" : "stopped measuring · the graph keeps what it has already seen", ); } const all = audits(); if (!all.length) { // Not "nothing is playing": a track is measured while the bar is idle all the time (a // prefetch, a seek that needed bytes), and the refusal should name what is actually absent. return bad("nothing measured yet · play something, then ask again"); } // The way out. A graph is for the person standing at the screen; the records are for the second // opinion, and for the machine doing the reading, and neither of them is in front of this page. // `save` is the default because it works on the http origins this app actually runs on, where // `navigator.clipboard` does not exist at all; `json` asks for the clipboard and falls back to // the file rather than failing in silence. if (arg === "save" || arg === "export") { const name = saveAuditReport(); return name ? ok(`${name} · ${count(all.length, "load")}, ${count(countSpans(all), "span")}`) : bad('this browser will not hand out a file · hackermusic.timeAudit("json") prints it'); } if (arg === "json" || arg === "copy") { // The only branch that is not instantaneous, and it is asynchronous because the clipboard is: // a promise from here is what puts the ellipsis on the line, which is a fair thing to spend a // press on when the answer is a pasteboard permission away. Every other argument to this verb // paints its line on the spot — including `save`, since a download starts synchronously. const said = `${count(all.length, "load")}, ${count(countSpans(all), "span")}`; return copyAuditReport().then((copied) => { if (copied) return ok(`copied · ${said}`); const name = saveAuditReport(); return name ? ok(`no clipboard here · saved ${name} instead`) : bad('no clipboard and no file · hackermusic.timeAudit("json") prints it'); }); } // A bare verb means *this track* — the one on the bar — and not the newest timeline there is, // which is usually the prefetch of the next one. The subject of "what went into loading it" is // the thing the listener is hearing; the arrows in the graph reach the rest. let audit = latestAudit(player().peekCurrent()?.id) ?? all[0]!; if (arg !== "") { // A number is which recorded load to open, counted from the newest — the 1-based addressing // `:queue` uses for rows. The walk-back is the point of recording them at all: the load // worth looking at is often the one that just got interrupted, and the arrows only work // once the graph is up. const at = Number(arg); if (!Number.isInteger(at) || at < 1) { return bad(`not a load: ${args[0]} · :timeaudit, :timeaudit 2, :timeaudit off`); } if (at > all.length) { return bad(`only ${count(all.length, "load")} recorded this session`); } audit = all[at - 1]!; } showAudit(audit); const ms = auditLength(audit); return ok( `${audit.title || audit.trackId} · ${audit.reason} · ${ ms < 1000 ? `${Math.round(ms)}ms` : `${(ms / 1000).toFixed(2)}s` } across ${count(audit.raw().length, "span")} · esc closes`, ); }, }, { name: "help", usage: "", says: "the verbs, on one line", also: ["?"], run: () => ok(COMMANDS.map((c) => c.name).join(" · ")), }, ]; /** The word a press is asking for, and the words after it. */ export function splitCommand(raw: string): { word: string; args: string[] } { const parts = raw.trim().split(/\s+/).filter(Boolean); return { word: parts[0] ?? "", args: parts.slice(1) }; } /** The verb a word names, aliases included; null when nothing does. */ export function findCommand(word: string): Command | null { const want = word.toLowerCase(); if (!want) return null; for (const c of COMMANDS) { if (c.name === want || c.also?.includes(want)) return c; } return null; } /** * What the line says about a word while it is being typed. * * The readout is the only documentation this app has, and it is worth the space it * takes: the list exists so the verbs are discoverable without a manual nobody * reads, and the one word a reader is typing is where the answer belongs. A command * that takes arguments says so only until they are typed, which is when the * description is wanted and the usage is not. */ export function describe(raw: string): CommandOutcome | null { const { word, args } = splitCommand(raw); if (!word) return null; const cmd = findCommand(word); if (!cmd) return bad(`no verb named ${word} · :help`); const needsArgs = cmd.usage !== "" && !cmd.usage.startsWith("["); return ok(needsArgs && args.length === 0 ? `${cmd.says} · ${cmd.name} ${cmd.usage}` : cmd.says); } /** * Run what the line holds. The outcome goes straight to the readout — the line that * stays there until the next key is the same kind of line `s` leaves behind in the * toolbar, and for the same reason: it is feedback on a press. A verb whose answer is * a round-trip hands back a promise of that line, and the store owns the wait (see * the placeholder in cli/store.ts). */ export function runCommand(raw: string): { outcome: CommandRun; ran: boolean; } { const { word, args } = splitCommand(raw); const cmd = findCommand(word); if (!cmd) { return { outcome: bad(`no verb named ${word} · :help`), ran: false }; } return { outcome: cmd.run(args), ran: true }; }