{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "color-field",
  "title": "ColorField",
  "description": "A color on the Field contract: a swatch that opens the system color picker, next to the same color as hex text, kept in step both ways.",
  "registryDependencies": [
    "@ouro/field",
    "@ouro/lib-env",
    "@ouro/lib-refs",
    "@ouro/lib-touch-target",
    "@ouro/lib-use-dev-messages",
    "@ouro/lib-use-field"
  ],
  "files": [
    {
      "path": "registry/ouro/components/ouro/color-field/color-field-styles.ts",
      "content": "export { boxClass, hexOf, pickerClass, plainSwatchClass, supportsColorInput, swatchClass, textClass, toHex };\n\n// Class strings and helpers for ColorField, apart from the component so its file exports only\n// components (React Fast Refresh). Class strings are literal so the app's Tailwind finds them\n// when it compiles.\n\n/**\n * A hex color as `#rrggbb` in lowercase: `#abc`, `abc`, `#AABBCC` and `aabbcc` all work, with\n * spaces around them. Anything else is `undefined`.\n *\n * @internal\n * @claim \"A hex color as `#rrggbb` in\" registry/ouro/components/ouro/color-field/color-field.test.tsx verify:testExists(registry/ouro/components/ouro/color-field/color-field.test.tsx::ColorField > is a labeled hex text input with a native color picker, on the Field contract)\n * @claim \"A hex color as `#rrggbb` in\" registry/ouro/components/ouro/color-field/color-field.test.tsx verify:testExists(registry/ouro/components/ouro/color-field/color-field.test.tsx::ColorField > moves the picker as a valid hex is typed, in any of its forms)\n * @claim \"A hex color as `#rrggbb` in\" registry/ouro/components/ouro/color-field/color-field.test.tsx verify:testExists(registry/ouro/components/ouro/color-field/color-field.test.tsx::ColorField > tidies the text when the input loses focus, and puts back the last color when it is not a hex)\n */\nfunction hexOf(text: string | undefined): string | undefined {\n  const match = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec((text ?? \"\").trim());\n  if (!match) return undefined;\n  const digits = match[1]!.toLowerCase();\n  return `#${digits.length === 3 ? [...digits].map((digit) => digit + digit).join(\"\") : digits}`;\n}\n\n/**\n * Any CSS color as `#rrggbb`, through the browser's own parser; black when it cannot parse it.\n * Development only (dev messages show the hex to use).\n *\n * @internal\n */\nfunction toHex(color: string): string {\n  const context = document.createElement(\"canvas\").getContext(\"2d\")!;\n  context.fillStyle = \"#000000\";\n  context.fillStyle = color;\n  return context.fillStyle;\n}\n\n/**\n * The box around the swatch and the text: Field's control look, 44px tall with a 16px font on\n * phones, stepping down from `sm` with a fine pointer, outlined while either input has keyboard focus.\n *\n * @internal\n * @claim \"The box around the swatch and\" registry/ouro/components/ouro/color-field/color-field.test.tsx verify:testExists(registry/ouro/components/ouro/color-field/color-field.test.tsx::ColorField > gives the swatch a 44px hit area on phones, and the box 44px with 16px text)\n * @claim \"The box around the swatch and\" registry/ouro/components/ouro/color-field/color-field.test.tsx verify:testExists(registry/ouro/components/ouro/color-field/color-field.test.tsx::ColorField > outlines the box when either input has keyboard focus)\n * @claim \"The box around the swatch and\" registry/ouro/components/ouro/color-field/color-field.touch.test.tsx verify:testExists(registry/ouro/components/ouro/color-field/color-field.touch.test.tsx::keeps a 44px box and 16px text on a landscape phone, past the sm breakpoint)\n */\nconst boxClass =\n  \"relative m-0 box-border flex w-full min-w-0 items-center gap-2 h-(--ouro-control-h) ps-2 pe-3 py-0 \" +\n  \"[--ouro-control-h:calc(var(--spacing)*11)] sm:pointer-fine:[--ouro-control-h:calc(var(--spacing)*9)] \" +\n  \"rounded-ouro-md border border-solid border-input bg-transparent text-base text-foreground sm:pointer-fine:text-sm \" +\n  \"outline-ring outline-offset-2 has-[input:focus-visible]:outline-2 has-[input:focus-visible]:outline-solid \" +\n  \"transition-[border-color] duration-(--ouro-duration-fast) ease-[ease] \" +\n  \"has-[input[aria-invalid=true]]:border-destructive has-[input:disabled]:cursor-not-allowed has-[input:disabled]:opacity-50 \" +\n  \"dark:bg-input/30\";\n\n/**\n * The swatch's hit area: a 28px square (24px from `sm` with a fine pointer), with a 44px\n * touch target on coarse pointers.\n *\n * @internal\n * @claim \"The swatch's hit area: a 28px\" registry/ouro/components/ouro/color-field/color-field.test.tsx verify:testExists(registry/ouro/components/ouro/color-field/color-field.test.tsx::ColorField > gives the swatch a 44px hit area on phones, and the box 44px with 16px text)\n * @claim \"The swatch's hit area: a 28px\" registry/ouro/components/ouro/color-field/color-field.touch.test.tsx verify:testExists(registry/ouro/components/ouro/color-field/color-field.touch.test.tsx::gives the swatch a 44px hit area that opens the picker)\n */\nconst swatchClass =\n  \"press relative flex size-7 shrink-0 cursor-pointer sm:pointer-fine:size-6 \" +\n  \"motion-safe:not-has-[input:disabled]:active:scale-(--ouro-press-scale) has-[input:disabled]:cursor-not-allowed\";\n\n/**\n * The swatch where the browser has no color picker: the color, shown only, beside the hex text\n * that takes it.\n * @claim \"The swatch where the browser has\" registry/ouro/components/ouro/color-field/color-field.test.tsx verify:testExists(registry/ouro/components/ouro/color-field/color-field.test.tsx::ColorField > shows a plain swatch and keeps the hex text where the browser has no color picker)\n */\nconst plainSwatchClass = \"relative block size-7 shrink-0 rounded-ouro-sm border border-solid border-border sm:pointer-fine:size-6\";\n\n/**\n * Whether the browser has a color picker. One without it treats `type=\"color\"` as text, so the\n * type reads back as \"text\". On the server, assume it does; the client corrects it.\n */\nfunction supportsColorInput(): boolean {\n  const probe = document.createElement(\"input\");\n  probe.setAttribute(\"type\", \"color\");\n  return probe.type === \"color\";\n}\n\n/**\n * The native color input drawn as a plain swatch: the browser's padding and border removed.\n *\n * @internal\n */\nconst pickerClass =\n  \"relative m-0 box-border block size-full cursor-[inherit] appearance-none rounded-ouro-sm border border-solid border-border bg-transparent p-0 \" +\n  \"outline-none [&::-webkit-color-swatch-wrapper]:p-0 [&::-webkit-color-swatch]:rounded-[inherit] [&::-webkit-color-swatch]:border-0 \" +\n  \"[&::-moz-color-swatch]:rounded-[inherit] [&::-moz-color-swatch]:border-0\";\n\n/**\n * The hex text input: borderless, filling the box, in a monospaced figure width.\n *\n * @internal\n */\nconst textClass =\n  \"m-0 box-border block h-full min-w-0 flex-1 self-stretch border-0 bg-transparent p-0 tabular-nums \" +\n  \"text-[length:inherit] text-inherit font-[inherit] outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed\";\n",
      "type": "registry:ui",
      "target": "@components/ouro/color-field/color-field-styles.ts"
    },
    {
      "path": "registry/ouro/components/ouro/color-field/color-field.tsx",
      "content": "\"use client\";\n\nimport { useEffect, useRef, useState, useSyncExternalStore, type JSX, type ReactNode, type Ref } from \"react\";\nimport { Field } from \"@/registry/ouro/components/ouro/field/field\";\nimport { FieldControl } from \"@/registry/ouro/components/ouro/field/field-parts\";\nimport { contractWarnings } from \"@/registry/ouro/components/ouro/field/field-styles\";\nimport { useMergedRef } from \"@/registry/ouro/lib/ouro/refs\";\nimport { TouchTarget } from \"@/registry/ouro/lib/ouro/touch-target\";\nimport { FieldOwnerContext, useField, type ReadonlyErrorMessages } from \"@/registry/ouro/lib/ouro/use-field\";\nimport { useDevWarnings } from \"@/registry/ouro/lib/ouro/use-dev-messages\";\nimport {\n  boxClass,\n  hexOf,\n  pickerClass,\n  plainSwatchClass,\n  supportsColorInput,\n  swatchClass,\n  textClass,\n  toHex,\n} from \"@/registry/ouro/components/ouro/color-field/color-field-styles\";\n\n/** Props for {@link ColorField}. */\nexport interface ColorFieldProps {\n  /**\n   * What the color is for (\"Accent color\"), shown above the field and read as the text input's\n   * name. Required: every control needs a name. To hide it visually, keep it and add `hideLabel`.\n   * @claim \"Required: every control needs a name\" registry/ouro/components/ouro/color-field/color-field.test-d.ts verify:fileLine(registry/ouro/components/ouro/color-field/color-field.test-d.ts, /\\{\\svalue:\\s\"#000000\"\\s\\}>\\(\\)\\.not\\.toExtend<ColorFieldProps>/)\n   */\n  label: string;\n  /** Hides the label visually; screen readers still read it. */\n  hideLabel?: boolean | undefined;\n  /** Supporting text under the label, read through `aria-describedby`. */\n  description?: ReactNode | undefined;\n  /**\n   * What is wrong, from your server action or client check. It shows under the field, which\n   * gets `aria-invalid`. A message is text or a React node (one with a link); an empty string or array means valid.\n   */\n  error?: ReadonlyErrorMessages | undefined;\n  /**\n   * Marks the field required: it gets `aria-required`, and the label a marker. A color always\n   * has a value, so it never blocks a submit, even with the text cleared.\n   * @claim \"A color always has a value\" registry/ouro/components/ouro/color-field/color-field.test.tsx verify:testExists(registry/ouro/components/ouro/color-field/color-field.test.tsx::ColorField > submits a required field whose text was cleared, with its color)\n   */\n  required?: boolean | undefined;\n  /** Disables the swatch and the text, and fades the field. */\n  disabled?: boolean | undefined;\n  /**\n   * The form field name the color submits under, always as `#rrggbb`.\n   *\n   * @claim \"The form field name the color\" registry/ouro/components/ouro/color-field/color-field.test.tsx verify:testExists(registry/ouro/components/ouro/color-field/color-field.test.tsx::ColorField > submits a required field whose text was cleared, with its color)\n   */\n  name?: string | undefined;\n  /** The color as hex (`#3366ff`, or short `#36f`), when you control it. Pair it with `onValueChange`. */\n  value?: string | undefined;\n  /** The color the field starts with, and goes back to when its form resets, as hex. @default \"#000000\" */\n  defaultValue?: string | undefined;\n  /** Called with the color as `#rrggbb` when it is picked, or typed as a whole hex. */\n  onValueChange?: ((hex: string) => void) | undefined;\n  /**\n   * The name of the swatch that opens the system color picker. The swatch is a color input,\n   * which can only be named by label text, so Playwright's loose `getByLabel(\"Color\")` also\n   * finds it when the field's label is in this name; find the field with\n   * `getByLabel(\"Color\", { exact: true })` or `getByRole(\"textbox\", { name: \"Color\" })`.\n   * Translate it with your app.\n   * @default \"Pick a color\"\n   */\n  pickerLabel?: string | undefined;\n  /**\n   * Layout only: margins, width, grid placement (`mt-4`). Appearance classes warn in\n   * development; style fields in your theme.\n   */\n  className?: string | undefined;\n  /** The hex text input. */\n  ref?: Ref<HTMLInputElement> | undefined;\n\n  /** Not a prop. ColorField takes and gives `#rrggbb`: `<ColorField defaultValue=\"#3366ff\">`. */\n  format?: { 'ColorField takes and gives #rrggbb: <ColorField defaultValue=\"#3366ff\">': never };\n  /**\n   * Not supported by ColorField. ColorField takes `#rrggbb`, with no transparency.\n   *\n   * @claim \"Not supported by ColorField\" registry/ouro/components/ouro/color-field/color-field.test-d.ts verify:fileLine(registry/ouro/components/ouro/color-field/color-field.test-d.ts, /\\{\\slabel:\\s\"Color\";\\salpha:\\strue\\s\\}>\\(\\)\\.not\\.toExtend<ColorFieldProps>/)\n   * @claim \"ColorField takes `#rrggbb`, with no transparency\" registry/ouro/components/ouro/color-field/color-field.test-d.ts verify:fileLine(registry/ouro/components/ouro/color-field/color-field.test-d.ts, /\\{\\slabel:\\s\"Color\";\\salpha:\\strue\\s\\}>\\(\\)\\.not\\.toExtend<ColorFieldProps>/)\n   */\n  alpha?: { 'ColorField takes #rrggbb, with no transparency': never };\n  /** Not a prop. Ouro UI uses `value` or `defaultValue`: `<ColorField defaultValue=\"#ff0000\">`. */\n  color?: { 'Use <ColorField defaultValue=\"#ff0000\">': never };\n  /** Not a prop. Ouro UI uses `onValueChange`, which gets the hex: `<ColorField onValueChange={(hex) => ...}>`. */\n  onChange?: { 'Use <ColorField onValueChange={(hex) => ...}>': never };\n  /** Not a prop. Ouro UI uses `error`: `<ColorField error=\"Pick a darker color.\">`. */\n  errorMessage?: { 'Use <ColorField error=\"Pick a darker color.\">': never };\n  /** Not a prop. Ouro UI uses `description`: `<ColorField description=\"...\">`. */\n  helperText?: { 'Use <ColorField description=\"...\">': never };\n  /** Not a prop. `error` marks the field invalid: `<ColorField error=\"What is wrong\">`. */\n  isInvalid?: { 'Use <ColorField error=\"What is wrong\">': never };\n  /** Not a prop. `error` marks the field invalid: `<ColorField error=\"What is wrong\">`. */\n  invalid?: { 'Use <ColorField error=\"What is wrong\">': never };\n  /** Not a prop. Ouro UI uses `required`: `<ColorField required>`. */\n  isRequired?: { 'Use <ColorField required>': never };\n  /** Not a prop. Ouro UI uses `disabled`: `<ColorField disabled>`. */\n  isDisabled?: { 'Use <ColorField disabled>': never };\n}\n\n/** Field's messages and root name ColorField. */\nconst owner = { name: \"ColorField\", data: \"color-field\" };\n\ninterface ControlProps {\n  color: string;\n  onPick: (hex: string) => void;\n  /** Puts the color back as the form resets, and gives the color it now has. */\n  onReset: () => string;\n  pickerLabel: string;\n  disabled: boolean | undefined;\n  inputRef: Ref<HTMLInputElement>;\n  textRef: { current: HTMLInputElement | null };\n}\n\n/** The browser keeps or lacks a color picker for the life of the page, so the subscription does nothing. */\nconst subscribeNever = () => () => {};\n\n/** The swatch and the text, inside the Field, where they read its server-known description ids. */\nfunction Control({ color, onPick, onReset, pickerLabel, disabled, inputRef, textRef }: ControlProps): JSX.Element {\n  const field = useField()!;\n  const hasPicker = useSyncExternalStore(subscribeNever, supportsColorInput, () => true);\n  // The text the person is typing; it follows the color whenever the color changes elsewhere.\n  const [draft, setDraft] = useState(color);\n  const [shown, setShown] = useState(color);\n  if (shown !== color) {\n    setShown(color);\n    if (hexOf(draft) !== color) setDraft(color);\n  }\n\n  // The form gets the color as #rrggbb, whatever the text says at that moment, and a form\n  // reset puts the color and the text back.\n  useEffect(() => {\n    const form = textRef.current!.form;\n    if (!form) return;\n    const onFormData = (event: FormDataEvent) => {\n      const input = textRef.current!;\n      if (input.name && !input.disabled) event.formData.set(input.name, color);\n    };\n    const onFormReset = () => setDraft(onReset());\n    form.addEventListener(\"formdata\", onFormData);\n    form.addEventListener(\"reset\", onFormReset);\n    return () => {\n      form.removeEventListener(\"formdata\", onFormData);\n      form.removeEventListener(\"reset\", onFormReset);\n    };\n  }, [textRef, color, onReset]);\n\n  return (\n    <div data-ouro-input-group=\"\" className={boxClass}>\n      {hasPicker ? (\n        <label className={swatchClass}>\n          <TouchTarget />\n          <input\n            type=\"color\"\n            data-ouro-control=\"color-field\"\n            data-ouro-part=\"picker\"\n            value={color}\n            aria-label={pickerLabel}\n            aria-describedby={field.describedBy}\n            disabled={disabled}\n            onChange={(event) => {\n              // Only a browser with a picker renders it, and its value is always #rrggbb.\n              const hex = hexOf(event.currentTarget.value)!;\n              setDraft(hex);\n              onPick(hex);\n            }}\n            className={pickerClass}\n          />\n        </label>\n      ) : (\n        // Without a picker the swatch only shows the color; the hex text takes it.\n        <span aria-hidden=\"true\" data-ouro-color-swatch=\"\" className={plainSwatchClass} style={{ backgroundColor: color }} />\n      )}\n      <FieldControl\n        ref={inputRef}\n        value={draft}\n        onValueChange={(text) => {\n          setDraft(text);\n          const hex = hexOf(text);\n          if (hex) onPick(hex);\n        }}\n        onBlur={() => setDraft(color)}\n        inputMode=\"text\"\n        autoComplete=\"off\"\n        autoCapitalize=\"none\"\n        spellCheck={false}\n        // A color always has a value (the form gets it from formdata), so the text is never\n        // natively required; aria-required and the label's marker still say it is.\n        render={(controlProps) => <input {...controlProps} type=\"text\" required={false} data-ouro-control=\"color-field\" data-ouro-part=\"input\" className={textClass} />}\n      />\n    </div>\n  );\n}\n\n/**\n * A color on the Field contract: a swatch that opens the system color picker, next to the\n * same color as hex text, kept in step both ways. Typing a whole hex (`#36f` or `#3366ff`)\n * moves the swatch, leaving the text tidies it, and the form always gets `#rrggbb`.\n *\n * Use `RadioGroup` instead when the colors come from a short fixed list, such as tag colors.\n *\n * @group Forms\n * @see https://ui.ouroboros.bot/docs/color-field\n *\n * @example\n * <ColorField label=\"Accent color\" name=\"accent\" defaultValue=\"#3366ff\" error={errors?.accent} />\n * <ColorField label=\"Tag color\" value={color} onValueChange={setColor} />\n * @claim \"Typing a whole hex (`#36f` or\" registry/ouro/components/ouro/color-field/color-field.test.tsx verify:testExists(registry/ouro/components/ouro/color-field/color-field.test.tsx::ColorField > moves the picker as a valid hex is typed, in any of its forms)\n * @claim \"Typing a whole hex (`#36f` or\" registry/ouro/components/ouro/color-field/color-field.test.tsx verify:testExists(registry/ouro/components/ouro/color-field/color-field.test.tsx::ColorField > tidies the text when the input loses focus, and puts back the last color when it is not a hex)\n * @claim \"Typing a whole hex (`#36f` or\" registry/ouro/components/ouro/color-field/color-field.test.tsx verify:testExists(registry/ouro/components/ouro/color-field/color-field.test.tsx::ColorField > submits the color as #rrggbb even while the text is untidy)\n */\nexport function ColorField(props: ColorFieldProps): JSX.Element {\n  const {\n    label,\n    hideLabel,\n    description,\n    error,\n    required,\n    disabled,\n    name,\n    value,\n    defaultValue,\n    onValueChange,\n    pickerLabel = \"Pick a color\",\n    className,\n    ref,\n    // Guard props (hint types), dropped here so they never reach the DOM.\n    format,\n    alpha,\n    color: colorGuess,\n    onChange,\n    errorMessage,\n    helperText,\n    isInvalid,\n    invalid,\n    isRequired,\n    isDisabled,\n  } = props;\n  useDevWarnings(\n    \"ColorField\",\n    process.env.NODE_ENV !== \"production\"\n      ? () => [\n          value !== undefined && !hexOf(value) && [`value=\"${value}\" is not a hex color`, `<ColorField value=\"${toHex(value)}\">`],\n          defaultValue !== undefined &&\n            !hexOf(defaultValue) && [`defaultValue=\"${defaultValue}\" is not a hex color`, `<ColorField defaultValue=\"${toHex(defaultValue)}\">`],\n          ...contractWarnings(\"ColorField\", { errorMessage, helperText, isInvalid, invalid, isRequired, isDisabled }),\n          format !== undefined && [\"format is not a prop; ColorField takes and gives #rrggbb\", '<ColorField defaultValue=\"#3366ff\">'],\n          alpha !== undefined && [\"alpha is not supported; ColorField takes #rrggbb\", '<ColorField defaultValue=\"#3366ff\">'],\n          colorGuess !== undefined && [\"color is not a prop\", `<ColorField defaultValue=\"${String(colorGuess)}\">`],\n          onChange !== undefined && [\"onChange is not a prop\", \"<ColorField onValueChange={(hex) => …}>\"],\n        ]\n      : /* istanbul ignore next @preserve -- production only */ undefined,\n  );\n\n  const [own, setOwn] = useState(() => hexOf(defaultValue) ?? \"#000000\");\n  const color = value !== undefined ? (hexOf(value) ?? \"#000000\") : own;\n  const pick = (hex: string) => {\n    if (value === undefined) setOwn(hex);\n    if (hex !== color) onValueChange?.(hex);\n  };\n  // A form reset puts back defaultValue; a controlled color stays the app's.\n  const reset = () => {\n    if (value !== undefined) return color;\n    const initial = hexOf(defaultValue) ?? \"#000000\";\n    pick(initial);\n    return initial;\n  };\n  const textRef = useRef<HTMLInputElement | null>(null);\n  const setRef = useMergedRef(ref, textRef);\n\n  return (\n    <FieldOwnerContext.Provider value={owner}>\n      <Field\n        label={label}\n        hideLabel={hideLabel}\n        description={description}\n        error={error}\n        required={required}\n        disabled={disabled}\n        name={name}\n        className={className}\n      >\n        <Control color={color} onPick={pick} onReset={reset} pickerLabel={pickerLabel} disabled={disabled} inputRef={setRef} textRef={textRef} />\n      </Field>\n    </FieldOwnerContext.Provider>\n  );\n}\n",
      "type": "registry:ui",
      "target": "@components/ouro/color-field/color-field.tsx"
    }
  ],
  "docs": "A color on the Field contract: a swatch that opens the system color picker, next to the same color as hex text, kept in step both ways. Import: import { ColorField } from \"@/components/ouro/color-field/color-field\", with @/components replaced by your components alias (aliases.components in components.json, such as ~/components). Also installed: field, the helpers they import in lib/ouro. Needs ouro-base in your stylesheet: add that item once per app, from the same place as this one, if you have not. Docs: https://ui.ouroboros.bot/docs/color-field.md Ouro UI v1.3.257.",
  "type": "registry:ui"
}