{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "color-picker",
  "title": "Color picker",
  "description": "ui-sdk’s Color picker: picks a colour by eye on an area, by number on OKLCH channels, or from presets, and reads any CSS colour typed in. A picked or typed colour glides every thumb to it.",
  "dependencies": [
    "@ui-sdk/react",
    "@ui-sdk/core"
  ],
  "registryDependencies": [
    "https://kinoui.com/r/collapsible.json",
    "https://kinoui.com/r/select.json",
    "https://kinoui.com/r/input.json",
    "https://kinoui.com/r/input-group.json",
    "https://kinoui.com/r/choice.json",
    "https://kinoui.com/r/swatch.json",
    "https://kinoui.com/r/track.json",
    "https://kinoui.com/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/components/kino/color-picker.tsx",
      "content": "'use client'\n\nimport { Collapsible, CollapsiblePanel } from '@/registry/components/kino/collapsible'\nimport { inputControlClassName } from '@/registry/components/kino/input'\nimport {\n  InputGroup,\n  InputGroupAddon,\n  inputGroupBesideStart,\n  InputGroupButton,\n} from '@/registry/components/kino/input-group'\nimport {\n  Select,\n  SelectContent,\n  SelectItem,\n  SelectTrigger,\n  SelectValue,\n} from '@/registry/components/kino/select'\nimport { IconPlaceholder } from '@/registry/icons/icon-placeholder'\nimport { choicePressHandlers } from '@/registry/lib/choice'\nimport { swatchClassName } from '@/registry/lib/swatch'\nimport { thumbDotClassName, trackDirClassName } from '@/registry/lib/track'\nimport {\n  type Color,\n  type ColorFormat,\n  colorDistance,\n  contrastRatio,\n  convertColor,\n  formatColor,\n  isInGamut,\n  parseColor,\n} from '@ui-sdk/core/color'\nimport {\n  type ColorChannel,\n  ColorPickerArea as ColorPickerAreaPrimitive,\n  ColorPickerAreaCanvas as ColorPickerAreaCanvasPrimitive,\n  ColorPickerAreaThumb as ColorPickerAreaThumbPrimitive,\n  ColorPickerChannelInput as ColorPickerChannelInputPrimitive,\n  type ColorPickerController,\n  ColorPickerEyeDropper as ColorPickerEyeDropperPrimitive,\n  ColorPickerInput as ColorPickerInputPrimitive,\n  ColorPicker as ColorPickerPrimitive,\n  ColorPickerSlider as ColorPickerSliderPrimitive,\n  ColorPickerSliderThumb as ColorPickerSliderThumbPrimitive,\n  type ColorPickerSpace,\n  type ColorPickerState,\n  ColorPickerSwatch as ColorPickerSwatchPrimitive,\n  ColorPickerSwatches as ColorPickerSwatchesPrimitive,\n  ColorPickerSwatchItem as ColorPickerSwatchItemPrimitive,\n  type ColorPickerValueChangeDetails,\n  type ColorPickerValueCommitDetails,\n  createColorPickerController,\n} from '@ui-sdk/react/color-picker'\nimport { Toggle as TogglePrimitive } from '@ui-sdk/react/toggle'\nimport {\n  type ComponentProps,\n  createContext,\n  type CSSProperties,\n  type ReactNode,\n  use,\n  useLayoutEffect,\n  useRef,\n  useState,\n  useSyncExternalStore,\n} from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * ui-sdk's Color picker with Kino's look. ui-sdk holds the colour, the\n * pointer and the keys; Kino draws the tracks and thumbs, glides a thumb on\n * `layout` to a colour picked, typed or keyed, and has it follow a drag at\n * once.\n */\n\ntype ChangeListener = (value: string, details: ColorPickerValueChangeDetails) => void\n\ninterface ColorPickerContextValue {\n  state: ColorPickerState\n  format: ColorFormat\n  setFormat: (format: ColorFormat) => void\n  /** Sets a colour as a press on a member of the picker does: a change, then a commit. */\n  choose: (value: string, details: { event?: Event; source: CommitSource }) => void\n  /** Hears every change, before the picker's own `onValueChange`. */\n  listen: (listener: ChangeListener) => () => void\n}\n\ntype CommitSource = ColorPickerValueCommitDetails['source']\n\nconst ColorPickerContext = createContext<ColorPickerContextValue | null>(null)\n\nfunction useColorPicker() {\n  const context = use(ColorPickerContext)\n  if (!context) throw new Error('A Color picker part must sit inside a ColorPicker.')\n  return context\n}\n\n/** How a picker writes its value when no format is given: as ui-sdk does, hex for HSV and the space otherwise. */\nconst formatOf = (space: ColorPickerSpace | undefined): ColorFormat =>\n  space === undefined || space === 'hsv' ? 'hex' : space\n\ntype ColorPickerProps = Omit<\n  ComponentProps<typeof ColorPickerPrimitive>,\n  'className' | 'children' | 'format'\n> & {\n  className?: string\n  children?: ReactNode\n  /** How the value is written; `ColorPickerFormat` changes it. */\n  format?: ColorFormat\n  defaultFormat?: ColorFormat\n  onFormatChange?: (format: ColorFormat) => void\n}\n\nfunction ColorPicker({\n  space,\n  gamut = false,\n  format: formatProp,\n  defaultFormat,\n  onFormatChange,\n  value,\n  defaultValue,\n  onValueChange,\n  onValueCommit,\n  controller: controllerProp,\n  className,\n  children,\n  'aria-label': ariaLabel = 'Colour picker',\n  ...props\n}: ColorPickerProps) {\n  const [formatState, setFormatState] = useState(defaultFormat ?? formatOf(space))\n  const format = formatProp ?? formatState\n  const [ownController] = useState(createColorPickerController)\n  const controller: ColorPickerController = controllerProp ?? ownController\n  // While a drag runs the thumbs follow it at once; a press, a key or a new colour glides.\n  // A drag ends in a commit; one that ends where it began commits nothing, and the next\n  // change, which commits at once, clears it before it draws.\n  const [following, setFollowing] = useState(false)\n  const listeners = useRef(new Set<ChangeListener>())\n  const commitRef = useRef(onValueCommit)\n  useLayoutEffect(() => {\n    commitRef.current = onValueCommit\n  })\n\n  // A new format rewrites the value: ui-sdk writes it in the format it has once it renders.\n  const written = useRef(format)\n  useLayoutEffect(() => {\n    if (written.current === format) return\n    written.current = format\n    controller.setValue(controller.getValue())\n  }, [controller, format])\n\n  const context = (state: ColorPickerState): ColorPickerContextValue => ({\n    state,\n    format,\n    setFormat: (next) => {\n      setFormatState(next)\n      onFormatChange?.(next)\n    },\n    choose: (value, { event, source }) => {\n      if (!controller.setValue(value, { reason: 'item-press', event })) return\n      const color = parseColor(value)\n      if (!color) return\n      commitRef.current?.(controller.getValue(), {\n        reason: 'item-press',\n        event: event as MouseEvent | KeyboardEvent | undefined,\n        source,\n        color: convertColor(color, state.space),\n      })\n    },\n    listen: (listener) => {\n      listeners.current.add(listener)\n      return () => listeners.current.delete(listener)\n    },\n  })\n\n  return (\n    <ColorPickerPrimitive\n      space={space}\n      gamut={gamut}\n      format={format}\n      value={value === undefined ? undefined : inFormat(value, format)}\n      defaultValue={\n        defaultValue === undefined ? undefined : inFormat(defaultValue, format)\n      }\n      controller={controller}\n      aria-label={ariaLabel}\n      data-following={following || undefined}\n      onValueChange={(value, details) => {\n        for (const listener of listeners.current) listener(value, details)\n        if (details.reason === 'drag') setFollowing(true)\n        onValueChange?.(value, details)\n      }}\n      onValueCommit={(value, details) => {\n        setFollowing(false)\n        onValueCommit?.(value, details)\n      }}\n      className={cn(\n        'group/color-picker flex w-full min-w-0 flex-col gap-(--surface-gap)',\n        trackDirClassName,\n        className,\n      )}\n      {...props}\n    >\n      {(state) => (\n        <ColorPickerContext value={context(state)}>{children}</ColorPickerContext>\n      )}\n    </ColorPickerPrimitive>\n  )\n}\n\n// ---------------------------------------------------------------------------\n// Swatch\n\n/** The squares a translucent colour is drawn over, in the theme's own colours. */\nconst checkerboard =\n  'repeating-conic-gradient(var(--muted) 0 25%, var(--background) 0 50%) 0 0 / 0.5rem 0.5rem'\n\n/** A colour over the checkerboard, so its alpha shows. */\nconst swatchBackground = (color: string) =>\n  `linear-gradient(${color}, ${color}), ${checkerboard}`\n\n/** `--color-picker-color`, ui-sdk's colour on a part, over the checkerboard. */\nconst swatchFillClassName =\n  '[background:linear-gradient(var(--color-picker-color),var(--color-picker-color)),repeating-conic-gradient(var(--muted)_0_25%,var(--background)_0_50%)_0_0/0.5rem_0.5rem] inset-ring inset-ring-foreground/10 forced-color-adjust-none'\n\n/** The colour as a square, named for screen readers: beside the value, or in a trigger. */\nfunction ColorPickerSwatch({\n  className,\n  ...props\n}: Omit<ComponentProps<typeof ColorPickerSwatchPrimitive>, 'className'> & {\n  className?: string\n}) {\n  return (\n    <ColorPickerSwatchPrimitive\n      className={cn(\n        'inline-block size-4 shrink-0 rounded-(--control-radius-xs)',\n        swatchFillClassName,\n        className,\n      )}\n      {...props}\n    />\n  )\n}\n\n// ---------------------------------------------------------------------------\n// Area\n\n/** Whether ui-sdk draws an area with a gradient: saturation across, brightness or lightness up, in HSV or HSL. */\nfunction areaHasGradient(\n  space: ColorPickerSpace,\n  x: ColorChannel | undefined,\n  y: ColorChannel | undefined,\n) {\n  if (space !== 'hsv' && space !== 'hsl') return false\n  const down = y ?? (space === 'hsv' ? 'brightness' : 'lightness')\n  return (\n    (x ?? 'saturation') === 'saturation' &&\n    (down === 'brightness' || down === 'lightness')\n  )\n}\n\n/**\n * A colour channel's dot: filled with `--slider-thumb`, the colour under it,\n * ringed in white and a hairline shadow so it stands out on any colour, in\n * either theme, and kept in forced colours.\n */\nconst channelThumbClassName =\n  'size-5 border-white bg-(--slider-thumb) shadow-[0_0_0_1px_rgb(0_0_0/0.2),0_1px_3px_rgb(0_0_0/0.25)] forced-color-adjust-none'\n\n/** A thumb's place glides on `layout`, and follows a drag at once. */\nconst thumbMoveClassName =\n  'transition-[translate] duration-(--motion-layout-duration) ease-(--motion-layout-easing) group-data-following/color-picker:duration-0 motion-reduce:transition-none'\n\n/**\n * The dot a thumb shows, centred on its point: the same as a channel\n * Slider's, so the two press and focus alike. It shrinks while the area or\n * the track under it is held.\n */\nfunction ThumbDot({ held, className }: { held: string; className: string }) {\n  return (\n    <span\n      className={cn(\n        'pointer-events-auto absolute start-0 flex size-6 [translate:calc(var(--track-dir)*-50%)_-50%] items-center justify-center',\n        className,\n      )}\n    >\n      <span aria-hidden className={cn(thumbDotClassName, channelThumbClassName, held)} />\n    </span>\n  )\n}\n\n/**\n * The colour as a surface for two channels: saturation across and\n * brightness up, by default. ui-sdk draws it with a gradient where one can,\n * and with a `ColorPickerAreaCanvas` otherwise, such as OKLCH's chroma by\n * lightness. Without children it holds its thumb, and the canvas it needs.\n */\nfunction ColorPickerArea({\n  className,\n  children,\n  x,\n  y,\n  ...props\n}: Omit<ComponentProps<typeof ColorPickerAreaPrimitive>, 'className'> & {\n  className?: string\n}) {\n  const { state } = useColorPicker()\n  return (\n    <ColorPickerAreaPrimitive\n      x={x}\n      y={y}\n      className={cn(\n        'group/area h-40 w-full shrink-0 rounded-(--control-radius-capped) select-none [background:var(--color-area-background)] inset-ring inset-ring-foreground/10 forced-color-adjust-none data-disabled:pointer-events-none data-disabled:opacity-50',\n        className,\n      )}\n      {...props}\n    >\n      {children ?? (\n        <>\n          {areaHasGradient(state.space, x, y) ? null : <ColorPickerAreaCanvas />}\n          <ColorPickerAreaThumb />\n        </>\n      )}\n    </ColorPickerAreaPrimitive>\n  )\n}\n\n/** Paints the area where no gradient can, inside its rounded corners. */\nfunction ColorPickerAreaCanvas({\n  className,\n  ...props\n}: Omit<ComponentProps<typeof ColorPickerAreaCanvasPrimitive>, 'className'> & {\n  className?: string\n}) {\n  return (\n    <ColorPickerAreaCanvasPrimitive\n      className={cn('rounded-(--control-radius-capped)', className)}\n      {...props}\n    />\n  )\n}\n\n/**\n * The area's thumb, a slider screen readers hear as both channels. It spans\n * the area and moves its dot by `translate`, from ui-sdk's `--area-x` and\n * `--area-y`, so it glides on the compositor.\n */\nfunction ColorPickerAreaThumb({\n  className,\n  style,\n  ...props\n}: Omit<\n  ComponentProps<typeof ColorPickerAreaThumbPrimitive>,\n  'className' | 'children'\n> & {\n  className?: string\n}) {\n  return (\n    <ColorPickerAreaThumbPrimitive\n      style={(state) => ({\n        '--slider-thumb': cssOf({ ...state.color, alpha: 1 }),\n        ...(typeof style === 'function' ? style(state) : style),\n      })}\n      className={cn(\n        // ui-sdk places it with insets, which motion.md won't let us animate: it fills the area instead.\n        'group/thumb pointer-events-none absolute inset-0! [translate:calc(var(--track-dir)*var(--area-x)*100%)_calc((1-var(--area-y))*100%)] focus-visible:outline-hidden',\n        thumbMoveClassName,\n        className,\n      )}\n      {...props}\n    >\n      <ThumbDot\n        className='top-0'\n        held='motion-safe:group-active/area:scale-[calc(1_-_(1_-_var(--motion-press-scale))_*_3)] group-active/area:duration-[calc(var(--motion-press-duration)*0.4)]'\n      />\n    </ColorPickerAreaThumbPrimitive>\n  )\n}\n\n// ---------------------------------------------------------------------------\n// Channel sliders\n\n/** The channel a slider edits, for its thumb. */\nconst SliderChannelContext = createContext<ColorChannel>('hue')\n\n/** Every hue at full saturation, red round to red. */\nconst HUE_STOPS = '#f00, #ff0, #0f0, #0ff, #00f, #f0f, #f00'\n\n/** Along the track, start to end: 90deg, or -90deg right to left, from `--track-dir`. */\nconst ALONG = 'calc(90deg * var(--track-dir))'\n\n/** A colour as CSS: OKLCH as OKLCH, so a colour past sRGB keeps it, and the rest as `rgb()`. */\nconst cssOf = (color: Color) =>\n  formatColor(color, color.space === 'oklch' ? 'oklch' : 'srgb')\n\n/** OKLCH hue stops every 30 degrees at `l` and `c`. */\nconst oklchHueStops = (l: number, c: number) =>\n  Array.from({ length: 13 }, (_, i) => `oklch(${l} ${c} ${i * 30})`).join(', ')\n\n/** The most chroma a lightness or chroma track runs to: ui-sdk's own end for chroma. */\nconst MAX_CHROMA = 0.4\n\n/**\n * A channel's track, as a CSS background, and its thumb's colour: the\n * colours the channel runs through with the others held where they are.\n * A hue runs round the wheel even for a grey, which has none of its own.\n * Channels it doesn't draw take ui-sdk's `--color-slider-background`.\n */\nfunction channelPaint(\n  color: Color,\n  channel: ColorChannel,\n): { track: string; thumb: string } {\n  const solid = cssOf({ ...color, alpha: 1 })\n  if (channel === 'alpha') {\n    return {\n      track: `linear-gradient(${ALONG}, ${cssOf({ ...color, alpha: 0 })}, ${solid}), ${checkerboard}`,\n      thumb: cssOf(color),\n    }\n  }\n  if (channel === 'hue' && color.space !== 'oklch') {\n    const hue = convertColor(color, 'hsv').coords[0] ?? 0\n    return {\n      track: `linear-gradient(${ALONG}, ${HUE_STOPS})`,\n      thumb: `hsl(${round(hue)} 100% 50%)`,\n    }\n  }\n  if (color.space === 'oklch') {\n    const [l = 0, c = 0, h = 0] = color.coords.map((n) => round(n ?? 0))\n    if (channel === 'hue') {\n      const shown = Math.max(c, 0.1)\n      return {\n        track: `linear-gradient(${ALONG} in oklch, ${oklchHueStops(l, shown)})`,\n        thumb: `oklch(${l} ${shown} ${h})`,\n      }\n    }\n    if (channel === 'lightness') {\n      return {\n        track: `linear-gradient(${ALONG} in oklch, oklch(0 ${c} ${h}), oklch(0.5 ${c} ${h}), oklch(1 ${c} ${h}))`,\n        thumb: solid,\n      }\n    }\n    if (channel === 'chroma') {\n      return {\n        track: `linear-gradient(${ALONG} in oklch, oklch(${l} 0 ${h}), oklch(${l} ${MAX_CHROMA} ${h}))`,\n        thumb: solid,\n      }\n    }\n  }\n  return { track: 'var(--color-slider-background)', thumb: solid }\n}\n\n/** Rounded to four places, so the server's arithmetic and the browser's write the same style. */\nconst round = (n: number) => Math.round(n * 1e4) / 1e4\n\n/**\n * One channel of the colour, such as `hue` or `alpha`, on a track drawn in\n * the colours it runs through. Without children it holds its thumb.\n */\nfunction ColorPickerSlider({\n  channel,\n  className,\n  style,\n  children,\n  ...props\n}: Omit<\n  ComponentProps<typeof ColorPickerSliderPrimitive>,\n  'className' | 'style' | 'orientation' | 'children'\n> & {\n  className?: string\n  style?: CSSProperties\n  /** The thumb; without one it holds its own. */\n  children?: ReactNode\n}) {\n  const { state } = useColorPicker()\n  const shown = channel ?? (state.space === 'srgb' ? 'blue' : 'hue')\n  const paint = channelPaint(state.color, shown)\n  return (\n    <SliderChannelContext value={shown}>\n      <ColorPickerSliderPrimitive\n        channel={channel}\n        style={\n          {\n            '--slider-track': paint.track,\n            '--slider-thumb': paint.thumb,\n            ...style,\n          } as CSSProperties\n        }\n        className={cn(\n          'group/channel flex h-(--control-height-xs) w-full shrink-0 items-center select-none data-disabled:pointer-events-none data-disabled:opacity-50',\n          className,\n        )}\n        {...props}\n      >\n        {/* A channel's track is its colours, which forced colours must keep. */}\n        <span\n          aria-hidden\n          className='h-3 w-full rounded-full [background:var(--slider-track)] shadow-[inset_0_0_0_1px_var(--border)] forced-color-adjust-none'\n        />\n        {children ?? <ColorPickerSliderThumb />}\n      </ColorPickerSliderPrimitive>\n    </SliderChannelContext>\n  )\n}\n\n/**\n * The slider's thumb. It spans the track and moves its dot by `translate`,\n * from ui-sdk's `--color-slider-thumb-position`, so it glides on the\n * compositor. The alpha channel is called Opacity.\n */\nfunction ColorPickerSliderThumb({\n  className,\n  ...props\n}: Omit<\n  ComponentProps<typeof ColorPickerSliderThumbPrimitive>,\n  'className' | 'children'\n> & {\n  className?: string\n}) {\n  const channel = use(SliderChannelContext)\n  return (\n    <ColorPickerSliderThumbPrimitive\n      aria-label={channel === 'alpha' ? 'Opacity' : undefined}\n      className={cn(\n        // ui-sdk places it with an inset, which motion.md won't let us animate: it spans the track instead.\n        'group/thumb pointer-events-none absolute inset-y-0! start-0! end-0! [translate:calc(var(--track-dir)*var(--color-slider-thumb-position))_0] focus-visible:outline-hidden',\n        thumbMoveClassName,\n        className,\n      )}\n      {...props}\n    >\n      <ThumbDot\n        className='top-1/2'\n        held='motion-safe:group-active/channel:scale-[calc(1_-_(1_-_var(--motion-press-scale))_*_3)] group-active/channel:duration-[calc(var(--motion-press-duration)*0.4)]'\n      />\n    </ColorPickerSliderThumbPrimitive>\n  )\n}\n\n// ---------------------------------------------------------------------------\n// Preview\n\n/**\n * The colour, large, and a note when the screen can't show it as it is: a\n * colour past sRGB is kept as it is and drawn as the nearest one the screen\n * shows.\n */\nfunction ColorPickerPreview({ className, ...props }: ComponentProps<'div'>) {\n  const { state } = useColorPicker()\n  const outside = !isInGamut(state.color, 'srgb')\n  return (\n    <div className={cn('flex flex-col gap-1.5', className)} {...props}>\n      <ColorPickerSwatch className='h-14 w-full rounded-(--control-radius-capped)' />\n      <p\n        className={cn(\n          'text-muted-foreground text-xs transition-opacity duration-(--motion-enter-duration) ease-(--motion-enter-easing)',\n          !outside &&\n            'opacity-0 duration-(--motion-exit-duration) ease-(--motion-exit-easing)',\n          // A wide-gamut screen shows it as it is. CSS knows the screen, so the server's page is the same.\n          '[@media(color-gamut:p3)]:invisible',\n        )}\n        aria-hidden={!outside}\n      >\n        This screen can’t show this colour, so it’s drawn as the nearest one it can.\n      </p>\n    </div>\n  )\n}\n\n// ---------------------------------------------------------------------------\n// Typing a colour\n\n/** The text the colour's inputs share: written left to right in any language, at the start right to left. */\nconst colorTextClassName = cn(\n  inputControlClassName,\n  inputGroupBesideStart,\n  'tabular-nums rtl:text-right',\n)\n\n/**\n * The colour as text, with its swatch at the start. ui-sdk reads what's\n * typed on Enter or when focus leaves, puts back the colour on Escape, and\n * puts it back too for text that isn't a colour. A colour's name, such as\n * `rebeccapurple`, reads too.\n */\nfunction ColorPickerInput({\n  className,\n  children,\n  'aria-label': ariaLabel = 'Colour',\n  ...props\n}: Omit<ComponentProps<typeof ColorPickerInputPrimitive>, 'className' | 'children'> & {\n  className?: string\n  /** Buttons at the end of the box, such as `ColorPickerEyeDropper`. */\n  children?: ReactNode\n}) {\n  return (\n    <InputGroup data-color-picker-input='' className={cn('w-full', className)}>\n      <InputGroupAddon>\n        <ColorPickerSwatch aria-hidden />\n      </InputGroupAddon>\n      <ColorPickerInputPrimitive\n        aria-label={ariaLabel}\n        dir='ltr'\n        className={colorTextClassName}\n        {...props}\n      />\n      {children}\n    </InputGroup>\n  )\n}\n\n/**\n * One channel as a number, in the units people read it in: 0 to 100 for\n * lightness and opacity, degrees for hue. Its children sit at the end of the\n * box, such as the unit.\n */\nfunction ColorPickerChannelInput({\n  className,\n  children,\n  ...props\n}: Omit<\n  ComponentProps<typeof ColorPickerChannelInputPrimitive>,\n  'className' | 'children'\n> & {\n  className?: string\n  children?: ReactNode\n}) {\n  return (\n    <InputGroup className={cn('h-(--control-height-sm) w-24 shrink-0', className)}>\n      <ColorPickerChannelInputPrimitive\n        dir='ltr'\n        className={cn(colorTextClassName, 'h-full text-end rtl:text-left')}\n        {...props}\n      />\n      {children}\n    </InputGroup>\n  )\n}\n\nconst FORMATS: { value: ColorFormat; label: string }[] = [\n  { value: 'hex', label: 'Hex' },\n  { value: 'srgb', label: 'RGB' },\n  { value: 'hsl', label: 'HSL' },\n  { value: 'oklch', label: 'OKLCH' },\n]\n\n/** Picks how the value is written. Its props go to the Select's trigger. */\nfunction ColorPickerFormat({\n  className,\n  disabled,\n  ...props\n}: ComponentProps<typeof SelectTrigger>) {\n  const { state, format, setFormat } = useColorPicker()\n  return (\n    <Select\n      items={FORMATS}\n      value={format}\n      disabled={disabled ?? state.disabled}\n      onValueChange={(next) => {\n        if (next) setFormat(next)\n      }}\n    >\n      <SelectTrigger\n        aria-label='Format'\n        className={cn('w-24 shrink-0', className)}\n        {...props}\n      >\n        <SelectValue />\n      </SelectTrigger>\n      <SelectContent>\n        {FORMATS.map((item) => (\n          <SelectItem key={item.value} value={item.value}>\n            {item.label}\n          </SelectItem>\n        ))}\n      </SelectContent>\n    </Select>\n  )\n}\n\nconst noSubscribe = () => () => {}\n\n/**\n * Picks a colour from anywhere on the screen, at the end of a\n * `ColorPickerInput`. Only Chrome and Edge on a desktop can, so elsewhere it\n * isn't drawn at all.\n */\nfunction ColorPickerEyeDropper({\n  'aria-label': ariaLabel = 'Pick a colour from the screen',\n  ...props\n}: Omit<ComponentProps<typeof InputGroupButton>, 'children'>) {\n  const supported = useSyncExternalStore(\n    noSubscribe,\n    () => 'EyeDropper' in window,\n    () => false,\n  )\n  if (!supported) return null\n  return (\n    <InputGroupAddon align='inline-end'>\n      <ColorPickerEyeDropperPrimitive\n        render={<InputGroupButton size='icon-xs' aria-label={ariaLabel} {...props} />}\n      >\n        <IconPlaceholder\n          lucide='PipetteIcon'\n          tabler='IconColorPicker'\n          hugeicons='ColorPickerIcon'\n          phosphor='EyedropperIcon'\n          remixicon='RiSipLine'\n          aria-hidden\n        />\n      </ColorPickerEyeDropperPrimitive>\n    </InputGroupAddon>\n  )\n}\n\n// ---------------------------------------------------------------------------\n// Swatches\n\n/** A preset colour and its name. */\ninterface ColorPreset {\n  /** Any CSS colour. */\n  value: string\n  /** Its name, for screen readers; without one ui-sdk describes it, such as \"dark blue\". */\n  label?: string\n}\n\nconst swatchesClassName =\n  'grid grid-cols-[repeat(auto-fill,var(--control-height-xs))] justify-between gap-2'\n\n/** A preset's square, on the swatch lib's press, focus and picked ring. */\nconst swatchItemClassName = cn(\n  swatchClassName,\n  'size-(--control-height-xs) rounded-(--control-radius-xs) after:rounded-[calc(var(--control-radius-xs)+4px)]',\n)\n\n/** A swatch's tick: in, while it's the colour. */\nconst tickClassName =\n  'size-3.5 opacity-0 transition-[opacity,scale] duration-(--motion-press-duration) ease-(--motion-press-easing) motion-safe:scale-95 group-data-[selected]/swatch:opacity-100 motion-safe:group-data-[selected]/swatch:scale-100 group-aria-pressed/swatch:opacity-100 motion-safe:group-aria-pressed/swatch:scale-100'\n\nfunction Tick({ light }: { light: boolean }) {\n  return (\n    <IconPlaceholder\n      lucide='CheckIcon'\n      tabler='IconCheck'\n      hugeicons='Tick02Icon'\n      phosphor='CheckIcon'\n      remixicon='RiCheckLine'\n      aria-hidden\n      strokeWidth={3}\n      className={cn(tickClassName, light ? 'text-white' : 'text-black')}\n    />\n  )\n}\n\n/**\n * A row of preset colours, a list that's one stop in the tab order: the\n * arrow keys move between them, and Enter, Space or a press picks one. The\n * one that is the colour is picked; while the colour is one of its own, none is.\n */\nfunction ColorPickerSwatches({\n  className,\n  'aria-label': ariaLabel = 'Presets',\n  ...props\n}: Omit<ComponentProps<typeof ColorPickerSwatchesPrimitive>, 'className'> & {\n  className?: string\n}) {\n  return (\n    <ColorPickerSwatchesPrimitive\n      aria-label={ariaLabel}\n      className={cn(swatchesClassName, className)}\n      {...props}\n    />\n  )\n}\n\n/** One preset colour, inside `ColorPickerSwatches`: picked while it's the colour. */\nfunction ColorPickerSwatchItem({\n  value,\n  label,\n  className,\n  onKeyDown,\n  onKeyUp,\n  onBlur,\n  ...props\n}: Omit<ComponentProps<typeof ColorPickerSwatchItemPrimitive>, 'className' | 'children'> &\n  ColorPreset & { className?: string }) {\n  return (\n    <ColorPickerSwatchItemPrimitive\n      value={value}\n      aria-label={label}\n      className={cn(swatchItemClassName, swatchFillClassName, className)}\n      {...choicePressHandlers({ onKeyDown, onKeyUp, onBlur })}\n      {...props}\n    >\n      <Tick light={prefersLightMark(value)} />\n    </ColorPickerSwatchItemPrimitive>\n  )\n}\n\n/**\n * Presets first: the presets and a Custom swatch after them. Custom opens\n * the children, the controls for a colour of your own, under the row on\n * `layout`; they stay open while the colour is your own, even when a drag\n * passes over a preset's colour. Your own colour is kept while a preset is\n * tried, and Custom puts it back.\n */\nfunction ColorPickerPalette({\n  presets,\n  className,\n  'aria-label': ariaLabel = 'Presets',\n  children,\n}: {\n  /** The colours before Custom; the Palette needs them all to know when the colour is your own. */\n  presets: readonly ColorPreset[]\n  /** The controls for a colour of your own, such as an area, a hue and an input. */\n  children: ReactNode\n  className?: string\n  'aria-label'?: string\n}) {\n  const { state, choose, listen } = useColorPicker()\n  const values = presets.map((preset) => preset.value)\n  const [palette, setPalette] = useState<PaletteState>({ mode: 'preset', own: null })\n  const custom = paletteShowsCustom(palette, state.value, values)\n\n  // A preset picked from the row keeps the colour you had, if it was your own, for Custom.\n  const latest = useRef({ palette, value: state.value, values })\n  useLayoutEffect(() => {\n    latest.current = { palette, value: state.value, values }\n  })\n  useLayoutEffect(\n    () =>\n      listen((_next, details) => {\n        if (details.reason !== 'item-press') return\n        const { palette: was, value, values: shown } = latest.current\n        setPalette(paletteStep(was, 'preset', value, shown))\n      }),\n    [listen],\n  )\n\n  return (\n    <Collapsible\n      open={custom}\n      role='group'\n      aria-label='Custom colour controls'\n      // Custom and the presets open and close it, so an agent can't either.\n      disabled\n      className={className}\n    >\n      <div className={swatchesClassName}>\n        {/* The row is one grid with Custom, which isn't a preset and so isn't in the list. */}\n        <ColorPickerSwatches aria-label={ariaLabel} className='contents'>\n          {presets.map((preset) => (\n            <ColorPickerSwatchItem key={preset.value} {...preset} />\n          ))}\n        </ColorPickerSwatches>\n        {/* Custom is picked, not opened: a preset unpicks it, so pressing it again does nothing. */}\n        <TogglePrimitive\n          aria-label='Custom colour'\n          pressed={custom}\n          onPressedChange={(pressed, details) => {\n            if (!pressed) return details.cancel()\n            // Custom puts your own colour back, if a preset was tried since. Before Custom's own\n            // step, which the step that change makes as a preset would otherwise overwrite.\n            if (palette.own !== null && palette.own !== state.value) {\n              choose(palette.own, details)\n            }\n            setPalette(paletteStep(palette, 'custom', state.value, values))\n          }}\n          disabled={state.disabled}\n          style={{\n            background: custom\n              ? swatchBackground('var(--color-picker-color)')\n              : `conic-gradient(from 90deg, ${HUE_STOPS})`,\n          }}\n          className={cn(\n            swatchItemClassName,\n            'inset-ring inset-ring-foreground/10 forced-color-adjust-none',\n          )}\n          {...choicePressHandlers({})}\n        >\n          <IconPlaceholder\n            lucide='PlusIcon'\n            tabler='IconPlus'\n            hugeicons='PlusSignIcon'\n            phosphor='PlusIcon'\n            remixicon='RiAddLine'\n            aria-hidden\n            strokeWidth={3}\n            className='size-3.5 text-white drop-shadow-[0_1px_1px_rgb(0_0_0/0.4)] transition-[opacity,scale] duration-(--motion-press-duration) ease-(--motion-press-easing) group-aria-pressed/swatch:opacity-0 motion-safe:group-aria-pressed/swatch:scale-95'\n          />\n          <Tick light={prefersLightMark(state.value)} />\n        </TogglePrimitive>\n      </div>\n      {/* The room above and below keeps the area's thumb and the focus rings clear of the panel's clip. */}\n      <CollapsiblePanel className='flex flex-col gap-(--surface-gap) ps-0 pe-0 pt-(--surface-gap) pb-1'>\n        {children}\n      </CollapsiblePanel>\n    </Collapsible>\n  )\n}\n\n/** What a Palette remembers: whether Custom was picked, and your own colour while a preset is tried. */\ninterface PaletteState {\n  mode: 'preset' | 'custom'\n  own: string | null\n}\n\n/**\n * A Palette's state once Custom or a preset is picked, while the colour is\n * `value`. Picking a preset keeps the colour you had, if it was your own, for\n * Custom to put back.\n */\nfunction paletteStep(\n  state: PaletteState,\n  picked: 'preset' | 'custom',\n  value: string,\n  presets: readonly string[],\n): PaletteState {\n  if (picked === 'custom') return { ...state, mode: 'custom' }\n  return {\n    mode: 'preset',\n    own: paletteShowsCustom(state, value, presets) ? value : state.own,\n  }\n}\n\n/**\n * A colour given to the picker, written in its format, as the field shows\n * it: ui-sdk keeps a value as it is given until it changes. A colour the\n * format can't hold, such as one past sRGB in hex, stays as it is, since\n * ui-sdk reads the colour from the value and would clip it. So does text\n * that isn't a colour.\n */\nfunction inFormat(value: string, format: ColorFormat) {\n  const color = parseColor(value)\n  if (!color) return value\n  if (format !== 'oklch' && !isInGamut(color, 'srgb')) return value\n  return formatColor(color, format)\n}\n\n/** Whether Custom is picked and its controls open: picked, or the colour is no preset. */\nfunction paletteShowsCustom(\n  state: PaletteState,\n  value: string,\n  presets: readonly string[],\n) {\n  return state.mode === 'custom' || !presets.some((preset) => sameColor(preset, value))\n}\n\n/**\n * Whether two CSS colours look the same, as ui-sdk matches a swatch to the\n * colour: a preset written in another format, or rounded, still matches.\n */\nfunction sameColor(one: string, other: string) {\n  const a = parseColor(one)\n  const b = parseColor(other)\n  if (!a || !b) return one === other\n  return colorDistance(a, b) < 2e-3 && Math.abs(a.alpha - b.alpha) < 5e-3\n}\n\n/**\n * Whether a mark drawn over the colour reads best in white rather than black:\n * the one with the higher WCAG contrast. A colour mostly see-through shows\n * the page under it, so it takes black.\n */\nfunction prefersLightMark(color: string) {\n  const parsed = parseColor(color)\n  if (!parsed) return true\n  if (parsed.alpha <= 0.35) return false\n  const opaque = { ...parsed, alpha: 1 }\n  return contrastRatio(WHITE, opaque) >= contrastRatio(BLACK, opaque)\n}\n\nconst WHITE: Color = { space: 'srgb', coords: [1, 1, 1], alpha: 1 }\nconst BLACK: Color = { space: 'srgb', coords: [0, 0, 0], alpha: 1 }\n\nexport {\n  ColorPicker,\n  ColorPickerArea,\n  ColorPickerAreaCanvas,\n  ColorPickerAreaThumb,\n  ColorPickerChannelInput,\n  ColorPickerEyeDropper,\n  ColorPickerFormat,\n  ColorPickerInput,\n  ColorPickerPalette,\n  ColorPickerPreview,\n  ColorPickerSlider,\n  ColorPickerSliderThumb,\n  ColorPickerSwatch,\n  ColorPickerSwatches,\n  ColorPickerSwatchItem,\n  channelPaint,\n  inFormat,\n  paletteShowsCustom,\n  paletteStep,\n  prefersLightMark,\n  sameColor,\n}\nexport type { ColorPickerProps, ColorPreset }\n",
      "type": "registry:component",
      "target": "@components/kino/color-picker.tsx"
    }
  ],
  "type": "registry:component"
}