{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "px-input",
  "title": "Text field",
  "description": "Labelled form text field whose underline lights from the caret outwards; validation on blur shakes on error or draws a check.",
  "registryDependencies": [
    "https://elements.lumesec.ai/r/lumesec-theme.json",
    "https://elements.lumesec.ai/r/lumesec-math.json",
    "https://elements.lumesec.ai/r/lumesec-motion.json",
    "https://elements.lumesec.ai/r/lumesec-pixel-canvas.json",
    "https://elements.lumesec.ai/r/lumesec-pixel-font.json",
    "https://elements.lumesec.ai/r/lumesec-roll-text.json",
    "https://elements.lumesec.ai/r/lumesec-use-controllable-state.json",
    "utils"
  ],
  "files": [
    {
      "path": "registry/components/lumesec/px-input.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\n\nimport { clamp, lerp, mixRgb, rand } from \"@/lib/lumesec/math\";\nimport { prefersReducedMotion, shake } from \"@/lib/lumesec/motion\";\nimport { usePixelCanvas } from \"@/lib/lumesec/pixel-canvas\";\nimport { SMALL_ALERT, SMALL_CHECK } from \"@/lib/lumesec/pixel-font\";\nimport { RollText } from \"@/lib/lumesec/roll-text\";\nimport { useControllableState, useFormReset } from \"@/lib/lumesec/use-controllable-state\";\nimport { cn } from \"@/lib/utils\";\n\n/** Result of the last blur validation: not validated (or empty and optional), valid, or invalid. */\nexport type PxInputValidation = \"idle\" | \"ok\" | \"error\";\n\n/** Imperative handle of `PxInput`. */\nexport interface PxInputHandle {\n  /** Move focus into the text field. */\n  focus(): void;\n}\n\n/** Props of `PxInput`. Other `div` props go to the wrapper; the input's own attributes are the props below. */\nexport interface PxInputProps extends Omit<\n  React.ComponentProps<\"div\">,\n  \"ref\" | \"children\" | \"defaultValue\" | \"onChange\" | \"inputMode\" | \"spellCheck\"\n> {\n  /** Controlled text. Use with `onValueChange`. */\n  value?: string;\n  /** Initial text when uncontrolled; also restored on form reset. */\n  defaultValue?: string;\n  /** Called with the new text on every edit. */\n  onValueChange?: (value: string) => void;\n  /** Called when the input commits a change: on blur after editing, like the native `change` event. */\n  onValueCommit?: (value: string) => void;\n  /** Label text, linked to the input. No label is rendered when empty. */\n  label?: React.ReactNode;\n  /** Help text under the field, shown when there is no error. */\n  hint?: string;\n  /** Message shown, and used as the validation message, when the value is invalid. Defaults to the browser's message. */\n  error?: string;\n  /** Message shown when a valid value is confirmed on blur. Falls back to `hint`. */\n  success?: string;\n  /** Form field name. */\n  name?: string;\n  /** Input type, for example `email`, `url` or `tel`. */\n  type?: React.HTMLInputTypeAttribute;\n  /** Placeholder text. */\n  placeholder?: string;\n  /** An empty field is invalid. */\n  required?: boolean;\n  /** Pattern the value must match; checked during validation. */\n  pattern?: string;\n  /** Minimum length; checked during validation. */\n  minLength?: number;\n  /** Maximum length. */\n  maxLength?: number;\n  /** Autofill hint for the input. */\n  autoComplete?: React.InputHTMLAttributes<HTMLInputElement>[\"autoComplete\"];\n  /** Virtual keyboard hint for the input. */\n  inputMode?: React.InputHTMLAttributes<HTMLInputElement>[\"inputMode\"];\n  /** Spell checking of the input. */\n  spellCheck?: boolean;\n  /** Dims the field and disables the input, so it cannot be edited, reached with Tab or submitted. */\n  disabled?: boolean;\n  /** Imperative handle with `focus()`. */\n  ref?: React.Ref<PxInputHandle>;\n}\n\n/**\n * Labelled text field whose pixel underline lights from the caret outwards. Validation runs on blur: an\n * invalid value shakes the field and shows a `!`, a valid one draws a check. Once an error shows, the\n * field re-validates on every keystroke. The native input takes part in forms and constraint validation.\n *\n * @example\n * <PxInput\n *   name=\"email\"\n *   label=\"Work email\"\n *   type=\"email\"\n *   required\n *   placeholder=\"you@example.com\"\n *   hint=\"We’ll send the invite here\"\n *   error=\"Enter a valid email address\"\n * />\n */\nexport function PxInput({\n  value: valueProp,\n  defaultValue = \"\",\n  onValueChange,\n  onValueCommit,\n  label,\n  hint,\n  error,\n  success,\n  name,\n  type = \"text\",\n  placeholder,\n  required,\n  pattern,\n  minLength,\n  maxLength,\n  autoComplete,\n  inputMode,\n  spellCheck,\n  disabled = false,\n  className,\n  ref,\n  ...props\n}: PxInputProps) {\n  const inputId = React.useId();\n  const messageId = `${inputId}-message`;\n  const inputRef = React.useRef<HTMLInputElement>(null);\n  const fieldRef = React.useRef<HTMLDivElement>(null);\n  const [value, setValue] = useControllableState({ value: valueProp, defaultValue, onChange: onValueChange });\n  const [validation, setValidation] = React.useState<PxInputValidation>(\"idle\");\n  /** The browser's own message from the last validation, shown when there is no `error` text. */\n  const [browserMessage, setBrowserMessage] = React.useState(\"\");\n\n  // animation state: how far the underline is lit, where the caret was, and the error jitter\n  const spread = React.useRef(0);\n  const caret = React.useRef(0.5);\n  const jitter = React.useRef(0);\n\n  const onCommitRef = React.useRef(onValueCommit);\n  const errorRef = React.useRef(error);\n  React.useEffect(() => {\n    onCommitRef.current = onValueCommit;\n    errorRef.current = error;\n  });\n\n  const { ref: canvasRef, redraw } = usePixelCanvas(({ clear, dot, palette, width, height, delta }) => {\n    const reduced = prefersReducedMotion();\n    const focused = document.activeElement === inputRef.current;\n    const target = focused || validation !== \"idle\" ? 1 : 0;\n    spread.current = reduced ? target : spread.current + clamp(target - spread.current, -delta * 3, delta * 4);\n    jitter.current = Math.max(0, jitter.current - delta * 2.5);\n    const color = validation === \"error\" ? palette.destructive : validation === \"ok\" ? palette.success : palette.accent;\n    clear();\n    const y = height - 4;\n    const x0 = 10;\n    const x1 = width - 10;\n    const caretX = lerp(x0, x1, caret.current);\n    for (let x = x0; x < x1; x += 3) {\n      const distance = Math.abs(x - caretX) / (x1 - x0);\n      const lit = distance < spread.current * 1.05;\n      const edge = lit && distance > spread.current - 0.08;\n      const offset = jitter.current && !reduced ? rand(-1.5, 1.5) * jitter.current : 0;\n      const tone = lit ? mixRgb(color, palette.shine, edge && spread.current < 1 ? 0.6 : 0) : palette.foreground;\n      dot(x, y + offset, tone, lit ? 0.95 : 0.1, 2);\n    }\n    if (validation === \"ok\") {\n      for (const [px, py] of SMALL_CHECK)\n        dot(width - 26 + px * 2, height / 2 - 5 + py * 2, palette.success, Math.min(1, spread.current), 2);\n    }\n    if (validation === \"error\") {\n      for (const [px, py] of SMALL_ALERT)\n        dot(width - 20 + px * 1.8, height / 2 - 6 + py * 1.8, palette.destructive, 1, 1.5);\n    }\n    return Math.abs(spread.current - target) > 0.001 || jitter.current > 0;\n  });\n\n  /** Mirror the input's constraints with the `error` text as the message the browser shows on submit. */\n  const syncValidity = React.useCallback(() => {\n    const input = inputRef.current;\n    if (!input) return;\n    input.setCustomValidity(\"\");\n    if (!input.validity.valid && errorRef.current) input.setCustomValidity(errorRef.current);\n  }, []);\n\n  /** Show the result of validating the current text. Returns whether it is valid. */\n  const validate = (announce: boolean) => {\n    const input = inputRef.current;\n    if (!input) return true;\n    syncValidity();\n    const next: PxInputValidation = !input.value && !input.required ? \"idle\" : input.validity.valid ? \"ok\" : \"error\";\n    if (next === \"error\" && validation !== \"error\" && announce) {\n      shake(fieldRef.current);\n      jitter.current = 1;\n    }\n    setValidation(next);\n    setBrowserMessage(input.validationMessage);\n    redraw();\n    return next !== \"error\";\n  };\n\n  // re-sync whenever the value or a constraint changes\n  React.useEffect(syncValidity, [value, error, required, pattern, minLength, maxLength, type, syncValidity]);\n  React.useEffect(redraw, [validation, redraw]);\n\n  // the native change event (commit on blur) has no React equivalent\n  React.useEffect(() => {\n    const input = inputRef.current;\n    if (!input) return;\n    const commit = () => onCommitRef.current?.(input.value);\n    input.addEventListener(\"change\", commit);\n    return () => input.removeEventListener(\"change\", commit);\n  }, []);\n\n  useFormReset(inputRef, () => {\n    setValue(defaultValue);\n    setValidation(\"idle\");\n    redraw();\n  });\n\n  React.useImperativeHandle(ref, () => ({ focus: () => inputRef.current?.focus() }), []);\n\n  /** Caret position as a share of the field width, so the underline lights from there. */\n  const caretFraction = () => {\n    const input = inputRef.current;\n    const canvas = canvasRef.current;\n    const context = canvas?.getContext(\"2d\");\n    if (!input || !canvas || !context || !canvas.clientWidth) return 0.5;\n    context.font = `14px ${getComputedStyle(input).fontFamily}`;\n    const textWidth = context.measureText(input.value.slice(0, input.selectionStart ?? input.value.length)).width;\n    return clamp((12 + textWidth) / canvas.clientWidth, 0, 1);\n  };\n\n  const message =\n    validation === \"error\" ? error || browserMessage : validation === \"ok\" ? success || hint || \"\" : hint || \"\";\n\n  return (\n    <div\n      data-slot=\"px-input\"\n      data-state={validation === \"idle\" ? undefined : validation}\n      data-disabled={disabled ? \"\" : undefined}\n      className={cn(\"block leading-[1.5] text-foreground\", disabled && \"pointer-events-none opacity-55\", className)}\n      {...props}\n    >\n      {label ? (\n        <label htmlFor={inputId} className=\"mb-1.5 block text-[12.5px] font-medium\">\n          {label}\n        </label>\n      ) : null}\n      <div\n        ref={fieldRef}\n        className={cn(\n          \"relative flex h-[42px] items-center gap-2 rounded-[10px] border bg-card px-3 transition-[border-color,box-shadow] duration-200 ease-[ease]\",\n          validation === \"error\"\n            ? \"border-[color-mix(in_srgb,var(--destructive)_65%,var(--border))] ring-[3px] ring-destructive/12\"\n            : \"border-border focus-within:border-[color-mix(in_srgb,var(--lumesec)_65%,var(--border))] focus-within:ring-[3px] focus-within:ring-lumesec/14\",\n        )}\n      >\n        <input\n          ref={inputRef}\n          id={inputId}\n          name={name}\n          type={type}\n          placeholder={placeholder}\n          required={required}\n          pattern={pattern}\n          minLength={minLength}\n          maxLength={maxLength}\n          autoComplete={autoComplete}\n          inputMode={inputMode}\n          spellCheck={spellCheck}\n          disabled={disabled}\n          value={value}\n          aria-invalid={validation === \"error\" || undefined}\n          aria-describedby={message ? messageId : undefined}\n          onChange={(event) => {\n            setValue(event.target.value);\n            if (validation === \"error\") validate(false);\n            else syncValidity();\n            redraw();\n          }}\n          onFocus={() => {\n            caret.current = caretFraction();\n            redraw();\n          }}\n          onBlur={() => validate(true)}\n          className=\"h-full min-w-0 flex-1 border-0 bg-transparent p-0 pr-[18px] font-[inherit] text-[14px] text-inherit outline-none placeholder:text-muted-foreground placeholder:opacity-75\"\n        />\n        <canvas\n          ref={canvasRef}\n          aria-hidden=\"true\"\n          className=\"pointer-events-none absolute inset-0 block size-full rounded-[10px] [image-rendering:pixelated]\"\n        />\n      </div>\n      <span\n        id={messageId}\n        className={cn(\n          \"mt-1.5 block min-h-[1.45em] text-[12px] text-muted-foreground\",\n          validation === \"error\" && \"text-destructive\",\n          validation === \"ok\" && \"text-lumesec-success\",\n        )}\n      >\n        {/* long messages (the browser's own validation text) wrap instead of running past the field */}\n        <RollText\n          text={message}\n          direction={validation === \"error\" ? 1 : -1}\n          aria-live=\"polite\"\n          className=\"max-w-full [&>span]:whitespace-normal\"\n        />\n      </span>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "@components/lumesec/px-input.tsx"
    }
  ],
  "meta": {
    "tag": "px-input",
    "collection": "pixel-ui",
    "react": "PxInput",
    "kind": "react"
  },
  "docs": "Text field docs: https://elements.lumesec.ai/components/pixel-ui/input",
  "categories": [
    "pixel-ui",
    "forms"
  ],
  "type": "registry:component"
}