# color2k: Recipes

Every example here runs against the built package in CI. The picture under each one is drawn from what that code returned, so the two can't disagree.

## Hover, active and focus states

Work them out from the brand color so you never hard-code them again.

```js
import { darken, readableColor, transparentize } from 'color2k';

function createTheme(brand) {
  return {
    brand,
    brandHover: darken(brand, 0.06),
    brandActive: darken(brand, 0.12),
    brandSubtle: transparentize(brand, 0.88),
    focusRing: transparentize(brand, 0.6),
    onBrand: readableColor(brand),
  };
}

const theme = createTheme('rebeccapurple');

theme.brandHover; // 'hsla(270, 50%, 34%, 1)'
theme.brandSubtle; // 'rgba(102, 51, 153, 0.12)'
theme.onBrand; // '#fff'
```

Result:

- brand: rebeccapurple
- brandHover: hsla(270, 50%, 34%, 1)
- brandActive: hsla(270, 50%, 28%, 1)
- brandSubtle: rgba(102, 51, 153, 0.12)
- focusRing: rgba(102, 51, 153, 0.4)
- onBrand: #fff

## Readable text on any background

`readableColor` answers black or white. `readableColorIsBlack` gives you the same answer as a boolean, for when you have your own ink and paper colors.

```js
import { readableColor, readableColorIsBlack } from 'color2k';

const backgrounds = ['gold', 'tomato', 'rebeccapurple', 'midnightblue'];

const labels = backgrounds.map((background) => ({
  background,
  color: readableColor(background),
  label: background,
}));

labels[0].color; // '#000'
labels[3].color; // '#fff'

// Use your own ink and paper colors instead of pure black and white.
const text = readableColorIsBlack('gold') ? '#1a1a1a' : '#fafafa'; // '#1a1a1a'
```

Result:

- gold: #000 on gold, contrast 14.97:1 (AAA)
- tomato: #000 on tomato, contrast 7.13:1 (AAA)
- rebeccapurple: #fff on rebeccapurple, contrast 8.41:1 (AAA)
- midnightblue: #fff on midnightblue, contrast 14.85:1 (AAA)

## Contrast checks

`getContrast` returns the WCAG contrast ratio, which runs from 1 to 21 for opaque, in-range colors. `hasBadContrast` compares it to a standard: `'decorative'` (1.5), `'readable'` (3), `'aa'` (4.5, the default) or `'aaa'` (7).

```js
import { getContrast, hasBadContrast } from 'color2k';

const pairs = [
  { color: '#767676', background: 'white' },
  { color: '#999', background: 'white' },
  { color: 'gold', background: 'midnightblue' },
];

getContrast('#767676', 'white').toFixed(2); // '4.54'

hasBadContrast('#767676'); // false
hasBadContrast('#767676', 'aaa'); // true
hasBadContrast('#999'); // true
hasBadContrast('gold', 'aa', 'midnightblue'); // false
```

Result:

- Aa Text: #767676 on white, contrast 4.54:1 (AA)
- Aa Text: #999 on white, contrast 2.85:1 (fails AA)
- Aa Text: gold on midnightblue, contrast 10.59:1 (AAA)

Both functions ignore alpha and do not clamp, so give them opaque, in-range colors. A see-through color has no contrast ratio of its own, because it depends on what is behind it. `getContrast('rgb(999, 0, 0)', 'black')` is a meaningless 103.

To nudge a color until it passes AA, flatten it onto the background first. Then a see-through color is measured the way it will be seen:

```js
import {
  darken,
  hasBadContrast,
  lighten,
  parseToRgba,
  readableColorIsBlack,
  rgba,
  toHex,
} from 'color2k';

// What `color` looks like on top of an opaque `background`.
function flatten(color, background) {
  const [red, green, blue, alpha] = parseToRgba(color);
  const under = parseToRgba(background);
  const over = (top, bottom) => top * alpha + bottom * (1 - alpha);

  return rgba(over(red, under[0]), over(green, under[1]), over(blue, under[2]), 1);
}

function accessible(color, background = '#fff') {
  // Move away from the background: darker on light, lighter on dark.
  const adjust = readableColorIsBlack(background) ? darken : lighten;
  let result = flatten(color, background);

  for (let i = 0; i < 50 && hasBadContrast(result, 'aa', background); i++) {
    result = adjust(result, 0.02);
  }

  return toHex(result);
}

const onLight = accessible('#4dabf7'); // '#0a75cd'
const onDark = accessible('#555', '#000'); // '#787878'
const fromClear = accessible('transparent'); // '#757575'
const fromGlass = accessible('rgba(77, 171, 247, 0.5)'); // '#0b75cb'
```

