# Color Picker

> Color picker from @salmonui/inputs/color-picker with a saturation and brightness area, hue and alpha sliders, a hex field, a swatch palette, recent colors, Apply / Cancel and parseColor, every part usable alone.

Canonical: https://salmonui.dev/docs/inputs/color-picker

`ColorPicker` picks a color. A trigger button with a
swatch preview opens a popover dialog, or `inline` renders the panel in
place. The panel composes parts that are exported on their own:
`ColorArea`, `ColorSlider`, `ColorField`, `ColorSwatch` and
`ColorSwatchPicker`. Everything is CSS gradients rendered on the server;
nothing is drawn on a canvas or measured before the first pointer press.

```tsx
import { ColorPicker, parseColor } from '@salmonui/inputs/color-picker';
import '@salmonui/inputs/color-picker/styles.css';

<ColorPicker label="Theme color" name="theme" defaultValue="#1971c2" clearable defaultRecentColors={[]} />
<ColorPicker label="Accent" inline mode="swatches" commitBehavior="immediate" columns={5} colors={['#e8590c', '#2b8a3e', '#1971c2']} />
parseColor('hsl(120, 100%, 25%)').toString('hexa'); // '#008000ff'
```

### Live demo: Color picker basics

Live demo: https://salmonui.dev/demos/inputs/color-picker-basics

A confirm-mode color popover with recent colors and no color, and an immediate palette picker with grouped swatches.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { ColorPicker } from '@salmonui/inputs/color-picker';

const BRAND = [
  { label: 'Brand', colors: ['#e8590c', '#f08c00', '#2b8a3e', '#1971c2', '#5f3dc4'] },
  { label: 'Neutrals', colors: ['#ffffff', '#ced4da', '#868e96', '#343a40', '#000000'] },
];

