Command palette

@yasinsensoy/web

Web · Components

ColorPicker

Color picker.

35 exports

Live example

Preview

Click the color in the box or type: #f00, rgb(…), hsl(…), oklch(…), red.

Code

import { ColorField } from "@yasinsensoy/web";

<ColorField label="Brand color" name="renk" recent clearable
  defaultValue="#6366f1"
  onValueCommit={save} />

Events

  1. Events appear here when you interact with the preview.

Inline, OKLCH and opacity

Theme colors: a chosen var(--ui-*) changes with the theme

Readable text color (WCAG contrast)

Readable text4.7:1

ColorSwatch: for showing in tables and lists

Import

import {
  ColorField,
  ColorPicker,
  ColorSwatch,
  resolveCssColor,
  COLOR_FORMATS,
  rgbToHsv,
  hsvToRgb,
  rgbToHsl,
  hslToRgb,
  rgbToOklch,
  oklchToRgb,
  keepHue,
  parseColor,
  isColor,
  detectColorFormat,
  formatColor,
  convertColor,
  luminance,
  contrastRatio,
  readableColor,
  THEME_SWATCHES,
  DEFAULT_SWATCHES,
  defaultColorNames,
  enColorNames,
} from "@yasinsensoy/web";

ColorPicker

componentClient component