Result:

- Before: #4dabf7 on #fff, contrast 2.48:1 (fails AA)
- After: #0a75cd on #fff, contrast 4.73:1 (AA)
- Before: #555 on #000, contrast 2.82:1 (fails AA)
- After: #787878 on #000, contrast 4.76:1 (AA)
- Transparent: #757575 on #fff, contrast 4.61:1 (AA)
- Half clear: #0b75cb on #fff, contrast 4.75:1 (AA)

## Color scales

`getScale` takes two or more colors and hands back a function. Give that function a number from 0 to 1 and you get the color at that point.

```js
import { getScale, toHex } from 'color2k';

const heat = getScale('#2ec4b6', '#ffd60a', '#ff3b5c');

heat(0); // 'rgba(46, 196, 182, 1)'
heat(0.5); // 'rgba(255, 214, 10, 1)'
heat(0.75); // 'rgba(255, 137, 51, 1)'

const steps = [0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1].map((n) =>
  toHex(heat(n))
);

steps[2]; // '#97cd60'
```

Result:

- #2ec4b6
- #62c98b
- #97cd60
- #cbd235
- #ffd60a
- #ffaf1e
- #ff8933
- #ff6248
- #ff3b5c

## Tints and shades

`mix` blends two colors. A weight of 0 is all the first color and 1 is all the second.

```js
import { mix, toHex } from 'color2k';

const base = 'rebeccapurple';
const tint = toHex(mix(base, 'white', 0.8)); // '#e0d6eb'
const shade = toHex(mix(base, 'black', 0.4)); // '#3d1f5c'
```

Result:

- tint: #e0d6eb
- base: rebeccapurple
- shade: #3d1f5c

## Tailwind palette

One color in, a 50 to 950 palette out. Use it in a Tailwind config or paste it into `@theme`.

```js
import { getScale, toHex } from 'color2k';

function palette(color) {
  const scale = getScale('white', color, 'black');
  const steps = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950];

  return Object.fromEntries(
    steps.map((step) => [step, toHex(scale(step / 1000))])
  );
}

const brand = palette('#6d28d9');

brand[100]; // '#e2d4f7'
brand[500]; // '#6d28d9'
brand[900]; // '#16082b'

// Tailwind 3: tailwind.config.js
const config = { theme: { extend: { colors: { brand } } } };

// Tailwind 4: paste into `@theme { ... }`
const variables = Object.entries(brand)
  .map(([step, hex]) => `--color-brand-${step}: ${hex};`)
  .join('\n');
```

Result:

- 50: #f0eafb
- 100: #e2d4f7
- 200: #c5a9f0
- 300: #a77ee8
- 400: #8a53e1
- 500: #6d28d9
- 600: #5720ae
- 700: #411882
- 800: #2c1057
- 900: #16082b
- 950: #0b0416

## CSS-in-JS

This is what color2k was written for. The functions that adjust, mix and convert colors return plain CSS strings, so they drop straight into a template.

```jsx
import styled from 'styled-components';
import { darken, readableColor, transparentize } from 'color2k';

const Button = styled.button`
  background: ${(props) => props.$color};
  color: ${(props) => readableColor(props.$color)};

  &:hover {
    background: ${(props) => darken(props.$color, 0.08)};
  }

  &:focus-visible {
    box-shadow: 0 0 0 3px ${(props) => transparentize(props.$color, 0.6)};
  }
`;

const save = <Button $color="#b3261e">Save</Button>;
```

Result:

- Save (default): #fff on #b3261e, contrast 6.54:1 (AA)
- Save (hover): #fff on hsla(3, 71%, 33%, 1), contrast 8.81:1 (AAA)
- Save (focus): #fff on #b3261e, contrast 6.54:1 (AA), ring rgba(179, 38, 30, 0.4)

