ColorPicker

A field for picking a color as #rrggbb, with hue / saturation / lightness sliders and swatches.

Import

ts
import { ColorPicker } from '@k8ordo/ui';

Usage

The value travels in a text field that carries name. A color picked with the sliders or a swatch is written into it and announced with an input event, just as if it had been typed. While typing, the text counts as a color only once it has six digits; on blur and on Enter it is tidied to lowercase #rrggbb (a three-digit #f80 is expanded there).

tsx
<ColorPicker aria-label="Accent color" defaultValue="#0d9488" name="accent" />

Swatches

Each swatch is a toggle button named by its label; the one matching the current color is pressed.

tsx
const swatches = [
  { value: '#0d9488', label: 'Teal' },
  { value: '#2563eb', label: 'Blue' },
  { value: '#f97316', label: 'Orange' },
  { value: '#e11d48', label: 'Rose' },
  { value: '#171717', label: 'Black' },
];

<ColorPicker
  aria-label="Accent color"
  defaultValue="#f97316"
  swatches={swatches}
/>

Controlled

onChange receives #rrggbb, or '' when the field is emptied.

value: #2563eb

tsx
const [color, setColor] = useState('#2563eb');

<ColorPicker
  aria-label="Accent color"
  onChange={setColor}
  swatches={swatches}
  value={color}
/>

Disabled

tsx
<ColorPicker aria-label="Accent color" defaultValue="#0d9488" disabled />

With @k8ordo/form

Spread the input that formFields derives as is. A .regex() in the schema arrives as pattern and replaces the built-in #[0-9a-fA-F]{6}. A change made with the sliders or a swatch reaches the form just as typing does (dirty state, rules, clearing an error, reset).

tsx
// schema.ts
export const themeSchema = z.object({
  accent: z.string().regex(/^#[0-9a-f]{6}$/),
});

// theme-form.tsx
const accent = form.field('accent');

<FormControl
  errorText={accent.error}
  invalid={accent.invalid}
  label="Accent color"
  required={accent.required}
  renderInput={(props) => <ColorPicker {...props} {...accent.input} />}
/>

Props

defaultValue?
Type: string
Default: -
invalid?
Type: boolean
Default: false
onChange?
Type: (value: string) => void
Default: -
ref?
Type: Ref<HTMLInputElement>
Default: -
swatches?
Type: readonly ColorPickerSwatch[]
Default: -
type?
Type: string
Default: -
value?
Type: string
Default: -

Type base (some attrs are managed internally): InputHTMLAttributes<HTMLInputElement>

Wording this component renders (labels, placeholders, and the like) comes from the message dictionary when no prop sets it. To change it, see: i18n