// A confirm-mode popover with recent colors, and an immediate palette picker.
export default function ColorPickerBasicsDemo() {
  const [value, setValue] = useState<string | null>('#1971c2ff');
  const [recent, setRecent] = useState<readonly string[]>([]);
  const [accent, setAccent] = useState<string | null>('#e8590c');
  return (
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 24, alignItems: 'start' }}>
      <ColorPicker label="Theme color" description="Apply to keep, Cancel or Escape to discard" value={value} onValueChange={setValue} recentColors={recent} onRecentColorsChange={setRecent} clearable />
      <ColorPicker label="Accent" valueFormat="hex" commitBehavior="immediate" defaultMode="swatches" colors={BRAND} columns={5} value={accent} onValueChange={setAccent} />
      <output style={{ flexBasis: '100%' }}>
        Theme color {value ?? 'no color'}, accent {accent ?? 'no color'}
      </output>
    </div>
  );
}
```

## Value

- `value` / `defaultValue` (`string | null`, default `'#008000ff'`) and
  `valueFormat: 'hex' | 'hexa' | 'rgb' | 'hsl'` (default `'hexa'`).
  The picker reports values in `valueFormat`; `'hex'` drops alpha and hides
  the alpha slider. `null` is "no color".
- `onValueChange(value, details)` fires on every pick, at most once per
  animation frame while dragging; `onValueCommit` fires
  when a value is committed. `details` is
  `{ source, reason, color }` with `reason` `'area' | 'hue' | 'alpha' |
  'field' | 'swatch' | 'recent' | 'clear' | 'apply' | 'cancel' | 'reset'`
  and `color` the parsed `Color` (or null).
- `name` submits the value through a hidden input (`''` for no color);
  `form` and `disabled` are forwarded. A form reset restores
  `defaultValue`.
- Controlled or uncontrolled: `value`, `mode`, `open` and `recentColors`
  are controlled with their `on...Change` callback, or start from
  `defaultValue`, `defaultMode`, `defaultOpen` and `defaultRecentColors`.
  `valueFormat` only sets the format of reported values: convert the
  value you hold yourself (`parseColor(value).toString(format)`) when you
  change it.

## Commit behavior

`commitBehavior: 'confirm'` (default) adds Apply and Cancel. Picks
update the value live; Apply commits (`onValueCommit` with reason
`'apply'`) and closes; Cancel, Escape, an outside press or focus leaving
the popover reverts to the value at open (`onValueChange` with reason
`'cancel'`). Inline, Cancel reverts to the last applied value.
`'immediate'` commits every finished pick (drag end, key step, field entry,
swatch) and closes the popover after a swatch pick.

## Modes

- `mode: 'area' | 'swatches'` / `defaultMode` (default `'area'`) /
  `onModeChange`. Area mode is a `ColorArea`, a hue
  `ColorSlider`, an alpha `ColorSlider` (`alpha`, default true),
  previous and current swatches and a hex `ColorField`. Swatches mode is a
  `ColorSwatchPicker` of `colors` (flat entries or `{ label, colors }`
  groups; default a 60-color palette) in `columns` (default 10).
- `showModeSwitch` (default true) shows the switch button;
  `onBeforeModeChange(event)` can veto with `event.preventDefault()`.
- `clearable` adds a "no color" swatch first in the palette and a clear
  button on the hex field.
- `renderSwatch({ color, value, label, selected, index })` replaces the
  content of each palette swatch;
  the option around it keeps the name, selection and keyboard behavior.

### Live demo: Color picker inline palette

Live demo: https://salmonui.dev/demos/inputs/color-picker-swatches

An inline ColorPicker in swatches mode with a configurable number of columns and custom swatches from renderSwatch.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { ColorPicker, type SwatchRenderContext } from '@salmonui/inputs/color-picker';
import { Select } from '@salmonui/dropdowns/select';

const COLUMNS = ['3', '4', '6', '12'];

const LABELS = [
  { value: '#e03131', label: 'Bug' },
  { value: '#f08c00', label: 'Urgent' },
  { value: '#f5c400', label: 'Review' },
  { value: '#2f9e44', label: 'Done' },
  { value: '#0ca678', label: 'Design' },
  { value: '#1971c2', label: 'Feature' },
  { value: '#5f3dc4', label: 'Research' },
  { value: '#c2255c', label: 'Blocked' },
  { value: '#495057', label: 'Chore' },
  { value: '#868e96', label: 'Later' },
  { value: '#a61e4d', label: 'Security' },
  { value: '#087f5b', label: 'Docs' },
];

// A filled chip with a check mark on the selected swatch; the picker draws the selection ring.
function chip({ value, label, selected }: SwatchRenderContext) {
  return (
    <span
      aria-hidden="true"
      style={{
        display: 'grid',
        placeItems: 'center',
        inlineSize: 20,
        blockSize: 20,
        borderRadius: 'var(--salmon-radius-sm)',
        background: value ?? 'transparent',
        color: '#fff',
        fontSize: 12,
        fontWeight: 700,
      }}
      title={label}
    >
      {selected ? '✓' : ''}
    </span>
  );
}

// An inline palette: columns and renderSwatch.
export default function ColorPickerSwatchesDemo() {
  const [columns, setColumns] = useState(6);
  const [custom, setCustom] = useState(true);
  const [value, setValue] = useState<string | null>('#1971c2');
  const name = LABELS.find((l) => l.value === value)?.label;
  return (
    <div style={{ display: 'grid', gap: 12, maxWidth: 420 }}>
      <div className="demo-toolbar">
        <label>
          Columns
          <Select aria-label="Columns" data={COLUMNS} value={String(columns)} onValueChange={(value) => value != null && setColumns(Number(value))} />
        </label>
        <Checkbox checked={custom} onCheckedChange={(checked) => setCustom(checked)}>
          Custom swatches
        </Checkbox>
      </div>
      <ColorPicker
        label="Label color"
        inline
        defaultMode="swatches"
        showModeSwitch={false}
        commitBehavior="immediate"
        valueFormat="hex"
        colors={LABELS}
        columns={columns}
        renderSwatch={custom ? chip : undefined}
        value={value}
        onValueChange={setValue}
      />
      <output>
        {value ?? 'no color'} {name ? `(${name})` : ''}
      </output>
    </div>
  );
}
```

## Recent colors

`recentColors` / `defaultRecentColors` / `onRecentColorsChange`:
when either is set, every committed color is prepended (deduplicated, at
most `maxRecentColors`, default 10) and shown as a "Recent colors" palette.
Nothing is stored; persist the array yourself if needed.

## Popover

