import { createEffect, createMemo, createSignal, For, type Component, onSettled, Show, type VoidComponent, } from "solid-js"; import { connectionSignal } from "../lib/connection"; import { locate } from "../lib/locate"; import { player } from "../lib/player"; import type { Notfound } from "../lib/player/detect"; import { trackCoverId } from "../lib/library/cover"; import { trackBadges, type TrackBadge } from "../lib/library/rows"; import { count } from "../lib/print"; import { formatClock } from "../lib/player/time"; import { heardBpm, pitchLabel, speedLabel } from "../lib/player/pitch"; import { WaveformRow } from "./WaveformRow"; import { formatVolume, formatVolumeDb } from "../lib/player/volume"; import { WAVEFORM_DEFAULTS } from "../lib/player/peaks"; import { SubsonicClient } from "../lib/subsonic/client"; import { initials } from "./AlbumGrid"; import { nameLines } from "../lib/naming"; import { LyricsColumn } from "./LyricsColumn"; /** Art tile edge in CSS px; the request is 2× so it stays crisp on a 2× screen. */ const ART = 44; /** * The row's entrance is one sweep across the whole track — `WAVE_SWEEP_MS` in `peaks.ts`, which * `sweepOf` breaks into the two numbers the row moves by: how long the reveal edge takes to cross the * row, and how long the row takes to rise out of its own axis. * * First, the sweep belongs to the *track*, not to the measurement. The edge's place is * `measured / buckets`, so the row arrives as one continuous motion from the first second of the file to * the last — and not as the several separate sections the fold happened to report in. Cutting each * report into its own staggered runs made exactly that mistake once: every report started its own * timeline when it arrived, so a listener watched a patch near the middle of the track animate while a * patch near the end had not started, which reads as sections loading rather than a track being drawn. * The edge cannot make that mistake, because there is one of it and it reads the artifact's own * fraction. * * Second, and this is the correction the first version cost: the sweep is a property of **one** * drawing, not something to be delegated to many. The row used to be cut into 48 lanes, each given an * animated path in each of its three layers — 144 elements, each with its own delay, its own duration, * and its own slice of a mirrored envelope to repaint — and 753 kB of path data to carry them. On a * 6×-throttled CPU that is ~1.3 s of main-thread rendering for a 1.4 s entrance, and it is why the row * did not run at 120fps: the browser was repainting a strip of waveform several times a frame, on the * main thread, to animate a wipe. What a listener sees is an edge and a rise. Both are now animated * once, on the two elements that own them, and the row's arrival costs about as much as the hairline * beside it. */ /** * Edge the blown-up cover is capped at, in CSS px — see `.art-stage` in * App.css, which also clamps it to the viewport. Requested at 2× for the same * reason as the tile; it is a second, separate `getCoverArt` because a 88px * cache hit blown up to this size is a smear. */ const ART_ZOOM = 720; const REPEAT_GLYPH = { none: "⇄ off", album: "⇄ album", artist: "⇄ artist", single: "⇄ one", } as const; /** * The transport, pinned to the bottom of the shell. * * It is a `flex: none` sibling of the routed view, not a `position: fixed` * overlay. The app shell already owns the viewport (body is a non-scrolling * flex column — see App.css), so a flex item *is* the fixed thing, and unlike * an overlay it cannot cover the last rows of a list that does not know it is * there. The panes shrink instead of being painted over. * * Two details that are not decoration: * * - the scrubber keeps its own `scrub` signal while dragged. The position * signal is sampled off the audio clock every 250ms; without a local value, * the thumb would be yanked back to the sampled position mid-drag, and the * seek would land wherever the last sample said, not where the user let go. * - position is *displayed* from that clock but *committed* on release: the * audio timeline restarts per seek (a BufferSource cannot be repositioned), * so scrubbing must not fire one of those per pixel. */ /** * The number row, one key per tenth of the track. Two bindings have to recognise * the same ten keys — the transport, which seeks with them, and the cover overlay, * which has to let them past — so the test sits here rather than in whichever * handler was written last. One answers, the other abstains, and a digit that * meant different things to the two would either seek from behind the overlay or * do nothing at all. */ const isDecileKey = (key: string) => /^[0-9]$/.test(key); /** * `+`/`-`, the master gain in half-deciles. Five percent of the slider's travel a * press, which the log curve makes the same *heard* change at the bottom of the * control as at the top (see `volume.ts`): ≈2.25 dB, clear of the ~1 dB it takes to * notice a change at all and well short of the 4.5 dB a whole decile would cost — * twenty presses end to end, four to fix an accident, and autorepeat does the rest. * * Both spellings of each key are taken, shifted and unshifted: on the key that * carries them, `=` *is* an unshifted `+` and `-` an unshifted `_`, and somebody * still holding Shift down from the last press is asking for more or less volume, * not for a key that has stopped working. The numpad's `+`/`-` arrive already * spelled, so they need nothing extra; matching on `key` rather than `code` is the * app's rule, so a layout that puts these glyphs elsewhere follows that layout. * * The direction, not a boolean, because the handler has to know which way to go and * `e.key === "+"` is not the whole answer once `=` is in the bargain. */ const isVolumeKey = (key: string): "up" | "down" | null => { if (key === "+" || key === "=") return "up"; if (key === "-" || key === "_") return "down"; return null; }; /** One press: half a decile of travel, i.e. a twentieth of the slider's length. */ const VOLUME_STEP = 0.05; /** * `[`/`]`, the key's two keys: the pitch down and up one semitone, without the tempo moving. * * They are next to `+`/`-` on the keyboard, and they belong next to them in meaning: both pairs are * a setting of the machine rather than a move within a track, which is why both work with nothing * loaded and both survive the cover being blown up. The brackets are chosen over `,`/`.` or `;`/`'` * because the pair is directional in the layout — `[` leans back toward the previous key, `]` * forward — and a key whose shape points the way it goes is worth more than a key that happens to * be free. * * One semitone, not one octave, because that is what a bracket-sized gesture is worth on a key you * can hold down: twenty-four presses reach the top of the range and the readout keeps up. The whole * octave is `{`/`}`, one press, below them. */ const isPitchKey = (key: string): "up" | "down" | null => { if (key === "[") return "down"; if (key === "]") return "up"; return null; }; /** * `<`/`>`, the deck's speed keys: ten percent of the record's speed a press, half as fast to twice as * fast, and nothing else in the app uses them. * * They sit by the brackets rather than in a row of their own because they belong to the same corner of * the keyboard as the pitch: `<` is "slower", `>` is "faster", and the shapes say which way round they * are — which is more than `{`/`}` can claim, and is why the fine control got the legible pair and the * octave jump kept the shifted brackets it already had. */ const isSpeedKey = (key: string): "up" | "down" | null => { if (key === "<") return "down"; if (key === ">") return "up"; return null; }; /** * `{`/`}`, the octave snap: half, normal, double — the three speeds that have names. * * The shifted forms of the two pitch keys, and that is not an accident of running out of letters: the * pair that moves the *whole* record is the shifted form of the pair that moves its *pitch*, so one * hand on the brackets reaches both of the things a listener might want to change about how a record * sits in the room. `\` and `|`, three keys away, are the lock and the reset. */ const isOctaveKey = (key: string): "up" | "down" | null => { if (key === "{") return "down"; if (key === "}") return "up"; return null; }; /** * `\`, the lock — and `|` for taking the pitch back to where the record was written. * * The lock is the difference between "play it faster" and "play it faster and keep the pitch", and * it is one keystroke because it is one decision, made once per song and then left alone. Both live * beside the brackets for the same reason the brackets do: this is the pitch's corner of the keyboard. */ const isLockKey = (key: string): "lock" | "reset" | null => { if (key === "\\") return "lock"; if (key === "|") return "reset"; return null; }; /** * The loop key: `l`, for the loop modes, and the keyboard's hand on the repeat * button. Same command, same cycle — one `cycleRepeat()` behind both, which is * why there is no second ordering of none → album → artist → single to keep in * step with. * * Matched on `key` case-folded, the way the digits are: on a layout that hides * the letter behind Shift, Shift+L *is* how one types L. Nothing is reserved * against it the way `n` reserves `N`: a reverse cycle would be a fifth mode's worth of * machinery, not a key's — and the transport's second loop gesture, `c`/`C`, is on its own * letters for that reason rather than on the shifted form of this one. */ const isLoopKey = (key: string) => key.toLowerCase() === "l"; /** * The A–B key: `m`, for mark. One key, one gesture, three presses — A at where the * track is now, B at where it is when the key lands next, and clear on the third — * because the alternative is two keys per boundary, or a modifier kept off a letter * to no purpose. * * Matched on `key` exactly, so `M` is not bound and not claimed: `m` has no second gesture * to hand a shifted form, and the third `m` already clears what the first two set. (The * shifted form is not free — that is `C`, below — so "no second gesture for `m`" is a * choice about which key owns it, not a claim that the app has none.) */ const isMarkKey = (key: string) => key === "m"; /** * The cycle key: `c`, for *here* — it arms the detected loop nearest the playhead. * * It used to walk the list, and the shifted form re-anchored; both gestures still exist, but one of * them had to become "the loop where I am", because that is what a listener pressing a key at a * moment in a song is asking for, and the walk is what the shifted key is for now. * * Matched exactly — `m`'s rule, not `l`'s — because the shifted form *is* the other key. */ const isCycleKey = (key: string) => key === "c"; /** See `isCycleKey`: the shifted form is the second gesture, not a way of typing `c`. */ const isWalkKey = (key: string) => key === "C"; /** * `↑`/`↓`, the loop's two growing keys: the next candidate up or down that still holds the playhead. * Not unconditional bindings — the library binds the same arrows to its row cursor, and yields to * this pair only while a detected loop is armed with somewhere to go (`store.loopOwnsArrows()`), so * the question is asked in the handler rather than at the predicate. */ const isResizeKey = (key: string) => key === "ArrowUp" || key === "ArrowDown"; /** * `←`/`→`, the loop's two travelling keys: the next place along the track, and the last one behind. * * Not unconditional the way `c` and `C` are, in two ways. A focused slider owns its own arrows — * that is how a keyboard user nudges a seek past the last second they heard — and a press that has * nowhere to go is not a press worth swallowing: the key is consumed only when the store says it * moved, so a track whose loops all stand where the listener already is leaves the arrows to * whatever the page would have done with them. */ const isPlaceKey = (key: string) => key === "ArrowLeft" || key === "ArrowRight"; /** * A place on the timeline, as the proportion of it CSS then multiplies out — the same * contract `--pb-fill` holds the two hairlines to, so no float reaches the stylesheet * as 40.00000000000001%. */ const proportion = (seconds: number, total: number) => String(Math.min(1, Math.max(0, seconds / total))); /** * What the chip is dressed as: a region the listener is hearing, a region the machine is * holding up for a decision nobody has made yet, or a readout about the search itself. */ type ChipTone = "region" | "detected" | "suggest" | "quiet"; interface Chip { tone: ChipTone; label: string; title: string; aria: string; } /** * The three refusals, in three sentences. They are not three ways of saying "no loop": the * bytes have not arrived, the track is through-composed, and the evidence existed but was * weak are different things for a listener who pressed a key and got silence to do next — and * the third is the only one where asking again can change the answer. * * The labels are written to be told apart at a glance, which is the same rule as the tone * below: each is a different number of words, and none of them is the *searching* label, so * the bar is never in two states that look the same and mean different things. */ const REFUSAL: Record = { "no-bytes": { label: "not yet", says: "there are no bytes to look at yet" }, "no-repeat": { label: "no loop", says: "nothing in this track repeats" }, "not-convincing": { label: "not sure", says: "something repeated, but not convincingly enough to bet a boundary on", }, }; export const PlayerBar: VoidComponent = () => { const store = player(); const song = store.current; const duration = store.duration; /** * The three names the way the bar prints them. * * Tags are written for a database rather than for a bar: the file this memo exists for is tagged * *Partners For Life ft. Pharrell Williams & Jamie Foxx* off *The Neptunes: The Other Side Of The * Planet (Disc 12) [Presented by ESSNSE & Cory Townes]*, and the bar's column is about fifty-two * characters wide. `lib/naming.ts` takes the credits, the disc and the compiler off what is * printed, and caps what is left so an absurd title cannot claim the artist's width from behind its * own ellipsis. * * Printed, and only printed: the tooltip, `locate()`, the lyrics cache and LRCLIB's questions all go * on seeing the tag the server sent, because a name that has been made legible by losing words is a * name that can no longer be trusted to find anything. */ const names = createMemo(() => nameLines(song()), { name: "pb-names" }); const [scrub, setScrub] = createSignal(null); const shown = () => scrub() ?? store.position(); /** * The A that is waiting for its B. * * Kept here in the bar rather than in the store: it is not a region, it is half a * gesture, and a half-region in the transport's state is exactly what the store holds * one signal for (`LoopRegion`) — the second half arriving as a different number is a * region that plays backwards. Keyed by track id, so leaving the track unmakes it * without anyone having to remember to clear it. * * Value and signal, the store's own pattern: the key handler asks "is there an A?" * synchronously, and a read of the signal there is an untracked read of a value the * press itself may have just written. */ let pending: { id: string; at: number } | null = null; const [pendingRead, pendingWrite] = createSignal<{ id: string; at: number } | null>(null, { name: "pb-pending-a", }); const setPending = (next: { id: string; at: number } | null) => { pending = next; pendingWrite(next); }; /** The A to mark B against, for this track only — the sync truth, from the key. */ const pendingFor = () => { const id = store.peekCurrent()?.id; return pending && pending.id === id ? pending.at : null; }; /** ...and the reactive half, for the hairline. */ const pendingShown = createMemo(() => { const p = pendingRead(); return p && p.id === song()?.id ? p.at : null; }); /** * Where the two marks sit, as fractions of `bufferDuration()`. * * Deliberately not the denominator the slider's `max` uses. `duration()` is rounded * and, before the bytes land, is only what the index claims; the boundary is a place * the audio thread has to return to, so it is measured against the bytes. The two * denominators can disagree by up to half a second — a couple of pixels at the * widest — and the alternative is a mark drawn where the boundary is not. * * Both are gated on the same condition as the `m` key: nothing decoded, nothing to * mark. A track with an index length and no bytes has a timeline you can look at and * no audio to put a boundary in. */ const marked = createMemo(() => store.bufferDuration() > 0); const region = createMemo(() => (marked() ? store.loop() : null)); const regionStart = createMemo(() => { const r = region(); return r ? proportion(r.start, store.bufferDuration()) : "0"; }); const regionWidth = createMemo(() => { const r = region(); return r ? proportion(r.end - r.start, store.bufferDuration()) : "0"; }); const caretOn = createMemo(() => marked() && pendingShown() !== null); const caretAt = createMemo(() => { const at = pendingShown(); return at === null ? "0" : proportion(at, store.bufferDuration()); }); /** * Which treatment the region's two edges wear — a look knob, so it costs an attribute and not a * re-fold: the artifact underneath is the same measurement whichever way the boundary is drawn. */ const loopEdge = createMemo(() => store.waveformTuning().loopEdge ?? WAVEFORM_DEFAULTS.loopEdge, { name: "pb-loop-edge", }); /** * What the detector said about this track, and which candidate `c` is standing on. Both * null until somebody asks, which is the point: nothing the machine found is armed by * itself, and the bar's silence is the readout for "no gesture yet". */ const suggestion = createMemo(() => store.loopSuggestion()); const analysis = createMemo(() => store.loopAnalysis()); /** * The track's detected tempo, in BPM — or null while the worker has not answered, for a track * whose beat grid refused, or for a frame-grid answer with no grid under it. * * It rides the loop analysis because they are the same computation: the grid the detector pools * its rows on is also the tempo, so there is no second pass to schedule and nothing to keep in * sync. It shows on the refusals too — "this does not repeat, at 92 BPM" is two facts about the * file, and only one of them is about loops. Rounded to the whole number because the decimal is * precision the DP never had; the tooltip says where it came from. * * Scaled by the deck's octave, and this is the one number in the bar that has to be: the tempo * is a fact about what the listener is hearing, and a track played at ×2 is at 184 however the * bytes were measured. The *pulse* below is deliberately not scaled with it — its interval is * measured in buffer seconds, so it doubles on its own — and the two are scaled in different * currencies on purpose. See `player/pitch.ts`. */ const bpm = createMemo(() => { const a = analysis(); if (!a || a.status === "searching" || !a.bpm) return null; return heardBpm(a.bpm, store.speed()); }); /** * The glyph that says *why* the tempo above is not the tempo on the sleeve: `×0.8`, `×2`, and * nothing at all at the record's own speed. Kept off the number rather than folded into it * because the number is a measurement and the glyph is a setting of the machine — one is read, * the other is pressed, and the bar has been drawing that distinction in different inks * throughout. */ const varispeed = createMemo(() => speedLabel(store.speed())); /** * The key readout: the shift the listener asked for, plus the lock when the lock is what is doing * the work. The whole string comes from `pitchLabel` rather than being assembled here, so the bar * cannot disagree with `:key` about what the state is called. */ const pitch = createMemo(() => pitchLabel(store.key(), store.locked(), store.speed())); /** * The pulse's cycle, once per track: the mean beat and where the grid said the first one * landed. The painting that reads them — and why the paint is the whole mechanism — lives * with the effect below. */ const beat = createMemo(() => { const a = analysis(); if (!a || a.status === "searching" || !a.bpm) return null; // Unscaled, against every instinct in the file: `position()` is in buffer seconds too, so // this interval is already crossed at the deck's rate and the beats arrive twice as often in // the wall clock by themselves. Scaling it here would put the flash half a beat off the // sound at ×2 — the readout and the pulse agree by disagreeing about units. return { period: 60 / a.bpm, at: a.beatAt ?? 0 }; }); /** The grid's transient times, or null when there is no grid to anchor on. */ const beatTimes = createMemo(() => store.loopBeats()); /** * The pulse, which is the tempo wearing the audio clock. * * One clock, on purpose. An earlier revision ran the flash as a CSS animation and kept it * honest by correcting its `currentTime` from the playhead at the 4 Hz tick cadence — two * clocks with a correction seam between them, and the seam is where the flakiness lived: * whenever a correction did not land (the animation not yet created when the first one was * due, the tab throttled, the tick racing the very style that arms the animation), the * pulse free-ran off-beat until the next correction did land. A `setInterval` at the beat * period would have added a *third* clock — one that keeps running through pauses and * background tabs, drifts against the audio by construction, and restarts on every seek: * all of the seam's failure modes, with more drift and less reason. * * This has no seam to fail. Every frame, the playhead's progress through the true interval * it stands in becomes `--pb-phase` — 0 exactly on a transient, 1 on the next — and CSS * turns the number into the flash. Pause freezes the phase because the position does; a * seek moves it because the position does; a tab that slept two minutes wakes in phase * because there was never another phase to wake in. The read is `peekLivePosition()` — the * `AudioContext` clock itself, not the 4 Hz sample of it — and the frame's whole job is a * binary walk of a few hundred floats and one custom-property write, which is why the * codebase's no-per-frame-signals rule stands untouched: nothing *reactive* is written * here; this is a draw. * * A track answered on the frame grid has no times, and its phase runs the mean period from * the grid's first beat — the honest degraded case, and CSS reads the same property either * way. * * Two elements wear the number, and both are painted from the one reading this frame already * made: the readout, which flashes, and the cover, which grows eight pixels and gives them back. * One phase, two wearers — so the tile cannot breathe half a beat away from the number that says * what beat it is. The two wearers are gated differently in the CSS: the number always flashes * while the grid runs, the cover only under the pointer. Both are still painted every frame, so * the gate is a matter of who is looking, not of when the measurement was last taken. */ let beatDot: HTMLSpanElement | undefined; /** The cover, which the frame below paints alongside the readout — and which wears it only under the pointer, so the phase is always live the moment the cursor arrives. See `.pb-art[data-beat]`. */ let artTile: HTMLButtonElement | undefined; createEffect( () => { // Armed by the number existing at all: no analysis, no pulse, no loop, no frame cost. return beat() !== null; }, (armed) => { if (!armed) return; let raf = 0; const paint = () => { raf = requestAnimationFrame(paint); const b = beat(); if (!b) return; // The finger on the bar wins over the audio clock while it is down, exactly as the // fill does: dragging the playhead drags the pulse with it, paused or not. // // Behind it by whatever the shifter is costing, when it is engaged. The playhead is where the // audio thread is; the listener is a window's worth behind that, and a flash painted at the // thread's position arrives early — which is not a cosmetic difference, it is the difference // between a pulse you can lock onto and one you cannot. Nothing else in the bar is moved: // the clock and the seek thumb name a second of the *file*, and a seek that aimed a frame // early would be a seek that did the wrong thing to the audio. const pos = (scrub() ?? store.peekLivePosition()) - store.shiftLatency(); const times = beatTimes(); let from = b.at; let to = b.at + b.period; if (times?.length) { let lo = 0; let hi = times.length; while (lo < hi) { const mid = (lo + hi) >> 1; if (times[mid]! <= pos) lo = mid + 1; else hi = mid; } const k = lo - 1; if (k >= 0) { from = times[k]!; to = times[k + 1] ?? from + b.period; } else { // Before the first transient there is no interval to stand in; count backwards // from it by the grid's first honest interval, so even the intro keeps time. to = times[0]!; from = to - (times.length > 1 ? times[1]! - times[0]! : b.period); } } const interval = to - from; const frac = interval > 0 ? Math.min(1, Math.max(0, (pos - from) / interval)) : 1; // Both wearers in the same frame, off the same float: the number and the cover are one // measurement seen twice, and a second `peekLivePosition()` read between the two writes // would be a second clock — the seam this whole block was rewritten to remove. const phase = String(frac); beatDot?.style.setProperty("--pb-phase", phase); artTile?.style.setProperty("--pb-phase", phase); }; raf = requestAnimationFrame(paint); return () => cancelAnimationFrame(raf); }, { name: "pb-beat-paint" }, ); /** * The chip, which now carries more than the region: nothing, the hand-marked region, an * armed candidate (`A–B 2/4`), a candidate held up because it misses the playhead, and * *searching* while the worker is out there — plus the three refusals. * * Two of those must not be confusable. *There's a loop, just not where you are* and * *nothing in this track repeats* are seconds of music apart in what they mean, and one * chip that said "no loop" for both would make the whole feature look broken on exactly the * tracks (game music with a one-shot head) where it works best. Hence `elsewhere` as a * word, and the tone below: * * - **region** — gold, the colour of the thing drawn on the seek row: this is playing. * - **suggest** — the same gold muted: a region exists and nobody has said yes to it. * - **quiet** — no gold at all, because the search being out there, and a track refusing * to repeat, are not regions and must not wear a region's ink. */ const chip = createMemo(() => { const armed = region(); const s = suggestion(); if (armed && store.loopOrigin() === "detected") { const span = `${formatClock(armed.start)} – ${formatClock(armed.end)}`; const at = s && s.index >= 0 ? `${s.index + 1}/${s.total}` : "·"; return { tone: "detected", label: `A–B ${at}`, title: `A–B ${span} · detected${s && s.r > 0 ? ` (r=${s.r.toFixed(2)})` : ""} · C for the next candidate, ↑ longer, ↓ shorter, m to make it your own`, aria: `Detected A–B loop ${span}${ s && s.total ? `, candidate ${s.index + 1} of ${s.total}` : "" }. Press C for the next candidate, ArrowUp for the longer one, ArrowDown for the shorter.`, }; } if (armed) { const span = `${formatClock(armed.start)} – ${formatClock(armed.end)}`; return { tone: "region", label: "A–B", title: `A–B ${span} · press m to clear`, aria: `Clear A–B loop, from ${formatClock(armed.start)} to ${formatClock(armed.end)}`, }; } const held = s; if (!held) return null; // nobody has asked; there is nothing to report if (held.index < 0) { // Pressed, and the track had nothing to hold up. Which nothing that was, said plainly. const a = analysis(); if (!a || a.status === "searching") { return { tone: "quiet", label: "A–B …", title: "listening for the loop", aria: "Listening for a loop in this track", }; } if (a.status === "found") return null; // it arrived after the press and can be pressed again const refusal = REFUSAL[a.why]; return { tone: "quiet", label: refusal.label, title: refusal.says, aria: refusal.says, }; } const span = `${formatClock(held.start)} – ${formatClock(held.end)}`; if (held.missesAnchor) { return { tone: "suggest", label: "A–B elsewhere", title: `there's a loop at ${span}, just not where you are · c arms the one nearest you`, aria: `There is a loop at ${span}, not under the playhead. Press c to arm it.`, }; } return { tone: "suggest", label: "A–B?", title: `A–B ${span} · c arms the loop nearest where you are`, aria: `Candidate loop at ${span}, not yet armed. Press c to arm it.`, }; }); /** * The three presses, read off whatever state the bar is standing in when the key * arrives — and read through the store's peeks, because a key handler that read the * signals could read the value from before the last write and set B against an A that * has already moved. */ const markAt = () => { if (!store.peekCurrent()?.id) return; // No bytes, no timeline: the press goes back unanswered rather than marking a region // against metadata, which is a region that will not match the file that arrives. // Same condition the marks and the chip are waiting on, so the three cannot // disagree about when there is something to mark. if (store.peekBufferDuration() <= 0) return; const at = store.peekLivePosition(); const start = pendingFor(); if (start !== null) { // B. A refusal — a B before the A, a region too short to hear — leaves A pending // rather than reset: the press did not happen, so the bar stays where it was. if (store.setLoop({ start, end: at })) setPending(null); return; } if (store.peekLoop()) { store.setLoop(null); return; } const id = store.peekCurrent()!.id; setPending({ id, at }); }; /** Whether the cover is blown up. Clicking the tile is the only way in — * the bar is out of the tab order, so there is no key that *should* reach * it — and Esc, Enter, or any click is the way out. */ const [artZoomed, setArtZoomed] = createSignal(false); const closeArt = () => setArtZoomed(false); // The cover goes with the track it is a picture of. Everything else that closes it is the listener's — // Esc, Enter, a click — and this is the queue's way out: the last track ending leaves the overlay // describing nothing, and a full-screen nothing over the library is the one state where the bar has taken // the page back and returns neither music nor list. Tracked on the id rather than the song, so the cover // landing late (which changes the song and not the track) is not mistaken for a departure, and only a // departure closes: advancing to a successor re-paints the same overlay with the next sleeve, which is what // an already-open cover should do. // // It closes without asking whether the cover is open, and that is not laziness — a callback of this split // is not a tracking scope, so a read there answers once and never again and the effect then reads as if it // never fires, while a read in the compute would make the zoom an input of the very effect that writes it. // Writing is free either way: a signal written to the value it already holds does not flush. createEffect( () => song()?.id, (id, previous) => { if (id === undefined && previous !== undefined) closeArt(); }, { name: "pb-art-with-track" }, ); // Same pattern as the cover cells: the URL is derived from the connection, so // it must be a memo (a body read would freeze it at boot) and the client is // cheap enough to rebuild when the connection changes. const client = createMemo(() => { const c = connectionSignal(); return c ? new SubsonicClient(c) : null; }); /** * The cover the bar wears for the track: its own picture when the server says the file * carries one, else its record's. `lib/library/cover.ts` holds the one rule, and it is * the same rule the grid's cells are cut from — which is the point: the tile and the * cell of one album cannot now disagree about whether that album has a sleeve. */ const coverId = createMemo(() => trackCoverId(song()), { name: "pb-cover-id" }); /** * The cover the server refused, by id. * * Asking a record for its sleeve is a question, and a server that never filed a * picture for that folder answers it with a refusal — which is what a track with no * art of its own now goes and asks, because only the server knows. The answer belongs * to the id rather than to the track: the next track of the same record would ask the * same question, and one record's refusal must not blacklist the next one the * listener lands on. * * The refusal is load-bearing rather than defensive. It is the only way the bar learns * that a record the index said nothing about has nothing on it, and with no id * standing here the tile keeps the initials it was already showing instead of * pretending to be a window onto an artwork. */ const [refused, setRefused] = createSignal("", { name: "pb-cover-refused" }); const artUrl = createMemo( () => { const c = client(); const id = coverId(); if (!c || !id || id === refused()) return ""; return c.coverArtUrl(id, ART * 2); }, { name: "pb-art-url" }, ); /** * The blown-up cover, asked for at its own size rather than reused from the * tile: the bar's is 88 raw pixels, and stretching that across the viewport is * a blur with a border on it. `getCoverArt` is cheap and the server caches per * size, so the two requests do not cost each other. */ const artZoomUrl = createMemo( () => { const c = client(); const id = coverId(); if (!c || !id || id === refused()) return ""; return c.coverArtUrl(id, ART_ZOOM * 2); }, { name: "pb-art-zoom-url" }, ); const artCaption = () => { const s = song(); if (!s) return ""; return [s.artist, s.album ?? s.title].filter(Boolean).join(" — "); }; /** * The chips over the cover: what this track is made of. Two of them — codec and * bitrate — because that is the pair that answers "what am I hearing, and is it * the real file". Sample rate and bit depth stay in the list rows, which have * room for four; up here a fourth chip would be a wider box than the cover it * sits over. They come from the same `trackBadges` the rows use, so `flac` here * means `flac` there. * * The container is the one thing they cannot get from the index. The index * describes the file on the server — probing where the server reports a probe * (`song.codec`, ffprobe's name for the stream inside the container) and its * extension where it does not — and the player knows what the browser was * actually handed, so when the decoder refused the original those are not the * same answer. Saying `flac` while an mp3 transcode is playing would be the * bar lying about the one thing a local player exists to tell you. */ const quality = createMemo(() => { const s = song(); if (!s) return []; const original = trackBadges(s).filter((b) => b.kind === "codec" || b.kind === "bitrate"); const served = store.servedFormat(); if (!served || served === "raw") return original; return [ { label: served, kind: "codec", codec: served, transcoded: true }, ...original.filter((b) => b.kind !== "codec"), ]; }); const qualityNote = createMemo(() => { const s = song(); const served = store.servedFormat(); if (!s || !served || served === "raw") return undefined; // Read off the same trackBadges call the chip would have made, so the // sentence about what the browser refused cannot name a different format // from the chip it explains. const filed = trackBadges(s).find((b) => b.kind === "codec")?.label; return `the browser could not decode ${filed ?? "the original"}, so the server served ${served} instead`; }); const volumeLabel = createMemo(() => formatVolume(store.volume())); /** * Whether the art should wear the paused mark. `paused` and nothing else: idle has no * track to mark, `loading` already says what it is in the harvest's own accent along the * bar's top border, and `error` is told by the refusal it belongs to. Marking those too * would spend the one glyph that means *stopped on purpose* on the states that merely * have not started. */ const paused = createMemo(() => store.state() === "paused", { name: "art-paused" }); /** * Space is the transport, and so is the number row: `0` restarts and `9` lands * nine tenths in, one key per decile of the track. Bound on the window — the bar * owns playback whether or not the library has focus — and bound *here*, next to * the slider they are the keyboard for, so the three cannot drift apart. `l`, the * loop modes, is bound here for the same reason: the button it drives lives in * this bar, and a key bound elsewhere would be a second owner of the readout. * * Four cases deliberately do nothing: * * - **typing.** "gr t" is a real filter and "dmo" is a real band, so the query * box keeps its spaces and its digits. This is the one that would silently * break searches. * - **a focused button.** Space already clicks the focused button; toggling from * here as well would pause and unpause in the same keystroke, which reads as a * key that does nothing. Digits have no such collision — a button does nothing * with a 7 — so they still reach the transport. * - **modifiers.** Either key with a modifier on is somebody else's shortcut. * - **nothing to stop, nothing to move.** With no track and nothing loaded the * browser still gets space — that is what scrolls the list — and a decile has * no timeline to belong to. `+`/`-` are the one exception, and a deliberate one: * the master gain is a fact about the room rather than about a track, so they * answer before anything is loaded — which is the commonest moment for wanting * them, since arriving to a crawl of a library at full volume is how ears get * rang. The bar's own readout arrives with the track; the level they set does not. * * `l` is the fourth key of the bar, and the same four guards cover it, with one * of them doing a little more work here than it looks like it does: the loop * mode is a fact about the queue, so the guard that refuses the key when nothing * is loaded is also what keeps it from silently changing a mode whose only * readout — the repeat button — is not on screen. An answer the user cannot see * is a key that appears not to work; with the bar up, the button answers. * * `m` is the fifth, bound beside the other four for the same reason they are: the * marks and the chip it drives are drawn in this bar, and a second owner of that * readout would be a second idea of what the region is. It inherits the four * abstentions rather than re-implementing them, and adds a stricter guard of its * own — the store refuses to mark anything while no bytes are decoded, so a track * that only has an index length has a timeline to look at and nothing to mark. * * `+`/`-` are the sixth and seventh — the same key as the slider they move, spelled two * ways because a fader has no keyboard of its own. They are bound here for the reason the * other six are: the percentage they change is the readout at the end of this row, and a * key that moved the gain from somewhere else would be a second owner of a number the bar * is already showing (see `isVolumeKey` for the step and the two spellings). */ onSettled(() => { const onKey = (e: KeyboardEvent) => { // Digits are matched on `key`, the way every unmodified binding in this app // is: on a layout that hides the digits behind Shift, Shift+7 *is* how one // types 7, and the "%" that US Shift+5 produces is not a request to seek. const digit = isDecileKey(e.key); const volume = isVolumeKey(e.key); const octave = isOctaveKey(e.key); const speed = isSpeedKey(e.key); const pitch = isPitchKey(e.key); const keyLock = isLockKey(e.key); const loop = isLoopKey(e.key); // `m` is the exception the comment on it makes: matched exactly, because the // shifted form is not a second gesture and would only cost somebody the letter. const mark = isMarkKey(e.key); // `c` and `C`, matched exactly for the reason on `isCycleKey`: the shifted form is the // other gesture, not a way of typing this one, so the two travel together. const cycle = isCycleKey(e.key); const walk = isWalkKey(e.key); // The loop's arrows, considered here rather than at the gate below: whether `↑` is the loop's // key or the library's cursor is a fact about the region that happens to be armed, and the // store is the only thing on the page that knows it. const resize = isResizeKey(e.key); const places = isPlaceKey(e.key); if ( !digit && !loop && !mark && !cycle && !walk && !resize && !places && !volume && !octave && !speed && !pitch && !keyLock && e.key !== " " ) return; if (e.metaKey || e.ctrlKey || e.altKey) return; const t = e.target as (HTMLElement & { isContentEditable?: boolean; type?: string }) | null; if (!t) return; if (t.tagName === "TEXTAREA" || t.isContentEditable) return; // A range input has no use for space (the arrows own it), so a focused // slider still answers to the transport; the search field does not. if (t.tagName === "INPUT" && t.type !== "range") return; if ( t.tagName === "BUTTON" && !digit && !loop && !mark && !cycle && !walk && !resize && !places && !volume && !octave && !speed && !pitch && !keyLock ) return; // space already pressed it if (volume) { // Before the "nothing loaded" guard below, which is the one guard this key does // not respect: the gain belongs to the page, not to a track. Rounded to the // slider's own 1% step so four presses from 50% is 70% and not // 70.000000000000003% — in the readout, and in what gets stored. The clamp is // the store's (`setVolume`), which is also the rule the thumb runs into at the // ends of its travel, so a held `-` walks to silence and stops there rather // than inventing a negative the graph has no room for. e.preventDefault(); // nothing in the page wants a bare +/-; keep them ours store.setVolume( Math.round((store.peekVolume() + (volume === "up" ? VOLUME_STEP : -VOLUME_STEP)) * 100) / 100, ); return; } if (pitch || keyLock) { // The pitch corner of the keyboard, and the same exemption from the "nothing loaded" guard // the level and the speed take: a key, a lock and a reset are settings of the deck, live // whether or not there is a record on it. None of the three re-arms anything — the shifter // sits on the master and takes the change at its next frame — so a press can land in the // middle of a phrase without touching the seam, the loop or the beat grid under it. e.preventDefault(); // nothing in the page wants a bare bracket or backslash; keep them ours if (pitch) store.stepKey(pitch === "up" ? 1 : -1); else if (keyLock === "lock") store.toggleLock(); else { // One key for the whole pitch state, because the state is one decision: the listener who // has had enough of the experiment wants the record back, not the record back three times. // One call, which also puts the shifter out of next session's graph — see putPitchAway. store.putPitchAway(); } return; } if (speed || octave) { // The deck's speed, in whatever unit the key speaks: ten percent or one octave. Both take the // same exemption from the "nothing loaded" guard below that `+`/`-` take for the level — the // speed belongs to the deck, so the setting is live whether or not there is a record on it: // press `>` at the idle bar, press `Enter`, and the track arrives at ×1.1. Nothing is reported // on the line: the number above the title moves, and the glyph beside it appears, which is the // readout these keys have. e.preventDefault(); // nothing in the page wants a bare bracket or an unshifted comma; keep them if (speed) store.stepSpeed(speed); else store.snapOctave(octave!); return; } if (store.peekState() === "idle" && !store.peekCurrent()) return; if (cycle || walk) { // The candidate machine, and all of it in the store. Whether the press did anything // is the chip's business rather than this handler's — a press with no candidates is // not a failed key, it is a readout — so nothing is reported back here, and nothing // is swallowed: a bare `c` has no default on a page. e.preventDefault(); if (cycle) store.armNearestLoop(); else store.cycleLoop(); return; } if (resize) { // A focused slider owns its own arrows — that is how a keyboard user nudges a seek past the // last second they heard — so the loop's claim on them starts where the slider's ends. if (t.tagName === "INPUT") return; // ...and the claim is conditional in the other direction too: no detected loop with somewhere // to grow or shrink means the arrows are the library's row cursor, and have been all along. if (store.peekLoopOrigin() !== "detected" || !store.loopOwnsArrows()) return; e.preventDefault(); // over the list's own arrow-to-scroll and the cursor's own move store.resizeLoop(e.key === "ArrowUp"); return; } if (places) { // A focused slider first, same as the growing keys: its arrows are how you nudge a seek, and // the loop does not take a key that is being used as a thumb. if (t.tagName === "INPUT") return; // ...and consumed only on success. `→` with every loop the track has already standing where // the listener is did not do anything, and a key that silently eats itself there is how an // app gets a reputation for keys that work on Tuesdays. if (!store.stepPlace(e.key === "ArrowRight")) return; e.preventDefault(); return; } if (mark) { // A–B, three presses, on the store's own terms: the refusal (nothing decoded, // a region too short to hear) is the store's to make and this to honour by // doing nothing at all. `l` guards the mode by whether a track is on the bar; // this one guards the boundary by whether there are bytes behind it, which is // the stricter question and the one the index cannot answer. e.preventDefault(); // over anything the page would do with a bare m markAt(); return; } if (loop) { e.preventDefault(); // over anything the page would do with a bare l store.cycleRepeat(); return; } if (digit) { const total = store.peekDuration(); // Nothing to take a fraction of — no length in the index and no decoded // bytes yet — so the key goes back unanswered rather than "seeking" to a // zero nobody asked for: a silent restart reads as a broken track. if (total <= 0) return; // The fraction lands where the slider would put it, clamp and all: the // store will not start a source inside the last few seconds of a track, so // `9` on a short one arrives at the same place dragging the thumb to the // far end does. One rule for both hands is the point. e.preventDefault(); store.seek((total * Number(e.key)) / 10); return; } e.preventDefault(); // over the list's own space-to-scroll store.toggle(); }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); }); /** * The blown-up cover takes the keyboard while it is up. * * Bound in the **capture** phase on purpose: the library view binds its own * keys (`g`, `/`, `j`/`k`, Escape) on the window in the bubble phase, and * `stopImmediatePropagation` from a capture listener on the same target runs * first — so a key that belongs to the overlay cannot also collapse the grid, * arm a search box the user cannot see, or move a cursor behind a wall of black. * * Five exceptions: * * - **space** is left to the transport, bound below. Pausing to look at a * cover is the one key worth keeping live behind the overlay. It is still * `preventDefault`ed here: the focused overlay scrolls on space, and a * caption drifting off-screen proves nothing. * - **the number row** is left to the transport for the same reason: the cover * is up because the music is still going, and skipping to where you are is the * other thing worth doing without dismissing it. Nothing is prevented on its * way past, because a digit has no default action in a focused overlay. * - **`l`** goes with them. Deciding how far the queue runs is the same kind of * act as deciding when to stop looking at the cover — the button it drives is * on screen the whole time, behind the art, and a dialog that swallows the one * key the bar still has is a dialog you can only look at. * - **`m`** goes with them too, and further: A–B is set while the track is playing, * so the overlay is up for the very reason the key is wanted, and the marks it * draws are on the bar underneath. * - **`c`/`C`** go with `m`, on the same argument: the candidates are read out on the bar * under the art, and the reason the cover is up is that the music is playing. * - **`+`/`-`** go with them: the level of the music is decided while the music is * playing, and the percentage they move is on the bar the art is covering. * - **`[`/`]`** go with `+`/`-` for the same reason and with the same readout: the octave is a * setting of the deck, the two keys are its pair on the same row, and the glyph they move is * on the bar underneath the art. * - **Tab** is left to the browser, because swallowing it would strand the * keyboard — a dialog you cannot leave is worse than one whose keys leak. The * overlay carries no controls of its own to visit, and nothing behind it binds * Tab, so the key has nowhere of ours to go. * - **modifiers** (Cmd/Ctrl/Alt/Meta + anything) are the browser's, not ours. * * Enter closes rather than falling through — there is no default control to * press, and a key that does nothing reads as a broken overlay. */ onSettled(() => { const onKey = (e: KeyboardEvent) => { if (!artZoomed()) return; if (e.key === " " && !e.metaKey && !e.ctrlKey && !e.altKey) { e.preventDefault(); // the overlay itself would otherwise scroll return; // ...but the transport still owns it } // ...and the deciles, same handoff: the overlay does not own the timeline. if (isDecileKey(e.key) && !e.metaKey && !e.ctrlKey && !e.altKey) return; // ...nor the loop, which the repeat button under the art is showing. if (isLoopKey(e.key) && !e.metaKey && !e.ctrlKey && !e.altKey) return; // ...nor the A–B marks, for the same reason as the two above and with a better // claim to it: a loop is decided *while the music is playing*, and the commonest // reason to have the cover up is that the music is playing. A cover that ate the // one key that marks a region would make the feature unusable at the exact moment // it is wanted — and the marks themselves are under the art, on the bar. if (isMarkKey(e.key) && !e.metaKey && !e.ctrlKey && !e.altKey) return; // ...nor the candidates, on the same argument as the mark above. if ((isCycleKey(e.key) || isWalkKey(e.key)) && !e.metaKey && !e.ctrlKey && !e.altKey) return; // ...nor the volume, and it has the plainest claim of the four: the cover is up while // something is playing, and the readout these two keys move is the percentage on the bar // underneath — a dialog that ate them would leave the listener reaching for the slider // they cannot see, which is the one control this bar does not draw over the art. if (isVolumeKey(e.key) && !e.metaKey && !e.ctrlKey && !e.altKey) return; // ...nor the pitch corner of the keyboard — the octave, the semitones, the lock and the reset, // all four: the speed and the key of the deck are decided while the deck is running, and the // marks these keys move are the glyphs above the title, which the cover is drawn over. if ( (isOctaveKey(e.key) || isSpeedKey(e.key) || isPitchKey(e.key) || isLockKey(e.key)) && !e.metaKey && !e.ctrlKey && !e.altKey ) return; if (e.key === "Tab" || e.metaKey || e.ctrlKey || e.altKey) return; e.preventDefault(); e.stopImmediatePropagation(); if (e.key === "Escape" || e.key === "Enter") closeArt(); }; window.addEventListener("keydown", onKey, true); return () => window.removeEventListener("keydown", onKey, true); }); const commit = (seconds: number) => { setScrub(null); store.seek(seconds); }; /** * The wait for this track's bytes, said in the harvest's voice: the same accent * crawl, riding the hairline this bar already has (its top border, as the * toolbar's crawl rides the toolbar's bottom one). * * `loading` and nothing else. The gapless prefetch is always in flight a track * ahead of the clock, so a bar that lit for *any* in-flight stream would crawl * forever and say nothing; this says the thing the user is actually waiting for * — the track under the thumb has no sound in it yet. * * And the cache gets a vote: `loading` alone cannot tell the server's seconds from * the decoder's third of one, and the crawl — the harvest's own accent, animated — * is a promise about the wire. A track whose bytes the caches already hold is * waiting on the browser's own machine; its row wears the full cached wash, its * cover is already up, and the few hundred milliseconds until the samples are ready * need a face that is not a download. So the crawl belongs to the network phase * alone, said by the store's `loadPhase` — the same reading the trace prints as * "bytes in memory, decoding". */ const loading = () => store.state() === "loading"; const fetching = () => loading() && store.loadPhase() === "network"; /** * How far along each hairline its accent fill reaches. The caret marks the * value and the filled line says how much of it is behind you — two readings, * and only one of them is something you can drag. * * The scrub follows the finger while a drag is in progress rather than the * 250ms sampler, so the line answers to the hand; the volume's fill is its * slider position, which is the level the log curve maps, not the gain. */ const seekFill = createMemo(() => { const d = duration(); return d > 0 ? String(Math.min(1, Math.max(0, shown() / d))) : "0"; }); // `--pb-fill` is one value with three readers: the volume's own track, and — on the scrub — the two // layers of the overview strip below plus its caret. All of them declarative, because a `style` object // binds per key (the compiler emits its own `effect(compute, apply)` per property, custom properties // included via `setStyleProperty`) and applies it at creation, so the bar arrives already showing the // position rather than painting it a frame late. An earlier revision hand-rolled that with two // `createEffect(compute, apply)` pairs and a ref callback for the first frame, on the belief that a style // object reads once at build time; the compiled output says otherwise, and the test that drags both // sliders and reads the property back is what keeps either version honest. // // The strip reads the *same string* from the same memo rather than deriving a proportion of its own, and // that is the point rather than a convenience: the strip is where the playhead is drawn now, and a second // computation of "how far along is this" would be a second answer to that question — the two would agree // most of the time, which is worse than disagreeing. /** * The bar takes clicks and nothing else. It is out of the tab order (`tabindex` * on all four controls) and it refuses to *keep* focus either, by two means * because the controls differ: * * - the buttons refuse `mousedown`, which is the event whose default action is * "focus me"; the click still fires, only the focus does not arrive. * - the sliders cannot refuse mousedown — that is also what starts a drag — so * they hand focus straight back with a blur. Dragging is unaffected: the * pointer keeps its capture through a blur, and the value arrives on input. * * The keyboard is the app's own (space, r, /), and a footer that holds focus * after a click has taken it away from the list until the next click. */ const noFocus = (e: MouseEvent) => e.preventDefault(); const loseFocus = (e: { currentTarget: HTMLInputElement }) => e.currentTarget.blur(); // The footer is on screen whether or not there is a track, and only the parts of it that describe a // track are gated. That is a change of shape rather than of styling, and the reason is the row: the // waveform's grow is a *transition*, and a transition needs a before. When the whole footer lived inside // `Show when={song()}`, the bar with nothing loaded was an empty stretch of panel, and the moment a track // was chosen the footer was created fresh — so the row's first frame was already the track's shape and // there was no arrival to see, only an appearance. Now the row is mounted from the start, holding // `WaveformRow`'s waiting silhouette, and the same element grows twice: once into the placeholder and // again into the track. // // It is also the bar's most common state — the app open, nothing chosen — and the row is the one part of // the bar with something true to say in it. return ( <>
<> {/* One rule with `.harvest-track`/`.harvest-bar--indeterminate`, not a copy of it: two rules that have to agree are one definition. */}
{/* Two rows, because the scrub earned the whole width. Top: the cover with its caption, the meta, the transport. Bottom: the progress line, edge to edge, with a clock at each end of what it measures — elapsed at the start of the track, duration at its end. The slash between the two was the syntax of a pair crowded into one place; apart, each labels the end it sits at, and they are still read together because the line joins them. */} {/* A button, not a div: it is clicked, it has an accessible name, and it is the only way in — the bar keeps itself out of the tab order (see `noFocus`), so the keyboard reaches the transport, not this. */} {/* Keyed by content, not identity: the badge list is rebuilt from the song on every recompute, so the default identity key threw away two spans to write the same two labels — UNSTABLE_LIST_IDENTITY named it in as many words. "codec:flac" *is* the chip; there is no other identity for it to have. */} `${b.kind}:${b.label}`}> {(b) => ( {b().label} )} {/* The tempo, in the faintest ink the bar owns and the smallest type it owns: a fact about the file, kept literally above the fact about the song — one line up, out of the title's way, and too quiet to read unless you look. It rides above the title button rather than inside it because the button's ellipsis would clip it on exactly the long titles that already hide everything else. */} {bpm()} {/* The deck's speed, after the tempo it explains, and in the same faint ink: the number is the measurement and this is the reason it does not match the sleeve. Absent at ×1, so the line is the one the app has always drawn. */} {varispeed()} {/* The key the record is being heard in, after the speed that explains it, in the same faint ink — and only when there is one: at 0 and unlocked this is the line the app has always drawn. No fader beside it: 49 positions are a thing you hold a key to walk, not a thing you drag, and the row is too narrow to be honest about a range that wide. */} {pitch()} {/* The three names are each a question the list can answer: clicking one asks the list to put that track, record or artist under the cursor (`lib/locate.ts`). Buttons, like the art tile above them — clicked, named, and kept out of the tab order by `noFocus`, because the keyboard's way into the list is the list's own keys and a tab stop in the bar would be a third way to do what `j` does. Disabled where there is nothing to ask for: an untagged track has no artist id to name to the list, and an affordance that cannot work is a lie about the interface. */} {/* The fourth thing the record can say about itself, and the only one that moves while you listen: the synced lyric, in a window against the transport and read to its right edge. It is here rather than in a pane of its own because a lyric is read against the transport — the line you are on is the line you are hearing, and the seek is one click away — and it is right-aligned so the lines end on the controls they are beside instead of ragged against the middle of the bar. Nothing is drawn when LRCLIB has nothing: the absence of the column is the readout, and the transport's auto margin comes back with it. */} {/* Inert on purpose: the queue panel is the next piece of work, and a control that is visible-but-honest beats one that is missing — the layout it will occupy is already the layout of the bar. */} {(c) => ( <> {/* The region said out loud, beside the button that says how far the queue runs — the two are the pair of answers about what repeats, and a mode nobody can see is an answer nobody can see. Click to clear, which is the same command the third `m` issues; the two seconds are in the tooltip because the chip has room for the fact, not the numbers. It says more than it used to, and the tone is what keeps the additions honest: gold for a region that is playing, gold muted for one the detector is holding up for a decision nobody has made, no gold at all for the readouts that are about the search rather than about a region. "There's a loop, just not where you are" and "nothing in this track repeats" are the pair that must never look alike, and they do not — one is the machine's blue, dimmed, with a place in it, the other is grey and says no. */} )} store.setVolume(Number(e.currentTarget.value))} /> {volumeLabel()} {formatClock(shown())} {/* The slider is about the track, not about the audio: a session restored from the previous visit has a timeline — a title, a length, a second the thumb is sitting at — with nothing fetched or heard yet. Disabling on "not playing" would show a position the user cannot move, and moving it is the reason to have put it there: dragging here sets where play will start. */} {/* The scrub and its marks share one box, so the marks are positioned against the timeline they belong to rather than against the row that also carries two clocks. The layer is out of the pointer's way: the slider underneath stays the only thing on this row you can drag. The treatment's name rides here as well as on the region, because the bar treatment needs geometry and geometry belongs to the row: `--pb-loop-lane` reserves the strip beneath the waveform that the rail is drawn in, and it is the wrap's height that the wave is sized against. Named on the row rather than inferred with `:has()` so the row's own layout does not depend on whether a loop happens to be set. */} {/* The row is the waveform now: a thousand bars mirrored about the axis the hairline used to be, with the part already heard in the accent and the caret down the middle of it. It is the first child so the marks and the slider stack over it, and it is inert — the slider underneath is still what a drag reaches, and it hands this the same `--pb-fill` it carries rather than letting the drawing compute its own answer to "how far along". */} setScrub(Number(e.currentTarget.value))} onChange={(e) => commit(Number(e.currentTarget.value))} /> {formatClock(duration())}
{/* The cover, blown up. Outside the footer rather than inside it: it has no business unmounting the transport row, which now outlives every track. It is gated on the zoom alone — the track's side of that gate is `pb-art-with-track`, which closes the zoom when the current track goes away, so a track ending with nothing queued closes this the same way it removes the title. */} ); }; interface ArtZoomProps { /** Full-size cover URL for the current track, or "" when it has none. */ url: string; /** What the cover is of — the album, or the track when there is no album. */ name: string; /** Who and what, under the cover. */ caption: string; /** * Whether the track this cover belongs to is paused. Passed rather than read: the overlay * is about the current track but knows nothing about the player, and the bar is the thing * that does. It matters because space still pauses behind this dialog — and when it does, * the bar that carries the mark is dimmed under the backdrop, so the cover is the only * thing on screen big enough to carry the news. */ paused: boolean; onClose: () => void; } /** * The lightbox itself — its own component so that opening it is one mount: the * focus, the load state and the image all begin together, and closing it throws * all four away rather than leaving a previous cover's state behind. * * Its load/failure state is keyed by URL rather than a `failed` boolean: the * overlay follows the current track (the queue can run on while it is up, and * space still pauses behind it), and a boolean set by a cover that 404s would * hide an unrelated cover after a track change — the kind of stale state that * only shows up in passing. * * Any click closes it, backdrop and cover alike: there is nothing in here to * click *on*, so a click means "done" — and that is the whole of the overlay's * chrome, because it is a picture rather than a tool. The keyboard has Esc and * Enter (the latter because a dialog whose default control does nothing reads as * broken), the pointer has anywhere at all, and neither is spelled out on top of * the sleeve the user came to look at. */ const ArtZoom: Component = (props) => { let backdropEl: HTMLDivElement | undefined; const [failedFor, setFailedFor] = createSignal(""); const [loadedFor, setLoadedFor] = createSignal(""); const img = () => (props.url === failedFor() ? "" : props.url); // Focus in the settle phase, not from a `ref`: refs run while the node is // still detached, and focus on a detached element is simply refused. The // backdrop is what takes it — the keyboard belongs to the overlay as a whole, // and a focused would be a tab stop nobody asked for. onSettled(() => { backdropEl?.focus(); }); return (
{ backdropEl = el; }} class="art-modal" role="dialog" aria-modal="true" aria-label={`Artwork for ${props.caption || "the current track"}`} tabindex={-1} onMouseDown={(e) => e.preventDefault()} onClick={() => props.onClose()} > {/* Under the image, as in the grid and the bar: this is a second, larger fetch, and a black box until it lands reads as a broken image. */} {`Album setLoadedFor(props.url)} onError={() => setFailedFor(props.url)} /> {/* The same mark as the tile's, at the size of the thing it is drawn on: this cover follows the queue while it is up, so a track ending or a space pressed behind it has to be said here rather than on the bar underneath the backdrop. */} {props.caption}
); }; export default PlayerBar;