UI

Color

A swatch button that expands into a color picker with 2D saturation-brightness, hue and opacity sliders, format morphing, WCAG contrast grading, eyedropper, and saved swatches.

import { ColorInput } from '@uthereal/ui/color-input'

Color input playground

Loading interactive preview…

Overview

ColorInput renders a pill swatch button showing a color chip, field label, and canonical hex value. Activating the button grows it into a floating picker panel with a 2D saturation-brightness area, hue and opacity sliders, a multi-format text input (hex, rgb(), hsl(), oklch()), a live WCAG contrast readout, an optional screen eyedropper, and reorderable saved swatches.

The component always emits canonical uppercase hex (#RRGGBB, or #RRGGBBAA when alpha is enabled and the color is translucent). Your application owns the value and saved swatches; ColorInput validates typed drafts inline and never opens browser validation bubbles.

CapabilityBehavior
Output valueCanonical hex (#2F6BFF, or #2F6BFF80 with alpha); hidden <input type="hidden"> when name is set
Text formatsCycles Hex, RGB, HSL, and OKLCH via defaultFormat and the format button; parses all four
Contrast gradingComposites the color over background: AAA (>= 7:1), AA (>= 4.5:1), AA large (>= 3:1), Fails (< 3:1)
Screen eyedropperShown when eyeDropper is true and the browser supports window.EyeDropper (Chromium); keeps alpha
Saved swatchesUp to maxSwatches (default 7, schema max 24); + saves, drag or Alt+arrows reorders, Delete removes

Use ColorInput for brand colors, theme tokens, chart palettes, and tag colors. Use Text when users enter arbitrary CSS tokens or design-system variable names instead of color values.

Usage

'use client'
import { useState } from 'react'
import { ColorInput, type ColorSwatch } from '@uthereal/ui/color-input'

export function BrandColor() {
  const [color, setColor] = useState('#2F6BFF')
  const [swatches, setSwatches] = useState<ColorSwatch[]>([
    { value: '#2F6BFF', label: 'Brand blue' },
    { value: '#0D9488', label: 'Teal' },
  ])

  return (
    <ColorInput
      label="Brand color"
      name="brand_color"
      value={color}
      onValueChange={setColor}
      swatches={swatches}
      onSwatchesChange={setSwatches}
    />
  )
}

Omit value for an uncontrolled field initialized from defaultValue. onValueChange fires on every change including pointer drags; use onValueCommit to capture settled values on drag end, key release, swatch selection, eyedropper pick, or text commit.

Examples

Opacity and contrast grading

Set background to the hex surface the color will sit on. Translucent colors composite over background before computing the ratio and WCAG grade. Set alpha={false} to hide the opacity slider and keep all values opaque #RRGGBB, and set defaultFormat to start the text field in rgb, hsl, or oklch while keeping hex output.

Translucent accent composited over #18181B.
Opacity slider hidden; edits in OKLCH while emitting opaque #RRGGBB.

Saved swatches

Pass swatches to seed a horizontal palette below the contrast readout. Pressing + saves the active color to the front (deduplicating existing values and dropping the oldest beyond maxSwatches). Users can apply any swatch, reorder swatches by dragging or pressing Alt with left/right arrows, and remove focused swatches with Delete or Backspace.

Capped at 4 swatches; saving a fifth drops the oldest.

API reference

These serializable arguments and defaults come directly from the component schema.

ArgumentType / defaultDescription
labelstringDefault: "Color"Visible label and accessible name. Name the information asked for, in sentence case.
hideLabelbooleanDefault: trueHide the label above the swatch button (the default, as in Arc: the button shows the label beside the color). It is still announced.
descriptionstring—Supporting text below the field, announced with it. Use it for format hints and constraints.
errorstring—Validation message from your application. Setting it marks the field invalid; the message is linked to the field and announced politely.
requiredbooleanDefault: falseMarks the field as required for assistive technology and shows an indicator. Your application validates the value.
readOnlybooleanDefault: falseThe picker opens and shows the color, but nothing changes it. It is still submitted with a form.
disabledbooleanDefault: falseUnavailable and removed from the tab order. A disabled field is not submitted with a form.
namestring—Native form field name, submitted with the value in a form.
defaultValuestringDefault: "#2F6BFF"Initial color as hex, e.g. "#2F6BFF" (or "#2F6BFF80" with alpha). Later argument edits do not reset an existing instance; use value and onValueChange to control it.
defaultFormathex | rgb | hsl | oklchDefault: "hex"Initial format of the color text in the picker: hex, rgb(), hsl() or oklch(). The format button cycles through them; the value is always hex.
alphabooleanDefault: trueShow the opacity slider (the default, as in Arc) and keep translucent colors (#RRGGBBAA). Turn it off to keep every color opaque.
swatchesColorSwatch[]Default: []Saved colors below the picker, each a hex value with an optional name for its button. People add the current color with +, drag or Alt+arrow to reorder, and Delete to remove; onSwatchesChange reports the list, which is host state.
maxSwatchesintegerDefault: 7Most saved swatches. Saving past it drops the oldest.
backgroundstringDefault: "#FFFFFF"The background the color will sit on, as hex. The contrast readout grades the color against it (AAA, AA, AA large, or fails).
eyeDropperbooleanDefault: trueShow the eyedropper, which picks a color from anywhere on the screen, in browsers that support it (Chromium). Elsewhere it is not shown.
variantoutline | soft | ghostDefault: "outline"Field surface: outline for forms, soft on busy surfaces, ghost for inline editing without a border.
sizesm | md | lgDefault: "md"Field height and text size: 32, 36, or 46 pixels. Matches the button and dropdown trigger of the same size.
labelsColorInputLabels—Accessible names, announcements and messages of the picker: the panel, area and sliders with their values, eyedropper, Done, format button, color text, invalid message, contrast readout and grades, and saved swatches. Templates fill {label}, {format}, {color}, {ratio} and {grade}. Translate them with the rest of your interface.
recipestudio | softDefault: "studio"Visual treatment. Both recipes use the same interaction behavior.
themeColorInputTheme—Color mode, accent, and semantic tokens. See Theming for all keys and defaults.
motionnone | subtle | expressiveDefault: "subtle"The panel growing out of the swatch, thumbs chasing the pointer, the format text morph and the grade swap. none makes them immediate; system reduced motion keeps a short fade.
motionOptionsColorInputMotionOptions—Springs or tweens for the panel opening (open), closing (close) and the thumbs following a press or key (thumb). Durations are milliseconds.
dirltr | rtl—Reading direction. Omit it to inherit the page direction.

React integration

PropPurpose
value, onValueChangeControlled hex color (#RRGGBB or #RRGGBBAA). onValueChange fires in both modes, including drags.
onValueCommit(value)Settled hex color on drag release, key release, swatch selection, eyedropper pick, or committed text draft.
onSwatchesChange(swatches)Updated swatch list after add, reorder, or removal. Pass back as swatches to persist host state.
open, onOpenChangeControlled panel visibility and toggle callback.
refRef to the swatch trigger <button>.
portalContainerCustom portal target for the floating panel (such as a native <dialog> top layer).
presetApplication defaults (such as background, alpha, and translated labels), overridden by props.
tokensCSS custom properties (--ui-*) applied after the typed theme on both the field root and portalled panel.
renderIcon(name, context)Custom icon renderer; context provides size (18) and slot ('eyeDropper', 'done', or 'add').
className, styleApplied to the root field element, which carries the resolved --ui-* tokens.
Native attributesForwarded to the swatch trigger <button> (onFocus, onBlur, onKeyDown, aria-*).

Keyboard & accessibility

KeyInteraction
Enter, SpaceOn trigger: open or close the picker panel. On format/add/swatch/Done buttons: activate control.
Tab, Shift+TabMoves from the trigger into the open panel, across its controls, and back out past the trigger.
Arrow keysOn 2D area: saturation (horizontal) and brightness (vertical) by 1%. On sliders: 1 unit.
Shift + arrow keysMoves the 2D area or focused slider by 10 steps.
PageUp, PageDownSteps saturation on the 2D area or the value on a slider by 10 units.
Home, EndOn a slider: jump to 0 or maximum (360 or 100). On swatches: focus first or last swatch.
ArrowLeft, ArrowRightOn swatches: move focus across saved colors; hold Alt to reorder the focused swatch.
Delete, BackspaceOn a saved swatch: remove it and move focus to the neighbor (or the color text input if empty).
Enter (text input)Parses and commits hex, rgb(), hsl(), or oklch(); invalid drafts trigger an error message.
EscapeCancels an uncommitted text draft first; otherwise closes the panel and returns focus to button.

The trigger button is labelled by label and its current hex readout, sets aria-haspopup="dialog", aria-expanded, and aria-controls, and links description and error through aria-describedby. The panel renders as a non-modal role="dialog" named by labels.dialog. The 2D area exposes role="slider" with aria-roledescription="2D slider" and combined saturation/brightness aria-valuetext; hue and opacity sliders expose role="slider" with degree and percentage aria-valuetext.

Typed parse errors announce through an aria-live="polite" region linked via aria-describedby. The contrast readout pairs its visual sample and ratio with a visually hidden summary (labels.contrastPass or labels.contrastFail). Saved swatches use role="listbox" with aria-orientation="horizontal", role="option", aria-selected, and roving tabIndex. In dir="rtl", panel clip expansion, gradients, thumbs, pointer coordinates, arrow keys, and swatch order mirror from the inline start. forced-colors: active preserves system borders, focus outlines (including focused swatches), disabled colors, and current-swatch rings.

Motion and theming

  • Panel expansion: a clip-path grows the panel out of the swatch button on motionOptions.open (0.42s, bounce 0.1) and collapses back on motionOptions.close (0.3s, bounce 0) while the drop shadow follows the clipped boundary and body content fades in across 10px.
  • Thumbs and ratio: click and keyboard jumps spring on motionOptions.thumb (0.26s, bounce 0.22) while pointer drags track on a stiff 0.1s spring; active thumbs scale to 1.2 on Arc's CSS spring curve, and the contrast ratio rolls to match.
  • Format morph and feedback: cycling formats morphs shared characters over 620ms through a trailing soft mask while the frame width follows the morph spring; contrast grade changes blur-swap, saved swatches spring in/out and glide during reorder, and invalid drafts shake horizontally (320ms).
  • Reduced motion: prefers-reduced-motion: reduce disables clip expansion, thumb springs, character morphing, blur, shakes, and press scales, keeping a 160ms panel opacity fade and 120ms grade crossfade. motion="none" makes all updates immediate (0ms).

theme accepts the core and control token groups, plus borderStrong, popupRadius, shadowResting, success, and warning. An optional UtherealProvider supplies application-wide defaults.

Composition

ColorInput is a leaf component. Its hex color is host state at /fields/instance-<id>/value (initialized from defaultValue), and its saved swatches are host state at /fields/instance-<id>/swatches. Stored values and swatches survive configuration edits while they remain valid for alpha and maxSwatches. See Building with agents.

{
  "type": "ColorInput",
  "props": {
    "label": "Accent color",
    "defaultValue": "#2F6BFF",
    "background": "#FFFFFF",
    "swatches": [
      { "value": "#2F6BFF", "label": "Blue" },
      { "value": "#0D9488", "label": "Teal" }
    ]
  },
  "children": []
}

On this page