`open` / `defaultOpen` / `onOpenChange(open, { source, reason })`
and the cancellable `onBeforeOpenChange(event)`
(`event.open`, `event.reason`, `event.preventDefault()`). The trigger is a plain
button with `aria-haspopup="dialog"` and `aria-expanded`, named by the
label and the current color ("Theme color dark vibrant blue"). The popover
is a `role="dialog"` named by the label, positioned below the trigger with
flip and shift, in the top layer. It takes focus (the area) on open and
returns it to the trigger on close. The popover code is a lazy chunk
loaded when the trigger is hovered, focused or opened, and the popover
renders only while open.

### Live demo: Color picker popover and events

Live demo: https://salmonui.dev/demos/inputs/color-picker-popover

A controlled popover with a cancellable open, a cancellable mode switch, the alpha channel, value formats and the live versus committed value events in a log.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { ColorPicker, parseColor, type ColorPickerMode } from '@salmonui/inputs/color-picker';
import { Select } from '@salmonui/dropdowns/select';
import { EventLog, useEventLog } from '../../components/demo-kit';

type Format = 'hex' | 'hexa' | 'rgb' | 'hsl';

const FORMATS: readonly Format[] = ['hexa', 'hex', 'rgb', 'hsl'];

// Controlled open and mode, cancellable open and mode switch, value formats and the two value events.
export default function ColorPickerPopoverDemo() {
  const [format, setFormat] = useState<Format>('hexa');
  const [value, setValue] = useState<string | null>('#2b8a3ecc');
  const [committed, setCommitted] = useState<string | null>('#2b8a3ecc');
  const [open, setOpen] = useState(false);
  const [mode, setMode] = useState<ColorPickerMode>('area');
  const [alpha, setAlpha] = useState(true);
  const [blockOpen, setBlockOpen] = useState(false);
  const [stayInArea, setStayInArea] = useState(false);
  const [log, push] = useEventLog(12);

  const changeFormat = (next: Format) => {
    setFormat(next);
    // The picker reports values in `valueFormat`; convert the current one too.
    setValue((v) => (v === null ? v : parseColor(v).toString(next)));
    setCommitted((v) => (v === null ? v : parseColor(v).toString(next)));
  };

  return (
    <div style={{ display: 'grid', gap: 12, maxWidth: 520 }}>
      <div className="demo-toolbar">
        <Button type="button" variant="outline" onClick={() => setOpen(true)}>
          Open the picker
        </Button>
        <Checkbox checked={blockOpen} onCheckedChange={(checked) => setBlockOpen(checked)}>
          Block opening
        </Checkbox>
        <Checkbox checked={stayInArea} onCheckedChange={(checked) => setStayInArea(checked)}>
          Stay in the area
        </Checkbox>
        <Checkbox checked={alpha} onCheckedChange={(checked) => setAlpha(checked)}>
          Opacity
        </Checkbox>
        <label>
          Value format
          <Select aria-label="Value format" data={FORMATS} value={format} onValueChange={(value) => value != null && changeFormat(value as Format)} />
        </label>
      </div>
      <ColorPicker
        label="Highlight"
        valueFormat={format}
        alpha={alpha}
        value={value}
        onValueChange={(v, d) => {
          setValue(v);
          push(`onValueChange ${v ?? 'null'} (${d.reason}, ${d.source})`);
        }}
        onValueCommit={(v, d) => {
          setCommitted(v);
          push(`onValueCommit ${v ?? 'null'} (${d.reason})`);
        }}
        open={open}
        onBeforeOpenChange={(event) => {
          if (blockOpen && event.open) {
            event.preventDefault();
            push(`onBeforeOpenChange open vetoed (${event.reason})`);
          }
        }}
        onOpenChange={(next, d) => {
          setOpen(next);
          push(`onOpenChange ${next ? 'open' : 'closed'} (${d.reason})`);
        }}
        mode={mode}
        onBeforeModeChange={(event) => {
          if (stayInArea && event.mode === 'swatches') {
            event.preventDefault();
            push('onBeforeModeChange swatches vetoed');
          }
        }}
        onModeChange={(next) => {
          setMode(next);
          push(`onModeChange ${next}`);
        }}
      />
      <output>
        Popover {open ? 'open' : 'closed'}, mode {mode}. Live value: {value ?? 'no color'}; committed: {committed ?? 'no color'}
      </output>
      <EventLog entries={log} label="Color picker events" />
    </div>
  );
}
```

## Server rendering

The trigger, the inline panel and every part render on the server with
the same markup as the first client render: colors are CSS custom
properties and gradients, ids come from `useId`, and nothing measures the
DOM before the first pointer press, so there are no hydration warnings.
The popover renders only on the client after it opens. Import the
stylesheet once, in the root layout of a Next.js app or the entry of a
Vite app.

## Parts

### Live demo: Color picker parts

Live demo: https://salmonui.dev/demos/inputs/color-picker-parts

ColorArea, hue and alpha ColorSlider, ColorField, ColorSwatch and ColorSwatchPicker composed by hand around one Color value.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { ColorArea, ColorField, ColorSlider, ColorSwatch, ColorSwatchPicker, parseColor, type Color } from '@salmonui/inputs/color-picker';

// The parts composed by hand around one `Color` (a `Color` keeps the hue of grays).
export default function ColorPickerPartsDemo() {
  const [color, setColor] = useState<Color>(() => parseColor('#7048e8'));
  return (
    <div style={{ display: 'grid', gap: 12, inlineSize: 240 }}>
      <ColorArea aria-label="Shade" value={color} onValueChange={setColor} />
      <ColorSlider channel="hue" value={color} onValueChange={setColor} />
      <ColorSlider channel="alpha" value={color} onValueChange={setColor} />
      <div style={{ display: 'flex', gap: 8, alignItems: 'end' }}>
        <ColorSwatch color={color} style={{ inlineSize: 32, blockSize: 32 }} />
        <ColorField label="Color" valueFormat="rgb" value={color} onValueChange={(_, d) => d.color && setColor(d.color)} />
      </div>
      <ColorSwatchPicker aria-label="Presets" columns={6} colors={['#f03e3e', '#f59f00', '#37b24d', '#1c7ed6', '#7048e8', '#495057']} value={color.toString('hex')} onValueChange={(_, d) => d.color && setColor(d.color)} />
      <output>{color.toString('hsl')}</output>
    </div>
  );
}
```

