# Colore JS > colore-js is a TypeScript color library and CLI: CSS Color 4 parsing, OKLCH-based manipulation, WCAG 2 and APCA contrast with minimal-change repair, CSS Color 4 gamut mapping, and accessible light/dark design systems exported as shadcn/ui, Tailwind v4, CSS variables or DTCG tokens. Package `colore-js` on npm. These docs cover v2.0.1: `npm install colore-js` or `yarn add colore-js`. Legacy 1.x docs live under https://colorejs.dev/docs/1.4.4/introduction. Not the Color.js library (`colorjs.io`). Entry points: - `colore-js`: the fluent `Color` class (`colore(input)` or `new Color(input)`), parsing, validation, `generateSystem`, `audit`, `auditCssVariables`, `fixCssVariables`, `ensureContrast`. - `colore-js/fn`: tree-shakable standalone functions (`lighten`, `mix`, `contrastRatio`, `palette`, `categoricalColors`, …). - `npx colore-js inspect|theme|adjust|set|extract|preview|check|audit|fix|init`: CLI for reading a project's theme, rebranding and adjusting it in place, checking, auditing and fixing contrast, and installing the Colore agent skill (`init`). Every command takes `--json`; edits are dry runs until `--write`. Conventions that differ from other color libraries: - `/fn` functions that return a color return a CSS string: hex when the color fits sRGB, otherwise `color(display-p3 …)` or `oklch(…)`. `toHex` clips explicitly. - `contrastRatio` returns a number (WCAG 2 ratio, 1–21) and `contrastAPCA` returns the Lc magnitude (0–108). - `isReadable`, `ensureContrast` and `generateStates` take the same target options: `algorithm: 'wcag2' | 'apca'`, `level: 'aa' | 'aaa'`, `intent: 'text' | 'largeText' | 'ui' | 'focus' | 'decorative'`, or an explicit `target`. `generateSystem`, `audit`, `auditCssVariables` and `fixCssVariables` take `algorithm` and `level`, and `categoricalColors` takes `algorithm`, `level` and `target`. `contrastRatio`, `contrastAPCA` and `bestTextColor` take no options: `bestTextColor` picks by APCA from an optional list of candidates. - Percent amounts are 0–100 (`lighten(c, 10)` is 10%). Ratios (`mix`, `interpolate`) are 0–1. - Untagged `{ r, g, b }` objects are 0–255. `{ space: 'srgb', r, g, b }` is 0–1, like CSS `color(srgb …)` and Figma. Object outputs use `alpha`. - Unknown options and out-of-range inputs throw a `ColorError` that names the fix instead of returning a guessed color. - `generateSystem(brand)` keeps the brand color as the primary when it passes contrast (`preserveSeed` defaults to true). --- # Introduction Colore (`colore-js` on npm) is a TypeScript color library for people who build interfaces. It does the everyday work (parsing, converting, mixing and lightening) in OKLCH, so results look the way you expect. And it handles the hard parts most libraries leave to you: text that stays readable, and complete light and dark themes from one brand color. ```bash npm install colore-js ``` ```bash yarn add colore-js ``` ## What it looks like ```ts import { colore, ensureContrast, generateSystem } from 'colore-js'; colore('#0f766e').oklch(); // 'oklch(0.51094 0.08606 186.39)' colore('#0f766e').mix('#f59e0b', 0.5, 'oklch').hex(); // '#759a41' // This gray is too light to pass on white. ensureContrast('#9ca3af', '#ffffff').color.hex(); // '#717782' generateSystem('#0f766e').toShadcnCss(); ``` ## What you get - Parse modern CSS colors: hex, `rgb()`, `hsl()`, `hwb()`, Lab, LCH, OKLab, OKLCH, Display P3 and `color-mix()`, with clear errors for anything invalid. - Lighten, darken, saturate, mix and build scales in OKLCH. Wide-gamut colors are never clipped by accident. - Check WCAG 2 and APCA contrast, repair a foreground that fails, simulate color blindness, and audit whole palettes and CSS files. - Generate light and dark themes from one brand color, with brand, surface, text, border, status and chart colors, exported as CSS variables, Tailwind CSS v4, shadcn/ui or design tokens. - Rebrand the theme you already have, add dark mode or make it warmer without rewriting the file. - Install the agent skill so Claude Code, Cursor and Codex compute colors with Colore instead of guessing them. - Zero dependencies, full TypeScript types, ESM and CommonJS, and tree-shakeable functions from `colore-js/fn`. ## Two ways to call it ```ts import { colore } from 'colore-js'; import { lighten } from 'colore-js/fn'; colore('#2563eb').lighten(8).hex(); // '#306ff8' lighten('#2563eb', 8); // '#306ff8' ``` Both give the same result. The functions return CSS strings and keep bundles small; the `Color` object is handy when you chain several steps. ## Built on the standards - [CSS Color Module Level 4](https://www.w3.org/TR/css-color-4/) for parsing, output and gamut mapping. - WCAG 2 contrast ratios for AA and AAA, and APCA, the draft perceptual contrast method. - The Design Tokens Format (DTCG 2025.10) for token export. ## Next steps - [Get started](https://colorejs.dev/docs/getting-started) in five minutes. - [Browse the API](https://colorejs.dev/docs/api/overview). - [Use Colore with a coding agent](https://colorejs.dev/docs/agents). - [Try the theme generator](https://colorejs.dev/playground) with your brand color. - Coming from another library? See [how they compare](https://colorejs.dev/docs/comparison), or the pages for [chroma.js](https://colorejs.dev/docs/comparison/chroma-js) and [tinycolor2](https://colorejs.dev/docs/comparison/tinycolor2). Source: https://colorejs.dev/docs/introduction --- # Get started Install Colore, then change a button color or check its contrast in a few lines of JavaScript or TypeScript. ## Install Colore ```bash npm install colore-js ``` ```bash yarn add colore-js ``` You need Node.js 20 or later to run the examples locally. ## Change a color and check its contrast ```ts import { colore } from 'colore-js'; const button = colore('#2563eb'); console.log(button.lighten(8).hex()); // '#306ff8' console.log(button.contrastRatio('#fff').toFixed(2)); // '5.17' ``` The lighter color is a new value. You can still use `button` for the default state. The second line measures the default blue against white, a ratio of about 5.17:1. ## Import one operation Use `colore-js/fn` if you need one operation and want the result as CSS. ```ts import { mix } from 'colore-js/fn'; console.log(mix('#ff0000', '#0000ff', 0.5, 'oklab')); // '#8c53a2' ``` `new Color(input)` creates the same kind of object as `colore(input)`. Either gives you methods for chaining several changes before you export. ## Related - [API reference](https://colorejs.dev/docs/api/overview) - [Check color contrast](https://colorejs.dev/docs/guides/check-color-contrast) - [Coding agents and CLI](https://colorejs.dev/docs/agents) for using Colore from your editor - [Theme generator](https://colorejs.dev/playground) to try a brand color before you write code - [How Colore compares](https://colorejs.dev/docs/comparison) if you're coming from another library, with pages for [chroma.js](https://colorejs.dev/docs/comparison/chroma-js) and [tinycolor2](https://colorejs.dev/docs/comparison/tinycolor2) Source: https://colorejs.dev/docs/getting-started --- # Coding agents and CLI The **Colore skill** lets you ask your coding agent for color changes in plain words. The agent uses the colore-js CLI to inspect your theme, compute colors, and check contrast in each theme mode. It can also move hard-coded component colors onto theme tokens so they follow the theme. ## Install the skill ```bash npx colore-js init ``` This copies the skill into `.agents/skills/colore` (read by Cursor, Codex and other Agent Skills clients) and `.claude/skills/colore` (Claude Code). With the [skills CLI](https://skills.sh) you can also run `npx skills add mallikcheripally/colore-js`. Try one of these requests in your coding agent. - "Rebrand the app to our logo" (attach or point to `logo.svg` / `logo.png`) - "Add dark mode" or "add chart colors" - "The gray text is hard to read" - "Make it feel warmer", "more premium", "less like every other AI app" - "Make the primary exactly #0f766e" For larger edits, the skill asks the agent to generate a before-and-after preview before writing changes. The agent finishes by running a contrast audit and reporting what changed and any issues that remain. ## CLI Run the same commands yourself or in CI. Commands that edit a stylesheet leave it on disk as-is until you pass `--write`. ```bash npx colore-js inspect npx colore-js theme "#0f766e" --apply app/globals.css --add --preview preview.html npx colore-js theme "#0f766e" --apply app/globals.css --add --write npx colore-js adjust app/globals.css --groups surfaces --hue 70 --chroma 0.008 --write npx colore-js audit app/globals.css ``` | Command | What it does | Exit code | | --- | --- | --- | | `inspect [dir]` | Finds the theme file and reports its format, modes, brand, missing tokens, contrast issues and hard-coded component colors with available token suggestions. | 0 | | `theme [brand] --apply ` | Applies generated colors to recognized shadcn/ui, Tailwind and plain CSS tokens in their existing formats. `--only ` narrows the edit. Omit the brand with `--add` to fill gaps using the existing brand. | 1 if contrast still fails | | `adjust ` | Moves colors in OKLCH for `--groups` or `--tokens`. A number sets a channel, a signed value shifts it, and `x` scales it. | 1 if contrast still fails | | `set =` | Sets tokens to exact colors in the file's format. | 1 if contrast still fails | | `extract ` | Extracts brand and neutral colors from an SVG or PNG. | 0 | | `preview ` | Generates an HTML preview of sample UI in light and dark. `--compare ` adds the previous theme. | 0 | | `theme ` | Generates a contrast-checked light and dark theme. Use `--format` to select an export. | 0 on success | | `check ` | Checks one color pair using WCAG 2 or APCA. For a failing pair, it suggests a passing foreground when available. | 1 on failure | | `audit ` | Checks inferred text/background pairs, such as `--x` / `--x-foreground`, and pairs passed with `--pair fg:bg`. | 1 on failure | | `fix ` | Rewrites only failing foreground values, keeping each value's format. Prints to stdout unless `--write`. | 1 if issues remain | | `init [dir]` | Installs the Colore skill for coding agents. | 0 | - `theme --apply --add` can add a missing dark block, `chart-1` through `chart-5`, and destructive tokens. Use `--only status` with `--add` to add success and warning tokens. - `adjust --groups` supports `surfaces`, `text`, `brand`, `accent`, `borders`, `status`, `charts` and `other`. - `theme --format` supports `shadcn` (the default, in OKLCH), `shadcn-hex`, `shadcn-hsl` (v3 bare HSL channels), `css`, `tailwind`, `json` and `dtcg`. - `check --intent` supports `text`, `largeText`, `ui` and `focus`. Select `--algorithm wcag2` or `--algorithm apca`, then use `--level aa`, `--level aaa`, or `--target `. Every command accepts `--json` for machine-readable output. Edit commands (`theme --apply`, `adjust`, `set`) repair contrast by default, accept `--no-fix` to skip repair, and can write a before-and-after page with `--preview `. ### The brand color stays the brand color `theme` keeps your brand color exactly as `--primary` when it meets the contrast target with white or black text, and picks a readable foreground. In a dark theme, the brand also needs enough contrast against dark surfaces. When Colore needs an accessible shade, it selects one from the generated scale. Use `--no-preserve-seed` to use the generated scale regardless of the seed's contrast. See [generateSystem](https://colorejs.dev/docs/api/system/generate-system) for details. ### Minimal-change fixes Fixes keep hue and move lightness only as far as needed: ```text $ npx colore-js check "#3b82f6" "#fff" #3b82f6 on #ffffff: 3.68:1 FAIL (text needs 4.5:1) Nearest passing: #2c72e5 (4.52:1) ``` When a foreground is paired with several backgrounds (for example `--muted-foreground` on both `--muted` and `--background`), the suggestion must pass on all of them. If no single value can, the audit says which backgrounds conflict instead of guessing. ### How `audit` reads CSS - Values may be hex, `rgb()`, `hsl()`, `oklch()`, any CSS Color 4 format, or shadcn/ui v3 bare HSL channels (`222.2 84% 4.9%`). - `var()` references are resolved where they are declared, like the browser: an inherited `--card: var(--background)` keeps the `:root` value inside `.dark`. - Foregrounds that are `var()` references or only inherited are reported as not auto-fixable, with a note. ## Docs for agents - [llms.txt](https://colorejs.dev/llms.txt): an index of every current page, with the conventions that differ from other color libraries. - [llms-full.txt](https://colorejs.dev/llms-full.txt): every page as Markdown in one file. - Any docs page is also served as Markdown at its URL plus `.md`, for example `https://colorejs.dev/docs/agents.md`. ## Library equivalents ```ts import { generateSystem, auditCssVariables, fixCssVariables, ensureContrast, inspectCssTheme, applyThemeToCss, adjustCssVariables, } from 'colore-js'; const globalsCss = generateSystem('#7c3aed').toShadcnCss({ format: 'oklch' }); // The report describes the theme type, color format, modes, brand, and missing parts. const theme = inspectCssTheme(globalsCss); const rebranded = applyThemeToCss(globalsCss, generateSystem('#0f766e'), { add: true }).css; const warmer = adjustCssVariables(globalsCss, { groups: ['surfaces'], hue: 70, chroma: 0.008 }).css; const report = auditCssVariables(globalsCss, { level: 'aa' }); const { css: fixed, changes } = fixCssVariables(globalsCss); const { color } = ensureContrast('#777777', '#ffffff'); console.log(color.hex()); // #767676 ``` See [inspectCssTheme](https://colorejs.dev/docs/api/system/inspect-css-theme), [applyThemeToCss](https://colorejs.dev/docs/api/system/apply-theme-to-css) and [adjustCssVariables](https://colorejs.dev/docs/api/system/adjust-css-variables) for the theme-file API references. Source: https://colorejs.dev/docs/agents --- # Check color contrast in JavaScript Your muted label looks fine on white, until you run a contrast check. At 4.48:1, `#777777` falls short of the 4.5:1 WCAG AA minimum for normal text. Colore can measure the pair and find a nearby gray that passes. ```bash npm install colore-js ``` ```bash yarn add colore-js ``` ## Check the color against its actual background Start with [contrastRatio](https://colorejs.dev/docs/api/operations/accessibility/contrast-ratio-wcag) to see how close you are to the limit. Use [isReadable](https://colorejs.dev/docs/api/operations/accessibility/is-readable) for the pass or fail decision. Both take the text color and the background behind it. ```ts import { contrastRatio, isReadable } from 'colore-js/fn'; const text = '#777777'; const background = '#ffffff'; console.log(contrastRatio(text, background).toFixed(2)); // '4.48' console.log(isReadable(text, background)); // false console.log(isReadable(text, background, { intent: 'largeText' })); // true ``` Large text has a 3:1 AA minimum. Use that intent only when the text meets the [WCAG definition of large text](https://www.w3.org/WAI/WCAG22/Understanding/contrast-minimum.html). For small labels and body text, keep the default text intent. Round the ratio for display after you make the decision. ## WCAG contrast thresholds | What you're checking | AA | AAA | Colore option | | --- | --- | --- | --- | | Normal text | 4.5:1 | 7:1 | Default, or `'aaa'` | | Large text: 24px, or 18.66px bold | 3:1 | 4.5:1 | `{ intent: 'largeText' }` | | Icons, input borders and other UI parts | 3:1 | None | `{ intent: 'ui' }` | For AAA large text, pass `{ intent: 'largeText', level: 'aaa' }`. Sources: WCAG 2.2 [contrast minimum](https://www.w3.org/WAI/WCAG22/Understanding/contrast-minimum.html), [enhanced contrast](https://www.w3.org/WAI/WCAG22/Understanding/contrast-enhanced.html) and [non-text contrast](https://www.w3.org/WAI/WCAG22/Understanding/non-text-contrast.html). ## How the ratio is calculated WCAG 2 compares the relative luminance of the two colors. If your colors are always six-digit hex, you can write it yourself in a few lines: ```js function channel(value) { const c = value / 255; return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; } function luminance(hex) { const [r, g, b] = [1, 3, 5].map((i) => channel(parseInt(hex.slice(i, i + 2), 16))); return 0.2126 * r + 0.7152 * g + 0.0722 * b; } function contrast(a, b) { const [light, dark] = [luminance(a), luminance(b)].sort((x, y) => y - x); return (light + 0.05) / (dark + 0.05); } contrast('#777777', '#ffffff'); // 4.478089453577214 ``` It returns `NaN` as soon as a color arrives in another form: `'#fff'`, `'oklch(0.6 0.2 260)'` from a Tailwind CSS v4 theme, or a translucent `rgb(0 0 0 / 50%)`. `contrastRatio` reads any CSS color and composites translucent ones over the background first: ```ts import { contrastRatio } from 'colore-js/fn'; contrastRatio('#777777', '#fff'); // 4.478089453577214 contrastRatio('oklch(0.6 0.2 260)', '#ffffff'); // 4.060703177675777 contrastRatio('rgb(0 0 0 / 50%)', '#ffffff'); // 3.97665302491244 ``` ## Fix a failing foreground Pass the same pair to [ensureContrast](https://colorejs.dev/docs/api/intelligence/ensure-contrast). It returns the color and a `satisfied` flag. Check the flag before writing the replacement, particularly if you restrict which direction the color can move. ```ts import { ensureContrast } from 'colore-js'; import { isReadable } from 'colore-js/fn'; const result = ensureContrast('#777777', '#ffffff'); console.log(result.satisfied); // true console.log(result.color.hex()); // '#767676' console.log(isReadable(result.color.hex(), '#ffffff')); // true ``` The difference is one step per RGB channel. At an exact cutoff, check the value you export. A color you measured before rounding can land on the other side of the threshold once you write it as hex. For a wide-gamut color, decide whether you intend to ship a wide CSS value or an sRGB fallback and check the fallback separately. If the same label appears on more than one surface, repeat the check for each background. ## Check and repair a stylesheet Use [auditCssVariables](https://colorejs.dev/docs/api/audit#css-custom-properties) when the colors already live in a stylesheet. It checks named pairs in each scope. [fixCssVariables](https://colorejs.dev/docs/api/audit#css-custom-properties) returns the updated CSS and the issues it could not repair. Review the changes before writing them back to a file. Here is the full workflow on a stylesheet with one text pair. ```ts import { auditCssVariables, fixCssVariables } from 'colore-js'; const css = ':root { --background: #fff; --foreground: #999; }'; const before = auditCssVariables(css); const after = fixCssVariables(css); console.log(before.issues[0]?.message); // '--foreground on --background in :root: 2.85:1, needs 4.5:1' console.log(after.css); // ':root { --background: #fff; --foreground: #767676; }' console.log(after.checked, after.issues.length); // 1 0 ``` Use the pair count alongside the issue count. A stylesheet with zero recognized pairs gives you no evidence about its text. ## What Colore checks for you Colore measures the foreground and background colors you provide. It composites translucent colors for the check and assumes white beneath a translucent background. If your component sits over a different page color, use the resolved background for that component. You can also read [contrastAPCA](https://colorejs.dev/docs/api/operations/accessibility/contrast-apca) when your project calls for APCA. WCAG AA and AAA use the WCAG ratio. ## Related - [Dark mode colors](https://colorejs.dev/docs/guides/dark-mode-colors) for the same check in two modes - [Black or white text](https://colorejs.dev/docs/guides/black-or-white-text) to pick a label color for any background - [Audit a palette or stylesheet](https://colorejs.dev/docs/api/audit) for explicit pair configuration - [Precision and equality](https://colorejs.dev/docs/concepts/precision-rounding-and-equality) for how hex export rounds channels Source: https://colorejs.dev/docs/guides/check-color-contrast --- # Pick black or white text for a background color A badge, avatar or tag takes its background from user data, and the label on it has to be black or white. With Colore that's one line: ```ts import { colore } from 'colore-js'; const label = colore(background).isDark() ? '#ffffff' : '#000000'; ``` `isDark()` switches at the point where white text starts to get more WCAG 2 contrast than black, so the label gets the color with the higher ratio. On any background, that color reaches at least 4.58:1, which passes WCAG AA for normal text. ```bash npm install colore-js ``` ```bash yarn add colore-js ``` If your design follows APCA, the newer contrast method, [`bestTextColor`](https://colorejs.dev/docs/api/operations/accessibility/best-text-color) picks by APCA instead: ```ts import { bestTextColor } from 'colore-js/fn'; bestTextColor('#3b82f6'); // '#ffffff' bestTextColor('#facc15'); // '#000000' ``` On some mid-tone colors the two disagree. On Tailwind's blue-500, `isDark()` picks black and `bestTextColor` picks white. ## Three ways to choose ### Perceived brightness Many answers online weight the RGB channels into a brightness value from 0 to 255 and switch at 128. The weights come from the YIQ color model used for analog TV. ```js function textColorByBrightness(hex) { const [r, g, b] = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16)); const brightness = (r * 299 + g * 587 + b * 114) / 1000; return brightness >= 128 ? '#000000' : '#ffffff'; } ``` It's short, but it predates the WCAG 2 contrast formula, and it reads only six-digit hex. ### WCAG 2 contrast ratio Pick whichever of black and white has the higher WCAG 2 ratio. This is the method behind the 4.5:1 rule that accessibility audits check, and it's what `isDark()` does in one call. Written out with `contrastRatio`, it looks like this: ```ts import { contrastRatio } from 'colore-js/fn'; function textColorByWcag(background) { return contrastRatio('#ffffff', background) >= contrastRatio('#000000', background) ? '#ffffff' : '#000000'; } ``` Without a library, compute the relative luminance as in [Check color contrast](https://colorejs.dev/docs/guides/check-color-contrast#how-the-ratio-is-calculated) and use white text when it's 0.179 or less. ### APCA APCA is a newer contrast method, developed as a possible replacement for the WCAG 2 formula. It isn't part of WCAG 2, which is the version audits and accessibility laws refer to. `bestTextColor` uses it. ## Where they disagree These are Tailwind CSS 3's 500 shades. Slate stands in for the five grays, which all pick white. The last two columns are the WCAG 2 ratios of white and black text on each one. | Color | Background | Brightness | WCAG 2 | APCA | White | Black | | --- | --- | --- | --- | --- | ---: | ---: | | red | `#ef4444` | white | black | white | 3.76 | 5.58 | | orange | `#f97316` | black | black | white | 2.80 | 7.49 | | amber | `#f59e0b` | black | black | black | 2.15 | 9.78 | | yellow | `#eab308` | black | black | black | 1.92 | 10.95 | | lime | `#84cc16` | black | black | black | 1.98 | 10.63 | | green | `#22c55e` | black | black | black | 2.28 | 9.22 | | emerald | `#10b981` | black | black | black | 2.54 | 8.28 | | teal | `#14b8a6` | black | black | black | 2.49 | 8.44 | | cyan | `#06b6d4` | black | black | black | 2.43 | 8.65 | | sky | `#0ea5e9` | white | black | white | 2.77 | 7.58 | | blue | `#3b82f6` | white | black | white | 3.68 | 5.71 | | indigo | `#6366f1` | white | black | white | 4.47 | 4.70 | | violet | `#8b5cf6` | white | black | white | 4.23 | 4.96 | | purple | `#a855f7` | black | black | white | 3.96 | 5.31 | | fuchsia | `#d946ef` | black | black | white | 3.46 | 6.07 | | pink | `#ec4899` | black | black | white | 3.53 | 5.95 | | rose | `#f43f5e` | white | black | white | 3.67 | 5.72 | | slate | `#64748b` | white | white | white | 4.76 | 4.41 | WCAG 2 picks black on every color except slate. APCA picks white on eleven of them, and on ten of those eleven, white is below the 4.5:1 that WCAG 2 AA needs for normal text. The brightness formula matches APCA on 14 of the 18 and WCAG 2 on 12, so it fails WCAG 2 on six of them. If your site is audited against WCAG 2, use `isDark()`. The APCA pick on this blue is 3.68:1, below AA. ## Keep white text on a brand color Sometimes the design calls for white text on a brand color that's a little too light for it. [`isReadable`](https://colorejs.dev/docs/api/operations/accessibility/is-readable) tells you whether the pair passes WCAG 2 AA, and [`ensureContrast`](https://colorejs.dev/docs/api/intelligence/ensure-contrast) darkens the background just enough to pass: ```ts import { contrastRatio, ensureContrast, isReadable } from 'colore-js/fn'; isReadable('#ffffff', '#3b82f6'); // false const fixed = ensureContrast('#3b82f6', '#ffffff'); // adjusts the first color, the background here // { color: '#2c72e5', satisfied: true, iterations: 1 } contrastRatio('#ffffff', fixed.color); // 4.52055373235116 ``` For a full theme, [`generateSystem`](https://colorejs.dev/docs/api/system/generate-system) checks every text and background pair. By default it follows WCAG 2, so on `#3b82f6` it keeps the blue and uses black text. Pass `{ algorithm: 'apca' }` to choose by APCA. You can try it on your own brand color in the [theme generator](https://colorejs.dev/playground). ## Related - [Check color contrast in JavaScript](https://colorejs.dev/docs/guides/check-color-contrast) for the WCAG thresholds and how the ratio is calculated - [bestTextColor](https://colorejs.dev/docs/api/operations/accessibility/best-text-color) to choose from your own candidate colors - [contrastAPCA](https://colorejs.dev/docs/api/operations/accessibility/contrast-apca) to read the APCA value directly Source: https://colorejs.dev/docs/guides/black-or-white-text --- # Generate a shadcn/ui theme from one color Your shadcn/ui app has a brand color, but the cards, buttons and dark theme still use the starter palette. Start with `#0f766e` and you get teal primary buttons with white text, tinted light surfaces, and a separate dark palette. Components can keep using the token names they already know. To see the theme on sample screens in light and dark mode first, open it in the [theme generator](https://colorejs.dev/playground?seed=%230f766e&surface=brand). ```bash npm install colore-js ``` ```bash yarn add colore-js ``` ## Generate light and dark tokens Pass the brand to [`generateSystem`](https://colorejs.dev/docs/api/system/generate-system). Use the [`.toShadcnCss()` exporter](https://colorejs.dev/docs/api/system/system-to-tailwind-css) with `radius: false` to keep your app's existing corner radius. This guide uses a shadcn/ui project on Tailwind CSS v4 with CSS variables enabled. ```js import { generateSystem } from 'colore-js'; const css = generateSystem('#0f766e').toShadcnCss({ radius: false }); console.log(css); ``` Here are the primary and page colors from the generated stylesheet. The rest of the output includes tokens for cards, muted surfaces, charts and more. ```css :root { --background: oklch(0.971 0.003 174.483); --foreground: oklch(0.13 0.002 186.391); --primary: oklch(0.511 0.086 186.391); --primary-foreground: oklch(1 0 0); } .dark { --background: oklch(0.129 0 0); --foreground: oklch(0.97 0.003 186.391); --primary: oklch(0.511 0.086 186.391); --primary-foreground: oklch(1 0 0); } ``` ## Put the colors in your app In `globals.css`, replace matching color declarations inside the existing `:root` and `.dark` blocks. If you need to add a block, use the generated declarations for that mode. Keep the Tailwind import, `@theme inline` aliases, radius and any custom variables. The aliases connect the underlying color tokens to utility classes. [shadcn/ui theming](https://ui.shadcn.com/docs/theming) For example, a primary button can use the two tokens as a pair. Once the CSS is loaded, it gets the theme's background and text in either mode. ```html ``` The dark block applies when your theme switch adds `.dark` to an ancestor such as ``. If your app already has a switch, check that it uses the same selector. [shadcn/ui dark mode](https://ui.shadcn.com/docs/dark-mode/next) If a primary action stays gray after you swap the tokens, inspect its classes. A fixed utility such as `bg-zinc-900` bypasses the primary token. Change that action to `bg-primary` and pair it with `text-primary-foreground` so both colors respond to your theme. ## Export a checked stylesheet Save this as `generate-shadcn-theme.mjs`. [`auditCssVariables`](https://colorejs.dev/docs/api/audit#css-custom-properties) reads the exported CSS. The script sends the check count to stderr and writes CSS to stdout, so you can save it to a separate file and review the changes before applying them. ```js import { auditCssVariables, generateSystem } from 'colore-js'; const css = generateSystem('#0f766e', { level: 'aa' }).toShadcnCss({ radius: false }); const report = auditCssVariables(css, { level: 'aa' }); console.error(`${report.checked} pairs checked, ${report.issues.length} issues`); if (!report.passed) { throw new Error('The generated theme has contrast issues'); } process.stdout.write(css + '\n'); ``` ```bash node generate-shadcn-theme.mjs > shadcn-colors.css ``` ```text 24 pairs checked, 0 issues ``` ## What Colore checks for you The generator chooses foregrounds for the surfaces it creates. The shadcn/ui exporter checks those pairs again after rounding the values for CSS, and the audit checks recognized pairs in the resulting stylesheet. If you change a token or use a foreground on a different surface, check the pair your component actually renders. ## Related - [Change the colors in an existing theme](https://colorejs.dev/docs/api/system/apply-theme-to-css) - [Generate Tailwind CSS v4 brand colors](https://colorejs.dev/docs/guides/tailwind-v4-colors) - [Build dark mode colors that pass contrast](https://colorejs.dev/docs/guides/dark-mode-colors) Source: https://colorejs.dev/docs/guides/shadcn-theme-from-one-color --- # Tailwind CSS v4 colors from your brand color A logo gives you one color. A button needs a hover color, and a banner needs a much lighter version of the same brand. Turn `#0f766e` into a Tailwind CSS v4 ramp so you can use `bg-brand-500` for a button, `hover:bg-brand-600` for hover, and `bg-brand-50` for a pale surface. In Tailwind CSS v4, custom colors are CSS variables in an `@theme` block. A variable named `--color-brand-500` gives you `bg-brand-500`, `text-brand-500` and the other color utilities ([Tailwind CSS theme variables](https://tailwindcss.com/docs/theme)). ```css @theme { --color-brand-500: #0f766e; } ``` That's one shade. Colore generates all eleven from the same color, and the [palette generator](https://colorejs.dev/palette?seed=%230f766e) shows you the scale before you write any code. ```bash npm install colore-js ``` ```bash yarn add colore-js ``` ## Build a 50–950 ramp [`palette`](https://colorejs.dev/docs/api/operations/scales-and-palette/palette) gives you the 11 shades in order from light to dark. It puts the brand at the step closest to its lightness. This teal lands at 500. A lighter brand can land earlier, so check the returned scale before naming a default shade. ```js import { palette } from 'colore-js/fn'; const shades = palette('#0f766e'); console.log(shades[0], shades[5], shades[6]); // #d8fff9 #0f766e #0c6962 ``` ## Check the button and hover colors The shade number tells you where a color sits in the ramp. Measure the actual text and background with [`contrastRatio`](https://colorejs.dev/docs/api/operations/accessibility/contrast-ratio-wcag). White text on brand 500 or 600 clears the WCAG AA target of 4.5:1 for normal text. White on brand 400 falls below it. [WCAG text contrast](https://www.w3.org/WAI/WCAG22/Understanding/contrast-minimum.html) ```js import { contrastRatio, palette } from 'colore-js/fn'; const shades = palette('#0f766e'); for (const [step, index] of [[400, 4], [500, 5], [600, 6]]) { console.log(step, contrastRatio('#ffffff', shades[index]).toFixed(2)); } ``` ```text 400 2.76 500 5.47 600 6.54 ``` ## Generate the Tailwind stylesheet Save this as `generate-brand-colors.mjs`. It pairs the ramp with Tailwind's shade numbers and prints the complete `@theme` block for your CSS build. ```js import { palette } from 'colore-js/fn'; const steps = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950]; const colors = palette('#0f766e'); const declarations = steps.map((step, index) => ` --color-brand-${step}: ${colors[index]};`); console.log(['@theme {', ...declarations, '}'].join('\n')); ``` ```bash node generate-brand-colors.mjs > brand.css ``` ```css @theme { --color-brand-50: #d8fff9; --color-brand-100: #a3fbf1; --color-brand-200: #8fe7dd; --color-brand-300: #72cac0; --color-brand-400: #52aaa0; --color-brand-500: #0f766e; --color-brand-600: #0c6962; --color-brand-700: #064a45; --color-brand-800: #022d2a; --color-brand-900: #011d1b; --color-brand-950: #000a09; } ``` Import `brand.css` after Tailwind in your main stylesheet. `@theme` goes at the top level. A token named `--color-brand-500` becomes available to color utilities such as `bg-brand-500`, `text-brand-500`, and `border-brand-500`. [Tailwind CSS theme variables](https://tailwindcss.com/docs/theme) ```css @import 'tailwindcss'; @import './brand.css'; ``` Use the complete class names in your component so Tailwind can find them at build time. [Tailwind source detection](https://tailwindcss.com/docs/detecting-classes-in-source-files) ```html ``` Run the generator again when the brand changes, then review the CSS alongside the contrast checks. If you reuse a pale shade for a banner, check its copy against that shade. The button's passing ratio only covers white text on the two button backgrounds. For a single brand shared across the app, the generated CSS is all the browser needs. Once a page needs named roles like `primary`, `surface` and `on-primary`, the [`.toTailwindCss()` exporter](https://colorejs.dev/docs/api/system/system-to-tailwind-css) can generate those tokens and their dark-mode overrides. The ramp above can stay in its own file if you want to keep the `brand` utilities alongside them. ## What Colore checks for you The generated ramp shades fit sRGB. The original seed stays at its assigned step, including when it is a wide-gamut color. Contrast depends on where you use each shade, so the button check measures both backgrounds against the text that sits on them. ## Related - [Build the 50–950 ramp](https://colorejs.dev/docs/api/operations/scales-and-palette/palette) - [Check text contrast](https://colorejs.dev/docs/guides/check-color-contrast) - [Generate a shadcn/ui theme from one color](https://colorejs.dev/docs/guides/shadcn-theme-from-one-color) Source: https://colorejs.dev/docs/guides/tailwind-v4-colors --- # Dark mode colors that pass contrast A gray label that looks fine on a white card can fade into the dark version. A dark brand button can disappear into the same card. Starting from `#164e63`, you can keep a deep blue button with white text in light mode and use a lighter blue with black text in dark mode. You can compare both modes in the [theme generator](https://colorejs.dev/playground?seed=%23164e63&mode=dark&surface=brand). ```bash npm install colore-js ``` ```bash yarn add colore-js ``` ## Measure the pair that fails Try [`contrastRatio`](https://colorejs.dev/docs/api/operations/accessibility/contrast-ratio-wcag) on a muted gray label against your dark background. Here, it gives `3.69:1`, below the `4.5:1` target for normal text at WCAG AA. If a label sits on a card, use the card's background for this check. ```js import { contrastRatio } from 'colore-js/fn'; console.log(contrastRatio('#6b7280', '#0f172a').toFixed(2)); // 3.69 ``` A card can be lighter than the page in dark mode, which shrinks the gap between the surface and muted text. Make a short list of the pairs you need before picking colors. For a settings page that might include the section title, the helper label and the action button. ## Give each mode its own colors [`generateSystem`](https://colorejs.dev/docs/api/system/generate-system) builds page, surface, text and action colors from the same brand. The primary button can change shade and foreground between modes. Keep them together, the way you keep muted text with the card it sits on. ```js import { generateSystem } from 'colore-js'; const system = generateSystem('#164e63', { level: 'aa' }); for (const mode of ['light', 'dark']) { const { primaryBase, onPrimary } = system.theme(mode); console.log(mode, primaryBase.hex(), onPrimary.hex()); } ``` ```text light #164e63 #ffffff dark #60a2bf #000000 ``` ## Export CSS and check the colors you use Save this complete example as `generate-theme.mjs`. It exports CSS to stdout and prints three text checks for each mode to stderr. These checks use the exact hex values written by [`.toCSS()`](https://colorejs.dev/docs/api/system/generate-system). ```js import { generateSystem } from 'colore-js'; import { contrastRatio } from 'colore-js/fn'; const system = generateSystem('#164e63', { level: 'aa' }); for (const mode of ['light', 'dark']) { const theme = system.theme(mode); const pairs = [ [theme.text, theme.background], [theme.textSubtle, theme.surface], [theme.onPrimary, theme.primaryBase], ]; const ratios = pairs.map(([text, bg]) => contrastRatio(text.hex(), bg.hex()).toFixed(2)); console.error(`${mode}: ${ratios.join(', ')}`); } const css = system.toCSS({ format: 'hex', darkSelector: '[data-theme="dark"]' }); process.stdout.write(css + '\n'); ``` ```bash node generate-theme.mjs > theme.css ``` ```text light: 19.23, 4.55, 9.11 dark: 20.14, 4.56, 7.42 ``` Load `theme.css` before the component styles that use its variables. The same classes work in both modes. Toggle `data-theme="dark"` on `` in the app's theme switch to activate the dark declarations. ```css :root { color-scheme: light; } [data-theme="dark"] { color-scheme: dark; } body { background: var(--color-background); color: var(--color-text); } .card { background: var(--color-surface); } .card-label { color: var(--color-text-subtle); } .primary-button { background: var(--color-primary-base); color: var(--color-on-primary); } ``` The `color-scheme` declarations tell the browser which appearance to use for native controls. The variable declarations set your own colors. To preview the full result, switch modes on a real page with a card and a button, since a swatch alone does not show the text over its surface. [CSS color scheme](https://www.w3.org/TR/css-color-adjust-1/#color-scheme-prop) Use the same approach for actual hover and selected states. If you lower a label's opacity or add an overlay over the card, measure again with those colors in place. ## What Colore checks for you The system uses the selected text contrast target when choosing role foregrounds. It also checks whether the primary seed stands out against dark surfaces and can pick a different shade for dark mode. Your layout decides which tokens end up next to each other. Check the actual foreground and background whenever you create a new pair. ## Related - [Check color contrast in JavaScript](https://colorejs.dev/docs/guides/check-color-contrast) - [Generate hover, active and focus colors](https://colorejs.dev/docs/api/system/states) - [Audit CSS color variables](https://colorejs.dev/docs/api/audit#css-custom-properties) Source: https://colorejs.dev/docs/guides/dark-mode-colors --- # Use OKLCH in JavaScript `toOklch('#2563eb')` returns `oklch(0.54615 0.21521 262.88)`. Once a color is in OKLCH you can move its lightness and keep its hue, which is what you want for a hover color: an 8% move toward white turns `#2563eb` into `#306ff8`. ```bash npm install colore-js ``` ```bash yarn add colore-js ``` ## Convert a hex color to OKLCH Use [toOklch](https://colorejs.dev/docs/api/operations/output/to-oklch) to write the color as CSS. The three values represent lightness, chroma and hue. Chroma is the color’s intensity, and hue is its angle on the color wheel. ```ts import { toOklch } from 'colore-js/fn'; console.log(toOklch('#2563eb')); // 'oklch(0.54615 0.21521 262.88)' ``` If a picker or a calculation needs numbers, call `toOklch()` on a `Color` object. The standalone function above returns a CSS string. ```ts import { colore } from 'colore-js'; colore('#2563eb').toOklch(); // { l: 0.5461497233109911, c: 0.21520774805039064, h: 262.88091714087415, alpha: 1 } ``` ## Make the hover state lighter [lighten](https://colorejs.dev/docs/api/operations/manipulation/lighten) takes a percentage from 0 to 100. Pass `8` for 8%. This moves the current lightness 8% of the distance toward white. If your design specifies a lightness of exactly `0.7`, use [setOklch](https://colorejs.dev/docs/api/operations/manipulation/set-oklch) instead. ```ts import { lighten, setOklch } from 'colore-js/fn'; console.log(lighten('#2563eb', 8)); // '#306ff8' console.log(setOklch('#2563eb', { l: 0.7 })); // 'oklch(0.70000 0.21521 262.88)' ``` The exact-lightness result is wider than sRGB and Display P3, so Colore writes OKLCH. For an older renderer that accepts only hex, decide where to map the color before you export. ## Mix a second color in OKLCH Choose the mixing space to control the result between two colors. Here [mix](https://colorejs.dev/docs/api/operations/manipulation/mix) goes 40% of the way from brand blue to teal. The ratio is 0–1, so the same value can come directly from a slider. ```ts import { mix } from 'colore-js/fn'; console.log(mix('#2563eb', '#0f766e', 0.4, 'oklch')); // 'oklch(0.53206 0.16355 232.29)' console.log(mix('#2563eb', '#0f766e', 0.4, 'srgb')); // '#1c6bb9' ``` Use the OKLCH mix when you want to work along the hue and chroma of the colors. Choose sRGB when you need to match an existing sRGB blend. If the accent needs to sit on white or carry a label, check the contrast for that use before settling on either result. ## Put the colors into a theme For several operations on the same input, create one [Color](https://colorejs.dev/docs/api/color-class/constructor-and-inputs) and export at the end. This gives you a consistent source for the default, hover and accent colors. The stylesheet keeps the original blue in hex and writes the wider mix in OKLCH. ```ts import { colore } from 'colore-js'; const brand = colore('#2563eb'); const hover = brand.lighten(8); const accent = brand.mix('#0f766e', 0.4, 'oklch'); const css = `:root { --brand: ${brand.css()}; --brand-hover: ${hover.css()}; --accent: ${accent.css()}; }`; console.log(css); ``` ```css :root { --brand: #2563eb; --brand-hover: #306ff8; --accent: oklch(0.53206 0.16355 232.29); } ``` ## Convert OKLCH back to hex Use [toHex](https://colorejs.dev/docs/api/operations/output/to-hex) when a design token, email template or older tool needs hex. Colors inside sRGB convert without clipping. The accent from the mix above is outside sRGB, so hex can't hold it. You can clip it, which is what `toHex` does, or map it into sRGB with [toGamut](https://colorejs.dev/docs/api/color-class/utility-methods) first, which keeps its lightness and hue closer and gives up some chroma. ```ts import { colore } from 'colore-js'; import { toHex } from 'colore-js/fn'; const accent = 'oklch(0.53206 0.16355 232.29)'; toHex(accent); // '#0078ba', clipped colore(accent).toGamut('srgb').hex(); // '#0077ab', gamut-mapped colore(accent).isInGamut('srgb'); // false ``` Check contrast against the hex value if that's what your renderer will display. To compare a shade's hex and OKLCH values, open the color in the [palette generator](https://colorejs.dev/palette?seed=%232563eb). ## How Colore handles wide colors Colore keeps numeric channels through a chain of edits and picks a CSS format based on the result’s gamut, so a wide color isn't clipped until you ask for hex. ## Related - [Gamut and CSS output](https://colorejs.dev/docs/concepts/gamut-and-css-output) for the format rules and a mapped fallback - [Check color contrast](https://colorejs.dev/docs/guides/check-color-contrast) before you use the mix for text - [Generate Tailwind CSS v4 colors](https://colorejs.dev/docs/guides/tailwind-v4-colors) for a full brand scale Source: https://colorejs.dev/docs/guides/oklch-in-javascript --- # Accessible chart colors for dashboards Four lines in a signup chart need to stand apart from each other and from the plot. On a pale card, a light teal stroke can be hard to spot. On a dark card, the same palette does a different job. Generate colors for each background, ranked by how distinct they stay for readers with red-green color blindness, then give each series a line style and label that stay the same across themes. ```bash npm install colore-js ``` ```bash yarn add colore-js ``` ## Generate colors for the plot background Tell [`categoricalColors`](https://colorejs.dev/docs/api/operations/scales-and-palette/categorical-colors) how many series you have and what sits behind the marks. Use the card's color if the chart is drawn on a card, even when the rest of the page has a different background. ```js import { categoricalColors } from 'colore-js/fn'; console.log(categoricalColors(4, { background: '#f8fafc' }).join(' ')); // #1781d4 #bf2e0f #a7207b #f35a86 ``` These colors are for categories like Direct, Search, Referral and Email. If color encodes an ordered value such as revenue or temperature, use a [scale](https://colorejs.dev/docs/api/operations/scales-and-palette/scale) with an ordered progression instead. ## Check a stroke against the card Use [`contrastRatio`](https://colorejs.dev/docs/api/operations/accessibility/contrast-ratio-wcag) to check the pair the reader sees. In this example, the pink line has `3.03:1` contrast against the card. That clears the `3:1` threshold for a graphical object that readers need to understand the data. Lowering the stroke opacity can change the result. Check against a neighboring fill, too, if the lines are drawn over one. [WCAG non-text contrast](https://www.w3.org/WAI/WCAG22/Understanding/non-text-contrast.html) ```js import { contrastRatio } from 'colore-js/fn'; console.log(contrastRatio('#f35a86', '#f8fafc').toFixed(2)); // 3.03 ``` ## Build the series styles for both modes This script emits the stroke color, dash pattern and contrast for each series on both plot backgrounds. Keep the `id` stable in your chart data and use it to look up the style. Give the chart's visible legend the same label and line pattern as the plotted series. ```js import { categoricalColors, contrastRatio } from 'colore-js/fn'; const series = [ { id: 'direct', label: 'Direct', dash: 'none' }, { id: 'search', label: 'Search', dash: '8 3' }, { id: 'referral', label: 'Referral', dash: '2 3' }, { id: 'email', label: 'Email', dash: '8 3 2 3' }, ]; for (const [mode, background] of Object.entries({ light: '#f8fafc', dark: '#0f172a' })) { const colors = categoricalColors(series.length, { background }); series.forEach(({ id, label, dash }, index) => { const stroke = colors[index]; const ratio = contrastRatio(stroke, background).toFixed(2); console.log(`${mode} ${id} (${label}): ${stroke}, dash ${dash}, ${ratio}:1`); }); } ``` ```text light direct (Direct): #1781d4, dash none, 3.91:1 light search (Search): #bf2e0f, dash 8 3, 5.56:1 light referral (Referral): #a7207b, dash 2 3, 6.40:1 light email (Email): #f35a86, dash 8 3 2 3, 3.03:1 dark direct (Direct): #70b2fb, dash none, 8.03:1 dark search (Search): #bcdb29, dash 8 3, 11.31:1 dark referral (Referral): #ec5480, dash 2 3, 5.23:1 dark email (Email): #2feac3, dash 8 3 2 3, 11.63:1 ``` For SVG, use the color as `stroke` and the dash pattern as `stroke-dasharray`. If the legend is far from the plot, add labels at the ends of the lines where there is room. Keep a readable table or equivalent text when readers need the exact values. [WCAG use of color](https://www.w3.org/WAI/WCAG22/Understanding/use-of-color.html) Check the chart at its smallest rendered size as well. Short dashes need enough room to be recognizable, and labels need a clear background. ## What Colore checks for you Colore checks the candidate colors against the supplied background. It also ranks them by how far apart they look in normal vision and in protanopia and deuteranopia simulations. Your chart still needs visible labels and a way to identify each series when lines cross. The patterns stay useful even if a display shows the chart in grayscale. ## Related - [Generate a categorical palette](https://colorejs.dev/docs/api/operations/scales-and-palette/categorical-colors) - [Preview a color-vision simulation](https://colorejs.dev/docs/api/operations/scales-and-palette/simulate-color-blindness) - [Check color contrast in JavaScript](https://colorejs.dev/docs/guides/check-color-contrast) Source: https://colorejs.dev/docs/guides/chart-colors --- # Handle invalid colors A color field can contain an unfinished hex code, a typo or a CSS variable the parser cannot resolve. Choose how to handle that input based on what you need to tell the user. ## Use a fallback while someone types ```ts import { Color } from 'colore-js'; const value = Color.try('rgb(12)') ?? new Color('#2563eb'); console.log(value.css()); // '#2563eb' ``` `Color.try()` gives you a Color or `null`. It suits a live preview whose input can be incomplete for a keystroke or two. ## Show a validation message ```ts import { ColorError, parse } from 'colore-js'; try { parse('not-a-color'); } catch (error) { if (!(error instanceof ColorError)) throw error; console.log('Enter a supported CSS color.'); // 'Enter a supported CSS color.' } ``` Use a stricter path when a form submits or a file imports. You can log the error’s message and show wording that fits the field. If only a boolean is needed, call [isValidColor](https://colorejs.dev/docs/api/validation/is-valid-color). ## Detect the format after validation ```ts import { detectFormat, isValidColor } from 'colore-js'; console.log(detectFormat('rgb(12)')); // 'rgb' console.log(isValidColor('rgb(12)')); // false ``` A recognizable function name still needs valid channels. Treat `detectFormat()` as a label for an input you have already checked. ## Related - [Color constructor and inputs](https://colorejs.dev/docs/api/color-class/constructor-and-inputs) - [Color.try](https://colorejs.dev/docs/api/color-class/static-factory-methods#accept-a-user-supplied-color) - [parse](https://colorejs.dev/docs/api/parsing/parse) for strict parsing Source: https://colorejs.dev/docs/advanced/error-handling-and-validation --- # Performance and bundling Import what you use. A named function from `colore-js/fn` fits an isolated conversion or edit. A Color object is useful when several operations work on the same input. ## Choose an import ```ts import { lighten } from 'colore-js/fn'; console.log(lighten('#2563eb', 8)); // '#306ff8' ``` Named imports let your bundler drop unused exports. One function still includes the parser it needs for named colors, supported CSS functions and tagged objects. ## What an import costs These are approximate gzip sizes for the local Colore v2 build, measured with Rollup 4.59, Terser 5.31 and gzip level 9. Measure your own production bundle to see what the rest of your app shares. | Import | Gzip | | --- | ---: | | `toHex` from `colore-js/fn` | 10 KiB | | `ensureContrast` from `colore-js/fn` | 14 KiB | | `colore()` / `Color` class | 18 KiB | | `audit` from `colore-js/fn` | 25 KiB | | `generateSystem` from `colore-js/fn` | 33 KiB | | All root exports | 39 KiB | ## Parse once for several changes ```ts import { colore } from 'colore-js'; const input = colore('#7c3aed'); console.log(input.lighten(8).saturate(6).css()); // 'color(display-p3 0.49629 0.27042 0.97260)' ``` The chain keeps the working color in memory until you call `css()`. Passing a CSS string from one standalone transform to the next formats and parses an intermediate value. For a palette you use on every render, compute it when its input changes. ## Run the benchmarks With the repo dependencies installed, build the package at the repo root and run its quick benchmark. ```bash yarn build yarn bench:quick ``` The runner measures parse-plus-hex, parse-plus-RGB and WCAG contrast on 256 opaque sRGB hex inputs or pairs. Each reported operation is a full pass over its dataset. For an app decision, also measure the color formats and operations your users run. ## Related - [Entry points and exports](https://colorejs.dev/docs/api/reference/entry-points-and-exports) for the names available from each import - [Immutability and chaining](https://colorejs.dev/docs/concepts/immutability-and-chaining) - [Benchmark source](https://github.com/mallikcheripally/colore-js/tree/main/benchmarks) Source: https://colorejs.dev/docs/advanced/performance-and-bundling --- # API reference Find the Colore function for the job you have. The references show which input each function accepts and what it returns. Most projects start with [`generateSystem`](https://colorejs.dev/docs/api/system/generate-system) for a light and dark theme, [`ensureContrast`](https://colorejs.dev/docs/api/intelligence/ensure-contrast) to fix a color that fails contrast, or [`applyThemeToCss`](https://colorejs.dev/docs/api/system/apply-theme-to-css) to change a theme file you already have. To work from the terminal or a coding agent, see [Coding agents and CLI](https://colorejs.dev/docs/agents). ## Pick an import Use `colore()` or `Color` when you want to chain several changes before writing the result. Standalone helpers from `colore-js/fn` handle one operation at a time. Each reference lists the available calls. ## Related - [Entry points and exports](https://colorejs.dev/docs/api/reference/entry-points-and-exports) for the full list of names and imports - [Get started](https://colorejs.dev/docs/getting-started) for a first example - [Check color contrast](https://colorejs.dev/docs/guides/check-color-contrast) for a complete workflow Source: https://colorejs.dev/docs/api/overview --- # Color constructor and inputs Create a `Color` when you have a CSS string, RGB channels or a color you want to edit. `colore(input)` and `new Color(input)` accept the same values and give you the same methods. ## Example ```ts import { Color, colore } from 'colore-js'; console.log(colore('rebeccapurple').hex()); // '#663399' console.log(new Color({ r: 37, g: 99, b: 235 }).hex()); // '#2563eb' ``` ## Syntax ```ts new Color(input: ColorInput | Color): Color colore(input: ColorInput | Color): Color ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | `input` | `ColorInput \| Color` | A supported CSS color, a packed RGB integer, a channel object or a `Color`. | ### Returns A `Color` with methods for editing, conversion and contrast. Passing an existing `Color` copies it. ### Throws A `ColorError` if the value has unsupported syntax, missing channels or invalid units. For values from a form, use [Color.try](https://colorejs.dev/docs/api/color-class/static-factory-methods#accept-a-user-supplied-color) if a fallback is enough. ## Pass normalized RGB from a picker Untagged RGB objects use 0–255. If your picker gives you 0–1 channels, mark them with `space: 'srgb'`. Use `alpha` for opacity. Untagged RGB, HSL, HSV and HWB objects also accept `a`. ```ts import { Color } from 'colore-js'; const swatch = new Color({ space: 'srgb', r: 0.5, g: 0.25, b: 1 }); console.log(swatch.hex()); // '#8040ff' console.log(new Color(0x2563eb).hex()); // '#2563eb' ``` Use explicit tags for Lab, LCH, OKLab, OKLCH, XYZ and Display P3. Lab and OKLab share channel names, so the tag tells Colore which units you mean. ## Related - [Color inputs and detection](https://colorejs.dev/docs/concepts/color-inputs-and-detection) for supported syntax and input forms - [Color static methods](https://colorejs.dev/docs/api/color-class/static-factory-methods) to construct from separate channels - [Color object output](https://colorejs.dev/docs/api/color-class/object-output-methods) to pass converted coordinates back into Colore Source: https://colorejs.dev/docs/api/color-class/constructor-and-inputs --- # Color static methods Use a static `Color` method to create a color from separate channels. A picker can pass its numbers directly, and you can format the result for CSS afterwards. ## Example ```ts import { Color } from 'colore-js'; console.log(Color.rgb(37, 99, 235).hex()); // '#2563eb' console.log(Color.oklch(0.62, 0.17, 250).oklch()); // 'oklch(0.62000 0.17000 250.00)' ``` ## Syntax | Method | Channel arguments | | --- | --- | | `Color.rgb(r, g, b, alpha?)` | sRGB channels 0–255 | | `Color.hsl(h, s, l, alpha?)`, `Color.hsv(h, s, v, alpha?)`, `Color.hwb(h, w, b, alpha?)` | Hue in degrees and the other channels in 0–100 | | `Color.lab(l, a, b, alpha?)`, `Color.lch(l, c, h, alpha?)` | Lab or LCH, with lightness 0–100 | | `Color.oklab(l, a, b, alpha?)`, `Color.oklch(l, c, h, alpha?)` | OKLab or OKLCH, with lightness 0–1 | | `Color.p3(r, g, b, alpha?)` | Encoded Display P3 channels, usually 0–1 | | `Color.try(input)` | A `ColorInput` or `Color` | | `Color.interpolate(colors, t, space?)` | A list of colors, a position 0–1 and an optional interpolation space | | `Color.fromCssMix(expression)` | A supported CSS `color-mix()` expression | ### Returns A `Color`. `Color.try()` returns `null` when Colore cannot read the input. ### Throws Channel constructors and strict parsing methods throw a `ColorError` for invalid arguments. Opacity defaults to `1`. Check [color spaces and ranges](https://colorejs.dev/docs/concepts/color-spaces-and-ranges) when you pass coordinates from another tool. ## Accept a user-supplied color Let someone enter their own accent color and keep a default when the field is empty or invalid. ```ts import { Color } from 'colore-js'; const accent = Color.try('var(--accent)') ?? Color.rgb(37, 99, 235); console.log(accent.hex()); // '#2563eb' ``` ## Related - [Color constructor and inputs](https://colorejs.dev/docs/api/color-class/constructor-and-inputs) - [fromCssMix](https://colorejs.dev/docs/api/parsing/from-css-mix) for CSS expressions - [interpolate](https://colorejs.dev/docs/api/operations/scales-and-palette/interpolate) for colors between stops Source: https://colorejs.dev/docs/api/color-class/static-factory-methods --- # Color string output Use `css()` to write a color to a stylesheet. Choose a specific method like `hex()` or `oklch()` when your output needs that format. ## Example ```ts import { colore } from 'colore-js'; const blue = colore('#2563eb80'); console.log(blue.hex()); // '#2563eb80' console.log(blue.rgb()); // 'rgb(37 99 235 / 0.502)' ``` ## Syntax | Method | Returns | | --- | --- | | `hex()` | Six-digit RGB hex, or eight-digit hex for alpha | | `rgb()`, `hsl()`, `hwb()` | The selected CSS function with sRGB channels | | `lab()`, `lch()` | CSS Lab or LCH coordinates | | `oklab()`, `oklch()` | CSS OKLab or OKLCH coordinates | | `p3()` | A `color(display-p3 …)` string | | `css()`, `toString()`, `toJSON()` | A CSS string chosen by gamut | ### Parameters These methods take no arguments. For named numeric channels, use [Color object output](https://colorejs.dev/docs/api/color-class/object-output-methods). ### Returns A string. `css()` uses hex when the color fits sRGB, Display P3 when it fits there, and OKLCH for wider colors. An explicit sRGB format such as `hex()` clips channels when the color is outside sRGB. ## Keep a wide-gamut color in a stylesheet ```ts import { colore } from 'colore-js'; const red = colore('color(display-p3 1 0 0)'); console.log(red.css()); // 'color(display-p3 1.00000 0.00000 0.00000)' console.log(red.toGamut('srgb').hex()); // '#ff0b0c' ``` Use the CSS string on a surface that can display P3. Call `toGamut('srgb')` first when you need a hex fallback that stays closer to the original appearance. ## Related - [toCss](https://colorejs.dev/docs/api/operations/output/to-css) for a standalone formatter - [toHex](https://colorejs.dev/docs/api/operations/output/to-hex) for an sRGB hex string - [Gamut and CSS output](https://colorejs.dev/docs/concepts/gamut-and-css-output) for the choice between formats Source: https://colorejs.dev/docs/api/color-class/string-output-methods --- # Color object output Read numeric channels when you need values for a color picker, renderer or calculation. Use `toObject(space)` to keep the space with the channels, or `toArray(space)` when the caller already knows the channel order. ## Example ```ts import { colore } from 'colore-js'; const blue = colore('#2563eb'); console.log(blue.toRgb()); // { r: 37, g: 99, b: 235, alpha: 1 } console.log(blue.toOklch().l.toFixed(3)); // '0.546' ``` ## Syntax | Method | Returns | | --- | --- | | `toRgb()` | `{ r, g, b, alpha }` with RGB channels rounded to integers | | `toHsl()`, `toHsv()`, `toHwb()` | Hue and the named percentage channels, with `alpha` | | `toLab()`, `toLch()`, `toOklab()`, `toOklch()`, `toXyz()`, `toP3()` | Named channels for the requested space and `alpha` | | `toObject(space?)` | A `TaggedColorObject` you can pass back to Colore | | `toArray(space?)` | An array of coordinates followed by alpha | ### Parameters | Name | Type | Description | | --- | --- | --- | | `space` | `ColorSpace \| 'srgb-linear'` | Defaults to `'srgb'`. Encoded sRGB and P3 use 0–1, while `'srgb-linear'` gives linear-light sRGB coordinates. | ### Throws A `ColorError` if the space name is unsupported. ## Keep an exact copy for later calculations ```ts import { colore } from 'colore-js'; const blue = colore('#2563eb'); const saved = blue.toObject('srgb-linear'); console.log(colore(saved).equals(blue, 0)); // true ``` Numeric conversions can produce out-of-range values. For example, P3 red gives an sRGB red channel above 255 through `toRgb()`. Use `toGamut()` if the caller requires an in-gamut result. ## Related - [Color spaces and ranges](https://colorejs.dev/docs/concepts/color-spaces-and-ranges) for channel units - [Color string output](https://colorejs.dev/docs/api/color-class/string-output-methods) for CSS strings - [Precision, rounding and equality](https://colorejs.dev/docs/concepts/precision-rounding-and-equality) Source: https://colorejs.dev/docs/api/color-class/object-output-methods --- # Color utilities Check a color before you branch on it. You can read opacity, test equality, check the gamut or find out whether the color is light or dark. ## Example ```ts import { colore } from 'colore-js'; const blue = colore('#2563eb80'); console.log(blue.alpha().toFixed(3)); // '0.502' console.log(blue.format()); // 'hex-alpha' console.log(colore('#111827').isDark()); // true ``` ## Syntax | Method | Returns or changes | | --- | --- | | `alpha()` | Opacity as a number from 0 to 1 | | `clone()` | A new `Color` with the same channels | | `equals(other, tolerance?)` | A boolean based on linear RGB and alpha, with a tolerance of `0.01` by default | | `isInGamut(space?)` | A boolean for `'srgb'` (default) or `'p3'` | | `toGamut(space?)` | A `Color` mapped into `'srgb'` (default) or `'p3'` | | `format()` | The format label Colore recorded for the color | | `luminance()` | Relative luminance as a number | | `isLight()`, `isDark()` | A boolean classifying the color by luminance | ### Throws A `ColorError` if a gamut name is unknown, the comparison color is invalid, or the tolerance is negative or non-finite. ## Check exact equality before exporting ```ts import { colore } from 'colore-js'; const black = colore('#000'); console.log(black.equals('#191919')); // true console.log(black.equals('#191919', 0)); // false ``` Set the tolerance to `0` to compare exact channel values. For similarity by appearance, choose [deltaE](https://colorejs.dev/docs/api/operations/distance/delta-e) or [deltaEOK](https://colorejs.dev/docs/api/operations/distance/delta-e-ok). For readable text, measure contrast against its background. ## Related - [Precision, rounding and equality](https://colorejs.dev/docs/concepts/precision-rounding-and-equality) - [Gamut and CSS output](https://colorejs.dev/docs/concepts/gamut-and-css-output) - [Check color contrast](https://colorejs.dev/docs/guides/check-color-contrast) Source: https://colorejs.dev/docs/api/color-class/utility-methods --- # parse `parse` reads a CSS color string into color coordinates and alpha that you can pass between functions. The result has the same tagged linear sRGB shape for hex, OKLCH, Display P3 and other supported inputs. ## Example ```ts import { parse } from 'colore-js'; parse('rgb(255 0 0 / 50%)'); // {space: "srgb-linear", r: 1, g: 0, b: 0, alpha: 0.5} ``` ## Syntax ```ts parse(input: string): ColorValue ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | **`input`** | `string` | CSS color string. Leading and trailing whitespace and case differences are accepted. | ### Returns A `ColorValue` with `space: 'srgb-linear'`, `r`, `g`, `b` and `alpha`. Channels are linear-light sRGB and can extend outside `0`–`1` for wide-gamut inputs. Alpha is between `0` and `1`. ### Throws A `ColorError` if the input is empty, malformed or uses unsupported syntax. This includes `currentColor`, which requires element context. ## Read a color once and pass it to another function `parse` accepts hex, RGB, HSL, HWB, Lab, LCH, OKLab, OKLCH, named colors, `transparent`, `color(srgb …)`, `color(display-p3 …)` and supported `color-mix()` expressions. Store the parsed value for code that needs the same color more than once. ```ts import { parse } from 'colore-js'; import { toCss } from 'colore-js/fn'; const accent = parse('color(display-p3 0 1 0)'); accent.space; // 'srgb-linear' toCss(accent); // 'color(display-p3 0.00000 1.00000 0.00000)' ``` Use `parseToSpace` when you need the input’s own channels, such as the chroma in `oklch()`. Use `isValidColor` for a boolean check on user input. ## Related - [parseToSpace](https://colorejs.dev/docs/api/parsing/parse-to-space) to read the source color space - [isValidColor](https://colorejs.dev/docs/api/validation/is-valid-color) to accept or reject input - [parseColorMix](https://colorejs.dev/docs/api/parsing/from-css-mix) to accept only CSS mix expressions Source: https://colorejs.dev/docs/api/parsing/parse --- # parseToSpace `parseToSpace` reads a CSS color into named numbers in the space it was written in. Read `space` first so TypeScript can tell you which channels are present. ## Example ```ts import { parseToSpace } from 'colore-js'; const value = parseToSpace('oklch(65% 0.18 280 / 80%)'); if (value.space === 'oklch') { // The space tag lets TypeScript narrow the result. [value.l, value.c, value.h, value.alpha].map((n) => Number(n.toFixed(2))); // [0.65, 0.18, 280, 0.8] } ``` ## Syntax ```ts parseToSpace(input: string): ParsedColorSpaceValue ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | **`input`** | `string` | A CSS color string in one of the spaces below. | ### Returns A frozen object with `space`, `alpha` and the named channels. Tiny differences can occur when coordinates are converted back to the source space. | `space` | Channels and units | | --- | --- | | `srgb`, `p3` | `r`, `g`, `b` on a nominal gamma-encoded `0`–`1` scale. | | `hsl`, `hwb` | `h` in degrees, other channels in percent. | | `lab`, `lch` | `l` on `0`–`100`, plus opponent channels or chroma and hue. | | `oklab`, `oklch` | `l` on `0`–`1`, plus opponent channels or chroma and hue. | ### Throws A `ColorError` for an empty or invalid color, unsupported `color()` space, `currentColor` or `color-mix()`. Use `parse` to resolve supported mixes. ## Read sRGB numbers on the CSS scale Hex, named colors, `rgb()` and `color(srgb …)` all use `space: 'srgb'`. Extended channels in `color(srgb …)` can remain outside `0`–`1`, while channels in `rgb()` are clamped. ```ts import { parseToSpace } from 'colore-js'; parseToSpace('color(srgb 0.5 0 0.75)'); // {space: "srgb", r: 0.5, g: 0, b: 0.75, alpha: 1} parseToSpace('color(srgb -0.2 0 1.1)'); // {space: "srgb", r: -0.2, g: 0, b: 1.1, alpha: 1} ``` Use `colore(color).toObject(space)` when you already know which space you want to convert into. ## Related - [parse](https://colorejs.dev/docs/api/parsing/parse) for a consistent linear shape - [Object output methods](https://colorejs.dev/docs/api/color-class/object-output-methods) to convert into a space you choose - [Color spaces and ranges](https://colorejs.dev/docs/concepts/color-spaces-and-ranges) for channel units Source: https://colorejs.dev/docs/api/parsing/parse-to-space --- # detectFormat `detectFormat` identifies the format a color string appears to use. Use it to label or group colors before you process their channels. ## Example ```ts import { detectFormat } from 'colore-js'; detectFormat('#2563eb80'); // 'hex-alpha' detectFormat('color(display-p3 0.9 0.3 0.2)'); // 'p3' detectFormat('var(--brand)'); // null ``` ## Syntax ```ts detectFormat(input: string): DetectedFormat | null ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | **`input`** | `string` | The text to classify. The check ignores surrounding whitespace and letter case. | ### Returns A name such as `hex`, `hex-alpha`, `rgb`, `rgba`, `hsl`, `hsla`, `hwb`, `lab`, `lch`, `oklab`, `oklch`, `p3`, `srgb-color`, `color-mix`, `named` or `transparent`. An unrecognized input returns `null`. ### Throws None. Use `isValidColor` to check if the recognized syntax parses. ## Tell a recognized format from a valid color A recognized function name can contain invalid channels. Check the value before letting it through a form or token import. ```ts import { detectFormat, isValidColor } from 'colore-js'; detectFormat('rgb(nope)'); // 'rgb' isValidColor('rgb(nope)'); // false ``` The parser reports the failing value if you need an error message. Format detection is useful when you already have a verified input and want to choose labels or controls for it. ## Related - [isValidColor](https://colorejs.dev/docs/api/validation/is-valid-color) to check a value - [parse](https://colorejs.dev/docs/api/parsing/parse) to get numeric channels - [parseToSpace](https://colorejs.dev/docs/api/parsing/parse-to-space) to read the source space Source: https://colorejs.dev/docs/api/parsing/detect-format --- # fromCssMix `Color.fromCssMix` resolves a CSS `color-mix()` expression in JavaScript. Use `parseColorMix` from `colore-js/fn` for a tagged value you can pass to other functions. ## Example ```ts import { Color } from 'colore-js'; import { parseColorMix } from 'colore-js/fn'; const expression = 'color-mix(in srgb, red, blue)'; Color.fromCssMix(expression).hex(); // '#800080' parseColorMix(expression).space; // 'srgb-linear' ``` ## Syntax ```ts Color.fromCssMix(expression: string): Color parseColorMix(expression: string): ColorValue ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | **`expression`** | `string` | A `color-mix(in , , )` expression. Each operand can include a weight from `0%` to `100%`. Nested mixes are supported. | ### Returns The static method returns a `Color`. The function returns a `ColorValue` with linear sRGB channels and alpha. The mix uses an explicit interpolation space from `srgb`, `srgb-linear`, `lab`, `lch`, `oklab`, `oklch`, `hsl`, `hwb`, `xyz`, `xyz-d65` or `display-p3`. ### Throws A `ColorError` for an ordinary color, unsupported or malformed expression, or two weights of `0%`. A `var(--brand)` operand needs stylesheet context to resolve. ## Mix a color with transparency A transparent operand affects alpha without tinting the visible color. In polar spaces, `shorter hue` is the default. You can choose `longer hue`, `increasing hue` or `decreasing hue`. ```ts import { Color } from 'colore-js'; Color.fromCssMix('color-mix(in srgb, red 25%, transparent)').rgb(); // 'rgb(255 0 0 / 0.25)' Color.fromCssMix('color-mix(in oklch, oklch(60% 0.2 none), oklch(80% 0.1 240))').oklch(); // 'oklch(0.70000 0.15000 240.00)' ``` An authored `none` channel can take its counterpart from the other operand before the mix. If explicit weights total less than 100%, that total multiplies the mixed alpha. The two-color syntax here requires an explicit interpolation space. ## Related - [parse](https://colorejs.dev/docs/api/parsing/parse) to handle mixes alongside ordinary colors - [mixToCss](https://colorejs.dev/docs/api/operations/output/mix-to-css) to write a CSS expression - [mix](https://colorejs.dev/docs/api/operations/manipulation/mix) to blend two values directly Source: https://colorejs.dev/docs/api/parsing/from-css-mix --- # isValidColor `isValidColor` checks if Colore can parse a CSS color string. Use it for a yes-or-no answer in a form, token import or stylesheet tool. ## Example ```ts import { isValidColor } from 'colore-js'; isValidColor('#2563eb80'); // true isValidColor('oklch(0.7 0.18 280)'); // true isValidColor('hsl(nope)'); // false ``` ## Syntax ```ts isValidColor(input: string): boolean ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | **`input`** | `string` | A string you want to check against Colore’s supported color formats. | ### Returns `true` when Colore can parse the string and `false` otherwise. `currentColor` and `var()` need CSS context, so they return `false` here. ### Throws None. For an error that explains why parsing failed, call `parse`. ## Validate a user-entered color Guard user input before you use it to build a style. Colore accepts modern formats such as Display P3 and explicit-space `color-mix()` expressions, so you can keep wide-gamut input. ```ts import { colore, isValidColor } from 'colore-js'; const input = 'color(display-p3 0 1 0)'; isValidColor(input) ? colore(input).css() : '#2563eb'; // 'color(display-p3 0.00000 1.00000 0.00000)' isValidColor('var(--brand)'); // false ``` Use `Color.try()` if you need the parsed color on success. It returns the object or `null` in one call. ## Related - [detectFormat](https://colorejs.dev/docs/api/parsing/detect-format) to identify the input syntax - [parse](https://colorejs.dev/docs/api/parsing/parse) to read numeric channels - [Color static methods](https://colorejs.dev/docs/api/color-class/static-factory-methods) for `Color.try()` Source: https://colorejs.dev/docs/api/validation/is-valid-color --- # toHex `toHex` turns a color into sRGB hex in JavaScript. Use it when an API, file or token needs a hex value. The conversion rounds channels to bytes and clips values outside sRGB. ## Example ```ts import { colore } from 'colore-js'; import { toHex } from 'colore-js/fn'; colore('rgb(37 99 235)').hex(); // '#2563eb' toHex('rgb(37 99 235)'); // '#2563eb' ``` ## Convert OKLCH to hex `toHex` reads `oklch()` the same way as any other CSS color. Alpha below `1` adds two more digits. ```ts import { toHex } from 'colore-js/fn'; toHex('oklch(0.6 0.15 250)'); // '#2784d5' toHex('hsl(221 83% 53%)'); // '#2463eb' toHex('oklch(0.62 0.19 260 / 0.5)'); // '#3a81f680' ``` Some OKLCH colors, such as a high-chroma accent from a Tailwind CSS v4 theme, are outside sRGB, so hex can't hold them exactly. `toHex` clips each channel. Map the color into sRGB first to keep its lightness and hue closer to the original. It gives up some chroma instead. ```ts import { colore } from 'colore-js'; const accent = colore('oklch(0.7 0.3 150)'); accent.hex(); // '#00cb00', clipped accent.toGamut('srgb').hex(); // '#00c248', gamut-mapped ``` ## Syntax ```ts colore(color).hex(): string toHex(color: ColorInput): string ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | **`color`** | `ColorInput` | Any supported CSS color, tagged color object, `Color` instance or packed RGB number. | ### Returns A lowercase `#rrggbb` string for an opaque color or `#rrggbbaa` when alpha is less than `1`. Each output byte is rounded to an integer from `0` to `255`. ### Throws A `ColorError` if the input is invalid. ## Convert a Display P3 color to an sRGB token If the input is outside sRGB, choose how you want to bring it into range. Direct conversion clips the channels. Gamut mapping can keep more of the color’s appearance before you round it to hex. ```ts import { colore } from 'colore-js'; const green = colore('color(display-p3 0 1 0)'); green.hex(); // '#00ff00' green.toGamut('srgb').hex(); // '#00fb29' ``` If your target accepts wide-gamut CSS, use `toCss` to keep the color in a suitable format. ## Related - [toCss](https://colorejs.dev/docs/api/operations/output/to-css) for automatic gamut-aware formatting - [toRgb](https://colorejs.dev/docs/api/operations/output/to-rgb) for RGB channels in CSS - [Gamut and CSS output](https://colorejs.dev/docs/concepts/gamut-and-css-output) for the difference between clipping and mapping Source: https://colorejs.dev/docs/api/operations/output/to-hex --- # toRgb `toRgb` converts a color to a CSS `rgb()` string. The result uses integer sRGB channels and includes an alpha value when the input is translucent. ## Example ```ts import { colore } from 'colore-js'; import { toRgb } from 'colore-js/fn'; colore('#2563eb').rgb(); // 'rgb(37 99 235)' toRgb('#2563eb'); // 'rgb(37 99 235)' ``` ## Syntax ```ts colore(color).rgb(): string toRgb(color: ColorInput): string ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | **`color`** | `ColorInput` | Any supported CSS color, tagged color object, `Color` instance or packed RGB number. | ### Returns A CSS string with three integer channels from `0` to `255`. If alpha is less than `1`, the output includes a slash and alpha rounded to at most four decimal places. Colors outside sRGB are clipped. ### Throws A `ColorError` if the input is invalid. ## Convert a transparent hex token to CSS or numbers Use the string for a CSS declaration. The class method named `toRgb()` gives you numeric channels and the full alpha value for use in application code. ```ts import { colore } from 'colore-js'; import { toRgb } from 'colore-js/fn'; toRgb('#2563eb80'); // 'rgb(37 99 235 / 0.502)' colore('#2563eb80').toRgb(); // {r: 37, g: 99, b: 235, alpha: 0.5019607843137255} ``` The class object channels are rounded to integers but can extend beyond the sRGB range. Use `toObject('srgb')` when you need floating-point channels. ## Related - [toHex](https://colorejs.dev/docs/api/operations/output/to-hex) for compact sRGB output - [toCss](https://colorejs.dev/docs/api/operations/output/to-css) to preserve wide-gamut colors - [Object output methods](https://colorejs.dev/docs/api/color-class/object-output-methods) for numbers in other color spaces Source: https://colorejs.dev/docs/api/operations/output/to-rgb --- # toHsl `toHsl` turns a color into CSS `hsl()` with a hue in degrees and saturation and lightness in percent. Use it for styles or tools that expect HSL. ## Example ```ts import { colore } from 'colore-js'; import { toHsl } from 'colore-js/fn'; colore('#0f766e').hsl(); // 'hsl(175 77% 26%)' toHsl('#0f766e'); // 'hsl(175 77% 26%)' ``` ## Syntax ```ts colore(color).hsl(): string toHsl(color: ColorInput): string ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | **`color`** | `ColorInput` | Any supported CSS color, tagged color object, `Color` instance or packed RGB number. | ### Returns A CSS string with hue, saturation and lightness rounded to whole numbers. Translucent colors include alpha with up to four decimals. Colors outside sRGB are clipped first. ### Throws A `ColorError` if the input is invalid. ## Read HSL channels for a color picker Read the class object to keep the fractional hue, saturation and lightness. The standalone function gives you a formatted CSS string for displaying or exporting the value. ```ts import { colore } from 'colore-js'; import { toHsl } from 'colore-js/fn'; toHsl('hsl(190.25 72.5% 40.25% / 50%)'); // 'hsl(190 73% 40% / 0.5)' Number(colore('hsl(190.25 72.5% 40.25% / 50%)').toHsl().s.toFixed(2)); // 72.5 ``` For a color that needs to remain wide-gamut, choose OKLCH or automatic CSS output. HSL is an sRGB format. ## Related - [toOklch](https://colorejs.dev/docs/api/operations/output/to-oklch) for perceptual lightness and chroma - [toCss](https://colorejs.dev/docs/api/operations/output/to-css) for automatic format selection - [Object output methods](https://colorejs.dev/docs/api/color-class/object-output-methods) for numeric channels Source: https://colorejs.dev/docs/api/operations/output/to-hsl --- # toOklab `toOklab` converts a color to a CSS `oklab()` string. OKLab has a lightness channel and two opponent color channels, which are useful for comparing or mixing colors. ## Example ```ts import { colore } from 'colore-js'; import { toOklab } from 'colore-js/fn'; colore('#7c3aed').oklab(); // 'oklab(0.54134 0.09638 -0.22697)' toOklab('#7c3aed'); // 'oklab(0.54134 0.09638 -0.22697)' ``` ## Syntax ```ts colore(color).oklab(): string toOklab(color: ColorInput): string ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | **`color`** | `ColorInput` | Any supported CSS color, tagged color object, `Color` instance or packed RGB number. | ### Returns An `oklab(l a b)` string with each channel rounded to five decimals. The output includes slash-separated alpha when the input is translucent. Conversion keeps colors outside sRGB. ### Throws A `ColorError` if the input color is invalid. ## Read the numeric lightness of a brand color The class method `toOklab()` returns numbers for calculations. The string form is for CSS output and rounds its channels. ```ts import { colore } from 'colore-js'; const color = colore('#0f766e'); Number(color.toOklab().l.toFixed(3)); // 0.511 color.oklab(); // 'oklab(0.51094 -0.08552 -0.00958)' ``` Use OKLCH when you want to work with chroma and hue in place of the two opponent channels. ## Related - [toOklch](https://colorejs.dev/docs/api/operations/output/to-oklch) to read chroma and hue - [deltaEOK](https://colorejs.dev/docs/api/operations/distance/delta-e-ok) to compare colors in OKLab - [mix](https://colorejs.dev/docs/api/operations/manipulation/mix) to blend colors in OKLab Source: https://colorejs.dev/docs/api/operations/output/to-oklab --- # toOklch `toOklch` converts hex or another supported CSS color to an `oklch()` string. The result exposes lightness, chroma and hue and can represent colors beyond sRGB. ## Example ```ts import { colore } from 'colore-js'; import { toOklch } from 'colore-js/fn'; colore('#0f766e').oklch(); // 'oklch(0.51094 0.08606 186.39)' toOklch('#0f766e'); // 'oklch(0.51094 0.08606 186.39)' ``` ## Syntax ```ts colore(color).oklch(): string toOklch(color: ColorInput): string ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | **`color`** | `ColorInput` | Any supported CSS color, tagged color object, `Color` instance or packed RGB number. | ### Returns An `oklch(l c h)` string. Lightness and chroma use five decimal places, and hue uses two. A translucent color includes slash-separated alpha. ### Throws A `ColorError` if the input color is invalid. ## Read OKLCH channels to edit lightness The class method `toOklch()` gives you numbers without CSS serialization rounding. Save the CSS string when you need to write the color to a stylesheet. ```ts import { colore } from 'colore-js'; const brand = colore('#0f766e'); Number(brand.toOklch().l.toFixed(3)); // 0.511 brand.setOklch({ l: 0.6 }).oklch(); // 'oklch(0.60000 0.08606 186.39)' ``` Lightness is expressed from `0` to `1`. Chroma describes how vivid the color is, and hue is an angle in degrees. ## Related - [setOklch](https://colorejs.dev/docs/api/operations/manipulation/set-oklch) to specify an exact channel - [toOklab](https://colorejs.dev/docs/api/operations/output/to-oklab) for OKLab’s Cartesian channels - [OKLCH in JavaScript](https://colorejs.dev/docs/guides/oklch-in-javascript) to convert and edit a color from start to finish Source: https://colorejs.dev/docs/api/operations/output/to-oklch --- # toCss `toCss` writes a color as CSS and chooses the output format based on gamut. Use it for styles and tokens that can accept more than one CSS color syntax. ## Example ```ts import { colore } from 'colore-js'; import { toCss } from 'colore-js/fn'; colore('#7c3aed').css(); // '#7c3aed' toCss('#7c3aed'); // '#7c3aed' ``` ## Syntax ```ts colore(color).css(): string toCss(color: ColorInput): string ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | **`color`** | `ColorInput` | Any supported CSS color, tagged color object, `Color` instance or packed RGB number. | ### Returns Hex for colors within sRGB, `color(display-p3 …)` for colors that need Display P3, and `oklch(…)` for colors outside both. Each format has its own output rounding. `toCss` selects a format and leaves any gamut mapping to you. ### Throws A `ColorError` if the input color is invalid. ## Keep a wide-gamut color in a stylesheet Pass the edited color to `toCss` so it can keep a wider format when required. The two examples land on opposite sides of Display P3’s gamut boundary. ```ts import { toCss } from 'colore-js/fn'; toCss('color(display-p3 0 1 0)'); // 'color(display-p3 0.00000 1.00000 0.00000)' toCss('oklch(0.7 0.35 20)'); // 'oklch(0.70000 0.35000 20.00)' ``` Use a fixed serializer when the consumer requires a specific format. For a perceptually mapped hex fallback, call `toGamut('srgb')` before `.hex()`. ## Related - [toHex](https://colorejs.dev/docs/api/operations/output/to-hex) for a fixed sRGB format - [toOklch](https://colorejs.dev/docs/api/operations/output/to-oklch) for a fixed OKLCH format - [Gamut and CSS output](https://colorejs.dev/docs/concepts/gamut-and-css-output) for wide-gamut decisions Source: https://colorejs.dev/docs/api/operations/output/to-css --- # mixToCss `mixToCss` generates a CSS `color-mix()` expression for two colors. The browser evaluates it in the interpolation space you choose. ## Example ```ts import { colore } from 'colore-js'; import { mixToCss } from 'colore-js/fn'; colore('red').mixToCss('blue', { space: 'srgb' }); // 'color-mix(in srgb, color(srgb 1 0 0), color(srgb 0 0 1))' mixToCss('red', 'blue', { space: 'srgb' }); // 'color-mix(in srgb, color(srgb 1 0 0), color(srgb 0 0 1))' ``` ## Syntax ```ts colore(color).mixToCss(other: ColorInput | Color, options?: MixToCssOptions): string mixToCss(color: ColorInput, other: ColorInput, options?: MixToCssOptions): string ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | **`color`** | `ColorInput` | Any supported CSS color, tagged color object, `Color` instance or packed RGB number. | | **`other`** | `ColorInput` | The second color in the expression. | | **`options.weight`** | `number` | Share of the second color from `0` to `1`. Defaults to `0.5`. | | **`options.space`** | `CssColorMixSpace` | Interpolation space, defaulting to `oklab`. See the supported spaces in `parseColorMix`. | ### Returns A CSS expression with two serialized color operands. The operands keep more channel precision than ordinary CSS output. Equal weights omit the percentages. ### Throws A `ColorError` if a color is invalid, the options are invalid or contain an unknown key, or a weight or space is unsupported. ## Write a muted color into a stylesheet Mix an accent with white and give white a quarter of the weight. In the expression, the accent occupies the remaining 75%. ```ts import { mixToCss } from 'colore-js/fn'; mixToCss('blue', 'white', { space: 'oklab', weight: 0.25 }); // 'color-mix(in oklab, color(srgb 0 0 1) 75%, color(srgb 1 1 1))' ``` Use `mix` when you want a concrete color in JavaScript. Use `parseColorMix` to evaluate a supported `color-mix()` string you already have. ## Related - [mix](https://colorejs.dev/docs/api/operations/manipulation/mix) for a computed JavaScript result - [parseColorMix](https://colorejs.dev/docs/api/parsing/from-css-mix) to resolve an existing CSS expression - [OKLCH in JavaScript](https://colorejs.dev/docs/guides/oklch-in-javascript) for choosing a mixing space Source: https://colorejs.dev/docs/api/operations/output/mix-to-css --- # lighten `lighten` moves a color toward white in OKLCH while keeping its hue. Use it for a hover state or when you want a lighter version of a swatch. ## Example ```ts import { colore } from 'colore-js'; import { lighten } from 'colore-js/fn'; colore('#2563eb').lighten(8).hex(); // '#306ff8' lighten('#2563eb', 8); // '#306ff8' ``` ## Syntax ```ts colore(color).lighten(amount: number): Color lighten(color: ColorInput, amount: number): string ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | **`color`** | `ColorInput` | Any color Colore accepts: hex, `rgb()`, `hsl()`, `oklch()`, a named color, an object or a `Color`. | | **`amount`** | `number` | A percentage from `0` to `100`: how far to move toward white. `0` changes nothing and `100` gives white. | ### Returns - The method returns a new `Color`. The original is not changed. - The function returns a CSS string: hex when the result fits sRGB, `color(display-p3 …)` or `oklch(…)` when it is more vivid than sRGB. ### Throws A `ColorError` when the input is not a valid color, or when `amount` is outside `0`–`100`. A fraction such as `0.1` also throws, with a hint to pass `10` for 10%. ## Lighten a color for hover states ```ts import { colore } from 'colore-js'; const button = colore('#0f766e'); button.lighten(10).hex(); // '#27857c' ``` For a pale background tint, use [`mix`](https://colorejs.dev/docs/api/operations/manipulation/mix) with white or a [`palette`](https://colorejs.dev/docs/api/operations/scales-and-palette/palette) shade instead: `lighten` keeps the chroma, so a strong lighten stays vivid. Lightening a vivid color can push it past what sRGB can show. The method's `hex()` clips the sRGB channels. The function keeps the wider color in CSS. ```ts import { colore } from 'colore-js'; import { lighten } from 'colore-js/fn'; colore('#7c3aed').lighten(12).hex(); // '#8b4fff' lighten('#7c3aed', 12); // 'color(display-p3 0.51406 0.32029 0.97004)' ``` See [Gamut and CSS output](https://colorejs.dev/docs/concepts/gamut-and-css-output) for when each format is used. ## Lightening in RGB or HSL instead Two hand-written approaches are common. One adds the same amount to each RGB channel. The other converts to HSL and raises its lightness, which is what tinycolor2 and Sass's `lighten()` do. Both change the color as well as its lightness. Here is Tailwind's yellow-500, `#eab308`, with 20 passed to each: ```js // Add 51 (20% of 255) to each RGB channel '#ffe63b' // Add 20 points of HSL lightness, as tinycolor2's lighten(20) does '#fad45e' lighten('#eab308', 20); // '#f8c02a' ``` The RGB version turns greener, with its OKLCH hue moving from 86.0 to 100.5. The HSL version loses some of its color, with chroma dropping from 0.162 to 0.141. `lighten` keeps hue 85.8 and chroma 0.162. HSL drains other colors more. On violet-500, `#8b5cf6`, tinycolor2's `lighten(20)` keeps only 40% of the chroma, and the result looks washed out. `lighten` moves 20% of the way to white on every hue and keeps the chroma. The [tinycolor2 comparison](https://colorejs.dev/docs/comparison/tinycolor2) shows the results for violet, blue and red. ## Related - [darken](https://colorejs.dev/docs/api/operations/manipulation/darken) - [mix](https://colorejs.dev/docs/api/operations/manipulation/mix) - [setOklch](https://colorejs.dev/docs/api/operations/manipulation/set-oklch) to set an exact lightness - [OKLCH in JavaScript](https://colorejs.dev/docs/guides/oklch-in-javascript) to convert, mix and adjust a color Source: https://colorejs.dev/docs/api/operations/manipulation/lighten --- # darken `darken` lowers OKLCH lightness by a percentage of the color’s current lightness. Use it to make a button or accent darker while keeping its hue and chroma before output. ## Example ```ts import { colore } from 'colore-js'; import { darken } from 'colore-js/fn'; colore('#2563eb').darken(10).css(); // '#1451d8' darken('#2563eb', 10); // '#1451d8' ``` ## Syntax ```ts colore(color).darken(amount: number): Color darken(color: ColorInput, amount: number): string ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | **`color`** | `ColorInput` | Any supported CSS color, tagged color object, `Color` instance or packed RGB number. | | **`amount`** | `number` | Percentage of the current lightness to remove. Pass `10` for 10%. `0` keeps the color and `100` gives black. | ### Returns The method returns a new `Color`. The standalone function returns a CSS string that keeps wide-gamut results in Display P3 or OKLCH when needed. ### Throws A `ColorError` if the input color is invalid or the amount is outside `0`–`100`, nonfinite, or strictly between `0` and `1`. ## Darken a button for its pressed state Start from the button’s base color. Here both adjustments return Display P3 because keeping the original chroma moves the results beyond sRGB. Check foreground contrast again if the same text sits on both states. ```ts import { darken } from 'colore-js/fn'; darken('#0f766e', 12); // 'color(display-p3 0.13409 0.38584 0.36213)' darken('#0f766e', 24); // 'color(display-p3 0.04357 0.31791 0.29604)' ``` Keep the CSS value for the wider color, or call `toGamut('srgb')` before `hex()` when you need a hex token. ## Related - [lighten](https://colorejs.dev/docs/api/operations/manipulation/lighten) to move toward white, with a comparison of OKLCH, HSL and RGB results - [setOklch](https://colorejs.dev/docs/api/operations/manipulation/set-oklch) to set an exact lightness - [OKLCH in JavaScript](https://colorejs.dev/docs/guides/oklch-in-javascript) for a workflow with both edits Source: https://colorejs.dev/docs/api/operations/manipulation/darken --- # saturate `saturate` makes a color more vivid by increasing OKLCH chroma. It keeps lightness and hue, which lets you strengthen an accent without choosing a new color. ## Example ```ts import { colore } from 'colore-js'; import { saturate } from 'colore-js/fn'; colore('#64836a').saturate(20).css(); // '#5f8567' saturate('#64836a', 20); // '#5f8567' ``` ## Syntax ```ts colore(color).saturate(amount: number): Color saturate(color: ColorInput, amount: number): string ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | **`color`** | `ColorInput` | Any supported CSS color, tagged color object, `Color` instance or packed RGB number. | | **`amount`** | `number` | Percentage of the current chroma to add. Pass `20` for a 20% increase and `100` to double chroma. | ### Returns The method returns a new `Color`. The standalone function returns hex in sRGB, Display P3 for a wider result, or OKLCH when neither gamut fits. ### Throws A `ColorError` if the color is invalid or the amount is outside `0`–`100`, nonfinite, or strictly between `0` and `1`. ## Make a wide-gamut accent more vivid The CSS result can move past the range of hex or Display P3. Keep the returned OKLCH string if that fits your output target. ```ts import { saturate } from 'colore-js/fn'; saturate('oklch(0.7 0.3 150)', 20); // 'oklch(0.70000 0.36000 150.00)' ``` Saturating a neutral gray leaves it neutral because its chroma is zero. To tint a gray, set both chroma and hue with `setOklch`. ## Related - [desaturate](https://colorejs.dev/docs/api/operations/manipulation/desaturate) to soften a color - [setOklch](https://colorejs.dev/docs/api/operations/manipulation/set-oklch) to give a gray a specific hue - [OKLCH in JavaScript](https://colorejs.dev/docs/guides/oklch-in-javascript) for more edits in this color space Source: https://colorejs.dev/docs/api/operations/manipulation/saturate --- # desaturate `desaturate` reduces OKLCH chroma by a percentage. It keeps lightness and hue before output, so a muted accent still belongs to the same palette. ## Example ```ts import { colore } from 'colore-js'; import { desaturate } from 'colore-js/fn'; colore('#2563eb').desaturate(30).css(); // '#3f6cc7' desaturate('#2563eb', 30); // '#3f6cc7' ``` ## Syntax ```ts colore(color).desaturate(amount: number): Color desaturate(color: ColorInput, amount: number): string ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | **`color`** | `ColorInput` | Any supported CSS color, tagged color object, `Color` instance or packed RGB number. | | **`amount`** | `number` | Percentage of the current chroma to remove. Pass `30` for 30%. `0` keeps the color and `100` removes all chroma. | ### Returns The method returns a new `Color`. The standalone function returns a CSS string, using hex, Display P3 or OKLCH as appropriate for the resulting color. ### Throws A `ColorError` if the color is invalid or the amount is outside `0`–`100`, nonfinite, or strictly between `0` and `1`. ## Make a quieter accent and a matching gray Try a partial reduction for a muted accent. Use `100` for a neutral with the same OKLCH lightness. Check contrast on the actual background if you use either as text. ```ts import { desaturate } from 'colore-js/fn'; desaturate('#db2777', 60); // '#a9677b' desaturate('#db2777', 100); // '#7e7e7e' ``` Repeated changes compound. A single `60` adjustment keeps 40% of the starting chroma. Use `setOklch` when every token needs the same chroma value. ## Related - [grayscale](https://colorejs.dev/docs/api/operations/manipulation/grayscale) to remove all chroma directly - [saturate](https://colorejs.dev/docs/api/operations/manipulation/saturate) to increase chroma - [setOklch](https://colorejs.dev/docs/api/operations/manipulation/set-oklch) to set an exact chroma Source: https://colorejs.dev/docs/api/operations/manipulation/desaturate --- # adjustHue `adjustHue` rotates a color around the OKLCH hue wheel. Lightness and chroma are kept before output, so you can explore another hue at the same starting intensity. ## Example ```ts import { colore } from 'colore-js'; import { adjustHue } from 'colore-js/fn'; colore('#0f766e').adjustHue(30).css(); // '#137286' adjustHue('#0f766e', 30); // '#137286' ``` ## Syntax ```ts colore(color).adjustHue(degrees: number): Color adjustHue(color: ColorInput, degrees: number): string ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | **`color`** | `ColorInput` | Any supported CSS color, tagged color object, `Color` instance or packed RGB number. | | **`degrees`** | `number` | Angle to add to the current hue. Negative values rotate the other way. Angles wrap into one turn. | ### Returns The method returns a new `Color`. The standalone function returns a CSS string in hex, Display P3 or OKLCH according to the result’s gamut. ### Throws A `ColorError` if the color is invalid or the angle is nonfinite. ## Rotate a hue through the start of the wheel An angle can cross zero in either direction. A hue of 350° with a 30° rotation becomes 20°. Read OKLCH output to see the new angle directly. ```ts import { colore } from 'colore-js'; colore('oklch(0.62 0.12 350)').adjustHue(30).oklch(); // 'oklch(0.62000 0.12000 20.00)' colore('oklch(0.62 0.12 20)').adjustHue(-30).oklch(); // 'oklch(0.62000 0.12000 350.00)' ``` A rotation can put the new color outside the starting gamut. Use `complement` for a 180° partner fitted to the source sRGB or Display P3 gamut. ## Related - [complement](https://colorejs.dev/docs/api/operations/manipulation/complement) for a fitted 180° partner - [triadic](https://colorejs.dev/docs/api/operations/harmony/triadic) for partners 120° apart - [setOklch](https://colorejs.dev/docs/api/operations/manipulation/set-oklch) to set an absolute hue Source: https://colorejs.dev/docs/api/operations/manipulation/adjust-hue --- # grayscale `grayscale` turns a color into a neutral gray at the same OKLCH lightness. It keeps the color’s opacity, which is handy when the original is a translucent overlay. ## Example ```ts import { colore } from 'colore-js'; import { grayscale } from 'colore-js/fn'; colore('#0f766e').grayscale().css(); // '#666666' grayscale('#0f766e'); // '#666666' ``` ## Syntax ```ts colore(color).grayscale(): Color grayscale(color: ColorInput): string ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | **`color`** | `ColorInput` | Any supported CSS color, tagged color object, `Color` instance or packed RGB number. | ### Returns The method returns a new `Color`. The standalone function returns the gray as a CSS string. With ordinary sRGB colors, the result is hex. ### Throws A `ColorError` if the input is an invalid color. ## Make a transparent overlay neutral Use the same lightness and opacity on a neutral overlay. The last two digits of the hex result encode the original alpha rounded to one byte. ```ts import { grayscale } from 'colore-js/fn'; grayscale('#2563eb80'); // '#70707080' grayscale('rgb(37 99 235 / 25%)'); // '#70707040' ``` For an accent that still has some color, use `desaturate` with a percentage below `100`. ## Related - [desaturate](https://colorejs.dev/docs/api/operations/manipulation/desaturate) to keep some chroma - [setAlpha](https://colorejs.dev/docs/api/operations/manipulation/set-alpha) to change the opacity - [Color spaces and ranges](https://colorejs.dev/docs/concepts/color-spaces-and-ranges) for OKLCH units Source: https://colorejs.dev/docs/api/operations/manipulation/grayscale --- # invert `invert` gives you a color negative. It flips the gamma-encoded sRGB channels, so black becomes white, red becomes cyan, and alpha stays as it was. ## Example ```ts import { colore } from 'colore-js'; import { invert } from 'colore-js/fn'; colore('#ff0000').invert().css(); // '#00ffff' invert('#ff0000'); // '#00ffff' ``` ## Syntax ```ts colore(color).invert(): Color invert(color: ColorInput): string ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | **`color`** | `ColorInput` | Any supported CSS color, tagged color object, `Color` instance or packed RGB number. | ### Returns The method returns a new `Color`. The function returns a CSS string, with hex for an sRGB result and a wider CSS format when needed. ### Throws A `ColorError` if the input color is invalid. ## Invert a translucent icon color Apply the channel inversion to the icon’s color and keep its alpha. This changes the painted color while retaining how much of the backdrop shows through. ```ts import { invert } from 'colore-js/fn'; invert('#11223380'); // '#eeddcc80' invert('#000000'); // '#ffffff' ``` Use `complement` when you want a partner on the OKLCH hue wheel. To choose a text color for a background, check contrast against that background. ## Related - [complement](https://colorejs.dev/docs/api/operations/manipulation/complement) for an OKLCH hue partner - [setAlpha](https://colorejs.dev/docs/api/operations/manipulation/set-alpha) to change transparency - [bestTextColor](https://colorejs.dev/docs/api/operations/accessibility/best-text-color) to pick a text color for a background Source: https://colorejs.dev/docs/api/operations/manipulation/invert --- # setAlpha `setAlpha` sets a color’s opacity directly. Use it for an overlay, shadow or tint that should keep its original color channels. ## Example ```ts import { colore } from 'colore-js'; import { setAlpha } from 'colore-js/fn'; colore('#2563eb').setAlpha(0.5).css(); // '#2563eb80' setAlpha('#2563eb', 0.5); // '#2563eb80' ``` ## Syntax ```ts colore(color).setAlpha(alpha: number): Color setAlpha(color: ColorInput, alpha: number): string ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | **`color`** | `ColorInput` | Any supported CSS color, tagged color object, `Color` instance or packed RGB number. | | **`alpha`** | `number` | Opacity from `0` (transparent) to `1` (opaque). Pass `0.5` for 50%. This replaces any alpha the color already carries. | ### Returns The method returns a new `Color`. The standalone function returns a CSS string. In sRGB a fractional alpha is encoded as the last byte of an eight-digit hex color. ### Throws A `ColorError` if the input is invalid or the alpha is nonfinite or outside `0`–`1`. ## Set the opacity of an overlay Use the same base color for several overlay strengths. On a broad-gamut color the output can stay in Display P3 with a decimal alpha channel. ```ts import { setAlpha } from 'colore-js/fn'; setAlpha('#2563eb80', 0.25); // '#2563eb40' setAlpha('color(display-p3 0 1 0)', 0.25); // 'color(display-p3 0.00000 1.00000 0.00000 / 0.25)' ``` If the overlay affects readability, check the resulting foreground and background together. A transparent color’s appearance depends on what sits behind it. ## Related - [toHex](https://colorejs.dev/docs/api/operations/output/to-hex) for the hex alpha format - [toCss](https://colorejs.dev/docs/api/operations/output/to-css) for gamut-aware output - [contrastRatio](https://colorejs.dev/docs/api/operations/accessibility/contrast-ratio-wcag) to measure a translucent color against its background Source: https://colorejs.dev/docs/api/operations/manipulation/set-alpha --- # setOklch `setOklch` sets one or more OKLCH channels to the values you choose. The channels you omit keep their current values, and opacity is preserved. ## Example ```ts import { colore } from 'colore-js'; import { setOklch } from 'colore-js/fn'; colore('#2563eb').setOklch({ l: 0.62 }).oklch(); // 'oklch(0.62000 0.21521 262.88)' setOklch('#2563eb', { l: 0.62 }); // 'color(display-p3 0.29547 0.47723 0.98934)' ``` ## Syntax ```ts colore(color).setOklch(channels: OklchChannels): Color setOklch(color: ColorInput, channels: OklchChannels): string ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | **`color`** | `ColorInput` | Any supported CSS color, tagged color object, `Color` instance or packed RGB number. | | **`channels`** | `OklchChannels` | An object with at least one of `l`, `c` and `h`. | | **`channels.l`** | `number` | Lightness from `0` to `1`. Pass `0.62` for 62%. | | **`channels.c`** | `number` | Chroma from `0` to `1`. CSS `100%` chroma corresponds to `0.4`. | | **`channels.h`** | `number` | Hue in degrees. Any finite angle wraps into one turn. | ### Returns The method returns a new `Color`. The function returns a CSS string in hex, Display P3 or OKLCH. Colore keeps the requested channels before output and leaves gamut mapping to you. ### Throws A `ColorError` if the color is invalid, the channel object is empty or contains an unknown key, a channel is out of range, or chroma is added to a gray without supplying its hue. ## Tint a neutral gray with a specific hue Set both hue and chroma on a gray. Start low on chroma when you want the new color to read as a neutral. ```ts import { colore } from 'colore-js'; colore('#ddd').setOklch({ c: 0.03, h: 75 }).oklch(); // 'oklch(0.89755 0.03000 75.00)' colore('#ddd').setOklch({ c: 0.03, h: 75 }).css(); // '#e9dbc8' ``` Use the method with `.oklch()` when you want to read the new coordinates. Use `toGamut('srgb')` when a color must fit in sRGB before you export it. ## Related - [lighten](https://colorejs.dev/docs/api/operations/manipulation/lighten) to shift lightness by a percentage - [adjustHue](https://colorejs.dev/docs/api/operations/manipulation/adjust-hue) to rotate an existing hue - [OKLCH in JavaScript](https://colorejs.dev/docs/guides/oklch-in-javascript) for a worked example Source: https://colorejs.dev/docs/api/operations/manipulation/set-oklch --- # mix `mix` calculates a color between two colors in JavaScript. It defaults to OKLab. Choose another space when the path between the colors matters to your design. ## Example ```ts import { colore } from 'colore-js'; import { mix } from 'colore-js/fn'; colore('#0f766e').mix('#f59e0b', 0.5, 'oklch').css(); // '#759a41' mix('#0f766e', '#f59e0b', 0.5, 'oklch'); // '#759a41' ``` ## Syntax ```ts colore(color).mix(other: ColorInput | Color, ratio?: number, space?: MixColorSpace): Color mix(color: ColorInput, other: ColorInput, ratio?: number, space?: MixColorSpace): string ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | **`color`** | `ColorInput` | Any supported CSS color, tagged color object, `Color` instance or packed RGB number. | | **`other`** | `ColorInput` | The second color to blend. | | **`ratio`** | `number` | The share of the second color from `0` to `1`. Defaults to `0.5` for an even blend. | | **`space`** | `MixColorSpace` | Defaults to `oklab`. Also supports `oklch`, `srgb`, `hsl`, `hwb`, `lab`, `lch`, `xyz` and `p3`. | ### Returns The method returns a new `Color`. The function returns a CSS string in hex, Display P3 or OKLCH. Alpha is interpolated linearly and hue follows the shortest path in spaces with a hue channel. ### Throws A `ColorError` if either color is invalid or if the ratio or color space is unsupported. ## Choose a color space for the midpoint Compare halfway blends of the same two colors. Select a space based on the midpoint you want, then keep it consistent across the palette. ```ts import { mix } from 'colore-js/fn'; mix('red', 'blue', 0.5, 'srgb'); // '#7f007f' mix('red', 'blue', 0.5, 'oklab'); // '#8c53a2' mix('red', 'blue', 0.5, 'oklch'); // 'oklch(0.53998 0.28545 326.64)' ``` Use `mixToCss` if the browser should do the mix. For a browser-authored expression with transparent operands, `parseColorMix` evaluates the CSS rules, including premultiplied alpha. ## Related - [mixToCss](https://colorejs.dev/docs/api/operations/output/mix-to-css) to emit a CSS expression - [parseColorMix](https://colorejs.dev/docs/api/parsing/from-css-mix) to evaluate an existing CSS expression - [interpolate](https://colorejs.dev/docs/api/operations/scales-and-palette/interpolate) to mix across multiple stops - [OKLCH in JavaScript](https://colorejs.dev/docs/guides/oklch-in-javascript) for a mixing walkthrough Source: https://colorejs.dev/docs/api/operations/manipulation/mix --- # complement `complement` finds the hue opposite a color on the OKLCH wheel. It keeps lightness and fits chroma to the source gamut for an sRGB or Display P3 input. ## Example ```ts import { colore } from 'colore-js'; import { complement } from 'colore-js/fn'; colore('#7c3aed').complement().css(); // '#707600' complement('#7c3aed'); // '#707600' ``` ## Syntax ```ts colore(color).complement(): Color complement(color: ColorInput): string ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | **`color`** | `ColorInput` | Any supported CSS color, tagged color object, `Color` instance or packed RGB number. | ### Returns The method returns a new `Color`. The function returns a CSS string. A partner may fit sRGB even when the input was written in Display P3. ### Throws A `ColorError` if the input color is invalid. ## Find a partner for a brand color Start with a brand hue and use its opposite as a candidate accent. A color wheel pairing can give you a palette direction. Check the accent against the background where it will appear. ```ts import { colore } from 'colore-js'; const blue = colore('blue'); blue.complement().css(); // '#6e5000' blue.complement().isInGamut('srgb'); // true blue.adjustHue(180).isInGamut('srgb'); // false ``` `adjustHue(180)` keeps the original chroma through the rotation. Use it if you want to keep that chroma and choose an output gamut later. ## Related - [adjustHue](https://colorejs.dev/docs/api/operations/manipulation/adjust-hue) for an unfitted rotation - [triadic](https://colorejs.dev/docs/api/operations/harmony/triadic) for three hues spaced evenly - [Gamut and CSS output](https://colorejs.dev/docs/concepts/gamut-and-css-output) to choose a display format Source: https://colorejs.dev/docs/api/operations/manipulation/complement --- # triadic `triadic` gives you three colors placed evenly around the OKLCH hue wheel. Colore fits the two partners into the starting gamut when the input fits sRGB or Display P3. ## Example ```ts import { colore } from 'colore-js'; import { triadic } from 'colore-js/fn'; colore('#7c3aed').triadic().map((color) => color.css()); // ["#7c3aed", "#ab5300", "#008269"] triadic('#7c3aed'); // ["#7c3aed", "#ab5300", "#008269"] ``` ## Syntax ```ts colore(color).triadic(): [Color, Color, Color] triadic(color: ColorInput): [string, string, string] ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | **`color`** | `ColorInput` | Any supported CSS color, tagged color object, `Color` instance or packed RGB number. | ### Returns The tuple contains the input color first, then the colors at `+120°` and `+240°`. The method returns `Color` objects. The function returns CSS strings in the appropriate gamut. ### Throws A `ColorError` if the input color is invalid. ## Build three accents from a Display P3 color Give the brand the first slot and use its partners as accent candidates. Read the hue before formatting it as hex if the exact spacing matters. ```ts import { colore } from 'colore-js'; const accents = colore('color(display-p3 1 0 0)').triadic(); accents.map((color) => Number(color.toOklch().h.toFixed(1))); // [29, 149, 269] accents.every((color) => color.isInGamut('p3')); // true ``` Triadic hues give you a palette direction. For chart series with measured separation against a background, start with `categoricalColors`. ## Related - [complement](https://colorejs.dev/docs/api/operations/manipulation/complement) for a two-color pairing - [adjustHue](https://colorejs.dev/docs/api/operations/manipulation/adjust-hue) to choose your own angle - [categoricalColors](https://colorejs.dev/docs/api/operations/scales-and-palette/categorical-colors) for chart series Source: https://colorejs.dev/docs/api/operations/harmony/triadic --- # contrastRatio `contrastRatio` calculates the WCAG 2 contrast ratio for foreground and background colors. Colore composites translucent layers before measuring them so you can check the color that actually appears on the page. ## Example ```ts import { colore } from 'colore-js'; import { contrastRatio } from 'colore-js/fn'; colore('#767676').contrastRatio('#fff').toFixed(2); // '4.54' contrastRatio('#777', '#fff').toFixed(2); // '4.48' ``` ## Syntax ```ts colore(foreground).contrastRatio(background: ColorInput | Color): number contrastRatio(foreground: ColorInput, background: ColorInput): number ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | `foreground` | `ColorInput` | Text, icon or other color drawn over the background. | | `background` | `ColorInput` | The color immediately behind it. | ### Returns Both APIs return the numerical ratio. For in-gamut sRGB colors, it runs from 1 (equal luminance) to 21 (black and white). Compare the raw value with your threshold and round only for display. ### Throws A `ColorError` when a color cannot be parsed. ## Check translucent text ```ts import { contrastRatio } from 'colore-js/fn'; contrastRatio('rgb(0 0 0 / 0.5)', '#fff').toFixed(2); // '3.98' contrastRatio('rgb(0 0 0 / 0.5)', '#fff') >= 4.5; // false ``` Colore layers the background over white, then the foreground over that result. If the actual canvas has another color, resolve the layers over that canvas first. Pass the foreground first when either color has opacity. For wide-gamut input, map it to sRGB before checking a WCAG sRGB threshold. ## Related - [Check color contrast in JavaScript](https://colorejs.dev/docs/guides/check-color-contrast) for WCAG thresholds and a worked example - [isReadable](https://colorejs.dev/docs/api/operations/accessibility/is-readable) for a boolean result - [ensureContrast](https://colorejs.dev/docs/api/intelligence/ensure-contrast) to repair a failing pair Source: https://colorejs.dev/docs/api/operations/accessibility/contrast-ratio-wcag --- # contrastAPCA `contrastAPCA` measures lightness contrast for text against a background using the sRGB APCA 0.0.98G-4g calculation. Colore returns the magnitude of Lc, so you can apply the same comparison in light and dark modes. ## Example ```ts import { colore } from 'colore-js'; import { contrastAPCA } from 'colore-js/fn'; colore('#111').contrastAPCA('#fff').toFixed(2); // '105.36' contrastAPCA('#fff', '#111').toFixed(2); // '107.38' ``` ## Syntax ```ts colore(textColor).contrastAPCA(background: ColorInput | Color): number contrastAPCA(textColor: ColorInput, background: ColorInput): number ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | `textColor` | `ColorInput` | The foreground color. | | `background` | `ColorInput` | The color behind the text. | ### Returns Both APIs return the absolute Lc score. APCA assigns opposite signs to light-on-dark and dark-on-light text. Colore drops the sign, while swapping the inputs can still change the score. Use in-gamut sRGB colors for this calculation. ### Throws A `ColorError` when a color cannot be parsed. ## Check translucent text against an Lc target ```ts import { contrastAPCA } from 'colore-js/fn'; const lc = contrastAPCA('rgb(0 0 0 / 0.5)', '#fff'); lc.toFixed(2); // '67.13' lc >= 60; // true ``` Colore composites translucent colors in sRGB and assumes white beneath a translucent background. Resolve layers over the actual canvas if it differs. Choose an APCA target for your project; WCAG 2 uses [contrast ratios](https://colorejs.dev/docs/api/operations/accessibility/contrast-ratio-wcag). ## Related - [Check color contrast in JavaScript](https://colorejs.dev/docs/guides/check-color-contrast) to choose a contrast measure - [isReadable](https://colorejs.dev/docs/api/operations/accessibility/is-readable) to apply Colore’s Lc presets - [APCA reference implementation](https://github.com/Myndex/apca-w3) Source: https://colorejs.dev/docs/api/operations/accessibility/contrast-apca --- # luminance `luminance` measures how much light an sRGB color contributes. It uses the same channel weights as WCAG 2 contrast, so you can rank colors with the values a contrast calculation uses. ## Example ```ts import { colore } from 'colore-js'; import { luminance } from 'colore-js/fn'; colore('#fff').luminance(); // 1 luminance('#000'); // 0 ``` ## Syntax ```ts colore(color).luminance(): number luminance(color: ColorInput): number ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | `color` | `ColorInput` | Color to measure. Map a wide-gamut color into sRGB first when you need a value on the sRGB scale. | ### Returns Both APIs return a `number`. In-gamut sRGB ranges from 0 for black to 1 for white. The result uses color channels only. For a translucent value, resolve its displayed color over the actual background before measuring. ### Throws A `ColorError` when a color cannot be parsed. ## Compare the luminance of RGB primaries ```ts import { luminance } from 'colore-js/fn'; ['#f00', '#0f0', '#00f'].map((color) => luminance(color)); // [0.2126, 0.7152, 0.0722] ``` The green primary contributes more luminance than red or blue. A pair’s accessibility depends on the difference in luminance between foreground and background, so use `contrastRatio` for that calculation. ## Related - [contrastRatio](https://colorejs.dev/docs/api/operations/accessibility/contrast-ratio-wcag) to measure a pair - [Check color contrast in JavaScript](https://colorejs.dev/docs/guides/check-color-contrast) to apply WCAG thresholds - [Color spaces and ranges](https://colorejs.dev/docs/concepts/color-spaces-and-ranges) for linear sRGB Source: https://colorejs.dev/docs/api/operations/accessibility/luminance --- # isReadable `isReadable` checks whether a text and background pair meets a contrast target. Use it when your code needs a boolean for WCAG AA, WCAG AAA or a project-specific target. ## Example ```ts import { colore } from 'colore-js'; import { isReadable } from 'colore-js/fn'; colore('#767676').isReadable('#fff'); // true isReadable('#767676', '#fff', 'aaa'); // false ``` ## Syntax ```ts colore(textColor).isReadable(background: ColorInput | Color, options?: ReadableOptions): boolean isReadable(textColor: ColorInput, background: ColorInput, options?: ReadableOptions): boolean ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | `textColor` | `ColorInput` | The foreground color. | | `background` | `ColorInput` | The color behind the foreground. | | `options` | `ReadableOptions` | A level shorthand (`'aa'` or `'aaa'`, also accepted in uppercase) or an object with `intent`, `algorithm`, and either `level` or `target`. The default is WCAG AA for normal text. | ### Returns `true` if the raw contrast reaches your target, otherwise `false`. ### Throws A `ColorError` for invalid colors, unknown options, unsupported values, or an options object with both `target` and `level`. ## Check contrast for large text ```ts import { isReadable } from 'colore-js/fn'; isReadable('#949494', '#fff', { intent: 'largeText' }); // true isReadable('#949494', '#fff'); // false ``` WCAG AA requires 3:1 for large text and 4.5:1 for body text. With `{ algorithm: 'apca' }`, the presets are Colore thresholds expressed in Lc. Use `target` to apply a threshold from your own project. ## Related - [Check color contrast in JavaScript](https://colorejs.dev/docs/guides/check-color-contrast) for thresholds by use - [contrastRatio](https://colorejs.dev/docs/api/operations/accessibility/contrast-ratio-wcag) to read the score - [ensureContrast](https://colorejs.dev/docs/api/intelligence/ensure-contrast) to find an adjusted color Source: https://colorejs.dev/docs/api/operations/accessibility/is-readable --- # bestTextColor `bestTextColor` picks black or white text for a background. Pass an array of approved colors to choose from that set instead. Colore compares the candidates using absolute APCA contrast. ## Example ```ts import { colore } from 'colore-js'; import { bestTextColor } from 'colore-js/fn'; colore('#7c3aed').bestTextColor().css(); // '#ffffff' bestTextColor('#7c3aed'); // '#ffffff' ``` ## Syntax ```ts colore(background).bestTextColor(candidates?: ColorInput[]): Color bestTextColor(background: ColorInput, candidates?: ColorInput[]): string ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | `background` | `ColorInput` | The color behind the text. | | `candidates` | `ColorInput[]` | Allowed foreground colors. Defaults to black and white. | ### Returns The method returns the winning candidate as a `Color`. The function returns it as CSS. It uses hex if the winner fits sRGB, Display P3 if it fits that wider gamut, and OKLCH otherwise. Check `isReadable` when you also require a specific minimum. ### Throws A `ColorError` for invalid colors or an empty candidate list. ## Choose from a brand palette ```ts import { bestTextColor } from 'colore-js/fn'; bestTextColor('#000', ['#aaa', 'color(display-p3 0 1 0)']); // 'color(display-p3 0.00000 1.00000 0.00000)' ``` For contrast checks with a wide-gamut candidate, map the candidate to sRGB before measuring an sRGB threshold. ## Related - [Black or white text](https://colorejs.dev/docs/guides/black-or-white-text) for how APCA, WCAG 2 and brightness picks compare - [Check color contrast in JavaScript](https://colorejs.dev/docs/guides/check-color-contrast) to verify the chosen color - [isReadable](https://colorejs.dev/docs/api/operations/accessibility/is-readable) to apply a minimum - [ensureContrast](https://colorejs.dev/docs/api/intelligence/ensure-contrast) to adjust a color when the candidates fall short Source: https://colorejs.dev/docs/api/operations/accessibility/best-text-color --- # ensureContrast `ensureContrast` turns `#777777` on white into `#767676`. It finds a passing foreground by moving lightness as little as it can under the rules you choose. You get the color and a flag saying whether the search succeeded. ## Example ```ts import { ensureContrast } from 'colore-js'; import { ensureContrast as fixContrast } from 'colore-js/fn'; ensureContrast('#777777', '#ffffff').color.hex(); // '#767676' fixContrast('#777777', '#ffffff'); // { color: '#767676', satisfied: true, iterations: 1 } ``` ## Syntax ```ts // colore-js ensureContrast(foreground: ColorInput | Color, background: ColorInput | Color, options?: EnsureContrastOptions): ResolveResult // colore-js/fn ensureContrast(foreground: ColorInput, background: ColorInput, options?: EnsureContrastOptions): { color: string; satisfied: boolean; unsatisfied?: string[]; iterations: number } ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | `foreground`, `background` | `ColorInput \| Color` | The color to adjust and the background to check it against. | | `options.algorithm` / `options.intent` | `ContrastAlgorithm` / `ContrastIntent` | Defaults to WCAG 2 and normal text. Choose `'largeText'`, `'ui'`, `'focus'` or `'decorative'` for another context. | | `options.level` / `options.target` | `'aa' \| 'aaa'` / `number` | Default WCAG AA body text target is 4.5. Set a level or give an explicit ratio or absolute APCA Lc. | | `options.preserve` | `'auto' \| 'hue' \| 'chroma' \| 'both'` | The default tries to keep hue first, then chroma. Choose an explicit rule to require it. | | `options.direction` | `'auto' \| 'darken' \| 'lighten'` | The direction lightness may move. With automatic direction and preservation, the search can also try a gray. | ### Returns The result contains `color`, `satisfied` and `iterations`. When the search cannot meet the target, `color` is the original foreground and `unsatisfied` is `['contrast']`. The root export returns a `Color` in `color`. The `/fn` export returns a CSS string, which can be Display P3 or OKLCH for a wide-gamut color. ### Throws A `ColorError` for invalid colors, unsupported options or a target outside the measure’s accepted range. ## Repair a pair for WCAG AAA ```ts import { ensureContrast as fixContrast } from 'colore-js/fn'; fixContrast('#3b82f6', '#fff', { level: 'aaa' }); // { color: '#0452c2', satisfied: true, iterations: 1 } fixContrast('color(display-p3 1 0 0)', '#fff', { direction: 'lighten', target: 7 }); // { color: 'color(display-p3 1.00000 0.00000 0.00000)', satisfied: false, unsatisfied: ['contrast'], iterations: 1 } ``` Check `satisfied` before applying the result when you set a strict preservation rule or direction. Use rendered sRGB colors for WCAG 2 checks. ## Related - [Check color contrast in JavaScript](https://colorejs.dev/docs/guides/check-color-contrast) to measure and repair a pair - [isReadable](https://colorejs.dev/docs/api/operations/accessibility/is-readable) to check a target without adjusting the color - [audit](https://colorejs.dev/docs/api/audit) to find failing pairs in a palette Source: https://colorejs.dev/docs/api/intelligence/ensure-contrast --- # simulate `simulate` previews how a color might appear with color vision deficiency. Compare chart or UI colors under the same simulation to find pairs that may be hard to tell apart. ## Example ```ts import { colore } from 'colore-js'; import { simulate } from 'colore-js/fn'; colore('#ef4444').simulate('protanopia').css(); // '#7a7a42' simulate('#ef4444', 'protanopia'); // '#7a7a42' ``` ## Syntax ```ts colore(color).simulate(type: ColorBlindnessType): Color simulate(color: ColorInput, type: ColorBlindnessType): string ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | `color` | `ColorInput` | The original color. Its alpha carries through to the result. | | `type` | `ColorBlindnessType` | `'protanopia'`, `'protanomaly'`, `'deuteranopia'`, `'deuteranomaly'`, `'tritanopia'`, `'tritanomaly'`, `'achromatopsia'` or `'achromatomaly'`. | ### Returns The method returns a `Color`. The function returns a CSS string, using hex when the result fits sRGB. ### Throws A `ColorError` for invalid colors or an unsupported simulation type. ## Compare red and green chart series ```ts import { simulate } from 'colore-js/fn'; simulate('#ef4444', 'deuteranopia'); // '#9a9a35' simulate('#10b981', 'deuteranopia'); // '#9b9b85' ``` These colors move closer in hue under the simulation. Add labels or change the line pattern when distinguishing the two series matters. ## Related - [Accessible chart colors](https://colorejs.dev/docs/guides/chart-colors) to build and check a dashboard palette - [categoricalColors](https://colorejs.dev/docs/api/operations/scales-and-palette/categorical-colors) to generate distinct series colors - [audit](https://colorejs.dev/docs/api/audit) to check named colors together Source: https://colorejs.dev/docs/api/operations/scales-and-palette/simulate-color-blindness --- # audit `audit` checks a named palette for contrast, gamut and colors that are difficult to distinguish. It tells you which pairs fail and suggests a replacement when Colore can find one. Color vision checks for protanopia, deuteranopia and tritanopia are on by default. ## Example ```ts import { audit } from 'colore-js'; import { audit as auditPalette } from 'colore-js/fn'; const colors = { text: '#777777', background: '#ffffff' }; const result = audit(colors); result.passed; // false result.checked; // 1 result.issues[0]?.suggestion?.value; // '#767676' auditPalette(colors).issues[0]?.type; // 'contrast' ``` ## Syntax ```ts audit(input: AuditInput, options?: AuditOptions): AuditResult ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | `input` | `Record` | Colors keyed by token or role name. | | `options.algorithm` / `options.level` | `ContrastAlgorithm` / `ContrastLevel` | Defaults to WCAG 2 AA. APCA levels apply Colore’s Lc presets. | | `options.gamut` | `'srgb' \| 'p3'` | Gamut to check. Defaults to sRGB. | | `options.minDeltaE` / `options.minCvdDeltaE` | `number` / `number` | CIEDE2000 distance for normal and simulated vision. Defaults to 10 and 8. | | `options.checkColorBlind` / `options.cvdTypes` | `boolean` / `ColorBlindnessType[]` | Color vision checks are on by default, with protanopia, deuteranopia and tritanopia. | | `options.pairs` / `options.autoPairs` | `ColorPair[]` or foreground/background tuples / `boolean` | Supply explicit pairs by name. Automatic pairing defaults to true. | ### Returns `AuditResult` includes `passed`, the number of pairs `checked`, and `issues`. Contrast and configuration errors fail the audit. Gamut, distinction, and color vision findings are warnings. Issues identify the colors involved and include a measured value, threshold or suggestion when available. ### Throws A `ColorError` for invalid colors or options. An explicit pair naming a missing color appears as a configuration error in the result. ## CSS custom properties Use the root exports to check or repair color custom properties. `auditCssVariables` returns a `CssAuditResult` with the checked scopes and resolved values on each issue. `fixCssVariables` returns a `CssFixResult` that adds `css` and `changes`. ```ts import { auditCssVariables, fixCssVariables } from 'colore-js'; const css = ':root { --background: #ffffff; --foreground: #999999; }'; auditCssVariables(css).issues[0]?.message; // '--foreground on --background in :root: 2.85:1, needs 4.5:1' fixCssVariables(css).css; // ':root { --background: #ffffff; --foreground: #767676; }' ``` The CSS functions accept `algorithm`, `level`, `pairs` and `autoPairs`. They detect names such as `--primary-foreground` for `--primary`. When supplying named pairs, you can set an `intent` such as `'ui'` on each pair object, and a `scope` such as `'.dark'` to check that pair in one selector only. ## Related - [Check color contrast in JavaScript](https://colorejs.dev/docs/guides/check-color-contrast) to review individual pairs - [Dark mode colors](https://colorejs.dev/docs/guides/dark-mode-colors) to audit both modes - [ensureContrast](https://colorejs.dev/docs/api/intelligence/ensure-contrast) to adjust one foreground Source: https://colorejs.dev/docs/api/audit --- # deltaE `deltaE` measures CIEDE2000 color difference in JavaScript. Use it to compare a target and sample when your workflow specifies ΔE00. You can set your own weights for lightness, chroma and hue. ## Example ```ts import { colore } from 'colore-js'; import { deltaE } from 'colore-js/fn'; colore('#7c3aed').deltaE('#7b3ae8').toFixed(3); // '0.647' deltaE('#7c3aed', '#2563eb').toFixed(3); // '18.267' ``` ## Syntax ```ts colore(first).deltaE(second: ColorInput | Color, kL?: number, kC?: number, kH?: number): number deltaE(first: ColorInput, second: ColorInput, kL?: number, kC?: number, kH?: number): number ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | `first`, `second` | `ColorInput` | The two colors to compare. The method can also take a `Color`. | | `kL`, `kC`, `kH` | `number` | Optional weighting factors for lightness, chroma and hue. Each defaults to `1`. Larger values reduce the contribution of that channel. | ### Returns Both APIs return a nonnegative ΔE00 number. Alpha is ignored, so colors with identical channels and different opacity have distance zero. ### Throws A `ColorError` if a color cannot be parsed or a weighting factor is non-finite or at most zero. ## Compare samples with lightness weighted down ```ts import { deltaE } from 'colore-js/fn'; deltaE('#7c3aed', '#7b3ae8', 1).toFixed(3); // '0.647' deltaE('#7c3aed', '#7b3ae8', 2).toFixed(3); // '0.518' ``` Use the same formula and weights as the specification you are comparing against. Pick a tolerance for your use case and compare the unrounded value in code. ## Related - [deltaEOK](https://colorejs.dev/docs/api/operations/distance/delta-e-ok) for distances measured in OKLab - [audit](https://colorejs.dev/docs/api/audit) to check color distinction across a palette - [Color precision, rounding and equality](https://colorejs.dev/docs/concepts/precision-rounding-and-equality) to compare individual channels Source: https://colorejs.dev/docs/api/operations/distance/delta-e --- # deltaEOK `deltaEOK` measures the straight-line distance between two colors in OKLab. It uses the same metric Colore applies to find the closest color in a list or the closest CSS color name. ## Example ```ts import { colore } from 'colore-js'; import { deltaEOK } from 'colore-js/fn'; colore('#7c3aed').deltaEOK('#7b3ae8').toFixed(4); // '0.0078' deltaEOK('#7c3aed', '#2563eb').toFixed(4); // '0.1239' ``` ## Syntax ```ts colore(first).deltaEOK(second: ColorInput | Color): number deltaEOK(first: ColorInput, second: ColorInput): number ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | `first`, `second` | `ColorInput` | The colors to compare. The method can also take a `Color`. | ### Returns Both APIs return a nonnegative distance. Identical OKLab coordinates give zero regardless of opacity. This number uses OKLab units. Use `deltaE` when your threshold is specified in CIEDE2000. ### Throws A `ColorError` when an input cannot be parsed. ## Rank possible replacements for a color ```ts import { colore } from 'colore-js'; const target = colore('#7c3aed'); const candidates = ['#2563eb', '#7b3ae8']; candidates.map((color) => target.deltaEOK(color).toFixed(4)); // ['0.1239', '0.0078'] ``` The smaller distance identifies the closer match. Keep the numerical distances when you need to compare several candidates in a report. For the winning candidate alone, use `nearest`. ## Related - [nearest](https://colorejs.dev/docs/api/operations/distance/nearest) to find the closest candidate directly - [deltaE](https://colorejs.dev/docs/api/operations/distance/delta-e) for a CIEDE2000 threshold - [OKLCH in JavaScript](https://colorejs.dev/docs/guides/oklch-in-javascript) to convert and edit perceptual color coordinates Source: https://colorejs.dev/docs/api/operations/distance/delta-e-ok --- # nearest `nearest` finds the closest color in a list of swatches or design tokens. It compares colors in OKLab by default and returns the index, so you can retrieve a label or token name from the original list. ## Example ```ts import { colore } from 'colore-js'; const match = colore('#7c3aed').nearest(['#f00', '#7b3ae8', '#0f0']); match.color.css(); // '#7b3ae8' match.index; // 1 match.distance.toFixed(4); // '0.0078' ``` ## Syntax ```ts colore(target).nearest( colors: (ColorInput | Color)[], distanceFn?: (first: InternalColor, second: InternalColor) => number ): NearestResult ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | `target` | `ColorInput` | The color you want to match. | | `colors` | `(ColorInput \| Color)[]` | A list of at least one candidate. | | `distanceFn` | `(first: InternalColor, second: InternalColor) => number` | Optional comparator. Smaller values win. The default uses OKLab distance and ignores opacity. | ### Returns | Name | Type | Description | | --- | --- | --- | | `color` | `Color` | The winning candidate as a Color instance. | | `distance` | `number` | Distance from the target under the chosen measure. | | `index` | `number` | Zero-based position in the original list. An exact tie keeps the earlier color. | ### Throws An `Error` for an empty list, or a `ColorError` for invalid color input or a non-array candidate argument. ## Match an imported color to a design token ```ts import { colore } from 'colore-js'; const tokens = { inverse: '#fff', ink: '#000', muted: '#767676' }; const keys = Object.keys(tokens); const token = colore('#777').nearest(Object.values(tokens)); keys[token.index]; // 'muted' ``` ## Related - [nearestNamed](https://colorejs.dev/docs/api/operations/distance/nearest-named) to search CSS color names - [deltaEOK](https://colorejs.dev/docs/api/operations/distance/delta-e-ok) for the default distance - [palette](https://colorejs.dev/docs/api/operations/scales-and-palette/palette) to build your own candidates Source: https://colorejs.dev/docs/api/operations/distance/nearest --- # nearestNamed `nearestNamed` finds the closest CSS named color to a hex, RGB or OKLCH value. Use the name to label a swatch and keep the distance if you also want to show how close the match is. ## Example ```ts import { colore } from 'colore-js'; import { nearestNamed } from 'colore-js/fn'; colore('#7c3aed').nearestNamed().name; // 'blueviolet' nearestNamed('#7c3aed').color; // '#8a2be2' nearestNamed('#7c3aed').distance.toFixed(4); // '0.0372' ``` ## Syntax ```ts colore(target).nearestNamed( distanceFn?: (first: InternalColor, second: InternalColor) => number ): NearestNamedResult nearestNamed(target: ColorInput): { name: string; color: string; distance: number } ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | `target` | `ColorInput` | The color you want to name. | | `distanceFn` | `(first: InternalColor, second: InternalColor) => number` | Optional class comparator. By default both APIs use OKLab distance. | ### Returns | Name | Type | Description | | --- | --- | --- | | `name` | `string` | The CSS color name. | | `color` | `Color \| string` | The named color as a `Color` from the method or a CSS string from the function. | | `distance` | `number` | Distance from the input under the chosen measure. | ### Throws A `ColorError` when an input cannot be parsed. ## Name a translucent swatch ```ts import { nearestNamed } from 'colore-js/fn'; nearestNamed('#0000'); // { name: 'black', color: '#000000', distance: 0 } ``` Default matching compares the color channels regardless of opacity. Use the original alpha if it matters to your swatch or displayed CSS. ## Related - [nearest](https://colorejs.dev/docs/api/operations/distance/nearest) to match against a private palette - [deltaEOK](https://colorejs.dev/docs/api/operations/distance/delta-e-ok) for the default distance - [OKLCH in JavaScript](https://colorejs.dev/docs/guides/oklch-in-javascript) to convert a color before labeling it Source: https://colorejs.dev/docs/api/operations/distance/nearest-named --- # scale `scale` builds a color scale between two endpoints. Use it for a stepped gradient or ordered data. The default OKLab interpolation gives you stops spaced evenly along the path in that space. ## Example ```ts import { colore } from 'colore-js'; import { scale } from 'colore-js/fn'; colore('#ef4444').scale('#3b82f6', { steps: 3 }).map((color) => color.css()); scale('#ef4444', '#3b82f6', { steps: 3 }); // ['#ef4444', '#a775a5', '#3b82f6'] from either line ``` ## Syntax ```ts colore(from).scale(to: ColorInput | Color, options?: ScaleOptions): Color[] scale(from: ColorInput, to: ColorInput, options?: ScaleOptions): string[] ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | `from`, `to` | `ColorInput` | Start and end colors. The method can take a `Color`. | | `options.steps` | `number` | The number of output colors, including endpoints. Defaults to 5. | | `options.space` | `InterpolationColorSpace` | `'oklab'` by default. Also accepts `'oklch'`, `'srgb'`, `'p3'`, `'hsl'`, `'lab'` and `'lch'`. | ### Returns The method returns `Color[]`. The function returns CSS strings, including Display P3 or OKLCH when a color falls outside sRGB. ### Throws A `ColorError` for an invalid color, unsupported space, unknown option, or step count under two or with a fractional part. ## Create seven stops for an ordered chart ```ts import { scale } from 'colore-js/fn'; scale('#ef4444', '#3b82f6', { steps: 7 }); // ['#ef4444', '#d85c69', '#c16b88', '#a775a5', '#8b7cc0', '#6a80db', '#3b82f6'] ``` ## Related - [interpolate](https://colorejs.dev/docs/api/operations/scales-and-palette/interpolate) to sample at one position - [palette](https://colorejs.dev/docs/api/operations/scales-and-palette/palette) for shades from one base - [Chart colors](https://colorejs.dev/docs/guides/chart-colors) for distinct series in unordered charts Source: https://colorejs.dev/docs/api/operations/scales-and-palette/scale --- # interpolate `interpolate` samples a color at a position between two or more stops. Pass endpoints for a two-color blend, or add intermediate stops for a gradient that follows a specific path. ## Example ```ts import { Color } from 'colore-js'; import { interpolate } from 'colore-js/fn'; const stops = ['#ef4444', '#f59e0b', '#10b981']; Color.interpolate(stops, 0.5, 'oklch').css(); // '#f59e0b' interpolate(stops, 0.25); // '#f47635' ``` ## Syntax ```ts Color.interpolate(colors: (ColorInput | Color)[], t: number, space?: InterpolationColorSpace): Color interpolate(colors: ColorInput[], t: number, space?: InterpolationColorSpace): string ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | `colors` | `ColorInput[]` | Ordered list of at least two stops. The class method also accepts Color objects. | | `t` | `number` | Position from `0` (first stop) to `1` (last stop). Stops divide the range evenly. | | `space` | `InterpolationColorSpace` | Defaults to `'oklab'`. Also accepts `'oklch'`, `'srgb'`, `'p3'`, `'hsl'`, `'lab'` and `'lch'`. | ### Returns A `Color` from the class method or a CSS string from the function. The function uses Display P3 or OKLCH when an output falls outside sRGB. ### Throws A `ColorError` for invalid colors, fewer than two stops, an unsupported color space, or a position outside `0–1`. ## Sample a wide-gamut gradient ```ts import { interpolate } from 'colore-js/fn'; interpolate(['color(display-p3 1 0 0)', 'color(display-p3 0 1 0)'], 0.5); // 'color(display-p3 0.78602 0.67702 0.01518)' ``` Each segment follows the chosen interpolation space. The function picks a CSS serialization that can hold the resulting color. ## Related - [scale](https://colorejs.dev/docs/api/operations/scales-and-palette/scale) for an array of evenly spaced colors - [mix](https://colorejs.dev/docs/api/operations/manipulation/mix) to blend two colors - [OKLCH in JavaScript](https://colorejs.dev/docs/guides/oklch-in-javascript) to choose a space for a color blend Source: https://colorejs.dev/docs/api/operations/scales-and-palette/interpolate --- # palette `palette` generates a Tailwind-style shade ramp from one color. The seed itself sits at the step nearest its OKLCH lightness, so your brand color appears in the ramp exactly. ## Example ```ts import { colore } from 'colore-js'; import { palette } from 'colore-js/fn'; colore('#6366f1').palette()[5]?.css(); // '#6366f1' palette('#6366f1'); // ['#f3f5fe', '#e2e7fc', '#cad2fa', '#a7b2f7', '#828df4', '#6366f1', // '#4640c9', '#311aa7', '#1d0d6c', '#11064b', '#040123'] ``` ## Syntax ```ts colore(base).palette(options?: PaletteOptions): Color[] palette(base: ColorInput, options?: PaletteOptions): string[] ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | `base` | `ColorInput` | Seed color to include in the ramp. | | `options.steps` | `number` | Integer from 2 to 101. The default is 11 shades, labeled 50, 100, 200 up to 900, and 950. Other counts sample the same lightness curve. | ### Returns The method returns `Color[]`. The function returns CSS strings. The generated shades fit sRGB and preserve the seed alpha and hue. A wide-gamut seed keeps its color coordinates and uses Display P3 or OKLCH output. ### Throws A `ColorError` for invalid input, an unknown option, or a step count outside the supported range. ## Build a compact five-shade ramp ```ts import { palette } from 'colore-js/fn'; palette('#6366f1', { steps: 5 }); // ['#f3f5fe', '#b8c2f9', '#6366f1', '#271389', '#040123'] ``` The nearest step depends on the seed’s lightness, so the brand can fall on a different step when you change the seed. ## Related - [Tailwind v4 colors from a brand color](https://colorejs.dev/docs/guides/tailwind-v4-colors) to turn a ramp into CSS tokens - [Palette generator](https://colorejs.dev/palette) to build and copy a scale from your own color - [generateSystem](https://colorejs.dev/docs/api/system/generate-system) for semantic roles and both modes - [scale](https://colorejs.dev/docs/api/operations/scales-and-palette/scale) for a ramp between two endpoints Source: https://colorejs.dev/docs/api/operations/scales-and-palette/palette --- # categoricalColors `categoricalColors` picks colors for chart series, legends and tags. It favors colors that stay far apart under normal vision and two red-green color vision simulations, and checks each one against your chart background (3:1 by default, or Lc 45 with APCA). ## Example ```ts import { categoricalColors } from 'colore-js'; import { categoricalColors as chartColors } from 'colore-js/fn'; categoricalColors(3).map((color) => color.css()); // ['#1781d4', '#4ba81b', '#ad1a6b'] chartColors(3); // ['#1781d4', '#4ba81b', '#ad1a6b'] ``` ## Syntax ```ts // colore-js categoricalColors(count: number, options?: CategoricalColorOptions): Color[] // colore-js/fn categoricalColors(count: number, options?: CategoricalColorOptions): string[] ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | `count` | `number` | A whole number from 1 to 12. | | `options.background` | `ColorInput` | The chart background. Defaults to white. | | `options.seed` | `ColorInput` | Optional first series color. Colore keeps it as supplied, so check its contrast separately. | | `options.algorithm` | `'wcag2' \| 'apca'` | Contrast measure. Defaults to WCAG 2. | | `options.level` / `options.target` | `'aa' \| 'aaa'` / `number` | Generated colors default to a 3:1 ratio or Lc 45. Pass `target` to set a different minimum. | ### Returns The root function returns `Color[]`. The `/fn` version returns CSS strings. With the same options, increasing the count keeps the earlier colors in place. ### Throws A `ColorError` for invalid colors, unsupported options, an out-of-range count or too few colors at the requested contrast. ## Pick colors for a dark dashboard ```ts import { categoricalColors as chartColors } from 'colore-js/fn'; chartColors(5, { background: '#0a0a0a' }); // ['#70b2fb', '#bcdb29', '#ec5480', '#2feac3', '#f86927'] ``` Check the displayed colors against the real chart background. Labels or line patterns also help readers distinguish nearby series. ## Related - [Accessible chart colors](https://colorejs.dev/docs/guides/chart-colors) for light and dark dashboard palettes - [simulate](https://colorejs.dev/docs/api/operations/scales-and-palette/simulate-color-blindness) to preview color vision differences - [scale](https://colorejs.dev/docs/api/operations/scales-and-palette/scale) for ordered values Source: https://colorejs.dev/docs/api/operations/scales-and-palette/categorical-colors --- # generateSystem `generateSystem` builds light and dark themes from one brand color. You get shade ramps, background and text pairs, and semantic colors for roles such as error and success. Your brand color stays exactly as given whenever it meets the contrast target, and text colors are chosen to pass contrast in both modes. ## Example ```ts import { generateSystem } from 'colore-js'; import { generateSystem as generateTheme } from 'colore-js/fn'; const system = generateSystem('#0f766e'); system.light.primaryBase.css(); // '#0f766e' system.light.text.css(); // '#000000' system.dark.text.css(); // '#ffffff' system.audit().passed; // true generateTheme('#0f766e').dark.background.css(); // '#070707' ``` ## Syntax ```ts generateSystem( brand: ColorInput | Color, config?: SystemConfig & { modes?: M } ): GeneratedSystem ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | `brand` | `ColorInput \| Color` | Seed color for the primary role and the theme. | | `config.modes` | `readonly ThemeMode[]` | Generate `'light'`, `'dark'` or both. Defaults to both. | | `config.roles` | `SemanticRole[]` | Defaults to primary, secondary, error, warning, success, info and neutral. | | `config.algorithm` / `config.level` | `ContrastAlgorithm` / `ContrastLevel` | Defaults to WCAG 2 AA. Use AAA or an APCA preset for the text pairs. | | `config.roleSeeds` | `Partial>` | Override specific role colors. Each seed appears in its shade ramp. | | `config.neutralHue` | `number \| 'auto'` | Tune the neutral hue. Defaults to `'auto'`. | | `config.preserveSeed` | `boolean` | Defaults to true. Keeps a seed as the role’s base when it meets that mode’s requirements. | ### Returns Both exports return a generated system with the requested modes, resolved `config`, original `seed`, `audit()` and [export methods](https://colorejs.dev/docs/api/system/system-to-tailwind-css). Each named mode has page tokens such as `background` and `text`. An omitted mode is `undefined`. ### Throws A `ColorError` for invalid colors or config. `system.theme(mode)` also throws if that mode was omitted. ## Generate only a dark theme ```ts import { generateSystem } from 'colore-js'; const darkOnly = generateSystem('#0f766e', { modes: ['dark'] }); darkOnly.dark.background.css(); // '#070707' darkOnly.light; // undefined ``` You can audit the system before exporting it. The audit checks the role text pairs and page text tokens against the configured contrast target. ## Related - [Generate a shadcn/ui theme from one color](https://colorejs.dev/docs/guides/shadcn-theme-from-one-color) to export your variables - [Dark mode colors](https://colorejs.dev/docs/guides/dark-mode-colors) to check the generated pairs - [Theme generator](https://colorejs.dev/playground) to preview a system on UI examples in light and dark mode - [Theme exports](https://colorejs.dev/docs/api/system/system-to-tailwind-css) for Tailwind v4, shadcn/ui and design tokens Source: https://colorejs.dev/docs/api/system/generate-system --- # inspectCssTheme `inspectCssTheme` reads a stylesheet and tells you what its color theme is made of: which kind of theme it is, which modes it covers, what the brand color is, and what a complete theme would still need. Use it before you change a theme, so the change fits the file you already have. ## Example ```ts import { inspectCssTheme } from 'colore-js'; const css = `:root { --bg: #ffffff; --text: #17212b; --brand: #4f46e5; }`; const theme = inspectCssTheme(css); console.log(theme.kind, theme.format, theme.modes.join(', ')); console.log(theme.brand?.token, theme.brand?.hex, theme.brand?.look); console.log(theme.missing); ``` ```text css-variables hex light --brand #4f46e5 common-default [ 'dark mode', 'success and warning colors (optional)' ] ``` The indigo matches Colore’s `common-default` category. The report also shows that the stylesheet has only a light theme. ## Syntax ```ts inspectCssTheme(css: string): ThemeReport ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | **`css`** | `string` | The contents of a stylesheet, such as `globals.css`. | ### Returns A `ThemeReport`: | Property | Description | | --- | --- | | **`kind`** | `'shadcn'`, `'tailwind'`, `'css-variables'` or `'none'`. | | **`format`** | The main value format: `'oklch'`, `'hex'`, `'rgb'`, `'hsl'` or `'hsl-channels'` (shadcn/ui v3). Can also be `'other'`, `'mixed'` or `'none'`. | | **`modes`** | The modes the file defines: `'light'`, `'dark'` or both. | | **`scopes`** | The first selector that holds colors for each mode, such as `:root`, `.dark` or `@theme`. | | **`tokens`** | Every color token with its `name` (without `--`), its `group` and its original `values` per mode. References such as `var(--primary)` are left out. | | **`brand`** | The brand token, its original `light` and `dark` values, `hex` and `oklch` conversions, and a `look`. | | **`missing`** | What a complete theme still needs, such as dark mode or shadcn/ui chart colors. | `brand.look` is `'neutral'` for a gray brand or an untouched shadcn/ui primary from any base color, Slate and Gray included, `'common-default'` for a saturated indigo to purple brand, and `'custom'` for anything else. ## Usage Token groups are the same ones [`applyThemeToCss`](https://colorejs.dev/docs/api/system/apply-theme-to-css) and [`adjustCssVariables`](https://colorejs.dev/docs/api/system/adjust-css-variables) accept, so the report tells you exactly which group to change. To check contrast in the same file, use [`auditCssVariables`](https://colorejs.dev/docs/api/audit#css-custom-properties). The [Colore CLI](https://colorejs.dev/docs/agents) runs this check across a whole project with `colore inspect`, and also lists colors hard-coded in components. ## Related - [applyThemeToCss](https://colorejs.dev/docs/api/system/apply-theme-to-css) - [adjustCssVariables](https://colorejs.dev/docs/api/system/adjust-css-variables) - [generateSystem](https://colorejs.dev/docs/api/system/generate-system) Source: https://colorejs.dev/docs/api/system/inspect-css-theme --- # applyThemeToCss `applyThemeToCss` rebrands the theme file you already have. Give it your stylesheet and a system from [`generateSystem`](https://colorejs.dev/docs/api/system/generate-system), and it rewrites the existing color tokens in place: same variable names, same value format, nothing else in the file touched. It can also add what the theme is missing, such as a dark mode or chart colors. ## Example ```ts import { applyThemeToCss, generateSystem } from 'colore-js'; const css = `:root { --bg: #ffffff; --text: #17212b; --brand: #4f46e5; }`; const result = applyThemeToCss(css, generateSystem('#0f766e'), { add: true }); console.log(result.css); ``` ```css :root { --bg: #f3f6f5; --text: #070707; --brand: #0f766e; } @media (prefers-color-scheme: dark) { :root { --bg: #070707; --text: #f3f6f5; } } ``` The brand is exactly the color you gave, and the new dark mode uses a media query because this hand-written theme has no `.dark` class. ## Syntax ```ts applyThemeToCss(css: string, system: ColorSystem, options?: ApplyThemeOptions): ThemeEditResult ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | **`css`** | `string` | The stylesheet to update. | | **`system`** | `ColorSystem` | A system from [`generateSystem`](https://colorejs.dev/docs/api/system/generate-system). | | **`options`** | `ApplyThemeOptions` | Optional. See below. | ### Options | Option | Type | Default | Description | | --- | --- | --- | --- | | **`only`** | `ThemeGroup[]` | all groups | Update only these [token groups](https://colorejs.dev/docs/api/system/adjust-css-variables#token-groups). A `-foreground` token follows its background. | | **`modes`** | `ThemeMode[]` | `['light', 'dark']` | Update only these modes. | | **`add`** | `boolean` | `false` | Add missing tokens, and a dark mode when the file has none. | | **`replace`** | `boolean` | `true` | Rewrite existing colors. Set it to `false` with `add: true` to fill gaps and keep every existing value. | ### Returns A `ThemeEditResult`: | Property | Type | Description | | --- | --- | --- | | **`css`** | `string` | The whole stylesheet with the edits applied. | | **`changes`** | `ThemeEditChange[]` | Each change with its `scope`, `variable`, old value `from` (`null` when added) and new value `to`. | ## Change only the brand Pass `only` and `modes` to keep the change small. Here only the light-mode primary changes, and its paired text is updated with it. ```ts import { applyThemeToCss, generateSystem } from 'colore-js'; const globalsCss = `:root { --primary: oklch(0.205 0 0); --primary-foreground: oklch(0.985 0 0); --muted-foreground: oklch(0.55 0 0); }`; const result = applyThemeToCss(globalsCss, generateSystem('#0f766e'), { only: ['brand'], modes: ['light'], }); console.log(result.changes); ``` ```text [ { scope: ':root', variable: '--primary', from: 'oklch(0.205 0 0)', to: 'oklch(0.511 0.086 186.391)' }, { scope: ':root', variable: '--primary-foreground', from: 'oklch(0.985 0 0)', to: 'oklch(1 0 0)' } ] ``` ## What it recognizes - **shadcn/ui** names such as `--primary`, `--muted-foreground`, `--sidebar` and `--chart-1`, in v4 OKLCH or v3 HSL channels. - **Tailwind CSS v4** scales such as `--color-brand-500` in `@theme`. - **Hand-written** names such as `--bg`, `--text`, `--surface` and `--on-primary`. Hex, OKLCH, RGB, HSL and bare HSL channel values keep their format. Other formats are written as OKLCH. ## What `add` fills in - A dark mode for every light token that differs by mode: a `.dark` block for shadcn/ui and Tailwind, and `@media (prefers-color-scheme: dark)` for hand-written themes. - `chart-1` to `chart-5` and `destructive` for shadcn/ui and Tailwind themes. Add `only: ['status']` to add `success` and `warning` with their foregrounds. - Matching `--color-*` aliases when a shadcn/ui file declares them in `@theme inline`. Check the result with [`auditCssVariables`](https://colorejs.dev/docs/api/audit#css-custom-properties), or run `colore theme "#0f766e" --apply globals.css --add` from the [CLI](https://colorejs.dev/docs/agents) to edit, repair and audit in one step. ## Related - [inspectCssTheme](https://colorejs.dev/docs/api/system/inspect-css-theme) - [adjustCssVariables](https://colorejs.dev/docs/api/system/adjust-css-variables) - [generateSystem](https://colorejs.dev/docs/api/system/generate-system) - [toShadcnCss and toTailwindCss](https://colorejs.dev/docs/api/system/system-to-tailwind-css) Source: https://colorejs.dev/docs/api/system/apply-theme-to-css --- # adjustCssVariables `adjustCssVariables` changes how a theme feels without rebuilding it. Pick the tokens (surfaces, borders, the brand), pick a mode, and move their lightness, chroma or hue in OKLCH. Every other value in the file stays exactly as it was. ## Example Warm and lift the dark-mode surfaces: ```ts import { adjustCssVariables } from 'colore-js'; const css = `:root { --surface: oklch(0.94 0 0); --brand: #0f766e; } .dark { --surface: oklch(0.2 0 0); }`; const result = adjustCssVariables(css, { groups: ['surfaces'], modes: ['dark'], lightness: '+0.03', chroma: 0.015, hue: 65, }); console.log(result.css); ``` ```css :root { --surface: oklch(0.94 0 0); --brand: #0f766e; } .dark { --surface: oklch(0.23 0.015 65); } ``` ## Syntax ```ts adjustCssVariables(css: string, options: AdjustThemeOptions): ThemeEditResult ``` ### Options Choose at least one group or token, and at least one channel. | Option | Type | Description | | --- | --- | --- | | **`groups`** | `ThemeGroup[]` | The [token groups](#token-groups) to change. | | **`tokens`** | `string[]` | Token names, with or without `--`. Combined with `groups`. | | **`modes`** | `ThemeMode[]` | The modes to change. Defaults to `['light', 'dark']`. | | **`lightness`** | `ChannelChange` | OKLCH lightness, kept between `0` and `1`. | | **`chroma`** | `ChannelChange` | OKLCH chroma, kept at `0` or above. | | **`hue`** | `ChannelChange` | OKLCH hue in degrees, wrapped around the color wheel. | A `ChannelChange` is a number to set the channel (`0.015`), a signed string to add or subtract (`'+0.03'`, `'-10'`), or `'x'` and a factor to scale it (`'x0.8'`). Grays have no hue, so give them some chroma when you tint them. Results stay in the gamut the color started in, sRGB or Display P3. ### Returns A `ThemeEditResult` with the updated `css` and the list of `changes`, the same shape as [`applyThemeToCss`](https://colorejs.dev/docs/api/system/apply-theme-to-css#returns). ## Token groups | Group | Typical tokens | | --- | --- | | **`surfaces`** | `background`, `card`, `popover`, `muted`, `secondary`, `sidebar` | | **`text`** | `foreground`, `muted-foreground` and every other `-foreground` | | **`brand`** | `primary`, `ring`, `sidebar-primary` | | **`accent`** | `accent` | | **`borders`** | `border`, `input` | | **`status`** | `destructive`, `success`, `warning` | | **`charts`** | `chart-1` to `chart-5` | | **`other`** | Anything else | ## Recipes | Request | Options | | --- | --- | | Warmer neutrals | `{ groups: ['surfaces', 'borders'], hue: 70, chroma: 0.008 }` | | Calmer accent | `{ groups: ['accent'], chroma: 'x0.6' }` | | Darker buttons in light mode | `{ tokens: ['primary'], modes: ['light'], lightness: '-0.04' }` | | Softer dark mode | `{ groups: ['surfaces'], modes: ['dark'], lightness: '+0.03' }` | An adjustment can lower contrast. Check the result with [`auditCssVariables`](https://colorejs.dev/docs/api/audit#css-custom-properties) and repair it with `fixCssVariables`, or use `colore adjust` from the [CLI](https://colorejs.dev/docs/agents), which repairs and audits for you. ## Related - [applyThemeToCss](https://colorejs.dev/docs/api/system/apply-theme-to-css) - [inspectCssTheme](https://colorejs.dev/docs/api/system/inspect-css-theme) - [setOklch](https://colorejs.dev/docs/api/operations/manipulation/set-oklch) Source: https://colorejs.dev/docs/api/system/adjust-css-variables --- # toTailwindCss, toShadcnCss and toDTCG Use the export methods on a system from `generateSystem`. Choose `toTailwindCss()` for `@theme` variables, `toShadcnCss()` for `globals.css`, or `toDTCG()` for a design-token document. ## Example ```ts import { generateSystem } from 'colore-js'; const system = generateSystem('#0f766e'); const tailwind = system.toTailwindCss({ format: 'hex' }); tailwind.includes('--color-primary-500: #0f766e;'); // true tailwind.includes('.dark {'); // true system.toDTCG().$schema; // 'https://www.designtokens.org/schemas/2025.10/format.json' ``` ## Syntax ```ts system.toTailwindCss(options?: SystemTailwindCssOptions): string system.toShadcnCss(options?: ShadcnCssOptions): string system.toDTCG(): DTCGDocument ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | Tailwind `format` | `'hex' \| 'oklch'` | Output format. Defaults to OKLCH. | | Tailwind `darkMode` / `darkSelector` | `'class' \| 'media'` / `string` | Defaults to class-based dark mode and `.dark`. | | Tailwind `includeThemeDirective` / `prefix` | `boolean` / `string` | Defaults to an `@theme` block and `color`, which gives names such as `--color-primary-500`. | | shadcn `format` | `'oklch' \| 'hex' \| 'hsl-channels'` | Defaults to OKLCH. For shadcn/ui v3 HSL variables, use `'hsl-channels'`. | | shadcn `selector` / `darkSelector` | `string` | Default selectors are `:root` and `.dark`. | | shadcn `radius` | `string \| false` | Defaults to `'0.625rem'`. Use `false` to omit the radius variable. | ### Returns The two CSS methods return a stylesheet string. `toDTCG` returns a design-token document object with a schema and color tokens. Serialize it as JSON to write a token file. ### Throws A `ColorError` for unknown or unsupported CSS export options. ## Prepare variables for shadcn/ui ```ts import { generateSystem } from 'colore-js'; const system = generateSystem('#0f766e'); system.toShadcnCss().split('\n').find((line) => line.includes('--primary:')); // ' --primary: oklch(0.511 0.086 186.391);' ``` The shadcn exporter checks its text pairs after formatting them. The check uses the system’s configured algorithm and target level. ## Related - [Tailwind v4 colors from one brand color](https://colorejs.dev/docs/guides/tailwind-v4-colors) to add the CSS to a Tailwind project - [Generate a shadcn/ui theme](https://colorejs.dev/docs/guides/shadcn-theme-from-one-color) for setup and verification - [generateSystem](https://colorejs.dev/docs/api/system/generate-system) to choose theme modes and roles Source: https://colorejs.dev/docs/api/system/system-to-tailwind-css --- # generateStates `generateStates` creates hover, active, disabled and focus colors from a base color. Set the background to let Colore check the disabled and focus colors as they appear after opacity is applied. ## Example ```ts import { generateStates } from 'colore-js'; const button = generateStates('#2563eb', { background: '#fff' }); button.hover.css(); // '#0b48cf' button.active.css(); // 'color(display-p3 0.04512 0.18278 0.68986)' button.disabled.css(); // '#526c9f' button.focusRing.css(); // '#00298f80' ``` ## Syntax ```ts generateStates(base: ColorInput | Color, options?: StateOptions): ColorStates ``` ### Parameters | Name | Type | Description | | --- | --- | --- | | `base` | `ColorInput \| Color` | Color to derive the states from. | | `options.background` | `ColorInput \| Color` | Color behind the states. Defaults to `#fafafa`. Passing it enables contrast checks. | | `options.hoverFactor` / `options.activeFactor` | `number` | Absolute OKLCH lightness changes from 0 to 1. Defaults to 0.08 and 0.15. | | `options.disabledOpacity` / `options.focusOpacity` | `number` | Alpha from 0 to 1. Defaults to the base alpha and 0.5, respectively. | | `options.focusColor` | `ColorInput \| Color` | Custom focus color. Defaults to the base. | | `options.intent` / `options.algorithm` / `options.level` / `options.target` | `TargetOptions` | Set a contrast target for disabled and focus colors. Default target when checking is WCAG 2 `'ui'`, or 3:1. | ### Returns `ColorStates` includes `base`, `hover`, `active`, `disabled` and `focusRing` as `Color` values. Active and hover move away from the background in lightness. ### Throws A `ColorError` for invalid colors or options, or when the requested opacity prevents disabled or focus contrast from reaching the target. ## Create a focus ring for dark mode ```ts import { generateStates } from 'colore-js'; const darkButton = generateStates('#2563eb', { background: '#0a0a0a', focusOpacity: 1, }); darkButton.focusRing.css(); // '#2563eb' darkButton.focusRing.contrastRatio('#0a0a0a').toFixed(2); // '3.83' ``` ## Related - [Dark mode colors](https://colorejs.dev/docs/guides/dark-mode-colors) to check states against the actual background - [generateSystem](https://colorejs.dev/docs/api/system/generate-system) for interaction states across theme roles - [ensureContrast](https://colorejs.dev/docs/api/intelligence/ensure-contrast) to repair a single color pair Source: https://colorejs.dev/docs/api/system/states --- # Entry points and exports Colore has two package imports. Use `colore-js` for Color objects and theme work, and `colore-js/fn` for standalone operations. ## `colore-js` Use the root for the fluent API, parsing and validation, and higher-level workflows. | Group | Runtime exports | | --- | --- | | Construction | `Color`, `colore`, `default` (`Color`) | | Parsing | `parse`, `parseToSpace`, `detectFormat` | | Validation | `isValidColor` (use `detectFormat` to learn which format a valid string uses) | | Higher-level workflows | `audit`, `ensureContrast`, `generateSystem`, `generateStates`, `categoricalColors` | | CSS variables | `auditCssVariables`, `fixCssVariables`, `inspectCssTheme`, `applyThemeToCss`, `adjustCssVariables`, `tokenGroup` | | Errors | `ColorError` | Export formats (CSS variables, Tailwind v4, shadcn/ui, DTCG, JSON) are methods on the system that `generateSystem` returns, not separate functions. ```ts import Color, { colore, ensureContrast } from 'colore-js'; const a = new Color('#2563eb'); const b = colore('#2563eb'); console.log(a.equals(b, 0)); // true console.log(ensureContrast(a, '#ffffff').satisfied); // true ``` ## `colore-js/fn` Use `/fn` for named standalone operations. Color transforms return CSS strings, and palettes return arrays of them. Parsers return numeric values. Workflows such as `audit` and `generateSystem` return typed results. | Group | Runtime exports | | --- | --- | | Parse and validate | `parse`, `parseToSpace`, `parseColorMix`, `detectFormat`, `isValidColor` | | Manipulation and output | `lighten`, `darken`, `saturate`, `desaturate`, `adjustHue`, `grayscale`, `invert`, `complement`, `setAlpha`, `setOklch`, `mix`, `mixToCss`, `toHex`, `toRgb`, `toHsl`, `toOklab`, `toOklch`, `toCss` | | Harmony, scale, palette | `triadic`, `scale`, `interpolate`, `palette`, `categoricalColors` | | Accessibility and distance | `contrastRatio`, `contrastAPCA`, `ensureContrast`, `luminance`, `isReadable`, `bestTextColor`, `deltaE`, `deltaEOK`, `nearestNamed` | | Color-vision simulation | `simulate` | | Advanced workflows | `audit`, `generateSystem` | ## Design tokens `generateSystem(...).toDTCG()` exports a DTCG 2025.10 document typed as `DTCGDocument` (exported from the package root). ## Type-only exports Each entry point also exposes TypeScript types appropriate to that surface. Import them with `import type` so they do not become runtime imports. See [Types](https://colorejs.dev/docs/api/reference/types) for the grouped index. Source: https://colorejs.dev/docs/api/reference/entry-points-and-exports --- # TypeScript types Colore exports TypeScript types for inputs, channel objects, options, and result shapes. ## Syntax ```ts import type { ColorInput, ColorValue, ColorObject, ColorSpace, MixColorSpace, InterpolationColorSpace, InternalColor, RgbObject, OklchObject, TaggedColorObject, SrgbColorInput, ReadableOptions, TargetOptions, ContrastAlgorithm, ContrastLevel, ScaleOptions, PaletteOptions, ColorBlindnessType, DetectedFormat, AuditOptions, AuditResult, ResolveResult, SystemConfig, ColorSystem, StateOptions, } from 'colore-js'; ``` ## Pick the input or channel type - `InternalColor`: untagged `{ r, g, b, alpha }` used by low-level internals. - `ColorValue`: public tagged linear-sRGB value `{ space: 'srgb-linear', r, g, b, alpha }`; returned by `parse` and `parseColorMix`, and accepted by all public color-input APIs. Channels can be outside `0–1` for out-of-sRGB colors. - `SrgbColorInput`: `{ space: 'srgb', r, g, b, alpha? }` with gamma-encoded `0–1` channels, like CSS `color(srgb …)`. Use it for Figma and three.js floats. - `TaggedColorObject`: what `toObject(space)` returns; always tagged with `space` and carrying `alpha`. - `ColorInput`: union of supported constructor inputs. - `ColorObject`: union of supported color object inputs. Use `TaggedColorObject` when every object includes a space. - `ColorSpace`: `'srgb' | 'hsl' | 'hwb' | 'hsv' | 'lab' | 'lch' | 'oklab' | 'oklch' | 'xyz' | 'p3'`. - `MixColorSpace`: `ColorSpace` without `'hsv'`. Used by `mix()`; HSV is a conversion target only. - `InterpolationColorSpace`: `'srgb' | 'p3' | 'hsl' | 'lab' | 'lch' | 'oklab' | 'oklch'`. Used by `scale()` and `interpolate()`; unsupported runtime names throw rather than falling back to OKLab. ## Use named channels Colore exports typed objects for each space, including alpha variants where relevant: - `RgbObject`, `RgbaObject` - `HslObject`, `HslaObject` - `HsvObject`, `HsvaObject` - `HwbObject`, `HwbaObject` - `LabObject`, `LabaObject` - `LchObject`, `LchaObject` - `OklabObject`, `OklabaObject` - `OklchObject`, `OklchaObject` - `XyzObject`, `XyzaObject` - `P3Object`, `P3aObject` The channel ranges on these types are nominal ranges for ordinary in-gamut colors, not runtime clamps. Numeric conversion methods preserve extended coordinates, so a wide-gamut source may produce negative components or values above the nominal maximum. Request a bounded sRGB display value with an explicit string serializer such as `hex()`, `rgb()`, or `hsl()`. Ambiguous input shapes use explicit tagged types: `LabColorInput`, `LchColorInput`, `OklabColorInput`, `OklchColorInput`, `XyzColorInput`, and `P3ColorInput`. For example: ```ts import type { ColorInput } from 'colore-js'; const perceptual: ColorInput = { space: 'oklch', l: 0.65, c: 0.18, h: 280, alpha: 0.8, }; ``` ## Type options and results - `ContrastAlgorithm` (`'wcag2' | 'apca'`), `ContrastLevel` (`'aa' | 'aaa'`), `TargetOptions` (`{ intent, algorithm, level, target }`): the one contrast vocabulary shared by `ensureContrast`, `isReadable`, `generateStates`, `generateSystem`, `audit`, and `auditCssVariables`. `contrastRatio` and `contrastAPCA` return plain numbers. - `ReadableOptions`: `'aa' | 'aaa' | TargetOptions`, accepted by `isReadable`. - `ScaleOptions`: `{ steps?: number; space?: InterpolationColorSpace }`. - `PaletteOptions`: `{ steps?: number }`. - `ColorBlindnessType`: supported simulation type union. - `DetectedFormat`: return type used by `detectFormat`. ## Find types for themes and audits - Audit: `AuditInput`, `AuditOptions`, `AuditResult`, `AuditIssue`, `AuditSuggestion`, `ColorPair`; for CSS, `CssAuditOptions`, `CssAuditResult`, `CssContrastIssue`, `CssFixResult`, `CssFixChange`. - Contrast repair: `ResolveResult` (returned by `ensureContrast`), `EnsureContrastOptions`, `ContrastIntent`. - Systems: `ColorSystem`, `SystemConfig`, `ResolvedSystemConfig`, `SemanticRole`, `ThemeMode`, `RoleColors`, `ThemeColors`, `GeneratedSystem`, `StateOptions`, `ColorStates`. - Export options: `SystemCSSExportOptions`, `SystemTailwindCssOptions`, and `ShadcnCssOptions` for the system's `toCSS`, `toTailwindCss`, and `toShadcnCss`. - Color results: `NearestResult`, `NearestNamedResult`, `MixToCssOptions`, `CssColorMixSpace`. - Theme files: `ThemeReport`, `ThemeEditResult`, `ApplyThemeOptions`, `AdjustThemeOptions`, `ThemeGroup` and `ChannelChange`. ## `/fn` Types `colore-js/fn` re-exports the core input/result types used in standalone signatures plus audit, system, accessibility, contrast-repair, and CSS-mix option types. ```ts import type { ColorInput, EnsureContrastOptions, ResolveResult } from 'colore-js/fn'; ``` ## Design token types - `DTCGDocument`, `DTCGGroup`, `DTCGToken`, `DTCGColorValue`, `DTCGColorSpace`: the DTCG 2025.10 output of `ColorSystem.toDTCG()`. Exported from the package root. ## Error Type - `ColorError`: exported error class used by strict parsing and invalid argument paths. ## Example ```ts import { colore, detectFormat, ColorError } from 'colore-js'; import type { ColorInput, ScaleOptions, DetectedFormat } from 'colore-js'; const input: ColorInput = '#7c3aed'; const format: DetectedFormat | null = detectFormat(input); const scaleOptions: ScaleOptions = { steps: 7, space: 'oklab' }; try { const out = colore(input).scale('#22c55e', scaleOptions).map(c => c.hex()); console.log(format, out.length); // hex 7 } catch (error) { if (error instanceof ColorError) { console.error(error.message); } } ``` ## Related - [Entry points and exports](https://colorejs.dev/docs/api/reference/entry-points-and-exports) - [Constructor and Inputs](https://colorejs.dev/docs/api/color-class/constructor-and-inputs) - [parse](https://colorejs.dev/docs/api/parsing/parse) Source: https://colorejs.dev/docs/api/reference/types --- # Color inputs and detection A stylesheet gives you strings. A color picker may give you numbers. Colore accepts both, as long as it knows which space and units your numbers use. ## Pass a CSS color or a packed integer Colore accepts hex, `rgb()`, `hsl()`, `hwb()`, `lab()`, `lch()`, `oklab()`, `oklch()`, `color(srgb …)`, `color(display-p3 …)`, named CSS colors, `transparent` and supported [color-mix() expressions](https://colorejs.dev/docs/api/parsing/from-css-mix). An integer packs red, green and blue into `0xRRGGBB`. ```ts import { colore } from 'colore-js'; console.log(colore('rebeccapurple').hex()); // '#663399' console.log(colore(0x2563eb).hex()); // '#2563eb' ``` ## Label the units you pass Plain `{ r, g, b }` objects use RGB channels from 0 to 255. Add `space: 'srgb'` for encoded 0–1 channels. The `space: 'srgb-linear'` tag means linear-light channels instead. Use `alpha` to represent opacity. ```ts import { colore } from 'colore-js'; const color = colore({ space: 'srgb', r: 0.5, g: 0.25, b: 1 }); console.log(color.hex()); // '#8040ff' ``` Check [color spaces and ranges](https://colorejs.dev/docs/concepts/color-spaces-and-ranges) for the other object tags. ## Check a string before using it [detectFormat](https://colorejs.dev/docs/api/parsing/detect-format) recognizes the syntax. [isValidColor](https://colorejs.dev/docs/api/validation/is-valid-color) also checks the contents. Use [parse](https://colorejs.dev/docs/api/parsing/parse) for numeric channels or [Color.try](https://colorejs.dev/docs/api/color-class/static-factory-methods#accept-a-user-supplied-color) to get a Color with a fallback path. ```ts import { detectFormat, isValidColor } from 'colore-js'; console.log(detectFormat('rgb(12)')); // 'rgb' console.log(isValidColor('rgb(12)')); // false ``` ## Related - [Color constructor and inputs](https://colorejs.dev/docs/api/color-class/constructor-and-inputs) - [Handle invalid colors](https://colorejs.dev/docs/advanced/error-handling-and-validation) Source: https://colorejs.dev/docs/concepts/color-inputs-and-detection --- # Color spaces and ranges An RGB triplet from a canvas can use 0–255, while a picker may give you 0–1. Choose the channel space and units before you move values between tools. ## Look up the channel ranges | Input or output space | Typical channel units | | --- | --- | | Untagged RGB object, `toRgb()` | Encoded 0–255 RGB and 0–1 alpha | | `'srgb'`, `'p3'` | Encoded 0–1 RGB | | `'srgb-linear'` | Linear-light RGB. Use with `toObject()` and `toArray()`. | | `'hsl'`, `'hsv'`, `'hwb'` | Hue in degrees and the remaining channels on a 0–100 scale | | `'lab'`, `'lch'` | D50 white point and lightness 0–100. LCH hue uses degrees. | | `'oklab'`, `'oklch'` | Lightness 0–1. OKLCH hue uses degrees. | | `'xyz'` | XYZ with a D65 white point | Alpha runs from 0 to 1 in each space. These are typical values. Numeric conversions can give you channels outside those ranges for wide-gamut colors. ## Read channels for a picker Use `toArray('srgb')` for encoded unit-range RGB followed by alpha. ```ts import { colore } from 'colore-js'; const blue = colore('#2563eb'); console.log(blue.toArray('srgb').map(value => Number(value.toFixed(3)))); // [0.145, 0.388, 0.922, 1] ``` Use `toObject('srgb')` if you need to pass that color back to Colore with its space attached. Use `toRgb()` when your consumer expects 0–255 integer channels. ## Mix colors in the space you want ```ts import { colore } from 'colore-js'; console.log(colore('#ff0000').mix('#0000ff', 0.5, 'oklab').css()); // '#8c53a2' ``` OKLab is a good starting point for a visual transition. Use sRGB when you need to match an existing sRGB blend. ## Related - [Gamut and CSS output](https://colorejs.dev/docs/concepts/gamut-and-css-output) for mapping and clipping - [Color object output](https://colorejs.dev/docs/api/color-class/object-output-methods) - [Use OKLCH in JavaScript](https://colorejs.dev/docs/guides/oklch-in-javascript) Source: https://colorejs.dev/docs/concepts/color-spaces-and-ranges --- # Gamut and CSS output Not every color fits on every screen. An OKLCH or Display P3 color can be more vivid than sRGB, the range older displays and hex codes cover. `css()` chooses a CSS format based on the color’s gamut. Use `toGamut()` when your output has to fit a narrower gamut. ## Let Colore choose the format ```ts import { colore } from 'colore-js'; colore('#7c3aed').css(); // '#7c3aed' colore('color(display-p3 0.95 0.25 0.3)').css(); // 'color(display-p3 0.95000 0.25000 0.30000)' colore('oklch(0.7 0.35 20)').css(); // 'oklch(0.70000 0.35000 20.00)' ``` `css()` and `toCss()` from `colore-js/fn` follow one rule: 1. The color fits sRGB: hex. 2. It fits Display P3: `color(display-p3 …)`. 3. Neither: `oklch(…)`. Standalone transforms such as `lighten()` and `mix()` use the same rule. For a fixed format, choose an output function like `toHex()`. ## Choose the format yourself Use a fixed method when an API, a test or a file format needs one format: | Method | Output | | --- | --- | | `hex()`, `rgb()`, `hsl()` | sRGB formats. Colors outside sRGB are clipped. | | `p3()` | `color(display-p3 …)` | | `oklch()`, `oklab()` | Perceptual formats that hold any color. | Object outputs such as `toRgb()`, `toObject()` and `toArray()` are not clipped: wide-gamut colors can have values outside the usual 0–255 range. ## Map a color into sRGB Clipping cuts each channel off at its limit, which can shift the hue. `toGamut()` uses the [CSS Color 4 binary-search gamut mapping method](https://www.w3.org/TR/css-color-4/#binsearch). It reduces OKLCH chroma and uses a local clip when the remaining difference is small. ```ts import { colore } from 'colore-js'; const red = colore('oklch(0.7 0.35 20)'); red.hex(); // clipped: '#ff0032' red.toGamut('srgb').hex(); // mapped: '#ff5464' ``` The mapped color passes `isInGamut()` for that gamut and keeps its alpha. Shades from [`palette`](https://colorejs.dev/docs/api/operations/scales-and-palette/palette) and [`generateSystem`](https://colorejs.dev/docs/api/system/generate-system) already fit sRGB, so they don't need this step. ## Check the gamut first ```ts import { colore } from 'colore-js'; const color = colore('oklch(0.68 0.22 300)'); color.isInGamut('srgb'); // false color.isInGamut('p3'); // false ``` ## Related - [Color spaces and ranges](https://colorejs.dev/docs/concepts/color-spaces-and-ranges) - [toCss](https://colorejs.dev/docs/api/operations/output/to-css) - [String output methods](https://colorejs.dev/docs/api/color-class/string-output-methods) Source: https://colorejs.dev/docs/concepts/gamut-and-css-output --- # Immutability and chaining Start with a brand color and you can derive several states from it. Each edit returns a new Color, so the default state remains available. ## Derive hover and pressed colors ```ts import { colore } from 'colore-js'; const brand = colore('#2563eb'); console.log(brand.lighten(8).hex()); // '#306ff8' console.log(brand.darken(8).hex()); // '#1855dc' console.log(brand.hex()); // '#2563eb' ``` Keep a reference to the value a method returns if you want to reuse that edit. ## Chain several edits before writing CSS ```ts import { colore } from 'colore-js'; const brand = colore('#2563eb'); console.log(brand.darken(8).saturate(6).hex()); // '#1052e3' ``` The chain keeps the channels numeric until `hex()` runs. If you pass a CSS string from one standalone transform to the next, the second step reads that already-rounded string. ## Import a helper for one operation ```ts import { lighten } from 'colore-js/fn'; console.log(lighten('#2563eb', 8)); // '#306ff8' ``` The function returns CSS, ready to use in a style rule or theme value. ## Related - [Performance and bundling](https://colorejs.dev/docs/advanced/performance-and-bundling) for when to choose each import - [lighten](https://colorejs.dev/docs/api/operations/manipulation/lighten) - [Gamut and CSS output](https://colorejs.dev/docs/concepts/gamut-and-css-output) Source: https://colorejs.dev/docs/concepts/immutability-and-chaining --- # Precision, rounding and equality A CSS string is an output format. If you plan to keep calculating with a color, keep the Color object or its tagged numeric channels. ## Choose where to round Hex and RGB strings round the sRGB channels to integers. Hex also rounds alpha to one byte. OKLCH strings keep five decimals for lightness and chroma and two for hue. Read channels with `toObject()` or `toArray()` when you need the numeric coordinates before formatting. ```ts import { colore } from 'colore-js'; const color = colore('#2563eb'); const stored = color.toObject('srgb-linear'); console.log(colore(stored).equals(color, 0)); // true ``` ## Compare channels or appearance `equals()` compares each linear RGB channel and alpha. Its default tolerance is `0.01`; pass `0` for exact equality. For appearance, use [deltaE](https://colorejs.dev/docs/api/operations/distance/delta-e) for CIEDE2000 or [deltaEOK](https://colorejs.dev/docs/api/operations/distance/delta-e-ok) for OKLab distance. Use a threshold chosen for that metric. ```ts import { colore } from 'colore-js'; const black = colore('#000'); console.log(black.equals('#191919')); // true console.log(black.deltaE('#191919').toFixed(2)); // '5.21' ``` ## Check a color after export ```ts import { colore } from 'colore-js'; const gray = colore('rgb(118.6 118.6 118.6)'); console.log(gray.contrastRatio('#fff').toFixed(4)); // '4.5036' console.log(gray.hex()); // '#777777' console.log(colore(gray.hex()).contrastRatio('#fff').toFixed(4)); // '4.4781' ``` If you ship the hex value, use its ratio for the decision. At the 4.5:1 AA threshold for normal text, the difference changes the result. ## Related - [Color object output](https://colorejs.dev/docs/api/color-class/object-output-methods) - [Check color contrast](https://colorejs.dev/docs/guides/check-color-contrast) - [Gamut and CSS output](https://colorejs.dev/docs/concepts/gamut-and-css-output) Source: https://colorejs.dev/docs/concepts/precision-rounding-and-equality --- # Colore compared Colore can [repair a low-contrast color](https://colorejs.dev/docs/api/intelligence/ensure-contrast), [generate light and dark themes](https://colorejs.dev/docs/api/system/generate-system) for shadcn/ui and Tailwind CSS v4, and [update the theme file you already have](https://colorejs.dev/docs/api/system/apply-theme-to-css). None of the five other libraries compared below can do any of those. Colore's [coding-agent skill](https://colorejs.dev/docs/agents) also gives your editor the same theme and contrast commands. Colore (`colore-js` on npm) is a separate project from Color.js (`colorjs.io`), which has a similar name. > Checked December 3, 2026. ✓ Supported · ◐ Partial support · — Unavailable The grid covers built-in features. Each library can also mix colors in code. ## Feature matrix | Capability | Colore v2 | Color.js | Culori | Chroma.js | tinycolor2 | colord | | --- | --- | --- | --- | --- | --- | --- | | Read and write OKLCH CSS Including wide-gamut colors | ✓ | ✓ | ✓ | ◐ Clips to sRGB | — | ◐ Plugin, clips to sRGB | | Read and write Display-P3 CSS | ✓ | ✓ | ✓ | — | — | — | | Evaluate CSS color-mix() | ◐ Two colors, explicit space | — | — | — | — | — | | Measure WCAG 2 contrast | ✓ | ✓ | ✓ | ✓ | ✓ | ◐ a11y plugin | | Measure APCA contrast | ✓ | ✓ | — | ✓ | — | — | | Adjust a color to meet a contrast target | ✓ ensureContrast() | — | — | — | — | — | | Simulate color-vision deficiencies Including achromatopsia | ✓ | — | ◐ Protan, deutan, tritan | — | — | — | | Import selected functions or features | ✓ /fn | ✓ /fn | ✓ /fn | ✓ /light and deep imports | — | ✓ Plugins | | Generate a light and dark UI theme from one color | ✓ generateSystem() | — | — | — | — | — | | Rebrand or extend an existing CSS theme file | ✓ applyThemeToCss() | — | — | — | — | — | | Check and fix contrast from the command line | ✓ colore audit, fix | — | — | — | — | — | | Skill for coding agents | ✓ npx colore-js init | — | — | — | — | — | ## Colore and Chroma.js Chroma.js is built for data visualization: scales with domains and classes, bezier interpolation and the ColorBrewer palettes. It converts every color to sRGB when it parses it, so OKLCH colors outside sRGB change and Display P3 colors don't parse. [Colore and chroma.js compared](https://colorejs.dev/docs/comparison/chroma-js) runs five common tasks in both. ## Colore and tinycolor2 tinycolor2 is small and has been stable for years, but it can't read `oklch()` or `color()`, so Tailwind CSS v4 and current shadcn/ui colors come back invalid. Its lighten and darken work in HSL, so `lighten(20)` on violet-500 keeps only 40% of the chroma. [Moving from tinycolor2](https://colorejs.dev/docs/comparison/tinycolor2) maps each method to Colore and shows where the results differ. ## Colore and Culori Culori covers many more color spaces and lets you register only the ones your app uses. Choose it for broad conversion work. It has no contrast repair or theme generation. ## Colore and Color.js Color.js converts across more spaces than Colore, such as Rec. 2020 and ProPhoto RGB, and lets you choose a chromatic adaptation method. Choose it for color science work across those spaces. It has no contrast repair or theme generation. ## Colore and colord colord has a very small core and adds features through plugins, including WCAG contrast, Lab, LCH and OKLCH. Its OKLCH plugin clips colors to sRGB, and it doesn't read Display P3. Choose it when bundle size matters most and your colors stay in sRGB. ## Bundle size | Library | Gzip size | Source | | --- | ---: | --- | | colord 2.14.1 | 2.3 kB | Core package, plugins extra | | tinycolor2 1.6.0 | 5.4 kB | Whole package | | Chroma.js 3.3.0 | 16.7 kB | Whole package | | Culori 4.0.2 | 22.2 kB | Whole package | | Color.js 0.7.1 | 32.4 kB | Whole package | | Colore 2.0.1 | 10 to 40 kB | One `/fn` function up to all root exports | The first five rows are bundlephobia's whole-package sizes, so they count everything even when your bundler would drop part of it. Colore's row is measured per import with Rollup and Terser. See [performance and bundling](https://colorejs.dev/docs/advanced/performance-and-bundling) for the full Colore table. Colore's upper figure includes contrast repair, auditing and theme generation, which none of the other five libraries has. ## Library references [Colore API](https://colorejs.dev/docs/api/overview) · [Culori 4.0.2](https://github.com/danburzo/culori/tree/v4.0.2) · [Chroma.js 3.3.0](https://gka.github.io/chroma.js/#3-3-0) · [Color.js 0.7.1](https://github.com/color-js/color.js/tree/v0.7.1) · [tinycolor2 1.6.0](https://www.npmjs.com/package/tinycolor2/v/1.6.0) · [colord 2.14.1](https://www.npmjs.com/package/colord/v/2.14.1) [Chroma.js OKLCH parsing source](https://github.com/gka/chroma.js/blob/v3.3.0/src/io/css/css2rgb.js#L210-L218) Source: https://colorejs.dev/docs/comparison --- # Colore and chroma.js compared chroma.js converts every color to sRGB as soon as it reads it. Some of Tailwind CSS v4's default colors sit outside sRGB, so chroma.js changes them on the way in, and it can't parse Display P3 colors at all. Colore keeps those colors as they are. It also repairs contrast and builds light and dark themes from one brand color, and it's written in TypeScript with its own types, where chroma.js needs `@types/chroma-js`. The outputs come from chroma-js 3.3.0 and colore-js 2.0.1, run on December 3, 2026. ```bash npm install colore-js ``` ## chroma.js keeps colors as sRGB A color outside sRGB loses its extra range when chroma.js parses it, and chroma.js doesn't report the change. Tailwind CSS v4's green-500 is one of those colors: ```js import chroma from 'chroma-js'; const green = chroma('oklch(72.3% 0.219 149.579)'); green.css('oklch'); // 'oklch(72.89% 0.21 147.82deg)' green.clipped(); // false chroma('color(display-p3 1 0 0)'); // throws "unknown format" ``` Writing the color back gives a different lightness, chroma and hue than the one you read. Colore keeps the original value. You choose when to bring it into sRGB, and how: ```js import { colore } from 'colore-js'; const green = colore('oklch(72.3% 0.219 149.579)'); green.isInGamut('srgb'); // false green.oklch(); // 'oklch(0.72300 0.21900 149.58)' green.toString(); // 'color(display-p3 0.30873 0.77475 0.37431)' green.hex(); // '#00c950', clipped green.toGamut('srgb').hex(); // '#00c950', gamut-mapped colore('color(display-p3 1 0 0)').toString(); // 'color(display-p3 1.00000 0.00000 0.00000)' ``` For this green, clipping and gamut mapping give the same hex. For colors further outside sRGB they don't: `oklch(0.7 0.3 150)` clips to `#00cb00` and maps to `#00c248`. chroma.js gives `#00cb00` with no way to choose. See [Gamut and CSS output](https://colorejs.dev/docs/concepts/gamut-and-css-output) for how Colore picks a format. ## Five tasks in both libraries ### Convert hex to OKLCH ```js chroma('#2563eb').css('oklch'); // 'oklch(54.61% 0.22 262.88deg)' toOklch('#2563eb'); // 'oklch(0.54615 0.21521 262.88)' ``` Both give the same color, and Colore writes more precision. ### Lighten and darken ```js chroma('#2563eb').brighten(1).hex(); // '#6f90ff' chroma('#2563eb').darken(1).hex(); // '#003ab8' lighten('#2563eb', 10); // '#3272fb' darken('#2563eb', 10); // '#1451d8' ``` chroma.js moves Lab lightness by a fixed 18 units per step, and Lab pulls blues toward violet: `brighten(1)` moves this blue's OKLCH hue from 262.9 to 269.1 and its chroma from 0.215 to 0.168. Colore moves OKLCH lightness by a percentage and keeps hue 262.8 and chroma 0.215, which suits small steps such as hover colors. The two amounts don't translate one to one. ### Mix two colors ```js chroma.mix('#2563eb', '#facc15', 0.5, 'oklab').hex(); // '#90a3ad' mix('#2563eb', '#facc15', 0.5); // '#90a3ad' ``` Same result. Colore mixes in OKLab unless you pass another space. chroma.js defaults to linear RGB, so pass `'oklab'` to it to match. ### Build a scale ```js chroma.scale(['#2563eb', '#facc15']).mode('oklab').colors(5); // ['#2563eb', '#5b87cf', '#90a3ad', '#c5b97f', '#facc15'] scale('#2563eb', '#facc15', { steps: 5 }); // ['#2563eb', '#5b87cf', '#90a3ad', '#c5b97f', '#facc15'] ``` Same result, so OKLab scales you built with chroma.js keep their colors when you switch. For data maps, chroma.js goes further: `chroma.scale('YlGnBu').domain([0, 100]).classes(5)` maps values to classed colors from a ColorBrewer palette. Colore has no domain mapping or ColorBrewer palettes. Colore's [`palette`](https://colorejs.dev/docs/api/operations/scales-and-palette/palette) builds 50 to 950 UI shades from one color instead, and [`categoricalColors`](https://colorejs.dev/docs/api/operations/scales-and-palette/categorical-colors) picks distinct series colors for charts. ### Check and fix contrast ```js chroma.contrast('#2563eb', '#ffffff'); // 5.168555560022562 chroma.contrastAPCA('#ffffff', '#2563eb'); // -80.24787933740542 contrastRatio('#2563eb', '#ffffff'); // 5.168555560022562 contrastAPCA('#ffffff', '#2563eb'); // 80.24787933740541 ``` Both measure WCAG 2 and APCA. chroma.js returns the signed APCA value and Colore returns its magnitude. When a pair fails, Colore can repair it, and chroma.js has no equivalent: ```js ensureContrast('#777777', '#ffffff'); // { color: '#767676', satisfied: true, iterations: 1 } ``` [`ensureContrast`](https://colorejs.dev/docs/api/intelligence/ensure-contrast) moves the color as little as it can to reach the target. The Colore calls above import from `colore-js/fn`: ```js import { contrastAPCA, contrastRatio, darken, ensureContrast, lighten, mix, scale, toOklch } from 'colore-js/fn'; ``` ## What Colore adds for interfaces [`generateSystem`](https://colorejs.dev/docs/api/system/generate-system) builds light and dark themes from one brand color, with text colors that pass contrast, and exports them for shadcn/ui, Tailwind CSS v4, CSS variables or design tokens. [`applyThemeToCss`](https://colorejs.dev/docs/api/system/apply-theme-to-css) and the CLI update the theme file a project already has. ## When chroma.js is the better choice chroma.js has been a go-to library for data visualization for over a decade. Pick it when you map numbers to colors: scales with domains and classes, bezier interpolation and the ColorBrewer palettes. If your colors all come in as hex and stay in sRGB, its parsing limits won't affect you. As a whole package it's smaller: 16.7 kB gzipped ([bundlephobia](https://bundlephobia.com/package/chroma-js@3.3.0)), against 39 KiB for all of Colore's root exports. Colore's functions import separately, though. `toHex` alone from `colore-js/fn` is about 10 KiB gzipped and `ensureContrast` about 14 KiB, both under chroma.js's full size. The `Color` class is about 18 KiB and `generateSystem` about 33 KiB ([measurements](https://colorejs.dev/docs/advanced/performance-and-bundling)). ## When Colore is the better choice Pick Colore when your colors come from modern CSS, such as Tailwind CSS v4 or shadcn/ui themes, and you need them back unchanged. Pick it too when text has to pass contrast checks and you want failing colors fixed for you, or when you want a full light and dark theme from one brand color instead of building one by hand. You can try that with your own color in the [theme generator](https://colorejs.dev/playground). ## Related - [How Colore compares with other color libraries](https://colorejs.dev/docs/comparison) - [Moving from tinycolor2](https://colorejs.dev/docs/comparison/tinycolor2) - [Use OKLCH in JavaScript](https://colorejs.dev/docs/guides/oklch-in-javascript) Source: https://colorejs.dev/docs/comparison/chroma-js --- # Moving from tinycolor2 to Colore tinycolor2 was written before CSS had `oklch()`. Tailwind CSS v4 writes its default colors in OKLCH, and so do current shadcn/ui themes. Pass one of those colors to tinycolor2 and it doesn't throw an error. It returns black. ```js import tinycolor from 'tinycolor2'; tinycolor('oklch(0.6 0.2 260)').isValid(); // false tinycolor('oklch(0.6 0.2 260)').toHexString(); // '#000000' tinycolor('color(display-p3 1 0 0)').isValid(); // false ``` Colore reads every CSS Color 4 format, including `oklch()`, `lab()`, `color()` and `color-mix()`. It's written in TypeScript and ships its own types, where tinycolor2 needs `@types/tinycolor2`. ```js import { isValidColor, toHex } from 'colore-js/fn'; isValidColor('oklch(0.6 0.2 260)'); // true toHex('oklch(0.6 0.2 260)'); // '#2e79f5' ``` ```bash npm install colore-js ``` The outputs on this page come from tinycolor2 1.6.0 and colore-js 2.0.1, run on December 3, 2026. ## Calling Colore instead of tinycolor2 tinycolor2 wraps every color in an object, and you call a format method at the end. Colore's `Color` class chains the same way. Colore also has plain functions in `colore-js/fn` that take a color and return a CSS string, hex when the result fits sRGB. ```js import tinycolor from 'tinycolor2'; import { colore } from 'colore-js'; import { lighten } from 'colore-js/fn'; tinycolor('#2563eb').lighten(10).toHexString(); // '#5484ef' colore('#2563eb').lighten(10).hex(); // '#3272fb' lighten('#2563eb', 10); // '#3272fb' ``` The lighter blue differs because tinycolor2 does most of its math in HSL and Colore does it in OKLCH, where a change in lightness keeps the color's hue and chroma. ## Method by method | tinycolor2 | Colore | Result | | --- | --- | --- | | `tinycolor(x).isValid()` | `isValidColor(x)` | Same for formats tinycolor2 reads. Colore also reads OKLCH, Lab, `color()` and `color-mix()`. | | `.toHexString()` / `.toHex8String()` | `toHex(x)` | Same. Colore adds the two alpha digits only when alpha is below 1 (`#2563eb80`), so one call covers both. | | `.toRgbString()` | `toRgb(x)` | Same values, written `rgb(37 99 235)` instead of `rgb(37, 99, 235)` | | `.toHslString()` | `toHsl(x)` | Same values, written `hsl(221 83% 53%)` | | `.setAlpha(0.5)` | `setAlpha(x, 0.5)` | Same color. Colore returns `#2563eb80`. | | `.getLuminance()` | `luminance(x)` | Same | | `tinycolor.readability(a, b)` | `contrastRatio(a, b)` | Same WCAG 2 ratio | | `tinycolor.isReadable(a, b)` | `isReadable(a, b)` | Same default: WCAG AA for normal text, 4.5:1 | | `tinycolor.mostReadable(bg, list)` | `new Color(bg).isDark()` or `bestTextColor(bg, list)` | `isDark()` gives the same WCAG 2 pick between black and white. `bestTextColor` picks by APCA. See below. | | `.isDark()` / `.isLight()` | `new Color(x).isDark()` / `.isLight()` | Different cutoff. Colore's tells you which text color has more contrast. See below. | | `.lighten(n)` / `.darken(n)` | `lighten(x, n)` / `darken(x, n)` | Different math, OKLCH instead of HSL | | `.saturate(n)` / `.desaturate(n)` | `saturate(x, n)` / `desaturate(x, n)` | Different math. A saturated result can be wider than sRGB. | | `.spin(deg)` | `adjustHue(x, deg)` | Different math, OKLCH hue | | `.greyscale()` | `grayscale(x)` | Different. Colore keeps the color's perceived lightness: `#707070` for `#2563eb`, where tinycolor2 gives `#888888`. | | `.complement()` | `complement(x)` | Different, OKLCH hue: `#906900` for `#2563eb`, where tinycolor2 gives `#ebad25` | | `.triad()` | `triadic(x)` | Different, OKLCH hue | | `tinycolor.mix(a, b, 50)` | `mix(a, b, 0.5)` | Different. tinycolor2 mixes sRGB values and Colore mixes in OKLab, so `#2563eb` and `#facc15` give `#909880` and `#90a3ad`. Pass `'srgb'` as the fourth argument to get tinycolor2's result. Colore takes 0 to 1. | | `.analogous()`, `.tetrad()`, `.splitcomplement()`, `.monochromatic()` | None in 2.0 | For shades of one color, use [`palette`](https://colorejs.dev/docs/api/operations/scales-and-palette/palette). | All the Colore names in the middle column are exports of `colore-js/fn` except `isDark` and `isLight`, which are methods on the `Color` class. ### Black or white text `mostReadable` returns the candidate with the best WCAG 2 ratio. In Colore, `isDark()` makes the same choice between black and white, apart from colors right at the crossover point. The color it picks always reaches at least 4.58:1, which passes WCAG AA for normal text. ```js tinycolor.mostReadable('#3b82f6', ['#000000', '#ffffff']).toHexString(); // '#000000' colore('#3b82f6').isDark() ? '#ffffff' : '#000000'; // '#000000' bestTextColor('#3b82f6'); // '#ffffff' ``` [`bestTextColor`](https://colorejs.dev/docs/api/operations/accessibility/best-text-color) picks by APCA, a newer contrast method that tinycolor2 doesn't have. It often picks white on saturated mid-tones like this blue, where WCAG 2 picks black. Across a grid of 4,096 background colors (16 levels per RGB channel), it picked differently from `mostReadable` on 1,151, about 28%. [Black or white text](https://colorejs.dev/docs/guides/black-or-white-text) compares the two methods on every Tailwind 500 shade. ### isDark tells you which text color to use tinycolor2 calls a color dark when its perceived brightness is under 128 out of 255. Colore calls it dark at a relative luminance of 0.179 or less, the point where white text starts to have more WCAG 2 contrast than black. The two cutoffs disagree on 627 of the same 4,096 colors, about 15%. If you switch text color on `isDark()`, those colors get a different text color after you move to Colore, and it's the one with more contrast. ## What changes when you lighten tinycolor2 adds points of HSL lightness. HSL lightness doesn't track what you see, so `lighten(20)` takes a different-size step on each color and lowers its chroma. Colore moves 20% of the way to white in OKLCH on every color, and keeps the hue and chroma. | Tailwind 500 shade | Chroma | After tinycolor2 `lighten(20)` | After Colore `lighten(x, 20)` | | --- | ---: | ---: | ---: | | yellow `#eab308` | 0.162 | 0.141 | 0.162 | | violet `#8b5cf6` | 0.219 | 0.088 | 0.219 | | blue `#3b82f6` | 0.188 | 0.091 | 0.188 | | red `#ef4444` | 0.208 | 0.101 | 0.208 | On violet, blue and red, tinycolor2's lighter shade keeps less than half the chroma of the original, which is why it looks washed out. Colore's lighter violet is still the same violet, and it stays that way in hex: `toHex(lighten('#8b5cf6', 20))` is `#a276ff`, with chroma 0.196 against tinycolor2's 0.088. Before you convert, Colore's functions write a color that's more vivid than sRGB as `oklch()` or `color(display-p3 …)`, which current browsers render. When you need hex, call [`toHex`](https://colorejs.dev/docs/api/operations/output/to-hex), or `.toGamut('srgb').hex()` on the `Color` class to keep the hue closer. See [Gamut and CSS output](https://colorejs.dev/docs/concepts/gamut-and-css-output). The same amount moves the color a different distance in each library, so don't copy the numbers across. Pick new amounts by eye, or replace hand-picked hover colors with [`generateStates`](https://colorejs.dev/docs/api/system/states). ## When to switch tinycolor2 is the smaller package, at 5.4 kB gzipped ([bundlephobia](https://bundlephobia.com/package/tinycolor2@1.6.0)). In Colore, `toHex` alone from `colore-js/fn` is about 10 KiB gzipped, because it brings the parser with it, and the `Color` class is about 18 KiB, measured with Rollup and Terser ([details](https://colorejs.dev/docs/advanced/performance-and-bundling)). Switch when your app reads OKLCH or Display P3 colors, when you want lighter and darker shades that keep their color, or when you need [contrast repair](https://colorejs.dev/docs/api/intelligence/ensure-contrast) and [theme generation](https://colorejs.dev/docs/api/system/generate-system), which tinycolor2 doesn't have. If designers signed off on colors that tinycolor2 calculated, switching changes them. Generate both sets and compare before you replace stored values. To see the shades and theme Colore makes from your brand color, open it in the [palette generator](https://colorejs.dev/palette) or the [theme generator](https://colorejs.dev/playground). ## Related - [How Colore compares with other color libraries](https://colorejs.dev/docs/comparison) - [Colore and chroma.js compared](https://colorejs.dev/docs/comparison/chroma-js) - [Get started with Colore](https://colorejs.dev/docs/getting-started) Source: https://colorejs.dev/docs/comparison/tinycolor2 --- # Colore 2.0 Colore 2.0 is a complete rebuild. It works in OKLCH, so colors change the way people see them; it keeps text readable without you checking every pair; and it turns one brand color into a full light and dark theme for the stack you already use. It is still zero dependencies, fully typed, and small enough to ship to the browser: one function from `colore-js/fn` is about 10 KiB gzipped. ## What is new ### Modern CSS colors Parse modern formats such as OKLCH and Display P3, and evaluate supported `color-mix()` expressions. Lighten and darken in OKLCH, or choose the space you want when you mix. Use `css()` to keep a wider color or `toGamut()` to map it. [Color spaces](https://colorejs.dev/docs/concepts/color-spaces-and-ranges) ### Readable by default [`ensureContrast`](https://colorejs.dev/docs/api/intelligence/ensure-contrast) searches for a foreground that passes your WCAG 2 or APCA target. Check its success flag before applying the result. [`audit`](https://colorejs.dev/docs/api/audit) checks a whole palette or a `globals.css`, and `fixCssVariables` repairs it. ### A complete theme from one color [`generateSystem`](https://colorejs.dev/docs/api/system/generate-system) builds brand, surface, text, border, status and chart colors for light and dark mode, all checked for contrast. Export it as CSS variables, a Tailwind CSS v4 theme, a shadcn/ui `globals.css` or design tokens. ### Edit the theme you already have Use [inspectCssTheme](https://colorejs.dev/docs/api/system/inspect-css-theme) to read the theme, [applyThemeToCss](https://colorejs.dev/docs/api/system/apply-theme-to-css) to rebrand it, and [adjustCssVariables](https://colorejs.dev/docs/api/system/adjust-css-variables) to tune selected colors. ### Built for coding agents Run `npx colore-js init` to install the Colore skill for Claude Code, Cursor and Codex. The CLI adds `inspect`, `theme --apply`, `adjust`, `set`, `extract` and `preview` for working with theme files. [Coding agents and CLI](https://colorejs.dev/docs/agents) ### Palettes and chart colors [`palette`](https://colorejs.dev/docs/api/operations/scales-and-palette/palette) builds shade ramps that contain your brand exactly. [`categoricalColors`](https://colorejs.dev/docs/api/operations/scales-and-palette/categorical-colors) gives chart series that stay distinct, including for color-blind readers. ## Upgrading from 1.x 2.0 has a new API, so plan a short migration. Most code maps directly: | 1.x | 2.0 | | --- | --- | | `hexToRgb`, `rgbToHsl` and other conversions | `colore(color).rgb()`, `.hsl()`, `.oklch()`, or `toRgb`, `toHsl` from `colore-js/fn` | | `lightenColor`, `darkenColor`, `saturateColor`, `desaturateColor` | `lighten`, `darken`, `saturate`, `desaturate` | | `invertColor`, `setAlphaValue`, `blendColors` | `invert`, `setAlpha`, `mix` | | `getContrastRatio`, `getLuminance` | `contrastRatio`, `luminance` | | `complementaryColor`, `triadicColors`, single-hue ramps | `complement`, `triadic`, `palette` | | `generateInterpolatedColors` | `interpolate` or `scale` | | `isValidHex`, `isValidRgb` and other validators | `isValidColor` | | `parseColorToRgba`, `detectColorFormat` | `parse`, `detectFormat` | `analogousColors`, `tetradicColors`, `enhanceColor`, `generateRandomColor`, the CSS-variable DOM helpers, `BlendingModes` and `ColorFormats` are gone. Three changes to know about: - Lighten, darken and saturate now work in OKLCH, so the same amount gives a slightly different, more even result than 1.x. - Functions from `colore-js/fn` return CSS strings: hex when the color fits sRGB, `oklch()` or `color(display-p3 …)` when it doesn't. - Invalid input and unknown options throw a `ColorError` that names the fix, instead of returning a guessed color. ```ts import { colore } from 'colore-js'; import { lighten, contrastRatio } from 'colore-js/fn'; colore('#2563eb').lighten(8).hex(); // '#306ff8' lighten('#2563eb', 8); // '#306ff8' contrastRatio('#111827', '#ffffff'); // ≈ 17.74 ``` The [1.x documentation](https://colorejs.dev/docs/1.4.4/introduction) stays online. ## Next steps - [Get started](https://colorejs.dev/docs/getting-started) - [API overview](https://colorejs.dev/docs/api/overview) - [Use Colore with a coding agent](https://colorejs.dev/docs/agents) Source: https://colorejs.dev/docs/release/v2-release-notes --- # FAQ ## What does Colore do? Colore is a JavaScript and TypeScript color library. Use it to convert a CSS color, change a foreground that fails contrast, generate a light and dark theme, or edit the color variables in a stylesheet. ## Can I use Colore with Tailwind CSS and shadcn/ui? Yes. A generated color system exports Tailwind CSS v4 theme variables and shadcn/ui color variables. Colore can also check foreground and background pairs in your existing `globals.css`. ## Does Colore support OKLCH and Display P3? Yes. Colore reads and writes OKLCH and Display P3. Use `css()` to choose an output format, or `toGamut()` to bring a wide-gamut color into sRGB before exporting hex. ## Which contrast standard does Colore use? Colore defaults to WCAG 2. Its contrast checks can use APCA when you choose that algorithm. Use WCAG 2 for an AA or AAA conformance check. ## Can Colore fix a color that fails contrast? Yes. `ensureContrast(foreground, background)` returns a passing foreground and changes its lightness as little as it can, so `#777777` on white becomes `#767676`. For a whole stylesheet, `npx colore-js fix app/globals.css --write` rewrites only the failing foreground values and keeps each value's format. ## Is Colore free? Yes. Colore uses the MIT license. It has zero runtime dependencies and works in browsers and in Node.js 20 or later. ## Can I use Colore with a coding agent? Yes. Run `npx colore-js init` to install the Colore skill for Claude Code, Cursor or Codex. The skill gives your agent CLI commands to inspect CSS themes and check contrast. ## Which Colore import should I use? Use `colore()` or `new Color()` when you want a Color object you can inspect or chain. Import from `colore-js/fn` when you need a named standalone helper, such as `toHex` or `contrastRatio`. ## How do I handle invalid color input? Use `Color.try()` when you want a Color or `null`. Use `isValidColor()` for a boolean check. Use `parse()` or `new Color()` when you want a `ColorError` for an invalid value. ## Can Colore read currentcolor or var()? Those values depend on the element or stylesheet they appear in. Resolve them to a color value before passing them to a standalone Colore parser. The CSS variable audit can follow supported aliases in a theme file. ## What units should I use for RGB objects? Use 0–255 for untagged RGB objects. For gamma-encoded 0–1 values from a tool like Figma, add the space tag `srgb`. Use `alpha` as the opacity key in either form. ## Where can I find the Colore 1.x docs? Use the version switcher to open the 1.x docs. The release notes show how common 1.x calls map to Colore 2. ## Related - [Colore compared](https://colorejs.dev/docs/comparison) - [Handle invalid colors](https://colorejs.dev/docs/advanced/error-handling-and-validation) - [Gamut and CSS output](https://colorejs.dev/docs/concepts/gamut-and-css-output) - [Colore 2.0 release notes](https://colorejs.dev/docs/release/v2-release-notes) Source: https://colorejs.dev/docs/faq