API
@pbroom/color-kit/driver
Headless picker state: color state, area and slider coordinate mapping, input parsing.
145 exports75 values70 types
@pbroom/color-kit/driver is the logic of a color picker without a view. It holds
picker state as plain data, maps pointer and keyboard input to colors, and
produces the strings a view paints. @pbroom/color-kit/react is built on it; a Vue,
Svelte or web-component binding can be too.
Domains
- State.
createColorStatekeeps the requested color apart from its sRGB and Display P3 mappings. Reducers such assetColorRequestedreturn the same object for a no-op. The multi-color reducers (createMultiColorModeland friends) manage named palettes. - Area and slider geometry. Pointer normalization, position-to-color and
color-to-thumb mappings for 2D areas and 1D sliders, plus area overlays
(
getColorAreaGamutBoundaryPoints,getColorAreaContrastRegionPaths). - Keyboard and ARIA. Arrow, Page and Home/End models, and
aria-valuetextstrings. - Drag.
createPointerDragControllercoalesces pointer moves to one commit per frame. - Painting and text. Slider gradients, swatch styles with an sRGB fallback, and parsing and formatting for channel and string inputs.
import { parse, toCss } from '@pbroom/color-kit';
import {
createColorState,
getColorAreaThumbPosition,
getColorAreaValueText,
resolveColorAreaAxes,
} from '@pbroom/color-kit/driver';
const state = createColorState(parse('oklch(0.7 0.25 150)'));
state.meta.outOfGamut; // → { srgb: true, p3: false }
toCss(state.displayed.srgb, 'hex'); // → '#00be58'
const axes = resolveColorAreaAxes(); // x: lightness, y: chroma
getColorAreaThumbPosition(state.requested, axes); // → { x: 0.7, y: 0.375 }
getColorAreaValueText(state.requested, axes); // → 'Lightness 70%, Chroma 0.25'The guide A headless color picker builds a full picker from these pieces.
Color area
- function
areColorAreaAxesDistinctWhether the x and y axes drive different channels. - const
COLOR_AREA_DEFAULT_RANGESDefault [start, end] range per color-area channel: l [0, 1], c [0, 0.4], h [0, 360]. start sits at the left/bottom edge. - function
getColorAreaFallbackPointMaps query.color into the requested gamut and returns its thumb position, e.g. to show where an out-of-gamut selection will actually render. - function
colorFromColorAreaKeyKeyboard model for a 2D color-area thumb: - function
getColorAreaKeyAxisAxis a color-area key acts on, or null when the key is not handled: ArrowLeft/ArrowRight/Home/End act on x, ArrowUp/ArrowDown/PageUp/PageDown on y. - function
getColorAreaValueTextHuman-readable aria-valuetext for both axes, x first, e.g. "Lightness 60%, Chroma 0.2". - function
colorFromColorAreaPositionReturns a copy of color with both axis channels set from a normalized area position (x right, y down, as from normalizeColorAreaPointer). - function
getColorAreaChromaBandPointsSamples the tonal strip at reference.c across lightness for hue degrees, kept inside the gamut (see mode), as area points ordered from l = 0 to l = 1 (y down). - function
getColorAreaContrastRegionPathsOutlines the region of the hue plane whose colors meet the contrast threshold against reference (WCAG AA 4.5:1 by default), as one or more paths of area points (y down). - function
getColorAreaGamutBoundaryPointsTraces the gamut boundary (max in-gamut chroma per lightness) at hue degrees as area points, ordered from l = 0 to l = 1. - function
getColorAreaThumbPositionNormalized thumb position of color in the area: x runs left to right and y top to bottom, so a y-axis value at its range end sits at y = 0. - function
normalizeColorAreaPointerNormalizes a pointer position against the area's client rect into clamped [0, 1] coordinates (x right, y down). - function
resolveColorAreaAxesFills in missing axis ranges from COLOR_AREA_DEFAULT_RANGES. - function
resolveColorAreaRangeReturns range when given, otherwise the channel's entry in COLOR_AREA_DEFAULT_RANGES. - function
toColorAreaPlaneDefinitionBuilds the plain plane definition for a color area's axes and reference color. - interface
ColorAreaAxesAxis configuration for a color area. - interface
ColorAreaAxisOne axis of a color area as authored: a channel and an optional range. - interface
ColorAreaPlaneDefinitionPlain, serializable OKLCH plane description of a color area; see toColorAreaPlaneDefinition. - interface
ColorAreaChromaBandOptionsOptions for getColorAreaChromaBandPoints. - type
ColorAreaChannelOKLCH channel a color-area axis can drive: lightness l (0..1), chroma c (0..~0.4) or hue h (degrees). - type
ColorAreaContrastRegionOptionsContrast-region options for a color area: the core ContrastRegionPathOptions. - interface
ColorAreaContrastRegionPointA contrast-region path point in OKLCH l/c plus its normalized area position (x right, y down, both [0, 1]). - interface
ColorAreaFallbackPointResult of getColorAreaFallbackPoint. - interface
ColorAreaGamutBoundaryOptionsOptions for getColorAreaGamutBoundaryPoints. - interface
ColorAreaGamutBoundaryPointA boundary or band point in OKLCH l/c plus its normalized area position (x right, y down, both [0, 1]). - type
ColorAreaKeyKeyboard keys handled by colorFromColorAreaKey. - interface
ColorAreaKeyOptionsOptions for colorFromColorAreaKey. - interface
ColorAreaPointerRectClient-space bounds of a color area, e.g. from getBoundingClientRect(). - interface
ResolvedColorAreaAxesColorAreaAxes with both ranges filled in; see resolveColorAreaAxes. - interface
ResolvedColorAreaAxisA ColorAreaAxis with its range filled in.
Drag controller
- function
createDefaultFrameSchedulerCreates the default DragFrameScheduler: requestAnimationFrame with a 16 ms setTimeout fallback, and performance.now() with a Date.now() fallback. - function
createPointerDragControllerCreates a framework-agnostic pointer drag controller. start() and end() commit immediately; move() inputs are coalesced to at most one commit per frame, skipped when within dragEpsilon of the current point, and capped at maxUpdateHz (a rate-limited point is retried next frame, never dropped). normalize maps raw input to a point; inputs it rejects are ignored. - const
DEFAULT_DRAG_EPSILONDefault normalized movement below which a drag move is skipped (0.0005). - const
DEFAULT_MAX_UPDATE_HZDefault cap on drag commits per second (60). - function
resolveDragEpsilonReturns value when it is a finite number of at least 0, otherwise DEFAULT_DRAG_EPSILON. - function
resolveMaxUpdateHzReturns value when it is a finite number above 0, otherwise DEFAULT_MAX_UPDATE_HZ. - interface
DragCommitInfoMetadata passed with each commit of a PointerDragController. - interface
DragFrameSchedulerFrame scheduling and clock used by a PointerDragController; inject a manual one to drive drags deterministically in tests. - interface
DragPointA normalized drag position, typically [0, 1] on each axis. - interface
PointerDragControllerDrag session handle returned by createPointerDragController. - interface
PointerDragControllerConfigConfiguration for createPointerDragController.
Color slider
- const
COLOR_SLIDER_DEFAULT_RANGESDefault [start, end] range per slider channel: l [0, 1], c [0, 0.4], h [0, 360], alpha [0, 1]. - function
colorFromColorSliderKeyKeyboard model for a 1D color slider: - function
colorFromColorSliderPositionReturns a copy of color with channel set from a normalized track position (clamped to [0, 1]; 0 = range start). - function
getColorSliderLabelDefault accessible label for a slider channel: 'Lightness', 'Chroma', 'Hue' or 'Opacity'. - function
getColorSliderValueTextHuman-readable aria-valuetext for a slider value, e.g. "Hue 213°", "Lightness 60%", "Opacity 50%", "Chroma 0.2". - function
getColorSliderNormFromValueNormalizes value into range as a clamped [0, 1] position. - function
getColorSliderThumbPositionNormalized thumb position ([0, 1], clamped) of color[channel] within range; 0 is the range start. - function
normalizeColorSliderPointerConverts a pointer coordinate into a clamped [0, 1] track position. - function
resolveColorSliderRangeReturns range when given, otherwise the channel's entry in COLOR_SLIDER_DEFAULT_RANGES. - function
resolveColorSliderWrapWhether keyboard steps wrap for a channel: wrap when given, otherwise true for hue only. - type
ColorSliderChannelColor channel a slider drives: OKLCH lightness l (0..1), chroma c (0..~0.4), hue h (degrees) or alpha (0..1). - type
ColorSliderKeyKeyboard keys handled by colorFromColorSliderKey. - interface
ColorSliderKeyOptionsOptions for colorFromColorSliderKey. - type
ColorSliderOrientationSlider track direction.
Slider gradient
- function
getSliderGradientStylesSamples a slider gradient (see sampleSliderGradient) and formats it as CSS linear-gradient() strings. - function
sampleSliderGradientSamples steps + 1 evenly spaced stops across range for one channel of a color model, for painting a slider track. - type
SliderHueGradientModeHow a hue-channel gradient is colored. 'static' draws a fixed full-saturation hue ramp that ignores the base color's other channels; 'selected-color' varies only the hue of the base color. - type
SliderColorModelColor model whose channel a slider gradient varies. - type
SliderColorSpaceTarget color space for gradient stops: 'display-p3' emits color(display-p3 …) stops, 'srgb' emits rgb(…) stops. - interface
SliderGradientStopOne sampled gradient stop; see sampleSliderGradient. - interface
SliderGradientStylesCSS-ready gradient output of getSliderGradientStyles. - type
SliderModelChannelAny channel of any SliderColorModel. - type
SampleSliderGradientOptionsOptions for sampleSliderGradient and getSliderGradientStyles, discriminated by model: channel must be a channel of that model, and range is in that channel's units. - type
OklchSliderModelChannelOKLCH channels: l 0..1, c 0..~0.4, h degrees, alpha 0..1. - type
HslSliderModelChannelHSL channels: h degrees, s and l 0..100, alpha 0..1. - type
HsvSliderModelChannelHSV channels: h degrees, s and v 0..100, alpha 0..1. - type
RgbSliderModelChannelRGB channels: r, g, b 0..255, alpha 0..1. - type
HctSliderModelChannelHCT channels: only hue h (degrees) is supported.
Color input
- const
COLOR_INPUT_DEFAULT_RANGESDefault [min, max] range of every channel input, keyed by model then channel: OKLCH l [0, 1], c [0, 0.4], h [0, 360]; RGB r/g/b [0, 255]; HSL h [0, 360], s/l [0, 100]; alpha [0, 1] in every model. resolveColorInputRange reads it. - function
colorFromColorInputChannelValueReturns color with one channel of model set to value. - function
colorFromColorInputKeyApplies a keyboard step to one channel of color. - function
formatColorInputChannelValueFormats a channel value for display: rounds to precision decimals (itself rounded and clamped to 0-6) and drops trailing zeros. -0 and non-finite values format as '0'. - function
getColorInputChangedChannelMaps an input's channel to the OKLCH ColorChannel reported as changedChannel in ColorUpdateEvent. - function
getColorInputChannelGlyphReturns the one-character glyph for a channel input's leading scrub handle: the uppercase channel letter, or 'α' for alpha. - function
getColorInputChannelValueReads one channel of color in model. - function
getColorInputLabelReturns the English accessible label for a channel input, e.g. 'OKLCH lightness', 'Red' or 'Opacity'. - function
getColorInputPrecisionFromStepNumber of decimal places needed to show values on a step grid: the count of decimals in |step|, capped at 6 (the most formatColorInputChannelValue shows), so steps finer than 1e-6, including exponent-notation steps such as 1e-9, return 6. - function
normalizeColorInputValueWraps value into range when wrap is true, otherwise clamps it. - function
parseColorInputExpressionParses text typed into a channel input into a number in channel units. - function
resolveColorInputDraftValueParses a typed draft with parseColorInputExpression, then wraps or clamps the result into options.range (see normalizeColorInputValue). - function
resolveColorInputRangeReturns range when given, otherwise the channel's default from COLOR_INPUT_DEFAULT_RANGES. - function
resolveColorInputStepsResolves the step sizes for a channel input: each option that is a finite positive number wins, anything else falls back to the channel default. - function
resolveColorInputWrapReturns wrap when given, otherwise whether the channel is a hue (OKLCH or HSL h), which wraps around its range instead of clamping. - type
ColorInputModelColor model a numeric channel input edits: OKLCH (l 0-1, c 0-0.4, h degrees), RGB (r/g/b 0-255) or HSL (h degrees, s/l 0-100). - type
ColorInputChannelAny channel of any ColorInputModel. - type
ColorInputChannelForChannels valid for Model, so ('rgb', 'h') fails to type-check. - interface
ColorInputPrimitiveExpressionOptionsOptions shape shared with primitive input expression parsers (structurally compatible with control-kit's PrimitiveExpressionParser callback). - type
ColorInputSpecA valid model/channel pair, e.g. { model: 'hsl', channel: 's' }. - type
OklchColorInputChannelChannels of the 'oklch' input model. - type
RgbColorInputChannelChannels of the 'rgb' input model. - type
HslColorInputChannelChannels of the 'hsl' input model. - type
ColorInputKeyKeyboard keys colorFromColorInputKey steps on: arrows by step, Page Up/Down by pageStep, Home/End to the range ends. - interface
ColorInputStepConfigResolved step sizes for one channel input, in channel units. - interface
ResolveColorInputStepsOptionsStep overrides for resolveColorInputSteps. - interface
ParseColorInputExpressionOptionsOptions for parseColorInputExpression. - interface
ResolveColorInputDraftValueOptionsOptions for resolveColorInputDraftValue.
Color string input
- function
formatColorStringInputValueFormats a color for a text input. 'hex' first gamut-maps into sRGB (chroma reduction), so an out-of-gamut color shows its mapped hex; 'rgb', 'hsl' and 'oklch' go through toCss without mapping (CSS rgb() clips each channel). - function
hasExplicitOklchHueTrue when input is an oklch() string whose hue component is stated (anything but none), i.e. the parsed color carries an OKLCH hue of its own. - function
isColorStringInputValueValidWhether value parses as a color (see parseColorStringInputValue). - function
parseColorStringInputValueParses any CSS color string parse accepts, returning null instead of throwing when it does not parse. - type
ColorStringInputFormatText format a color string input displays.
Color state
- function
getColorDisplayHexFormats a color as sRGB hex (#rrggbb, or #rrggbbaa when alpha < 1). - function
getColorDisplayStylesBuilds swatch styles for the active gamut. - function
colorsEqualChannel-wise equality on OKLCH colors: true when l, c, h and alpha each differ by at most epsilon (default 0, exact). - function
createColorStateCreates a ColorState from a requested OKLCH color: copies requested as is (no clamping) and derives the displayed sRGB and P3 colors and out-of-gamut flags with mapDisplayedColors. - function
getActiveDisplayedColorReturns the displayed color for the state's active gamut: displayed.p3 for 'display-p3', otherwise displayed.srgb. - function
mapDisplayedColorsMaps a requested color into both display gamuts and reports whether it was outside each one. - function
resolveColorSourceResolves the state source for an interaction. - function
resolveIncomingRequestedResolves a new requested color against the previous one so an achromatic input does not discard the hue. - function
setColorActiveGamutSwitches the active display gamut without touching requested/displayed values. - function
setColorActiveViewSwitches the active view model without touching requested/displayed values. - function
setColorChannelSets one requested channel. - function
setColorRequestedReplaces the requested color, re-deriving displayed colors and gamut flags while keeping the active gamut/view and gamut mapping method (state.meta.gamutMapMethod, unless options.gamutMapMethod overrides it). - interface
ColorDisplayStylesInline style pair for a color swatch. - type
ColorChannelOKLCH channel of a requested color. - type
ColorInteractionInput mechanism behind an update, reported on ColorUpdateEvent. - type
ColorSourceWho caused a state change: 'user' (direct interaction), 'programmatic' (set by code, e.g. a controlled prop) or 'derived' (computed from another change). - interface
ColorStateSingle-color picker state. requested is the OKLCH color the user or code asked for, kept unclamped even when it lies outside every display gamut so that later edits do not drift. displayed holds that color gamut-mapped into sRGB and Display P3, which is what should be painted; activeGamut picks which of the two the UI shows (see getActiveDisplayedColor). - interface
ColorUpdateEventChange notification a single-color picker emits with its next state. - interface
CreateColorStateOptionsOptions for createColorState. - type
GamutTargetDisplay gamut a color state renders in. - interface
MapDisplayedColorsOptionsOptions for mapDisplayedColors and the requested-color setters. - interface
ResolveIncomingRequestedOptionsOptions for resolveIncomingRequested. - interface
SetColorRequestedOptionsOptions for setColorRequested. - type
ViewModelColor model a picker shows its channels or text in.
Multi color
- function
addMultiColorEntryAppends an entry (string colors are parsed). - function
createMultiColorModelCreates a normalized multi-color model. - function
materializeMultiColorStateExpands a model into a MultiColorState: one full ColorState per entry (with displayed colors and gamut flags), all sharing the model's active gamut and view. - function
multiColorModelFromStateConverts a materialized MultiColorState back into a model, the inverse of materializeMultiColorState. - function
removeMultiColorEntryRemoves an entry. - function
renameMultiColorEntryRenames an entry in place, keeping its position, color and selection, and sets its source. - function
selectMultiColorEntrySelects an entry. - function
setMultiColorActiveGamutSwitches the shared display gamut and sets every entry's source to source. - function
setMultiColorActiveViewSwitches the shared view model and sets every entry's source to source. - function
setMultiColorChannelSets one OKLCH channel of an entry's requested color (unclamped) and its source. - function
setMultiColorRequestedReplaces an entry's requested color. - interface
CreateMultiColorModelOptionsOptions for createMultiColorModel. - interface
MultiColorEntryInputOne initial entry of a multi-color model. - interface
MultiColorEntryModelStored data of one multi-color entry. - type
MultiColorInputInitial colors of a multi-color model: an { id: color } record (in key order) or an ordered array of entries. - interface
MultiColorModelNormalized multi-color model: requested colors plus one shared display context. - interface
MultiColorStateMaterialized multi-color state: every entry expanded to a full ColorState that shares one display context (activeGamut/activeView). - interface
MultiColorUpdateEventChange notification a multi-color picker emits with its next state. - interface
SetMultiColorRequestedOptionsOptions for setMultiColorRequested.