@sdxc/color
Immutable CSS colors: parse every CSS color syntax, convert through OKLCH, gamut-map, mix, build scales and measure WCAG contrast
- Installs with
- @sdxc/result
- Source
- packages/color
Immutable CSS colors: parse every CSS color syntax, convert through OKLCH, gamut-map, mix, build scales and measure WCAG contrast.
Installation
npm add @sdxc/color @sdxc/resultColor.parse and ensureContrast answer a @sdxc/result Result. The package has no other dependency and runs in Workers, browsers and Node.
Usage
Parse and print
Color.parse reads any CSS color, including what getComputedStyle returns, and never throws. toString() prints rgb() inside sRGB and oklch() outside it, so ${color} is always valid CSS.
import { Color } from "@sdxc/color";
import { isSuccess } from "@sdxc/result";
let result = Color.parse("oklch(0.62 0.19 260)");
if (isSuccess(result)) {
let brand = result.data;
brand.toString(); // "rgb(57.75 128.67 246.1)"
brand.toString("hex"); // "#3a81f6"
}Adjust in OKLCH
Every operation answers a new Color. darken(0.1) is 10% darker in OKLCH lightness, keeping hue and chroma.
let hover = brand.darken(0.1);
let muted = brand.desaturate(0.5).withAlpha(0.6);
let accent = brand.with({ hue: 30 });Check contrast
contrast paints a translucent foreground over the background (and a translucent background over white) before measuring with WCAG 2.1.
let text = Color.rgb(0.47, 0.47, 0.47);
let page = Color.rgb(1, 1, 1);
text.contrast(page).ratio; // 4.42
text.contrast(page).aa.text; // false
let fixed = text.ensureContrast(page, 4.5); // Success: rgb(118.66 118.66 118.66)
page.contrastingText(); // blackMix and build scales
Interpolation follows CSS color-mix(): Oklab by default, premultiplied alpha, and a hue arc in OKLCH.
let red = Color.rgb(1, 0, 0);
let blue = Color.rgb(0, 0, 1);
red.mix(blue); // rgb(140.36 83.03 162.31), as color-mix(in oklab, red, blue)
red.mix(blue, 0.25, { space: "oklch", hue: "longer" });
let heat = Color.scale([blue, Color.rgb(1, 1, 0), red]);
heat(0.5); // yellow
Color.steps([red, blue], 5); // 5 colors, both ends includedAPI
Color
A frozen value storing sRGB as unclamped floats (extended sRGB) plus alpha, so a wide-gamut color from oklch() or color(display-p3 …) survives losslessly. An authored hue on a gray and none components do not survive: a gray reads back with hue 0 and none reads as 0.
Creating
Color.parse(input): hex, named colors,transparent,rgb(),hsl(),hwb(),lab(),lch(),oklab(),oklch()andcolor()insrgb,srgb-linear,display-p3,a98-rgb,rec2020,prophoto-rgbandxyz/xyz-d50/xyz-d65; aColorParseErrorotherwise (includingcurrentcolorand relative colors)Color.rgb(r, g, b, alpha?): sRGB channels 0–1, unclampedColor.hsl(h, s, l, alpha?)andColor.hwb(h, w, b, alpha?): hue in degrees, the rest 0–1Color.oklab(l, a, b, alpha?)andColor.oklch(l, c, h, alpha?): lightness 0–1, hue in degrees
Alpha defaults to 1 and is clamped to 0–1; a non-finite number reads as 0.
Reading
toString(format?):"hex","rgb"and"hsl"gamut-map first;"srgb"(color(srgb …)),"oklch"and"oklab"are losslesstoRgb(),toHsl(),toOklab(),toOklch(): plain objects withalpha;toHsl()is gamut-mappedalpha,equals(other, epsilon = 1e-6),inGamut()toGamut(): CSS Color 4 gamut mapping, lowering OKLCH chroma until the color fits sRGB
Operations
over(background): source-over compositing in sRGB, as browsers paintmix(other, amount = 0.5, { space, hue }):amountis the share ofother;spaceis"oklab"(default),"oklch"or"srgb";hueis"shorter"(default),"longer","increasing"or"decreasing"withAlpha(alpha),fade(factor)lighten(n),darken(n): OKLCH lightness × (1 ± n), clamped to 0–1saturate(n),desaturate(n): OKLCH chroma × (1 ± n)rotate(degrees),complement(),grayscale(),invert()with({ lightness, chroma, hue, alpha }): exact OKLCH values
Operations do not gamut-map, so a result may leave sRGB; call toGamut() when it must fit.
Contrast
contrast(background, algorithm = "WCAG21")andColor.contrast(foreground, background): aWcagContrastwithratio,aa.text(4.5),aa.largeText(3),aa.nonText(3),aaa.text(7) andaaa.largeText(4.5). Both colors are gamut-mapped before measuringensureContrast(background, ratio): the closest color reachingratioby changing only OKLCH lightness, or aContrastUnreachableErrorwhosebestis the most contrasting lightness extremecontrastingText(): black or white, whichever contrasts more
Scales
Color.scale(colors, options?): a function fromtin 0–1 to a color, evenly spaced acrosscolorsColor.steps(colors, count, options?):countcolors along that scale, both ends included
Errors
ColorParseError:inputholds the rejected textContrastUnreachableError:target, the bestratioreached and thebestcolor
Pattern: Theming A Page From A Chosen Color
A Worker serves a stylesheet built from the accent a visitor picked. An unreadable value falls back to a default, links are darkened until they pass AA on white, and text on the accent is whichever of black or white reads better.
import { Color } from "@sdxc/color";
import { unwrap } from "@sdxc/result";
function themeStylesheet(accentText: string | null): string {
let accent = unwrap(Color.parse(accentText ?? ""), () => Color.oklch(0.55, 0.15, 260)).toGamut();
let page = Color.rgb(1, 1, 1);
let link = accent.ensureContrast(page, 4.5);
return `:root {
--accent: ${accent.toString()};
--accent-hover: ${accent.darken(0.1).toGamut().toString()};
--on-accent: ${accent.contrastingText().toString()};
--link: ${(link.status === "success" ? link.data : link.error.best).toString()};
}`;
}
export default {
async fetch(request: Request): Promise<Response> {
let accent = new URL(request.url).searchParams.get("accent");
return new Response(themeStylesheet(accent), { headers: { "Content-Type": "text/css" } });
},
};Pattern: Validating A Submitted Color
A settings form accepts any CSS color, rejects text that is not one, requires the color to stand out on white as a UI part (WCAG 1.4.11), and stores it as hex.
import { Color } from "@sdxc/color";
import { isFailure } from "@sdxc/result";
async function saveBrandColor(request: Request): Promise<Response> {
let form = await request.formData();
let parsed = Color.parse(String(form.get("color") ?? ""));
if (isFailure(parsed)) return Response.json({ error: parsed.error.message }, { status: 422 });
let color = parsed.data.toGamut();
if (!color.contrast(Color.rgb(1, 1, 1)).aa.nonText) {
return Response.json({ error: "Pick a color that stands out on white" }, { status: 422 });
}
return Response.json({ color: color.toString("hex") });
}Pattern: Finding Low-Contrast Text On A Rendered Page
In the browser, getComputedStyle answers every color in a syntax Color.parse reads, color-mix() results included. A transparent background shows its ancestors through, so the backdrop is every translucent layer up to the first opaque one, painted over the white canvas.
import { Color } from "@sdxc/color";
import { isSuccess } from "@sdxc/result";
function backdropOf(element: Element): Color {
let layers: Color[] = [];
for (let node: Element | null = element; node !== null; node = node.parentElement) {
let parsed = Color.parse(getComputedStyle(node).backgroundColor);
if (!isSuccess(parsed) || parsed.data.alpha === 0) continue;
layers.push(parsed.data);
if (parsed.data.alpha === 1) break;
}
return layers.reduceRight((below, layer) => layer.over(below), Color.rgb(1, 1, 1));
}
function lowContrastText(root: ParentNode): Element[] {
return [...root.querySelectorAll("p, a, li, label, button")].filter((element) => {
let text = Color.parse(getComputedStyle(element).color);
return isSuccess(text) && !text.data.contrast(backdropOf(element)).aa.text;
});
}