Color picker. Clicking the color button in the box (or the text field) opens a panel with a saturation/brightness area, hue and alpha sliders, swatches and an eyedropper; a color can also be typed.

  • Formats: the value is returned in the format format (hex, rgb, hsl, oklch). The text field understands any CSS color (#f00, rgb(…), hsl(…), oklch(…), red, var(--ui-primary)); the format button changes the display.
  • Theme: swatches="theme" offers the theme colors; a selected var(--ui-*) value is returned as is, so the color changes with the theme.
  • Keyboard: the area with arrow keys (horizontal saturation, vertical brightness), sliders with ←/→, Home/End; Shift takes 10× steps. ↓ in the box opens the panel.
  • Hue is kept: going down to gray or black doesn't lose the hue; coming back returns to the same hue.
  • Mobile: the panel is a bottom sheet; the page doesn't scroll while dragging with a finger, and vertical scrolling works on the sliders. Closes by pulling down and with the back button.
  • Form: the value is submitted with name; required works and it returns to the initial color when the form resets.

To use it with a label, description and error message see ColorField; to only display a color see ColorSwatch.

ColorPicker(props: ColorPickerProps): JSX.Element

Examples

<ColorPicker name="color" defaultValue="#3b82f6" />

<ColorPicker value={color} onValueChange={setColor} format="oklch" alpha
  swatches="theme" recent />

<ColorPicker inline defaultValue="#22c55e" swatches={["#22c55e", { value: "#0ea5e9", label: "Sky" }]} />

ColorField

componentClient component

ColorPicker with its label, description and error message. Takes all ColorPicker props (format, alpha, swatches, recent, inline…).

  • With required the form can't be submitted without a color; an asterisk appears on the label.
  • Clicking the label focuses the text field.
  • Server errors come from error or from the nearest Form's state by name; they clear when the color changes.
ColorField(input: ColorFieldProps): JSX.Element

Examples

<ColorField label="Brand color" name="brand" defaultValue="#3b82f6" required
  description="Used in buttons and links." />

<ColorField label="Tag color" name="tag" format="oklch" alpha swatches="theme" recent />

ColorSwatch

componentServer component

Shows a color in a small box. Transparent colors are drawn over a checkerboard; an empty value is shown with a "no color" stripe. A server component.

ColorSwatch({ color, size, shape, label, effect, className, style, ...props }: ColorSwatchProps): JSX.Element

Examples

<ColorSwatch color="#3b82f6" />
<ColorSwatch color="var(--ui-primary)" shape="circle" size="lg" label="Primary color" />

Resolves any color text the browser understands: names (rebeccapurple), theme variables (var(--ui-primary)), color-mix(), lab()… Variables are resolved where the scope element is (e.g. inside data-theme). parseColor is tried first; only it works on the server.

resolveCssColor(input: string, scope?: Element | null): Rgba | undefined

Supported formats, in picker order.

COLOR_FORMATS: readonly ColorFormat[]

rgbToHsv

function

RGB → HSV. Grays return hue 0; to keep the hue see keepHue.

rgbToHsv({ r, g, b, a }: Rgba): Hsva

hsvToRgb

function

HSV → RGB (fractional channels; rounded when written).

hsvToRgb({ h, s, v, a }: Hsva): Rgba

rgbToHsl

function

RGB → HSL (h 0–360, s/l 0–1).

rgbToHsl({ r, g, b }: Rgba): {
    h: number

hslToRgb

function

HSL → RGB.

hslToRgb(h: number, s: number, l: number, a?: number): Rgba

rgbToOklch

function

RGB → OKLCH (l 0–1, c ~0–0.4, h 0–360).

rgbToOklch(rgba: Rgba): {
    l: number

oklchToRgb

function

OKLCH → RGB.

oklchToRgb(l: number, c: number, h: number, a?: number): Rgba

keepHue

function

Keeps the hue (and saturation on black) from the previous value when the new HSV value loses it. A picker dragged to gray or black does not jump to red.

keepHue(next: Hsva, previous: Hsva | undefined): Hsva

parseColor

function

Parses a color string. Supported forms: #rgb, #rgba, #rrggbb, #rrggbbaa (with or without #), rgb()/rgba(), hsl()/hsla(), hwb(), oklch(), oklab(), color(srgb …) (comma and space separated, with percentage and angle units) and transparent.

For forms the browser has to resolve, such as names (red) and theme variables (var(--ui-primary)), see resolveCssColor.

parseColor(input: string): Rgba | undefined

Examples

parseColor("#3b82f6");            // { r: 59, g: 130, b: 246, a: 1 }
parseColor("hsl(217 91% 60% / .5)");
parseColor("oklch(0.62 0.19 260)");

isColor

function

Is the string a valid color? See parseColor.

isColor(input: string): boolean

Format the string is written in; undefined when unknown.

detectColorFormat(input: string): ColorFormat | undefined

formatColor

function

Writes a color in the requested format. See ColorFormat.

formatColor(color: Rgba, format?: ColorFormat, options?: FormatColorOptions): string

Examples

formatColor({ r: 59, g: 130, b: 246, a: 1 }, "hex");   // "#3b82f6"
formatColor({ r: 59, g: 130, b: 246, a: 0.5 }, "rgb"); // "rgb(59 130 246 / 0.5)"

convertColor

function

Converts a string to another format; undefined when it cannot be parsed.

convertColor(input: string, format: ColorFormat, options?: FormatColorOptions): string | undefined

Examples

`convertColor("#ff0000", "oklch") // "oklch(0.628 0.258 29.2)"`

luminance

function

WCAG relative luminance (0 black – 1 white).

luminance(color: Rgba): number

WCAG contrast ratio of two colors (1–21). At least 4.5 is recommended for normal text, 3 for large text. 1 when a color cannot be parsed.

contrastRatio(a: string | Rgba, b: string | Rgba): number

Examples

`contrastRatio("#ffffff", "#3b82f6") // 3.68`

A readable text color on a color background: "#000000" or "#ffffff" (whichever has the higher contrast).

readableColor(background: string | Rgba): "#000000" | "#ffffff"

Theme colors: swatches="theme" shows this list. Since the values are var(--ui-*), the selected color is that theme's color in every theme.

THEME_SWATCHES: readonly ColorSwatchOption[]

Default swatches: the 500 shades of the Tailwind palette, white and black. Shown when swatches is omitted.

DEFAULT_SWATCHES: readonly ColorSwatchOption[]

Turkish swatch names.

defaultColorNames: ColorNameMessages

enColorNames

constant

English swatch names.

enColorNames: ColorNameMessages

Rgba

interface

sRGB color: channels 0–255 (may be fractional), alpha 0–1. See parseColor, formatColor.

NameTypeDescription
rnumberRed, 0–255.
gnumberGreen, 0–255.
bnumberBlue, 0–255.
anumberAlpha: 0 fully transparent, 1 fully opaque.

Hsva

interface

HSV (hue, saturation, value) color: the color picker's internal model. h 0–360, s and v 0–1, a 0–1.

NameTypeDescription
hnumberHue, 0–360 degrees.
snumberSaturation, 0–1.
vnumberValue (brightness), 0–1.
anumberAlpha, 0–1.

Format of a color string.

  • "hex": #3b82f6 (with alpha #3b82f680)
  • "rgb": rgb(59 130 246) (with alpha rgb(59 130 246 / 0.5))
  • "hsl": hsl(217 91% 60%)
  • "oklch": oklch(0.623 0.188 259.8): perceptually even steps; the library's themes use this format.
type ColorFormat = "hex" | "rgb" | "hsl" | "oklch"

formatColor options.

NameTypeDefaultDescription
alpha?boolean | "auto""auto"Write the alpha? "auto" writes it only when the color is transparent; false drops the alpha.

Props of the ColorField component.

Extends: Omit<FieldOwnProps, "classNames"> & Omit<Omit<PickerBaseProps, "icon" | "classNames" | "placeholder">, "className" | "classNames">

NameTypeDefaultDescription
value?stringColor in controlled use (any CSS color); "" for no color.
defaultValue?stringInitial color in uncontrolled use.
onValueChange?(value: string) => voidCalled when the color changes; on every step while dragging. The value is in the format format; names and var(--ui-*) theme variables coming from a swatch or typing are returned as is.
onValueCommit?(value: string) => voidCalled when a selection completes: when a drag ends, on a key press, when a swatch or the eyedropper is used, and when typed color is confirmed. Use this to save to the server.
format?ColorFormat"hex"Format of the returned value. See ColorFormat. Even if the user sees another format in the text field, the value is returned in this format.
alpha?booleanfalseShow an alpha slider and include alpha in the value?
formats?readonly ColorFormat[]["hex", "rgb", "hsl", "oklch"]Formats the format button in the text field cycles through. With a single format the button is hidden.
swatches?readonly (string | ColorSwatchOption)[] | "theme" | falseSwatches. An array of strings or { value, label }; "theme" shows the theme colors (THEME_SWATCHES, var(--ui-*)); false hides them. Defaults to DEFAULT_SWATCHES.
recent?boolean | stringfalseRemember recently chosen colors (at most 8, stored in the browser). true uses a list shared by all pickers; a string keeps a separate list under that key (e.g. "brand-colors").
eyeDropper?booleantruePick color from screen (eyedropper) button. Only visible in supporting browsers (Chromium desktop).
inline?booleanfalseShow the picker inline on the page instead of a dropdown (panel always open). For settings pages and side panels.
placeholder?stringText shown in the text field while empty. Defaults to a format example like #000000.
classNames?FieldClassNames & ColorPickerClassNamesClasses added to the inner parts; control goes to the picker's container.

Classes that can be given to the inner parts of ColorPicker.

NameTypeDescription
box?stringThe field's visible box (color button and text field).
input?stringText field in the box or the panel.
content?stringThe open panel (popover / mobile bottom sheet).
panel?stringThe picker itself (area, sliders, swatches).
area?stringSaturation/brightness area (e.g. h-56 for height).
swatches?stringGrid of swatches.

Props of the ColorPicker component.

Extends: Omit<PickerBaseProps, "icon" | "classNames" | "placeholder">

NameTypeDefaultDescription
value?stringColor in controlled use (any CSS color); "" for no color.
defaultValue?stringInitial color in uncontrolled use.
onValueChange?(value: string) => voidCalled when the color changes; on every step while dragging. The value is in the format format; names and var(--ui-*) theme variables coming from a swatch or typing are returned as is.
onValueCommit?(value: string) => voidCalled when a selection completes: when a drag ends, on a key press, when a swatch or the eyedropper is used, and when typed color is confirmed. Use this to save to the server.
format?ColorFormat"hex"Format of the returned value. See ColorFormat. Even if the user sees another format in the text field, the value is returned in this format.
alpha?booleanfalseShow an alpha slider and include alpha in the value?
formats?readonly ColorFormat[]["hex", "rgb", "hsl", "oklch"]Formats the format button in the text field cycles through. With a single format the button is hidden.
swatches?readonly (string | ColorSwatchOption)[] | "theme" | falseSwatches. An array of strings or { value, label }; "theme" shows the theme colors (THEME_SWATCHES, var(--ui-*)); false hides them. Defaults to DEFAULT_SWATCHES.
recent?boolean | stringfalseRemember recently chosen colors (at most 8, stored in the browser). true uses a list shared by all pickers; a string keeps a separate list under that key (e.g. "brand-colors").
eyeDropper?booleantruePick color from screen (eyedropper) button. Only visible in supporting browsers (Chromium desktop).
inline?booleanfalseShow the picker inline on the page instead of a dropdown (panel always open). For settings pages and side panels.
placeholder?stringText shown in the text field while empty. Defaults to a format example like #000000.
classNames?ColorPickerClassNamesClasses added to the inner parts.

A color in a swatch list.

NameTypeDescription
valuestringCSS color text: #3b82f6, oklch(0.62 0.19 260), rebeccapurple or a theme variable var(--ui-primary). Returned as is on click; theme variables follow the new color when the theme changes.
label?stringScreen reader and tooltip name. Defaults to name's translation, then value.
name?ColorNameA built-in color name; its text comes from the dictionary's ui.colorNames (used by THEME_SWATCHES and DEFAULT_SWATCHES).

Props of the ColorSwatch component.

Extends: Omit<ComponentProps<"span">, "color">

NameTypeDefaultDescription
colorstring | undefinedCSS color to show (any format and var(--ui-*)). When empty, a cross-striped "no color" box is drawn.
size?"sm" | "md" | "lg""md"` (20 px)Size.
shape?"rounded" | "circle" | "square""rounded"Corner shape.
label?stringScreen reader name. When omitted it is treated as decorative (aria-hidden); no name is needed when the color's name is written next to it.
effect?EffectPropEffect or effects of the box (e.g. "shine", "lift"). Defaults to UIProvider appearance.defaults.colorSwatch.effect. See BuiltinEffect.

Names of the built-in ColorPicker swatches: screen reader names and tooltips.

NameTypeDefaultDescription
primarystring"Birincil"
secondarystring"İkincil"
accentstring"Vurgu"
successstring"Başarı"
warningstring"Uyarı"
destructivestring"Tehlike"
foregroundstring"Ön plan"
mutedForegroundstring"Soluk yazı"
borderstring"Kenarlık"
backgroundstring"Arka plan"
redstring"Kırmızı"
orangestring"Turuncu"
amberstring"Kehribar"
yellowstring"Sarı"
limestring"Limon"
greenstring"Yeşil"
tealstring"Deniz yeşili"
cyanstring"Camgöbeği"
bluestring"Mavi"
indigostring"Çivit"
violetstring"Mor"
fuchsiastring"Fuşya"
pinkstring"Pembe"
stonestring"Taş"
whitestring"Beyaz"
blackstring"Siyah"

Key of a built-in swatch name.

type ColorName = keyof ColorNameMessages