import { describe, expect, it } from "vitest"; import { oklchToRgb, rgbToOklch } from "colorthief/internals"; import { DEFAULT_ACCENT, DEFAULT_ACCENT_LIGHT, deriveAccent, explainPalette, pickAccent, tonalAccent, type Swatch, } from "./accent"; /** * The choice, without a cover. * * colourthief's quantizer gets its own tests somewhere near the pixels; what matters * here is the argument above them — that the wall does not win, that a colour with no * hue to lend is refused, that the two hues the seek bar is drawn in cannot become the * accent, and that what survives comes back at the app's lightness rather than the * photograph's. So the inputs are numbers: an oklch and a share of the cover, which is * exactly the shape a colourthief Color has. */ const swatch = (l: number, c: number, h: number, proportion: number): Swatch => ({ oklch: () => ({ l, c, h }), proportion, }); const contrastOn = (hex: string, bg: [number, number, number]): number => { const rgb = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16)) as [number, number, number]; const lin = (v: number) => { const s = v / 255; return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4; }; const lum = (c: [number, number, number]) => 0.2126 * lin(c[0]) + 0.7152 * lin(c[1]) + 0.0722 * lin(c[2]); const a = lum(rgb); const b = lum(bg); return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05); }; const PANEL: [number, number, number] = [7, 7, 8]; // The light theme's ground: the whiter of its two near-whites (the panel), the surface that // gives a dark ink the least room. The floor is met against the tightest ground so it is met // on every light surface. const PANEL_LIGHT: [number, number, number] = [255, 255, 255]; /** The typing wash on the light panel: 18% of the ink mixed into white, in OkLab. Matches * LIGHT_GROUND.wash in accent.ts and App.css's light `[data-typing]` rule. */ const washOfLight = (hex: string): [number, number, number] => { const lab = (o: { l: number; c: number; h: number }) => { const r = (o.h * Math.PI) / 180; return [o.l, o.c * Math.cos(r), o.c * Math.sin(r)] as [number, number, number]; }; const rgb = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16)) as [number, number, number]; const from = lab(rgbToOklch(...PANEL_LIGHT)); const to = lab(rgbToOklch(...rgb)); const l = from[0] + (to[0] - from[0]) * 0.18; const a = from[1] + (to[1] - from[1]) * 0.18; const b = from[2] + (to[2] - from[2]) * 0.18; return oklchToRgb( l, Math.hypot(a, b), ((((Math.atan2(b, a) * 180) / Math.PI) % 360) + 360) % 360, ); }; /** * The typing wash, modelled the way the browser mixes it. * * A channel blend is not a stand-in for `color-mix(in oklab, …)` here: the two disagree * by enough to move which side of the floor a hue falls on, so the assertion would be * checking the derivation against a ground nobody paints. */ const washOf = (hex: string): [number, number, number] => { const lab = (o: { l: number; c: number; h: number }) => { const r = (o.h * Math.PI) / 180; return [o.l, o.c * Math.cos(r), o.c * Math.sin(r)] as [number, number, number]; }; const rgb = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16)) as [number, number, number]; const from = lab(rgbToOklch(...PANEL)); const to = lab(rgbToOklch(...rgb)); const l = from[0] + (to[0] - from[0]) * 0.34; const a = from[1] + (to[1] - from[1]) * 0.34; const b = from[2] + (to[2] - from[2]) * 0.34; return oklchToRgb( l, Math.hypot(a, b), ((((Math.atan2(b, a) * 180) / Math.PI) % 360) + 360) % 360, ); }; describe("pickAccent", () => { it("lets the rare colour that was put there on purpose beat the wall", () => { // A cover that is 62% dark blue-grey, with a vermilion print over 3% of it: measured // linearly, the wall wins every time, and the app paints itself in the colour of a // photograph's background. const wall = swatch(0.22, 0.04, 250, 0.62); const print = swatch(0.64, 0.19, 41, 0.03); expect(pickAccent([wall, print])?.color).toBe(print); }); it("demotes the wall's own family without refusing it", () => { // The wall and three neighbours of it, plus one colour that is actually different: // the neighbours are worth an eighth of what a real candidate is, so the print wins // by a mile. const wall = swatch(0.47, 0.175, 25, 0.17); const neighbours = [swatch(0.52, 0.182, 28, 0.055), swatch(0.52, 0.195, 24, 0.099)]; const print = swatch(0.66, 0.15, 200, 0.02); expect(pickAccent([wall, ...neighbours, print])?.color).toBe(print); }); it("still lets a single-colour sleeve speak for itself", () => { // The reason the wall gate demotes rather than refuses: a sleeve that is one colour // once the white has been discarded has the wall as its only offer, and refusing it // would answer "an all-red record" with the app's own green. const wall = swatch(0.47, 0.175, 25, 0.17); const neighbour = swatch(0.52, 0.182, 28, 0.055); expect(pickAccent([wall, neighbour])?.color).toBe(neighbour); }); it("splits an all-red record between its red and its black", () => { // Fifty-fifty, exactly: the black half has no hue to lend and the red half is the // wall, so this is the cover where the picker looks most like it is guessing. It is // not — the red is the only chromatic thing on the sleeve and it is allowed to say // so, and what keeps that from being "the app wears the background" is that the // colour arrives at the app's lightness rather than the sleeve's. const black = swatch(0.15, 0.01, 250, 0.5); const red = swatch(0.5, 0.2, 28, 0.5); expect(pickAccent([black, red])?.color).toBe(red); }); it("refuses a cover with no hue in it", () => { // Black-and-white photography: every box the quantizer returns is a grey, and a grey // accent is --text-muted wearing the accent's job. Null here is what keeps the house // pair on screen. const greys = [swatch(0.47, 0.006, 286, 0.09), swatch(0.28, 0.005, 286, 0.075)]; expect(pickAccent(greys)).toBeNull(); }); it("refuses the two hues the seek bar is drawn in", () => { // The A–B region and the detector's boundary are laid over the accent's own fill, so // a record that is nothing but the region's gold would draw the part of the bar that // says "you are in a loop" in the colour of the bar underneath it. const loopInk = swatch(0.79, 0.139, 85.1, 0.5); const detectedInk = swatch(0.79, 0.115, 246.7, 0.4); expect(pickAccent([loopInk, detectedInk])).toBeNull(); // …and its dim siblings are the same hues, so they are refused with them. expect(pickAccent([swatch(0.504, 0.102, 81.3, 0.5)])).toBeNull(); expect(pickAccent([swatch(0.445, 0.061, 245, 0.5)])).toBeNull(); }); it("keeps the neighbourhood of the house hue rather than refusing it", () => { // The green the app has always worn is not anywhere near the two inks, so the most // likely accent in the world stays available — including in the same hue family. const green = swatch(0.695, 0.181, 146, 0.3); expect(pickAccent([green])?.color).toBe(green); // A hue just clear of the gold's tolerance is a different colour and says so. const yellow = swatch(0.75, 0.15, 118, 0.3); expect(pickAccent([yellow])?.color).toBe(yellow); }); it("asks nothing of a palette that is not there", () => { expect(pickAccent([])).toBeNull(); }); it("refuses a colour too small to be on the sleeve at all", () => { // A speck of JPEG ringing beats nothing, because nothing else is competing: without // this floor a single artefact on a 96px cover decides the theme. const wall = swatch(0.2, 0.01, 250, 0.9); const speck = swatch(0.72, 0.22, 300, 0.004); expect(pickAccent([wall, speck])).toBeNull(); }); it("wears a thin saturated wordmark over a dull majority — if it clears the floor", () => { // The `Whole Lotta Red` regression: a ~3% red wordmark on a black-and-white sleeve. // Read off the real master the red clears `MIN_POPULATION` and wins over the largest // dull colour (an 8% brown); the bar goes red. Read off a thumbnail small enough to // crush the same wordmark under 1%, it is a speck and the brown is all that is left. // The floor is correct and the size is the lever — this pins which is which. const black = swatch(0.0, 0.0, 0, 0.5); const brown = swatch(0.44, 0.075, 57, 0.081); const redAbove = swatch(0.58, 0.152, 17, 0.029); expect(pickAccent([black, brown, redAbove])?.color).toBe(redAbove); const redBelow = swatch(0.58, 0.152, 17, 0.006); expect(pickAccent([black, brown, redBelow])?.color).toBe(brown); }); it("chooses by population, not by position in the palette", () => { // colourthief's short-circuit path returns swatches in first-seen order, so the wall // is not reliably palette[0] — and the whole rule hangs on knowing which one is. const print = swatch(0.72, 0.22, 200, 0.05); const wall = swatch(0.3, 0.09, 140, 0.6); expect(pickAccent([print, wall])?.wall).toBe(wall); expect(pickAccent([wall, print])?.wall).toBe(wall); }); it("lets a whole wheel of hues through, minus the two the bar is drawn in", () => { // The gate that protects the region must not be a gate that protects the app from // its own feature: measured at a typical accent chroma, only two arcs of the wheel // are refused at all, and they are the two the seek bar uses. const refused: number[] = []; for (let h = 0; h < 360; h++) { const alone = swatch(0.66, 0.16, h, 0.3); if (!pickAccent([alone])) refused.push(h); } expect(refused.length).toBeLessThanOrEqual(80); // …and the two inks' own hues are among them, which is the point of the exercise. expect(refused).toContain(85); expect(refused).toContain(247); }); }); describe("deriveAccent", () => { it("keeps the hue and takes the lightness", () => { // The contract in one assertion: the record lends its hue and its chroma, and the // app supplies the lightness it already knew was legible. const dark = swatch(0.2, 0.15, 250, 0.05); const recipe = deriveAccent({ color: dark, wall: swatch(0.15, 0.01, 200, 0.6) }); const rgb = oklchToRgb(0.0, 0, 0); // keep the import honest before the real read below expect(rgb).toHaveLength(3); const [r, g, b] = [1, 3, 5].map((i) => parseInt(recipe.tokens.accent.slice(i, i + 2), 16)) as [ number, number, number, ]; const painted = rgbToOklch(r, g, b); expect(Math.abs(((painted.h - 250 + 540) % 360) - 180)).toBeLessThan(6); expect(painted.l).toBeGreaterThanOrEqual(0.69); expect(painted.c).toBeLessThanOrEqual(0.15 + 0.01); }); it("never hands back ink nobody can read at 11px", () => { // Swept rather than sampled: the floor has to hold for every hue the picker can // return, including the yellows and cyans that sit brightest at a given lightness // and would otherwise be the ones that fail. for (let h = 0; h < 360; h += 10) { for (const c of [0.04, 0.12, 0.2, 0.3]) { const recipe = deriveAccent({ color: swatch(0.25, c, h, 0.05), wall: swatch(0.12, 0.01, 200, 0.6), }); expect(contrastOn(recipe.tokens.accent, PANEL), `${h}@${c} panel`).toBeGreaterThanOrEqual( 4.5, ); expect( contrastOn(recipe.tokens.accent, washOf(recipe.tokens.accent)), `${h}@${c} wash`, ).toBeGreaterThanOrEqual(4.5); } } }); it("trims a colour to what sRGB can show rather than clipping it", () => { // Clipping is not a quieter failure than trimming: an ochre pushed past the gamut // arrives as an olive, which is a different colour and a misquote of the sleeve. const outOfGamut = swatch(0.72, 0.34, 130, 0.05); const recipe = deriveAccent({ color: outOfGamut, wall: swatch(0.12, 0.01, 200, 0.6) }); const [r, g, b] = [1, 3, 5].map((i) => parseInt(recipe.tokens.accent.slice(i, i + 2), 16)) as [ number, number, number, ]; expect([r, g, b]).not.toContain(255); expect([r, g, b]).not.toContain(0); const painted = rgbToOklch(r, g, b); expect(painted.c).toBeLessThan(0.34); expect(Math.abs(((painted.h - 130 + 540) % 360) - 180)).toBeLessThan(8); }); it("keeps the dim a border rather than a second accent", () => { // The dim is a focus ring and a selected-row edge: too faint and the control has no // edge, too strong and the screen has two competing accents at once. for (let h = 0; h < 360; h += 20) { const recipe = deriveAccent({ color: swatch(0.3, 0.2, h, 0.05), wall: swatch(0.12, 0.01, 200, 0.6), }); const c = contrastOn(recipe.tokens.dim, PANEL); expect(c, `${h} dim ${recipe.tokens.dim}`).toBeGreaterThanOrEqual(2.2); expect(c, `${h} dim ${recipe.tokens.dim}`).toBeLessThanOrEqual(4.5); } }); it("speaks CSS", () => { const recipe = deriveAccent({ color: swatch(0.6, 0.18, 320, 0.05), wall: swatch(0.12, 0.01, 200, 0.6), }); for (const value of Object.values(recipe.tokens)) { expect(value).toMatch(/^#[0-9a-f]{6}$/); } expect(DEFAULT_ACCENT.accent).toMatch(/^#[0-9a-f]{6}$/); }); it("never hands back ink nobody can read at 11px on a light ground either", () => { // The inversion the whole theme-aware derivation exists for: on white, contrast is // bought by darkening the ink, not brightening it, so the walk goes the other way and // the floor has to hold for every hue the picker can return just as it does on black. // This is the assertion that fails if the light ground quietly reuses the dark walk — a // bright ink on a light panel would sail through the code and be invisible. for (let h = 0; h < 360; h += 10) { for (const c of [0.04, 0.12, 0.2, 0.3]) { const recipe = deriveAccent( { color: swatch(0.75, c, h, 0.05), wall: swatch(0.95, 0.01, 250, 0.6) }, "light", ); expect( contrastOn(recipe.tokens.accent, PANEL_LIGHT), `${h}@${c} panel`, ).toBeGreaterThanOrEqual(4.5); expect( contrastOn(recipe.tokens.accent, washOfLight(recipe.tokens.accent)), `${h}@${c} wash`, ).toBeGreaterThanOrEqual(4.5); } } }); it("keeps the light accent dark, where the dark one is bright", () => { // One record, both grounds: the same hue and chroma at opposite ends of the lightness // range, because "ink" means the opposite thing on each. If these two came back near // each other, the ground was not actually being honoured. const from = swatch(0.7, 0.18, 20, 0.05); const wall = swatch(0.2, 0.01, 250, 0.6); const darkHex = deriveAccent({ color: from, wall }).tokens.accent; const [dr, dg, db] = [1, 3, 5].map((i) => parseInt(darkHex.slice(i, i + 2), 16)); const dark = rgbToOklch(dr, dg, db); const lightHex = deriveAccent({ color: from, wall }, "light").tokens.accent; const [lr, lg, lb] = [1, 3, 5].map((i) => parseInt(lightHex.slice(i, i + 2), 16)); const light = rgbToOklch(lr, lg, lb); expect(light.l, "the light ink is markedly darker than the dark one").toBeLessThan( dark.l - 0.1, ); // …and it kept the record's hue, which is the half the record is allowed to choose. expect(Math.abs(((light.h - 20 + 540) % 360) - 180)).toBeLessThan(8); }); it("keeps the dim a border rather than a second accent on the light ground too", () => { // The dim lands on the ground's own side of the ink either way — a shadow below a bright // ink, a lighter edge above a dark one — and stays in the same contrast band. for (let h = 0; h < 360; h += 20) { const recipe = deriveAccent( { color: swatch(0.7, 0.2, h, 0.05), wall: swatch(0.95, 0.01, 250, 0.6) }, "light", ); const c = contrastOn(recipe.tokens.dim, PANEL_LIGHT); expect(c, `${h} dim ${recipe.tokens.dim}`).toBeGreaterThanOrEqual(2.2); expect(c, `${h} dim ${recipe.tokens.dim}`).toBeLessThanOrEqual(4.5); } }); }); describe("the light house pair", () => { it("is legible on the light panel, and reads as the house green worn as ink", () => { // The fallback before any record has earned one must obey the floor too, so it is // derived through the same walk rather than guessed as a hex — and it is the house hue, // not a new colour, taken down to the lightness that reads on white. expect(contrastOn(DEFAULT_ACCENT_LIGHT.accent, PANEL_LIGHT)).toBeGreaterThanOrEqual(4.5); expect( contrastOn(DEFAULT_ACCENT_LIGHT.accent, washOfLight(DEFAULT_ACCENT_LIGHT.accent)), ).toBeGreaterThanOrEqual(4.5); const [r, g, b] = [1, 3, 5].map((i) => parseInt(DEFAULT_ACCENT_LIGHT.accent.slice(i, i + 2), 16), ); const o = rgbToOklch(r, g, b); expect(Math.abs(((o.h - 146 + 540) % 360) - 180), "still the house green").toBeLessThan(8); expect(o.l, "…worn as dark ink").toBeLessThan(0.695); expect(DEFAULT_ACCENT_LIGHT.accent).not.toBe(DEFAULT_ACCENT.accent); }); }); describe("tonalAccent", () => { /** * A black-and-white sleeve: every swatch under the chroma floor, and a cool print * photographed through all of them. This is the case the second pass exists for — the * record is a photograph of a road in fog, the listener chose it, and the bar used to * go house green on the grounds that a grey is not an ink. Correct about the grey, and * done too early: it never asked what the grey was shot through. */ const COOL_PRINT: Swatch[] = [ swatch(0.12, 0.008, 255, 0.55), swatch(0.55, 0.012, 250, 0.3), swatch(0.9, 0.004, 245, 0.1), ]; it("refuses the greys, and then wears them", () => { // The two passes have to disagree in exactly this way, or one of them is redundant: // the chromatic picker still says no — a grey is not an ink and never will be — and // the tonal one says yes to the temperature underneath the greys. expect(pickAccent(COOL_PRINT)).toBeNull(); const pick = tonalAccent(COOL_PRINT); expect(pick).not.toBeNull(); const o = pick!.color.oklch(); expect(Math.abs(o.h - 251)).toBeLessThan(8); expect(o.c).toBeGreaterThanOrEqual(0.03); // The wall survives the second pass, because the accent still has to not be it. expect(pick!.wall.proportion).toBe(0.55); }); it("pays the same contrast rent as a colour the cover actually had", () => { // The one path that adds saturation the pixels never contained is the one most // likely to hand back something nobody can read at 11px — so it goes through the // same derivation, which is where legibility is bought rather than assumed. const recipe = deriveAccent(tonalAccent(COOL_PRINT)!); expect(contrastOn(recipe.tokens.accent, PANEL)).toBeGreaterThanOrEqual(4.5); expect(contrastOn(recipe.tokens.accent, washOf(recipe.tokens.accent))).toBeGreaterThanOrEqual( 4.5, ); }); it("invents nothing when the print has no temperature", () => { // A flat grey, a pure black sleeve, a scanned page: there is no hue in any of them, // and a hue averaged out of c=0.0002 is a coin flip with a decimal point on it. The // house green means "this record had nothing to say", which is the true answer. const FLAT: Swatch[] = [swatch(0.15, 0.0002, 250, 0.6), swatch(0.85, 0.0002, 90, 0.3)]; expect(tonalAccent(FLAT)).toBeNull(); expect(tonalAccent([])).toBeNull(); }); it("asks the cover rather than its smallest box what the print was shot through", () => { // Most of the page points cool; a 2% box points warm with four times the chroma. // Weighted by chroma × share the field answers and the speck does not get a vote it // cannot pay for — otherwise one JPEG artefact themes the app. const print: Swatch[] = [swatch(0.2, 0.006, 250, 0.9), swatch(0.6, 0.05, 40, 0.02)]; expect(Math.abs(tonalAccent(print)!.color.oklch().h - 250)).toBeLessThan(15); }); it("caps a tint that has stopped being a tint", () => { // Past a faint bias this is no longer a greyscale with a temperature: it is a // strongly-coloured cover, and the answer is the cap rather than a refusal — the // accent stays a third of the saturation the print has, which is also what keeps it // out of the neighbourhood of the two hues the seek bar draws its signals in. The // hue is still the print's; it is only ever the loudness that is the app's. const strong: Swatch[] = [swatch(0.2, 0.022, 247, 0.7), swatch(0.6, 0.024, 250, 0.25)]; const pick = tonalAccent(strong)!; expect(pick.color.oklch().c).toBeLessThanOrEqual(0.07); expect(Math.abs(pick.color.oklch().h - 248)).toBeLessThan(6); }); it("wears the mostly-white sleeve too — the case the floor was set for", () => { // The white itself is gone before this module sees it (`ignoreWhite`, because the // white of a product shot is the largest colour on most covers and the least // interesting thing about them), so what is left to measure is the lettering's greys // and the shadow under the type: a whisper of warm bias, measuring c=0.0032, which a // floor of 0.004 discarded. const WHITE_PRINT: Swatch[] = [ swatch(0.95, 0.003, 70, 0.55), swatch(0.35, 0.004, 65, 0.12), swatch(0.6, 0.002, 60, 0.05), ]; const pick = tonalAccent(WHITE_PRINT)!; expect(Math.abs(pick.color.oklch().h - 68)).toBeLessThan(8); expect(pick.color.oklch().c).toBeGreaterThanOrEqual(0.03); }); it("says which floor the sleeve fell at, and by how much", () => { // The silence this module's worst failure hides behind: four different verdicts used // to share one sentence — greys, specks, ink-collisions, nothing at all — and only // the listener can say which floor was too high. So the line counts the floors, names // the swatch that came closest with the numbers it fell short by, and quotes the // measured temperature beside the floor that discarded it. const greys: Swatch[] = [swatch(0.2, 0.0004, 250, 0.6), swatch(0.68, 0.0006, 300, 0.22)]; const line = explainPalette(greys); expect(line).toContain("2 colours: 2 too grey to wear"); expect(line).toContain("nearest miss oklch(0.68 0.001 300) at 22.0% of the cover"); expect(line).toMatch(/no temperature to take: measured c=0\.\d+ at h \d+/); expect(line).toContain("0.002 needed to believe it"); expect(explainPalette(COOL_PRINT)).toContain("print temperature c=0.010 at h 25"); expect(explainPalette([])).toContain("quantized to nothing at all"); }); });