Each part is usable alone and takes `value` / `defaultValue` as a
color string or a `Color`. Passing a `Color` keeps the hue of grays and
blacks while dragging.

- `ColorArea`: saturation along the inline axis, brightness along the
  block axis, `onValueChange(color, { source, reason })` (reason `'drag' |
  'step' | 'reset'`) and `onValueCommit` (drag end, key step). An
  uncontrolled area paints a drag directly and renders once at the end.
- `ColorSlider channel="hue" | "alpha"`, `orientation` (vertical sliders
  grow upward and never mirror).
- `ColorField`: a text field that parses hex, `rgb()` and `hsl()` text on
  blur or Enter and reverts text that does not parse; it reports in its own
  `valueFormat` and shares the Field parts (label, description, error,
  `validation`).
- `ColorSwatch`: a `role="img"` preview named by the color.
- `ColorSwatchPicker`: the palette listbox, `value` as given in `colors`.
- `parseColor(text)` returns a `Color` (`hue`, `saturation`, `brightness`,
  `alpha`, `toRgb()`, `toHsl()`, `toHsv()`, `with()`, `equals()`,
  `toString(format)`), or throws a `TypeError`. `rgbColor`, `hslColor`, `hsvColor` build colors
  and `colorName(color)` describes one.

## Keyboard

`ColorArea` is two visually hidden range inputs (APG Slider, two sliders
for one 2D control); `ColorSlider` is one. `aria-valuetext` names the
color: "Saturation 75%, light vibrant green", "120°, green", "50%".
Horizontal keys mirror in right-to-left content.

| Key (ColorArea) | Action |
| --- | --- |
| Tab | Focuses the saturation slider (one tab stop) |
| Arrow Right / Arrow Left | Saturation up / down (mirrored in RTL); focuses the saturation slider |
| Arrow Up / Arrow Down | Brightness up / down; focuses the brightness slider |
| Shift+Arrow | Ten times the step |
| Page Up / Page Down | Focused channel up / down by ten steps |
| Home / End | Focused channel to 0 / 100 |

