# Dither inks

Reads theme colors through a canvas probe and observes <html> for theme changes.

Source: https://www.ui95.dev/ui/dither-inks

## Installation

```bash
npx shadcn@latest add https://www.ui95.dev/r/dither-inks.json
```

Run it in a Radix shadcn project that already has the UI95 theme.

`lib/dither/inks.ts`

```tsx
export type Rgb = readonly [number, number, number]

export type Rgba = readonly [number, number, number, number]

export type InkPalette = readonly [Rgb, Rgb, ...Rgb[]]

export const INK_TOKENS = ["--ink-0", "--ink-1", "--ink-2", "--ink-3"] as const

const THEME_ATTRIBUTES = ["class", "data-theme", "style"]

let colorProbe: CanvasRenderingContext2D | null = null

function readColorProbe(): CanvasRenderingContext2D | null {
  if (colorProbe) {
    return colorProbe
  }
  const canvas = document.createElement("canvas")
  canvas.width = 1
  canvas.height = 1
  colorProbe = canvas.getContext("2d", { willReadFrequently: true })
  return colorProbe
}

export function parseCssColor(value: string): Rgba {
  const probe = readColorProbe()
  if (!probe || value === "") {
    return [0, 0, 0, 255]
  }
  probe.clearRect(0, 0, 1, 1)
  probe.fillStyle = "#000000"
  probe.fillStyle = value
  probe.fillRect(0, 0, 1, 1)
  const [red, green, blue, alpha] = probe.getImageData(0, 0, 1, 1).data
  return [red, green, blue, alpha]
}

export function readInks(
  root: Element,
  tokens: readonly [string, string, ...string[]] = INK_TOKENS
): InkPalette {
  const style = getComputedStyle(root)
  const readInk = (token: string): Rgb => {
    const [red, green, blue] = parseCssColor(style.getPropertyValue(token).trim())
    return [red, green, blue]
  }
  const [first, second, ...rest] = tokens
  return [readInk(first), readInk(second), ...rest.map(readInk)]
}

export function observeInkChange(onChange: () => void): () => void {
  const observer = new MutationObserver(onChange)
  observer.observe(document.documentElement, {
    attributes: true,
    attributeFilter: THEME_ATTRIBUTES,
  })
  return () => observer.disconnect()
}
```

## Used by

- [dither-image](https://www.ui95.dev/ui/dither-image)
- [shader-mount](https://www.ui95.dev/ui/shader-mount)
- [skeleton](https://www.ui95.dev/ui/skeleton)
