/**
* The wiring between a cover image and the two custom properties App.css paints.
*
* Split from `accent.ts` for the reason that module gives: choosing a colour is
* arithmetic on numbers and is tested with numbers, while this half touches a network,
* a decoder, localStorage and a DOM node. Nothing here decides *which* colour — it
* asks for pixels, hands them over, and paints what comes back.
*
* Three behaviours worth naming, because each is a way this kind of feature usually
* goes wrong:
*
* - **Nothing ever resets the accent to the house green on its own.** A cover that
* 404s, a server that refuses the fetch, a palette with nothing in it — each leaves
* the last accent standing, because the last accent came from the record you are
* listening to and is still the true answer. Only a palette that says something
* newer gets a vote, and the way back to the app's own colour is a sign-out, not an
* album that failed to load.
* - **The colour survives a reload.** The tokens are stored, so the first paint of a
* resumed session is already the record's colour rather than the green's, arriving a
* few hundred milliseconds before the queue is even restored. What is persisted is
* the *answer* and not the cover's pixels or their source id: a colour is not a claim
* about the server, and the alternative is a cache of swatches nobody can read.
* - **One request per cover, and it can be cancelled.** The effect keys on the cover
* id, a cover already read is never asked again, and an in-flight request is aborted
* by the cleanup rather than left to paint an accent for a track that has moved on.
*/
import { createEffect, onCleanup } from "solid-js";
import * as v from "valibot";
import { createPersistentSignal } from "../persist";
import { SubsonicClient } from "../subsonic/client";
import type { ConnectionSettings } from "../subsonic/types";
import type { LibrarySong } from "../harvest/types";
import { trackCoverId } from "../library/cover";
import { mark, noteAudit, span } from "../loadaudit";
import { effectiveTheme, resolveTheme, type Theme } from "./mode";
import {
DEFAULT_ACCENTS,
deriveAccent,
explainPalette,
explainTone,
pickAccent,
tonalAccent,
type AccentTokens,
type Swatch,
} from "./accent";
export { DEFAULT_ACCENT, DEFAULT_ACCENTS, type AccentTokens, type Swatch } from "./accent";
export {
applyTheme,
cycleThemeMode,
effectiveTheme,
peekThemeMode,
resolveTheme,
setThemeMode,
startThemeSync,
themeMode,
themeModes,
type Theme,
type ThemeMode,
} from "./mode";
const STORAGE_KEY = "hackermusic.accent.v1";
/**
* The cover size the palette is read from.
*
* Big enough that a real design element stays a real share of the frame. This is the one
* number that decides whether a thin, saturated mark — a title wordmark, a logo, a single
* instrument in a dark photo — survives the walk to the picker: `accent.ts` refuses any
* colour under `MIN_POPULATION` (1%) as a JPEG "speck", and area-resizing roughly preserves
* a colour's share, but a server that point-samples or chroma-subsamples a *small* cover
* blends a 1px red stroke into the black around it and drops it under the floor. `Whole
* Lotta Red` is the case that found this: its ~3% red wordmark came back from a 96px
* thumbnail at `c=0.152` and under 1%, refused as a speck, so the bar wore an 8% brown
* instead of the red the sleeve is named for. 200² is forty thousand pixels, `quality: 2`
* samples about twenty thousand, and the same wordmark holds ~3% — comfortably over the
* floor. It is still sub-millisecond and tens of kilobytes, one cache entry.
*
* It is its own request rather than the bar's tile or the zoom's: `getCoverArt` is
* cached by size on the server and by URL in the browser, so a size of one's own costs
* one small entry and buys an extraction that never races the two `
` elements.
*/
export const ART_SIZE = 200;
/**
* How the palette is asked for, as its own seam.
*
* The default implementation decodes bytes rather than reusing the `
` the bar
* already loaded on purpose: drawing a cross-origin `
` into a canvas taints it and
* `getImageData` then throws, whereas `createImageBitmap(blob)` from a response has no
* origin to taint anything. It also means the extraction is not racing whichever of the
* bar's two `
` elements happens to have finished.
*/
export type PaletteLoader = (url: string, signal: AbortSignal) => Promise;
/**
* The record's colour as localStorage keeps it, before the app has made it ink.
*
* What survives a reload is the *hue and chroma the cover lent* (and the wall it was
* chosen against, for the trace line), not the pair of hexes the derivation painted from
* them. That is a deliberate change from storing the answer: the answer is now a function
* of the ground as well as the record — the same crimson is a bright ink on the dark panel
* and a dark one on the light — so caching the answer would cache it for whichever theme
* happened to be up when the cover loaded, and repaint the wrong brightness after a reload
* into the other one. Caching the source instead means the first paint of a resumed
* session is already this record's colour *at the current ground's lightness*, and a theme
* flip between sessions costs nothing but a re-derivation of the same colour. Still the
* answer and not the pixels: three numbers and a share, not a swatch cache.
*/
interface StoredSource {
from: { l: number; c: number; h: number; proportion: number };
wall: { l: number; c: number; h: number };
}
const OklchShare = v.object({
l: v.pipe(v.number(), v.minValue(0), v.maxValue(1)),
c: v.pipe(v.number(), v.minValue(0)),
h: v.number(),
proportion: v.pipe(v.number(), v.minValue(0), v.maxValue(1)),
});
const OklchOnly = v.object({
l: v.pipe(v.number(), v.minValue(0), v.maxValue(1)),
c: v.pipe(v.number(), v.minValue(0)),
h: v.number(),
});
const SourceSchema = v.object({ from: OklchShare, wall: OklchOnly });
const accentStore = createPersistentSignal(STORAGE_KEY, null, {
schema: SourceSchema,
});
/** Rebuild the pure picker's `AccentPick` from the stored source, for re-derivation. */
function pickFromSource(src: StoredSource): { color: Swatch; wall: Swatch } {
return {
color: { oklch: () => src.from, proportion: src.from.proportion },
wall: { oklch: () => src.wall, proportion: 0 },
};
}
/**
* The pair to paint right now: the record's colour derived for the current theme's ground,
* or the house pair for that theme until a record has earned one. Defaults to the live
* theme so callers that ask "what should be on screen" get the answer for the theme that is
* actually up; pass a theme to ask about the other one.
*/
export function accentTokens(theme: Theme = resolveTheme()): AccentTokens {
const src = accentStore.peek();
return src ? deriveAccent(pickFromSource(src), theme).tokens : DEFAULT_ACCENTS[theme];
}
/** What the derivation last decided, for the console and for tests. */
export function accentSource(): AccentTokens | null {
const src = accentStore.peek();
return src ? deriveAccent(pickFromSource(src), resolveTheme()).tokens : null;
}
export interface AccentSyncDeps {
/** The connection the cover is fetched over — read, not reacted to. */
connection: () => ConnectionSettings | null;
/**
* The track the accent follows, and nothing else's.
*
* The track rather than its cover id, because "why did the colour not change" is
* answered about a track and not about an id: which cover gets asked for is one rule
* (`library/cover.ts`, the same one the bar's tile and the grid's cells are cut from),
* and the reasons for not asking — no picture in the file and no album to inherit one
* from, a server that has settled the record artless — are facts about this song that a
* bare id has thrown away.
*/
track: () => LibrarySong | null;
/** Test seam: the pixels the colour is chosen from. */
loadPalette?: PaletteLoader;
}
/**
* Call once from the app root, beside the other `start*Sync`s.
*
* Two effects, deliberately apart: one paints whatever the tokens are (which includes the
* value loaded from storage at boot, before any request has gone out), and one asks the
* server for the pixels that decide it. Coupling them would mean a slow cover holds up
* the paint of a colour that is already known.
*/
export function startAccentSync(deps: AccentSyncDeps): void {
const loadPalette = deps.loadPalette ?? defaultPaletteLoader;
// Paints whatever the record's colour is at the ground that is up. The compute reads
// both the stored source and the effective theme, so a theme flip re-runs this scope and
// repaints the pair for the new ground — without a single byte asked of the server, since
// the record's own colour is already in hand. Two properties both written in the effect
// phase keeps the ink and its dim on the same frame, matching the CSS cross-fade.
createEffect(
() => ({ source: accentStore.get(), theme: effectiveTheme() }),
({ source, theme }) => {
const tokens = source
? deriveAccent(pickFromSource(source), theme).tokens
: DEFAULT_ACCENTS[theme];
const root = document.documentElement;
root.style.setProperty("--accent", tokens.accent);
root.style.setProperty("--accent-dim", tokens.dim);
},
{ name: "accent-paint" },
);
createEffect(
() => {
const settings = deps.connection();
const song = deps.track();
const coverId = trackCoverId(song);
if (!settings) {
trace("nothing to ask: no server");
return null;
}
if (!coverId) {
// The two silences the bar's tile also obeys, said out loud here because this is
// the line a reader comes to: a track that wears a placeholder has not failed to
// update its colour, it has declined to ask, and why it declined is the answer.
trace(`nothing to ask: ${named(song)} — ${whyNoCover(song)} · keeping ${worn()}`);
return null;
}
const url = new SubsonicClient(settings).coverArtUrl(coverId, ART_SIZE);
// The settled check belongs in the compute rather than the effect: it is the answer
// to "is there anything to ask", and a cover already read is the same no-ask that
// no connection is.
if (settled.has(url)) {
// Worth its line: this is the case where the colour on screen is not this
// record's, and the reason is a cache that kept the question and dropped the
// answer. `worn()` names whose colour is still being worn, which is the whole
// difference between "it is stale" and "it never changed".
trace(`${coverId} already read: not asked again · keeping ${worn()}`);
return null;
}
// Owned by the execution, so the run that replaces it — and the teardown of the
// root that owns it — cancels the ask rather than leaving it to arrive for a track
// that has moved on. Registered here rather than in the effect phase, which is not
// a reactive context and would take the cleanup and never run it; carried in the
// value as well, which is what makes the two phases run in lockstep — a fresh
// controller is a fresh object, so the effect never skips a run the compute made.
const ctl = new AbortController();
onCleanup(() => {
ctl.abort();
trace(`${coverId} cancelled — the listener moved on before its wall arrived`);
});
trace(`asked ${coverId} for a ${ART_SIZE}px wall`);
return { coverId, url, signal: ctl.signal, trackId: song?.id };
},
(ask) => {
if (!ask) return;
void decide(ask.coverId, ask.url, ask.signal, loadPalette, ask.trackId);
},
{ name: "accent-sync" },
);
}
/**
* Ask, choose, paint — or say nothing.
*
* Every exit that is not "a better colour than the one we have" leaves the tokens
* alone, and only a palette actually read counts as settled: a cover the server
* wouldn't hand over is worth asking about again when the track comes round, since the
* bytes are the browser's to cache and the answer may not be.
*/
async function decide(
coverId: string,
url: string,
signal: AbortSignal,
loadPalette: PaletteLoader,
/** The track whose colour this is being asked for, so the load audit can draw the accent where it
* actually sits — beside the stream rather than inside it. A cover can be asked for with no track
* on the bar at all, which is why this is optional and why nothing here assumes a timeline. */
trackId?: string,
): Promise {
const asking = span(trackId, "accent from the cover", "accent");
let palette: readonly Swatch[] | null;
try {
const pixels = asking.child("cover pixels", "network");
palette = await loadPalette(url, signal);
pixels.close(() => ({
swatches: palette?.length ?? 0,
size: ART_SIZE,
}));
} catch (e) {
asking.abandon(signal.aborted ? "cancelled — the listener moved on" : reason(e));
if (signal.aborted) return;
trace(`cover ${coverId} could not be read (${reason(e)}) — keeping ${worn()}`);
return;
}
if (signal.aborted) {
asking.abandon("answered after the listener had left");
trace(`${coverId} answered after the listener had left — dropped`);
return;
}
// Two passes over the same palette, in order, and the order is the argument: ask the
// cover for a colour first, and only if it has none ask what the print was shot
// through. A sleeve with a red logo on it is never wearing a temperature instead.
//
// Measured as its own bar because it is the one part of the accent that is pure arithmetic on
// this thread: when the colour arrives late and the cover was already here, this is the bar to
// look at, and nothing else in here can tell you whether it was the choosing or the fetching.
const choosing = asking.child("choose the colour", "main");
const pick = palette && palette.length > 0 ? pickAccent(palette) : null;
const chosen = pick ?? (palette && palette.length > 0 ? tonalAccent(palette) : null);
choosing.close(() => ({
swatches: palette?.length ?? 0,
from: chosen ? (pick ? "its own colour" : "the print's temperature") : undefined,
}));
if (!chosen) {
settled.add(url);
asking.close(() => ({ lent: "nothing" }));
trace(
`cover ${coverId} has nothing to lend — ${
palette
? explainPalette(palette)
: "no palette at all: the browser would not hand over the pixels"
} · keeping ${worn()}`,
);
return;
}
const recipe = deriveAccent(chosen, resolveTheme());
asking.close(() => ({
accent: recipe.tokens.accent,
from: pick ? "its own colour" : "the print's temperature",
}));
noteAudit(trackId, () => ({ accent: recipe.tokens.accent }));
mark(trackId, "accent worn", () => ({ from: coverId }));
settled.add(url);
wornBy = { coverId, accent: recipe.tokens.accent };
// Store the source, not the tokens: the same colour is different ink on each ground, and
// the theme may have changed since this cover was read. See `StoredSource`.
accentStore.set({
from: {
l: recipe.from.l,
c: recipe.from.c,
h: recipe.from.h,
proportion: recipe.from.proportion,
},
wall: { l: recipe.wall.l, c: recipe.wall.c, h: recipe.wall.h },
});
trace(
`cover ${coverId} → ${recipe.tokens.accent} off ${
pick ? "its own colour" : explainTone(palette ?? [])
} · took oklch(${recipe.from.l.toFixed(2)} ${recipe.from.c.toFixed(3)} ${recipe.from.h.toFixed(0)}) off a wall at oklch(${recipe.wall.l.toFixed(2)} ${recipe.wall.c.toFixed(3)} ${recipe.wall.h.toFixed(0)}) holding ${(recipe.from.proportion * 100).toFixed(1)}% of the cover · contrast ${recipe.contrast.panel.toFixed(1)}:1 on the panel, ${recipe.contrast.wash.toFixed(1)}:1 on its own typing wash${livedElsewhere(palette ?? [], recipe.from.c)}`,
);
}
/**
* The colour the cover most wanted to be, when the accent is not it.
*
* The decision line otherwise records only the winner — and the one question a listener
* ever actually asks of a colour they did not expect is the one the winner cannot answer:
* *was the red there at all?* A cover whose red survived into the palette but lost the pick
* (a bar-ink collision, say) and a cover whose red was never in the bytes the server handed
* over both end in the same `→ #865b3a`, and they have opposite remedies — one is a bug in
* the picker, the other is a thumbnail too small or recompressed too hard to keep a thin
* saturated wordmark. So when the ink we settled on is materially duller than the most
* saturated thing on the sleeve, say so, and name it: if the pair disagrees, the cover was
* given a colour it did not take, and the reader can see immediately whose fault that is.
*
* `0.05` of OkLab chroma is the gap where a human reads the two as different colours rather
* than a shade of one — below it the two are the same hue at different weights and naming
* the difference is noise. Only the `pick` path prints this: the tonal path has already said
* in `explainTone` that the cover had no colour to lend, so it has nothing to contradict.
*/
function livedElsewhere(palette: readonly Swatch[], takenC: number): string {
let vivid: { l: number; c: number; h: number } | null = null;
for (const s of palette) {
const o = s.oklch();
if (!vivid || o.c > vivid.c) vivid = o;
}
if (!vivid || vivid.c - takenC < 0.05) return "";
return ` · but the cover's most saturated colour was oklch(${vivid.l.toFixed(2)} ${vivid.c.toFixed(3)} ${vivid.h.toFixed(0)}) — it did not survive to be worn`;
}
/**
* Whose colour is on screen, in the words the trace lines use.
*
* The hex plus the cover that earned it, because "keeping #b281fe" reads as a verdict
* about this record when half the time it is a verdict about the one before it: the
* accent is the last cover that had something to say, not the current track's colour, and
* only the second half of this string tells the reader which of the two they are looking
* at. Cleared with `resetAccent`, so a test's second boot does not read as if the first
* were still being worn.
*/
function worn(): string {
const t = accentTokens();
return wornBy
? `${t.accent} (worn since ${wornBy.coverId})`
: `${t.accent} (the house pair, so far)`;
}
/** Which cover the colour currently on screen came from. */
let wornBy: { coverId: string; accent: string } | null = null;
/**
* Covers already read, keyed by the request that read them.
*
* Module scope rather than inside `startAccentSync` so that `resetAccent()` can empty it:
* a settled cover that outlives the accent derived from it would be a cover the app
* never asks about again, and a test that resets the accent would silently be testing
* the cache instead of the fetch.
*/
const settled = new Set();
/** Forget the record's colour and every cover already read: a test's `beforeEach`, or a sign-out. */
export function resetAccent(): void {
settled.clear();
wornBy = null;
accentStore.set(null);
}
// ---------------------------------------------------------------------------
// The default palette source
// ---------------------------------------------------------------------------
const defaultPaletteLoader: PaletteLoader = async (url, signal) => {
if (typeof createImageBitmap !== "function") return null;
const res = await fetch(url, { signal });
if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
const bitmap = await createImageBitmap(await res.blob());
try {
// Imported where it is used rather than at module scope: the node entry of this
// package pulls an optional `sharp` dependency with it, which the test runner resolves
// and a browser never needs — and the quantizer is 17 kB raw, 6.7 gzipped of code
// nobody pays for until the first cover asks for it.
const { getPalette } = await import("colorthief");
return await getPalette(bitmap, {
// 20 is the most the library will hand over (it clamps anything above it), and the
// default of 10 is what makes rare colours lose: MMCQ spends its boxes on the
// population it can see, so a logo in 2% of the cover only survives if there are
// boxes to spare for it. `getColor()` is worse again — it answers with the wall.
colorCount: 20,
// Every second pixel — `quality` is a stride over the pixel list. All 9,216 of them
// buy nothing a 96px cover has in it, and the quantizer's cost is in the boxes
// rather than the samples.
quality: 2,
// Cluster where equal distances mean equal perceived differences, so a box is a
// colour rather than a third of the RGB cube.
colorSpace: "oklch",
// The white of a product shot's background is the largest colour in most covers and
// the least interesting thing about them.
ignoreWhite: true,
signal,
});
} finally {
bitmap.close?.();
}
};
// ---------------------------------------------------------------------------
// Trace
// ---------------------------------------------------------------------------
/** The track, named the way the bar names it. */
function named(song: LibrarySong | null): string {
if (!song) return "nothing playing";
return `${song.title || "an untitled track"}${song.album ? ` · ${song.album}` : ""}`;
}
/**
* Why there was no cover to ask for, in the same breath as the refusal.
*
* `trackCoverId` answers with an id or nothing, which is right for a tile and too terse
* for a log: the three nothings it can mean want to be told apart here, because they have
* three different remedies — a file with no album has no sleeve to inherit, a server that
* settled the record artless has looked and found nothing, and a track that names no
* album has been harvested wrongly, which is a bug rather than an absence.
*/
function whyNoCover(song: LibrarySong | null): string {
if (!song) return "there is no track";
if (song.imageAbsent === true)
return "the server has settled that neither this file nor its record has a picture";
if (!song.albumId) return "no picture in the file, and it names no album to inherit one from";
return "no cover id of its own and no album id to ask about — the row is malformed";
}
/**
* One line per decision, dev-only and silent under the tests, for the same reason the
* playback trace exists: every way an accent can fail to change is a silence, and the
* interesting one is which of the six silences it was. The gate is the house one — `DEV`
* minus the test mode — with the console switch below overriding it, because the question
* "why is the bar still green" is asked while listening and not after a rebuild.
*/
let forced: boolean | null = null;
/** Whether the accent is printing its decisions. On by default in dev, off under tests. */
export function accentTrace(): boolean {
if (forced !== null) return forced;
return import.meta.env.DEV && import.meta.env.MODE !== "test";
}
/**
* On, off, or back to "nobody has said" with `null` — which is what a test finishes with
* so it does not leave the page in the setting it borrowed.
*/
export function setAccentTrace(on: boolean | null): void {
forced = on;
}
/**
* The console handle, installed the way the playback trace installs its own:
*
* hackermusic.accentTrace() // is it on?
* hackermusic.accentTrace(false) // quiet, for this page
*
* Worth having because the trace is on by default and skips two entries a line apiece:
* the reader who is skip-listening does not want a cancel line per keypress, and the way
* to say so has to be a keystroke rather than a rebuild.
*/
export interface AccentTraceHandle {
(): boolean;
(on: boolean): boolean;
}
export const accentTraceHandle: AccentTraceHandle = ((on?: boolean) => {
if (on !== undefined) setAccentTrace(on);
return accentTrace();
}) as AccentTraceHandle;
if (import.meta.env.DEV && typeof globalThis !== "undefined") {
const g = globalThis as unknown as { hackermusic?: Record };
g.hackermusic = { ...g.hackermusic, accentTrace: accentTraceHandle };
}
function trace(line: string): void {
if (!accentTrace()) return;
console.debug(`[accent] ${line}`);
}
function reason(e: unknown): string {
return e instanceof Error ? e.message : String(e);
}