## React

```jsx
import { useMemo } from 'react';
import { readableColor, transparentize } from 'color2k';

function Tag({ color, children }) {
  const style = useMemo(
    () => ({
      background: color,
      color: readableColor(color),
      boxShadow: `0 0 0 4px ${transparentize(color, 0.8)}`,
    }),
    [color]
  );

  return <span style={style}>{children}</span>;
}

const tags = [
  <Tag color="tomato">New</Tag>,
  <Tag color="gold">Sale</Tag>,
  <Tag color="midnightblue">Pro</Tag>,
];
```

Result:

- New: #000 on tomato, contrast 7.13:1 (AAA), ring rgba(255, 99, 71, 0.2)
- Sale: #000 on gold, contrast 14.97:1 (AAA), ring rgba(255, 215, 0, 0.2)
- Pro: #fff on midnightblue, contrast 14.85:1 (AAA), ring rgba(25, 25, 112, 0.2)

## Convert between formats

```js
import { parseToHsla, parseToRgba, toHex, toHsla, toRgba } from 'color2k';

const hex = toHex('hsl(210, 100%, 50%)'); // '#0080ff'
const rgb = toRgba(hex); // 'rgba(0, 128, 255, 1)'
const hsl = toHsla(hex); // 'hsla(210, 100%, 50%, 1)'

// Need the numbers? Parse to a tuple.
parseToRgba('#0080ff80'); // [0, 128, 255, 0.5019607843137255]
parseToHsla('tomato'); // [9.130434782608695, 1, 0.6392156862745098, 1]
```

Result:

- hex: #0080ff
- rgb: rgba(0, 128, 255, 1)
- hsl: hsla(210, 100%, 50%, 1)

Going the other way, `rgba` and `hsla` build a color string from numbers:

```js
import { hsla, rgba } from 'color2k';

const glass = rgba(0, 128, 255, 0.5); // 'rgba(0, 128, 255, 0.5)'
const sky = hsla(210, 1, 0.5, 1); // 'hsla(210, 100%, 50%, 1)'
```

Result:

- glass: rgba(0, 128, 255, 0.5)
- sky: hsla(210, 100%, 50%, 1)

## Check what color2k accepts

color2k throws a `ColorError` when it can't parse a string, so a `try` tells you whether it will take one:

```js
import { ColorError, parseToRgba } from 'color2k';

function canParse(value) {
  try {
    parseToRgba(value);
    return true;
  } catch (error) {
    if (error instanceof ColorError) return false;
    throw error;
  }
}

const inputs = ['#0d6efd', 'rgb(13, 110, 253)', 'rgb(13 110 253)', '#12345'];
const results = inputs.map((input) => [input, canParse(input)]);

canParse('#0d6efd'); // true
canParse('rgb(13 110 253)'); // false

// Loose: the shape is checked, the numbers are not.
canParse('rgb(999, 0, 0)'); // true
```

Result:

- #0d6efd: parses
- rgb(13, 110, 253): parses
- rgb(13 110 253): throws
- #12345: throws

Don't use this as a CSS validator. The parser is small and loose on purpose:

- Channel and alpha values are not range-checked. `rgb(999, 0, 0)` parses as it is written. An alpha that is not a number, such as `rgba(1, 2, 3, .)`, does throw a `ColorError`.
- Named colors are stored as hashes to save bytes, so about 3% of made-up words are accepted as if they were a color name.

If you need real validation, do it with your own rules or an allow-list before calling color2k. `CSS.supports('color', value)` won't do it either. Browsers accept forms color2k rejects, such as `rgb(13 110 253)`, so a string can pass there and still throw here.

## Invert and complement

```js
import { complement, invert } from 'color2k';

const original = '#0d6efd';
const inverted = invert(original); // 'rgba(242, 145, 2, 1)'

// The opposite side of the color wheel.
const opposite = complement(original); // 'hsla(36, 98%, 52%, 1)'

// Part of the way there. Halfway is always gray.
invert(original, 0.5); // 'rgba(128, 128, 128, 1)'
```

Result:

- original: #0d6efd
- inverted: rgba(242, 145, 2, 1)
- opposite: hsla(36, 98%, 52%, 1)