| Key (ColorSlider) | Action |
| --- | --- |
| Arrow Right / Arrow Up | Increase (in horizontal RTL, Arrow Left increases) |
| Arrow Left / Arrow Down | Decrease |
| Shift+Arrow, Page Up / Page Down | Ten steps |
| Home / End | Minimum / maximum |

| Key (ColorSwatchPicker) | Action |
| --- | --- |
| Tab | Enters and leaves the palette (one tab stop, on the selected swatch) |
| Arrow Left / Arrow Right | Previous / next swatch (mirrored in RTL) |
| Arrow Up / Arrow Down | Same column in the previous / next row (across groups) |
| Home / End | First / last swatch of the row |
| Ctrl+Home / Ctrl+End | First / last swatch |
| Enter / Space | Selects the focused swatch |

| Key (ColorPicker) | Action |
| --- | --- |
| Enter / Space / Alt+Arrow Down on the trigger | Opens the popover |
| Escape | Closes the popover (reverts in confirm mode); in the hex field with `clearable`, clears first |
| Tab | Moves through the panel; leaving the popover closes it |

## Design notes

- the popover content always renders only while open, and its
  code is a lazy chunk loaded on hover, focus or first open, so there is no
  eager-render option.

## API

Every exported symbol and type is listed in the
[`@salmonui/inputs/color-picker` reference](https://salmonui.dev/docs/reference/inputs/color-picker).

| Prop | Type | Default |
| --- | --- | --- |
| `value`, `defaultValue` | `string \| null` | `'#008000ff'` |
| `valueFormat` | `'hex' \| 'hexa' \| 'rgb' \| 'hsl'` | `'hexa'` |
| `onValueChange`, `onValueCommit` | `(value, { source, reason, color }) => void` | |
| `commitBehavior` | `'confirm' \| 'immediate'` | `'confirm'` |
| `mode`, `defaultMode` | `'area' \| 'swatches'` | `'area'` |
| `onModeChange` / `onBeforeModeChange` | `(mode) => void` / `(event) => void` | |
| `showModeSwitch`, `alpha` | `boolean` | `true` |
| `inline`, `clearable` | `boolean` | `false` |
| `colors` | `(string \| { value, label })[] \| { label, colors }[]` | 60-color palette |
| `columns` | `number` | `10` |
| `renderSwatch` | `({ color, value, label, selected, index }) => ReactNode` | |
| `recentColors`, `defaultRecentColors` | `readonly string[]` | not tracked |
| `onRecentColorsChange` | `(colors) => void` | |
| `maxRecentColors` | `number` | `10` |
| `open`, `defaultOpen` | `boolean` | `false` |
| `onOpenChange` / `onBeforeOpenChange` | `(open, { source, reason }) => void` / `(event) => void` | |
| `name`, `form` | `string` | not submitted |
| `disabled`, `required` | `boolean` | `false` |
| `label`, `description`, `errorMessage`, `invalid`, `validation` | see [Field](https://salmonui.dev/docs/inputs/field) | |
| `aria-label` | `string` (trigger and popover name without `label`) | `'Color'` (trigger), `'Color picker'` (popover) |
| `localeText` | `{ trigger, dialog, area, colors, recentColors, noColor, apply, cancel, current, previous, clear, hex, switchToSwatches, switchToArea, saturation, brightness, hue, alpha, colorName, validation* }` | English |
| `size` | `'sm' \| 'md' \| 'lg'` | `'md'` |
| `className`, `style` | root | |
| `ref` | `HTMLElement` (the trigger, or the panel group when `inline`) | |

`ColorArea` and `ColorSlider` take `value`, `defaultValue` (`string |
Color`), `onValueChange`, `onValueCommit`, `name`, `form`, `valueFormat`,
`step`, `disabled`, `localeText`, `aria-label`, `aria-labelledby`, `id`,
`className`, `style` and `ref` (the root); `ColorSlider` adds `channel`
and `orientation`. `ColorField` takes the TextField props plus
`valueFormat`, `showSwatch` and `onValueChange(value, { source, reason,
color })`. `ColorSwatchPicker` takes `colors`, `columns`, `value`,
`defaultValue`, `onValueChange(value, { source, reason, color })`,
`clearable`, `renderSwatch`, `name`, `form`, `disabled`, `localeText` and
`aria-label`. `ColorSwatch` takes `color`, `aria-label` (`''` makes it
decorative) and `colorName`.
