/** * Which colour the app wears, decided from the record being heard. * * Two questions, kept deliberately apart because they have different owners: * * - **Which colour does the record want to be?** Answered from the cover's palette: * colourthief's MMCQ pass over OKLCH-sampled pixels does the quantizing, and * `pickAccent` does the choosing — vivid over common, the wall's own family demoted * rather than refused, and colourless covers and the two seek-bar hues refused * outright. * - **Which colour can the app draw with?** Answered here, not by the record: the * accent is ink, drawn at 11px as the query text, the share line and the playing * row's title, and as the fill of the seek bar. Its lightness is therefore the * app's own property and the record lends only its hue and its chroma. * * The lightness rule is not a taste call: the house accent `#3fb950` measures * `oklch(0.695 0.181 146)`, and every hue parked at that same lightness lands between * 6.7:1 and 8.7:1 against `--panel`. On the typing wash the wheel spans 4.34:1 to 5.15:1 * — the green itself sits at 4.87:1 there — and about half of it comes in under the floor * below, which is why the nudge exists rather than a one-off exception: it is a few * hundredths of a lightness, swept across the wheel topping out at 0.725, and nothing the * picker can return lands under the floor. The floor is WCAG's number for body text and * not a number chosen for this theme, which is what makes it worth checking at all: * an album cover is not to be trusted with choosing how bright the app's ink is. The * palette's own Gaussian (`L_MEAN` below) already preferred candidates sitting near there. * * Everything here is pure and takes plain numbers: the only thing that touches an * image is `theme/index.ts`, and the only thing from colourthief is the palette. That * separation is what makes the two rules testable without a canvas. */ import { oklchToRgb, rgbToOklch, srgbToLinear } from "colorthief/internals"; import type { Theme } from "./mode"; import { count } from "../print"; /** OKLCH: L 0–1, chroma 0–~0.32, hue in degrees. */ export interface Oklch { l: number; c: number; h: number; } /** * The part of a colourthief `Color` this module reads. * * Declared structurally rather than imported so the picker can be tested with hand-made * swatches — a cover is a canvas, a network and a decode, and none of that is the * question "which of these five colours should the app wear". */ export interface Swatch { oklch(): Oklch; /** Fraction of the sampled pixels this swatch stands for (0–1). */ readonly proportion: number; } /** The two custom properties this app paints, as CSS hexes. */ export interface AccentTokens { accent: string; dim: string; } /** What the derivation actually did, for the trace line and for tests. */ export interface AccentRecipe { tokens: AccentTokens; /** The chosen swatch as the cover had it, before this module touched the lightness. */ from: Oklch & { proportion: number }; /** The cover's wall — the colour the accent had better not be another reading of. */ wall: Oklch; /** The accent's contrast ratios on the two grounds it is drawn as ink on. */ contrast: { panel: number; wash: number }; } /** The house accent and its dim, as App.css declares them — the dark theme's pair. */ export const DEFAULT_ACCENT: AccentTokens = { accent: "#3fb950", dim: "#237a41" }; // The light house pair is derived from this one's hue through `deriveAccent`, so it lives // at the bottom of the file where the contrast helpers it needs have been initialized. See // `DEFAULT_ACCENTS` there for why it is derived rather than spelled as a literal. // --------------------------------------------------------------------------- // Choosing a colour off the cover // --------------------------------------------------------------------------- /** * What makes two colours the same colour, for the two gates that have to ask. * * The 28 in the ΔE76 rule this was ported from is a number on CIE's scale (L 0–100, * chroma ±128) and OKLab covers the same perceptual span in L 0–1 with chroma out to * about 0.32, so the translation has to be per component rather than one rescaled * radius. It has to be: the axes differ by a factor of six, and a single radius generous * enough to refuse "the wall, but brighter" also swallows a teal badge on a grey wall — * Δchroma 0.10, which is a different colour to any eye — and throws the whole cover back * with it. */ interface Tolerance { /** how much lighter/darker still counts as the same colour under a different lamp */ l: number; /** how much less/more saturated still counts as the saturation knob being nudged */ c: number; /** how far around the wheel, in turns, still counts as one hue */ h: number; } /** Below this chroma a colour has no hue, so two of them cannot disagree about one. */ const HUELESS = 0.02; /** * The same colour when they agree on hue and saturation, at any lightness. * * Lightness is switched off — `Infinity` makes its term vanish — because in both * questions below it is the one component the app is about to overwrite anyway: the * accent is always painted at `ACCENT_L` or nudged from it, and the region it is compared * against has its lightness fixed by the theme. What the app cannot fix afterwards is a * hue and a saturation that already agree, so that is the pair the tolerance keeps: a * twentieth of chroma, a sixteenth of the wheel. * * A sixteenth is ±22°, and at the chroma an accent usually lands at that is what refuses * 80 of the 360 hues — two 40° arcs, one around each of the inks below — and nothing else * on the wheel. Both gates are the same test for the same reason, and the reason is the * lightness: see `SAME_COLOUR`. */ const SAME_COLOUR: Tolerance = { l: Infinity, c: 0.05, h: 0.06 }; /** * Two colours are one colour when they agree on every component at once: the quadrature * of the differences, each in units of its tolerance, lands under 1. */ function sameColour(a: Oklch, b: Oklch, t: Tolerance): boolean { return Math.hypot(Math.abs(a.l - b.l) / t.l, Math.abs(a.c - b.c) / t.c, hueApart(a, b) / t.h) < 1; } /** Separation around the hue wheel, in turns — and zero when either colour has no hue. */ function hueApart(a: Oklch, b: Oklch): number { if (a.c < HUELESS || b.c < HUELESS) return 0; return Math.abs(((a.h - b.h + 540) % 360) - 180) / 360; } /** * What a wall-family candidate is worth against a colour that is genuinely its own. * * Demotion rather than elimination, and covers decided it rather than theory: an all-red * sleeve, a product shot that is one colour once colourthief has discarded the white it * was shot on, and a red-and-black sleeve split fifty-fifty all have the wall as their * only offer, and a hard gate here answered all three with "nothing to lend". A factor * of eight still hands the cover to anything real instantly — the Gaussian scores a true * candidate several times over before the penalty is in the argument — and lets the wall * speak only when the cover has nothing else to say. */ const WALL_PENALTY = 8; /** The vivid-and-medium-bright preference, as a Gaussian on each axis. */ const L_MEAN = 0.72; const L_SPREAD = 0.18; const C_MEAN = 0.24; const C_SPREAD = 0.1; /** * Population enters as a fourth root, and this is the term that makes the whole thing * work. Linear, it is the wall again by another route — the most common colour always * wins a sum that includes its own share of the pixels. To the fourth root a colour * holding 2% of the cover is worth 0.37 of one holding 50% rather than 0.04, which is * the difference between "the album cover is brown, so the app is brown" and the small * red logo in the corner being allowed to be the accent. */ const POPULATION_EXPONENT = 0.25; /** * Below this a colour has no hue to lend, only a shade. * * A black-and-white cover produces only greys, and a grey accent is worse than the * house green: it says "signal" in the same ink as `--text-muted`, so the playing row, * the caret and the query stop meaning anything. Refusing here is what makes a * colourless record keep the app's own colour rather than lose it. */ const MIN_CHROMA = 0.03; /** * And below this it is not a colour the quantizer found so much as a colour it invented: * JPEG ringing along an edge, one pixel of a 96px sleeve. Twenty boxes over ~4,600 * samples will fill the last few with whatever is left, and letting a 0.4% speck decide * the theme is how an app gets a chartreuse accent off a photograph of a grey street. */ const MIN_POPULATION = 0.01; /** * The inks drawn *on top of* the accent, and therefore the ones it cannot resemble: the * A–B region and the detector's suggested boundary, both laid over the played part of the * seek bar, which is the accent's own fill. * * Their `-dim` siblings are named with them rather than dropped: they are the same hues at * half the lightness, and since lightness is not part of this test (see `SAME_COLOUR`), * whichever of each pair is nearer the accent in hue and chroma is the one that gets the * say. A hairline drawn in `--loop-dim` across an accent that equals it is the same * mistake as the region vanishing, and cheaper to catch here than to explain there. */ const BAR_INKS: readonly Oklch[] = [ rgbToOklch(0xe3, 0xb3, 0x41), // --loop rgbToOklch(0x8a, 0x65, 0x16), // --loop-dim rgbToOklch(0x79, 0xc0, 0xff), // --detected rgbToOklch(0x2f, 0x5f, 0x86), // --detected-dim ]; function gauss(x: number, mean: number, spread: number): number { return Math.exp(-((x - mean) ** 2) / (2 * spread * spread)); } export interface AccentPick { color: Swatch; wall: Swatch; } /** * The candidate to take the accent from, or null when the record has none to lend. * * Null is a real answer and not a failure: a cover that is a wall plus a few greys, or * one whose only colours are the two hues the seek bar is drawn in, has nothing to give * that the app could draw with, and keeping its own green is the honest result. Being * the wall's own colour is not on that list — a wall-family candidate is demoted by * `WALL_PENALTY` and left to win an empty field, because for a sleeve that is one colour * once the white has been discarded, the wall is the whole cover. */ export function pickAccent(palette: readonly Swatch[]): AccentPick | null { if (palette.length === 0) return null; const wall = mostPopulous(palette); const wallColour = wall.oklch(); let best: Swatch | null = null; let bestScore = 0; for (const color of palette) { const score = scoreCandidate(color, wallColour); if (score > bestScore) { bestScore = score; best = color; } } return best ? { color: best, wall } : null; } /** Zero means refused, and every refusal is a reason this module has a name for. */ type Refusal = "grey" | "speck" | "ink-collision"; /** Which floor a swatch fell at, or null when it is eligible to be scored at all. */ function refusalOf(color: Swatch): Refusal | null { const o = color.oklch(); if (o.c < MIN_CHROMA) return "grey"; // Below this it is not a colour the quantizer found so much as a colour it invented. if (color.proportion < MIN_POPULATION) return "speck"; if (onTheBar(o)) return "ink-collision"; return null; } const REFUSAL_PHRASE: Record = { grey: "too grey to wear", speck: "too small a share of the cover", "ink-collision": "a hue the bar already draws in", }; /** What a candidate would have been worth had no floor stopped it — one formula, two * readers: the picker scores with it, and `explainPalette` ranks the rejects by it. */ function merit(o: Oklch, proportion: number): number { return ( gauss(o.l, L_MEAN, L_SPREAD) * gauss(o.c, C_MEAN, C_SPREAD) * Math.pow(proportion, POPULATION_EXPONENT) ); } function scoreCandidate(color: Swatch, wall: Oklch): number { if (refusalOf(color)) return 0; const o = color.oklch(); const score = merit(o, color.proportion); return sameColour(o, wall, SAME_COLOUR) ? score / WALL_PENALTY : score; } // --------------------------------------------------------------------------- // The cover's temperature, for the cover that has no colour // --------------------------------------------------------------------------- /** * How much of a print's tint counts as a tint. * * A swatch at chroma 0.008 is not a colour an eye can see, but it is also not nothing: * it is the average opinion of a few thousand pixels, and MMCQ does not put a hue on a * box that does not have one. What it measures is the temperature of the print — the * selenium warmth of an old photograph, the blue in a black-and-white reissue — which is * exactly the thing a listener chose a greyscale record for and the one thing the app can * still draw with. * * The number is a measurement off real sleeves rather than a taste call, and it sits a * decade under the thing it is meant to refuse. A black-and-white photograph came in at * c=0.010 and an all-black sleeve at c=0.005; a mostly-white one — whose white the * quantizer is told to ignore, leaving only the lettering's greys and the shadow under the * type to carry a whisper of the ink's warm bias — measured c=0.0032, and the first * version of this floor threw it away at 0.004: failing the exact case the pass exists * for, by one part in four thousand. A genuinely neutral sleeve, a scanned page or a flat * grey, measures c=0.0002 — ten times under, so the floor still means "nothing there" * rather than "nothing I was willing to see". When it refuses, the trace line quotes the * measurement beside the floor, so the next argument about this number is made with * numbers. */ const BIAS_FLOOR = 0.002; /** * How far the measured tint is pushed before it is worn. * * Amplification rather than invention: the hue stays exactly where the pixels put it, and * only the saturation comes up, for the same reason the lightness does — the accent is * ink at 11px on a panel, and a chroma the cover has is a chroma the app cannot show at * that size either way. Clamped at the bottom so the result is a colour and not a smudge * of grey, which is the failure `MIN_CHROMA` exists to refuse. */ const TONAL_GAIN = 4; const TONAL_MIN_C = MIN_CHROMA; /** * The ceiling on a borrowed tint, and incidentally the reason a tonal accent cannot turn * into one of the seek bar's own inks: the nearest of those (`--detected`) sits at chroma * 0.115, and nothing painted from a greyscale gets past 0.07. A print with a *strong* * colour in it is not a greyscale with a temperature, and the cap is what says so — it * keeps the answer a photograph of concrete rather than a billboard for the four percent * of it that happened to be a blue doorway. */ const TONAL_MAX_C = 0.07; /** How much tint is asked to wear: the measured bias, pushed, clamped at both ends. */ function tonalChroma(bias: number): number { return Math.max(TONAL_MIN_C, Math.min(TONAL_MAX_C, bias * TONAL_GAIN)); } /** The tint a palette carries, weighted by how much of it there is to see. */ interface PrintTone { /** degrees, on the circle — the mean of angles, not of numbers */ hue: number; /** the average chroma of the pixels that pulled that way */ chroma: number; /** the print's own lightness, for the trace line; the accent overwrites it */ lightness: number; /** how much of the cover agreed (sum of the participating swatches) */ share: number; } /** * The one direction the greys all point in. * * Hue is an angle, so the mean has to be taken on the circle: averaging 350° and 10° * arithmetically says 180°, which is not a compromise between two reds, it is a * fabrication about a cyan. Weighting by chroma × share is what makes the answer belong to * the cover rather than to its smallest box: a big cool wall moves the mean, a vivid pinprick * does not get a vote it cannot pay for. */ function coverTone(palette: readonly Swatch[]): PrintTone { let x = 0; let y = 0; let weight = 0; let lift = 0; let lightness = 0; let share = 0; for (const s of palette) { const o = s.oklch(); // The floor is a decision, not a filter: everything the quantizer kept at a // respectable share of the cover is counted, however faint, because the number that // decides this cover's fate is the average that comes out the other side. Discard the // faint ones here and the refusal has nothing left to quote. if (s.proportion < MIN_POPULATION || o.c <= 0) continue; const w = o.c * s.proportion; const r = (o.h * Math.PI) / 180; x += w * Math.cos(r); y += w * Math.sin(r); lift += w * o.c; weight += w; lightness += o.l * s.proportion; share += s.proportion; } if (weight === 0) return { hue: 0, chroma: 0, lightness: 0, share: 0 }; // nothing measurable const hue = ((((Math.atan2(y, x) * 180) / Math.PI) % 360) + 360) % 360; return { hue, chroma: lift / weight, lightness: lightness / Math.max(share, 1e-6), share }; } /** * The accent a colourless cover still has: its temperature, worn. * * The second pass, taken only when `pickAccent` found nothing — and it is a different * question rather than a lower bar. `pickAccent` asks which of the cover's colours could * be an ink; a black-and-white sleeve has none, and this asks what the print was shot * through instead. Same discipline otherwise: the hue is the pixels' and only the * saturation is the app's, the result goes back through `deriveAccent` for the lightness * and the gamut fit, and it is refused outright if the colour it would paint is one the * seek bar already draws in — a warm-grey print lifting into `--loop` amber is the same * vanishing region as any ink-collision, arrived at by a longer route. * * Returns null for the genuinely neutral cover, which is the answer the app should keep: * the house green means "this record had nothing to say", and a green picked because the * hue average of a flat grey was numerically nonzero says it falsely. */ export function tonalAccent(palette: readonly Swatch[]): AccentPick | null { const tone = coverTone(palette); if (tone.share === 0 || tone.chroma < BIAS_FLOOR) return null; const c = tonalChroma(tone.chroma); if (clashesWithAnInk({ l: DARK_GROUND.inkL, c, h: tone.hue })) return null; return { color: { oklch: () => ({ l: tone.lightness, c, h: tone.hue }), proportion: tone.share, }, wall: mostPopulous(palette), }; } /** * How much of an ink's saturation a candidate needs to have before it counts as that * ink's colour. Below three fifths, the stripe drawn in the ink keeps two fifths of its * own saturation as margin over the field it is laid on. */ /** * Near enough to an ink that a hairline drawn in it would vanish into the accent. * * The chromatic path's `onTheBar` switches lightness off, and it is right to: its * candidates are colours the cover actually had, and the app overwrites their lightness * anyway, so of each ink's two readings only the one nearer the accent in hue and chroma * can matter. Asked of a *tonal* accent, that omission is fatal. Every candidate there * arrives at the accent's own lightness carrying a third of an ink's saturation, which * makes all four inks "the same colour" to a lightness-blind test whose chroma tolerance * (±0.05) is wider than the candidates' entire range — and the commonest greyscale there * is, a cool print, is refused for resembling a boundary line that is a third lighter than * it and would show up against it perfectly well. * * So this check keeps lightness in: a stripe can only vanish into a field it is nearly the * colour of, and how light the field is belongs to being its colour. It is the second * guard rather than the first — `TONAL_MAX_C` already holds the accent's saturation well * under the nearest ink's, and for most hues that is the whole argument. What is left for * this one is the corner the first guard cannot see: a hue whose *contrast* fix drags an * accent at the cap up into an ink's lightness, where the two would then agree on every * axis that matters. Measured across the wheel, that is a narrow band, and it is exactly * as wide as the inks' own neighbourhoods. */ const NEAR_INK: Tolerance = { l: 0.12, c: 0.05, h: SAME_COLOUR.h }; function clashesWithAnInk(o: Oklch, ground: Ground = DARK_GROUND): boolean { const p = painted(o, ground); return BAR_INKS.some((ink) => sameColour(p, ink, NEAR_INK)); } /** * The temperature a palette carries, said out loud for the trace line that wears it: * what was measured, how much of the cover agreed, and what the app is going to paint * from it. Beside the success line it is the whole audit trail of a greyscale record — * the number that says whether `BIAS_FLOOR` discarded a cover that should have been * allowed through, and the one that says `TONAL_GAIN` took a photograph of concrete and * turned it into a sign. */ export function explainTone(palette: readonly Swatch[]): string { const tone = coverTone(palette); if (tone.share === 0 || tone.chroma < BIAS_FLOOR) return "a print with no temperature to take"; const worn = tonalChroma(tone.chroma); return ( `a colourless print shot through c=${tone.chroma.toFixed(3)} at h ${tone.hue.toFixed(0)}, ` + `${(tone.share * 100).toFixed(0)}% of the cover agreeing, worn at c=${worn.toFixed(3)}` ); } /** * Why a cover got no colour, in the numbers a person can rule on. * * The refusal is the interesting output of this module and it was a silence: "nothing to * lend" is the same sentence for a black-and-white photograph, a flat grey sleeve, a JPEG * wall of specks and a record that is entirely drawn in the two hues the seek bar uses — * and those four want different things from the thresholds above. So this says which * floor every swatch fell at, names the one that came closest, and quotes the print's * measured temperature beside the floor that discarded it, which is the pair of numbers * that decides whether `MIN_CHROMA` or `BIAS_FLOOR` was too high. Dev-only, from the * accent's own trace line. */ export function explainPalette(palette: readonly Swatch[]): string { if (palette.length === 0) return "the cover quantized to nothing at all"; const tally = new Map(); let closest: { o: Oklch; share: number; why: Refusal; merit: number } | null = null; for (const s of palette) { const why = refusalOf(s); if (!why) continue; tally.set(why, (tally.get(why) ?? 0) + 1); const o = s.oklch(); const m = merit(o, s.proportion); if (!closest || m > closest.merit) closest = { o, share: s.proportion, why, merit: m }; } const counts = [...tally] .sort((a, b) => b[1] - a[1]) .map(([why, n]) => `${n} ${REFUSAL_PHRASE[why]}`) .join(", "); const near = closest ? ` · nearest miss oklch(${closest.o.l.toFixed(2)} ${closest.o.c.toFixed(3)} ${closest.o.h.toFixed(0)}) at ${(closest.share * 100).toFixed(1)}% of the cover, ${REFUSAL_PHRASE[closest.why]}` : ""; const tone = coverTone(palette); const tint = tone.share === 0 ? " · no swatch left big enough to have an opinion" : tone.chroma < BIAS_FLOOR ? ` · no temperature to take: measured c=${tone.chroma.toFixed(4)} at h ${tone.hue.toFixed(0)}, ${BIAS_FLOOR} needed to believe it` : ` · print temperature c=${tone.chroma.toFixed(3)} at h ${tone.hue.toFixed(0)}, ${MIN_CHROMA} needed to wear it, ${BIAS_FLOOR} to be believed`; return `${count(palette.length, "colour")}: ${counts || "none refused"}${near}${tint}`; } /** * The wall, by count rather than by position. * * `palette[0]` is the wall whenever MMCQ ran, since its boxes leave the priority queue * by population. It is not when the image had fewer distinct colours than were asked * for — that short-circuit path returns them in first-seen order, so `palette[0]` is * whatever pixel came first. Taking the maximum costs one pass and removes a difference * between two code paths that the rest of this function cannot see. */ function mostPopulous(palette: readonly Swatch[]): Swatch { let best = palette[0]!; for (const c of palette) if (c.proportion > best.proportion) best = c; return best; } /** * Would the A–B region vanish into this candidate? * * Asked of the colour the app would actually paint — see `painted` — because that is the * colour that ends up behind the region. The candidate's own oklch is a photograph's * colour, generally a good deal darker than anything drawn here, and comparing one of * those to a UI ink compares a colour that never appears on screen. * * This is a refusal rather than a demotion, unlike the wall: there is no reading of "the * accent is the region's colour" that is acceptable, and no fallback that makes it so. * It costs a band of the wheel and the band is worth it — the region is a 5px stripe that * has to survive being laid on top of the accent's own fill, and the two are 11px apart * in the same row of the bar. */ function onTheBar(o: Oklch, ground: Ground = DARK_GROUND): boolean { const p = painted(o, ground); return BAR_INKS.some((ink) => sameColour(p, ink, SAME_COLOUR)); } // --------------------------------------------------------------------------- // Making it drawable // --------------------------------------------------------------------------- /** * The grounds the accent is drawn on, and the pair it is drawn in. * * `--panel` (#070708) is the tighter of the two near-black surfaces, so checking it * covers `--bg` (#000) as well. The typing wash is the binding constraint and is * modelled rather than trusted: it is `color-mix(in oklab, var(--accent) 34%, * var(--panel))` in App.css — and modelled in OkLab for the same reason, since that is * what the browser does to it, and the two mixes disagree by enough to change the answer * (see `mix`). A check that ignored the wash could pass an accent that is legible on the * bar's ground and unreadable on the bar's own wash, which is the only pair in this app * where the text and its background are made of the same token, so nothing else will ever * catch it. Change the percentage there and change it here. */ const TYPING_WASH = 0.34; /** 4.5:1 is WCAG's floor for body text, and the accent *is* body text here: the query, * the counts, the share line and the playing row's title are all drawn in it at 11px. * 3:1 — the large-text floor — would be the wrong number to accept for 11px ink. */ const MIN_INK_CONTRAST = 4.5; /** * The ground the accent has to be legible against, and the pair of numbers that describe * wearing it as ink. * * Two grounds exist now that the app has a light theme, and they are not two ends of one * dial — the whole derivation *inverts* between them. On the near-black panel, contrast is * bought by brightening the ink, so the accent walks *up* from `inkL` toward a `limitL` * ceiling and its dim sibling sits *below* it as a shadow. On a near-white panel, contrast * is bought by darkening the ink, so the walk goes *down* toward a `limitL` floor and the * dim sits *above* the ink as a lighter border. `contrastDirection` is the sign of that * walk — `+1` brighten-to-read (dark), `-1` darken-to-read (light) — and it is what keeps * the two grounds sharing one `fitContrast`/`painted` rather than two parallel copies that * drift. * * `panel` is the *tightest* surface for that ground — the one that gives ink the least * room — so a floor met here is met everywhere on the theme: the dark ground checks the * lighter of its two near-blacks (#070708, not #000), the light ground checks the whiter * of its two near-whites (#ffffff, not the greyed page behind it). `wash` stays 0.34 for * both because the toolbar washes by the same percentage of the accent whichever theme is * up; the ground it is mixed into is what changes. */ interface Ground { readonly panel: Rgb; readonly wash: number; /** The lightness the app wants its ink at before the contrast rent is paid. */ readonly inkL: number; /** How far the ink may be walked for contrast: a ceiling for bright ink, a floor for dark. */ readonly limitL: number; /** Which way walking buys contrast: `+1` brightens (dark ground), `-1` darkens (light). */ readonly contrastDirection: 1 | -1; /** The dim's lightness as a multiple of the accent's — toward the ground either way. */ readonly dimLRatio: number; } const DARK_GROUND: Ground = { panel: [7, 7, 8], // --panel wash: TYPING_WASH, inkL: 0.695, limitL: 0.8, contrastDirection: 1, dimLRatio: 0.74, }; const LIGHT_GROUND: Ground = { panel: [255, 255, 255], // --panel, the whiter of the two light surfaces // The typing wash, lighter than the dark theme's 34% — and the reason it must be is the // asymmetry that makes this the ground's defining constraint. On the dark theme the wash // is 34% of a *bright* ink mixed into near-black: it stays dark, and the bright ink still // reads on it. On the light theme the same 34% of a *dark* ink into white lands on a mud // mid-tone (luminance ~0.6), and no ink both reads on white and reads on its own brown // wash at once — the walk would darken toward black chasing 4.5 there and hand back olive. // A lighter tint is what a light theme paints anyway (a whisper of the accent behind the // query, not a flooded bar); 18% is that, and it is the tightest wash so it is the rent // paid here. Change the percentage in App.css's light `[data-typing]` rule and here. wash: 0.18, // The house ink lightness starts higher than the dark theme's would suggest (0.62) and // floors at 0.42 rather than walking toward black: a light-theme ink that has to darken // for contrast should stop as soon as it clears the floor on the wash, not grind down into // the brown the old floor produced. Between 0.62 and 0.42 the whole wheel clears 4.5 on // both the panel and the wash with its chroma — and therefore its identity — intact. inkL: 0.62, limitL: 0.42, contrastDirection: -1, dimLRatio: 1.3, }; /** The ground for a theme. Everything about wearing the accent as ink follows from this. */ function groundFor(theme: Theme): Ground { return theme === "light" ? LIGHT_GROUND : DARK_GROUND; } /** `--accent-dim` measured against `--accent`: #237a41 is oklch(0.514 0.121 151) beside * oklch(0.695 0.181 146). Ratios rather than absolutes, so the dim stays the dim of a * crimson record as much as of a green one — and it stays a border you can see rather * than a second accent: the band below is where it lands across the whole wheel. The * light theme's ratio (`GROUND.dimLRatio`) is above 1 where the dark one is below it, for * the reason in `Ground`: the dim is always on the ground's side of the ink. */ const DIM_C_RATIO = 0.67; const DIM_CONTRAST_MIN = 2.2; const DIM_CONTRAST_MAX = 4.5; const LUMA: [number, number, number] = [0.2126, 0.7152, 0.0722]; type Rgb = [number, number, number]; /** * The tokens to paint, from the pick. * * Hue and chroma come from the record, lightness from the app, chroma then trimmed to * what the sRGB gamut can show at that lightness rather than letting the conversion * clip it: clipping a saturated ochre at L 0.58 moved its hue 17° and turned an orange * into an olive, which is the palette being misquoted rather than quoted quietly. */ export function deriveAccent(pick: AccentPick, theme: Theme = "dark"): AccentRecipe { const ground = groundFor(theme); const from = pick.color.oklch(); const wall = pick.wall.oklch(); const p = painted(from, ground); const rgb = toRgb(p.l, p.c, p.h); const dimL = fitContrast( p.l * ground.dimLRatio, p.h, p.c * DIM_C_RATIO, DIM_CONTRAST_MIN, DIM_CONTRAST_MAX, ground, ); const dimRgb = toRgb(dimL, fitChroma(dimL, p.h, p.c * DIM_C_RATIO), p.h); return { tokens: { accent: hexOf(rgb), dim: hexOf(dimRgb) }, from: { ...from, proportion: pick.color.proportion }, wall, contrast: { panel: contrastOf(rgb, ground.panel), wash: contrastOf(rgb, mix(ground.panel, rgb, ground.wash)), }, }; } /** * The colour the app would paint from a candidate: the app's lightness, lifted until it * reads as ink, at the chroma the sRGB gamut will actually show at it. * * Shared by the two places that must ask about the painted colour rather than the * cover's — the bar check above, and the derivation below — so that neither of them * reasons about a colour that never appears on screen. Both are asked of the candidate's * hue and chroma only, which is the whole of what the record is allowed to choose. */ function painted(from: Oklch, ground: Ground = DARK_GROUND): Oklch { let l = ground.inkL; // The walk only ever goes the way that buys contrast on this ground, and stops at the // limit beyond which the ink starts outshining (dark) or sinking under (light) the washes // it tints. On the dark ground that is a lift — a near-black cover colour is the failure // mode a palette hands back, and it has to come up to read; on the light ground it is a // drop, and a near-white cover colour has to come down for the same reason. One rule, // its sign taken from the ground. let guard = 0; while ( guard++ < 60 && inkContrast(l, from.c, from.h, ground) < MIN_INK_CONTRAST && (ground.contrastDirection === 1 ? l < ground.limitL : l > ground.limitL) ) { l = ground.contrastDirection === 1 ? Math.min(ground.limitL, l + 0.01) : Math.max(ground.limitL, l - 0.01); } return { l, c: fitChroma(l, from.h, from.c), h: from.h }; } /** * How legible the ink would be at this lightness, on whichever of the two grounds is * tighter — the panel, or the 34% wash of itself the typing toolbar becomes. */ function inkContrast( l: number, askedChroma: number, h: number, ground: Ground = DARK_GROUND, ): number { const c = fitChroma(l, h, askedChroma); const rgb = toRgb(l, c, h); return Math.min( contrastOf(rgb, ground.panel), contrastOf(rgb, mix(ground.panel, rgb, ground.wash)), ); } /** * The largest chroma at or below `asked` that is still inside sRGB at this L and hue, * found by bisection. * * The test is the conversion's own rounding: `oklchToRgb` clamps, so a channel that comes * back at either rail is a channel that wanted to be past it. Sixteen passes is a * hundredth of a chroma, which is well below what an eye separates. */ function fitChroma(l: number, h: number, asked: number): number { if (inGamut(l, h, asked)) return asked; let lo = 0; let hi = asked; for (let i = 0; i < 16; i++) { const mid = (lo + hi) / 2; if (inGamut(l, h, mid)) lo = mid; else hi = mid; } return lo; } /** * A lightness inside [min, max] whose contrast is inside the band, keeping the direction * it was sent: a dim that is too faint to serve as a border is lifted, one that has * become the accent again is dropped. */ function fitContrast( l: number, h: number, c: number, min: number, max: number, ground: Ground = DARK_GROUND, ): number { let value = Math.max(0.15, Math.min(0.95, l)); // The two walks are the accent's walk shrunk to a border's band, and they take their // direction from the ground the same way: a dim that is too faint to serve as a border // moves *toward* the ground's contrast direction (brighter on dark, darker on light), one // that has become the accent again moves back off it. const step = 0.02 * ground.contrastDirection; let guard = 0; while (guard++ < 40 && contrastOf(toRgb(value, fitChroma(value, h, c), h), ground.panel) < min) { value = Math.max(0.15, Math.min(0.95, value + step)); } guard = 0; while ( guard++ < 40 && contrastOf(toRgb(value, fitChroma(value, h, c), h), ground.panel) > max && value > 0.15 && value < 0.95 ) { value = Math.max(0.15, Math.min(0.95, value - step)); } return value; } function inGamut(l: number, h: number, c: number): boolean { return toRgb(l, c, h).every((v) => v > 0 && v < 255); } function toRgb(l: number, c: number, h: number): Rgb { return oklchToRgb(l, c, h); } /** * WCAG's ratio. The channels are sRGB 0–255, which is what colourthief's conversion hands * back and what `srgbToLinear` expects — the library's own `relativeLuminance` is node-only * in its entry points, so the two lines of weighting it adds live here instead. */ function contrastOf(fg: Rgb, bg: Rgb): number { const a = luminance(fg); const b = luminance(bg); return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05); } function luminance(rgb: Rgb): number { return ( LUMA[0] * srgbToLinear(rgb[0]) + LUMA[1] * srgbToLinear(rgb[1]) + LUMA[2] * srgbToLinear(rgb[2]) ); } /** * `color-mix(in oklab, tint amount%, base)`, for the grounds the accent is read against. * * Interpolated in OkLab rather than in channels because that is what the browser does to * the rule in App.css, and the two do not agree: a channel mix of the house green into * `--panel` at 34% lands at rgb(26,68,32) and the real wash at rgb(29,59,32) — a ground * bright enough to change which side of the contrast floor an accent falls on. Checking * the mix this module would rather not have to make, against the colour the browser will * actually paint, is how a legibility floor stops meaning anything. */ function mix(base: Rgb, tint: Rgb, amount: number): Rgb { const from = toOklab(rgbToOklch(...base)); const to = toOklab(rgbToOklch(...tint)); const o = toOklch([ from[0] + (to[0] - from[0]) * amount, from[1] + (to[1] - from[1]) * amount, from[2] + (to[2] - from[2]) * amount, ]); return oklchToRgb(o.l, o.c, o.h < 0 ? o.h + 360 : o.h); } /** Oklab's Cartesian axes — the space `color-mix` interpolates, not polar chroma and hue. */ function toOklab(o: Oklch): [number, number, number] { const r = (o.h * Math.PI) / 180; return [o.l, o.c * Math.cos(r), o.c * Math.sin(r)]; } function toOklch(lab: [number, number, number]): Oklch { return { l: lab[0], c: Math.hypot(lab[1], lab[2]), h: (Math.atan2(lab[2], lab[1]) * 180) / Math.PI, }; } function hexOf(rgb: Rgb): string { return `#${rgb.map((v) => v.toString(16).padStart(2, "0")).join("")}`; } // --------------------------------------------------------------------------- // The house pair, per theme // --------------------------------------------------------------------------- /** * The house green expressed as a cover would hand it over: the hue and chroma of the * `#3fb950` App.css and the `@property` initial value both spell, at the lightness a sleeve * would actually carry it. Only the hue and chroma are read back out of `deriveAccent`; * the lightness here is a starting point the walk from the ground overwrites. */ const HOUSE_SWATCH: Swatch = { oklch: () => rgbToOklch(0x3f, 0xb9, 0x50), proportion: 0.3, }; const HOUSE_WALL: Swatch = { oklch: () => ({ l: 0.99, c: 0.004, h: 250 }), proportion: 0.6, }; /** * The light theme's house pair, and the fallback when nothing has been derived. * * The dark house green is ink at `oklch(0.695 …)` — bright, because it is drawn on a * near-black ground. On a white panel the same green is a watermark, not ink: it fails the * floor this whole file exists to hold. So the light default is the *same* hue taken down to * the lightness that reads as ink on a light ground — derived, not guessed, through the very * walk a real accent goes down, so the fallback obeys the same legibility floor a record's * colour is made to. `DEFAULT_ACCENT` is kept as the literal `#3fb950` rather than being * recomputed, because that hex is what App.css spells and a fallback drifted from the * stylesheet's would be a second house green nobody painted; the light pair has no such * literal to agree with, so it is allowed to be computed here. */ export const DEFAULT_ACCENT_LIGHT: AccentTokens = deriveAccent( { color: HOUSE_SWATCH, wall: HOUSE_WALL }, "light", ).tokens; /** The house pair to wear when nothing has been derived, by theme. */ export const DEFAULT_ACCENTS: Record = { dark: DEFAULT_ACCENT, light: DEFAULT_ACCENT_LIGHT, }; /** The house pair for one theme — the accent before a record has earned one. */ export function defaultAccent(theme: Theme): AccentTokens { return DEFAULT_ACCENTS[theme]; }