{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"floating-label","type":"registry:component","title":"Floating label","description":"The label peels up letter by letter, and never covers what you wrote.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/floating-label.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useId, useState } from \"react\";\nimport { motion } from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\ntype Status = \"idle\" | \"error\" | \"valid\";\n\nconst ICON_SWAP = { type: \"spring\", duration: 0.3, bounce: 0 } as const;\n// Per letter: 14ms reads as a ripple without the end of a long label\n// lagging. Past the cap every letter moves together, so no label takes\n// longer than 200ms + 8 * 14ms to land.\nconst RISE_STAGGER = 14;\n// Settling back is quicker: the field is being left, not entered.\nconst SETTLE_STAGGER = 8;\nconst STAGGER_CAP = 8;\n\nexport function FloatingLabel({\n  label,\n  type = \"text\",\n  name,\n  autoComplete,\n  defaultValue,\n  validate,\n  onValueChange,\n  className,\n}: {\n  label: string;\n  type?: \"text\" | \"email\" | \"tel\" | \"url\";\n  name?: string;\n  autoComplete?: string;\n  defaultValue?: string;\n  // Returns an error message, or null when the value is fine.\n  validate?: (value: string) => string | null;\n  onValueChange?: (value: string) => void;\n  className?: string;\n}) {\n  const id = useId();\n  const errorId = `${id}-error`;\n  const reduceMotion = useReducedMotion();\n  const [status, setStatus] = useState<Status>(\"idle\");\n  // Kept after the error clears so the message never empties while its row\n  // is still collapsing.\n  const [message, setMessage] = useState(\"\");\n  // Validation starts on blur and only follows every keystroke once the\n  // user has seen an error, so nobody is scolded for a half-typed address.\n  const [live, setLive] = useState(false);\n\n  const check = (value: string) => {\n    const error = validate?.(value) ?? null;\n    if (error) setMessage(error);\n    setStatus(error ? \"error\" : \"valid\");\n    return error;\n  };\n\n  const invalid = status === \"error\";\n  // Only flips when focus moves or the field crosses empty, never per\n  // keystroke; setState with an unchanged value skips the render.\n  const [focused, setFocused] = useState(false);\n  const [filled, setFilled] = useState(() => !!defaultValue);\n  const floated = focused || filled;\n  const letters = Array.from(label);\n\n  return (\n    <div className={cn(\"flex flex-col\", className)}>\n      <div className=\"relative\">\n        {/* placeholder=\" \" lets CSS know when the field is filled, so the\n            label floats without a re-render on every keystroke. */}\n        <input\n          id={id}\n          name={name}\n          type={type}\n          autoComplete={autoComplete}\n          defaultValue={defaultValue}\n          placeholder=\" \"\n          spellCheck={false}\n          aria-invalid={invalid || undefined}\n          aria-describedby={invalid ? errorId : undefined}\n          onFocus={() => setFocused(true)}\n          onChange={(e) => {\n            const value = e.target.value;\n            setFilled(value !== \"\");\n            onValueChange?.(value);\n            if (!validate) return;\n            if (live) check(value);\n            // A valid field stops claiming so the moment it isn't, but only\n            // turns red again on blur.\n            else if (status === \"valid\" && validate(value)) setStatus(\"idle\");\n          }}\n          onBlur={(e) => {\n            setFocused(false);\n            if (!validate) return;\n            const value = e.target.value;\n            // Tabbing past an untouched field is not a mistake.\n            if (value === \"\" && !live) return;\n            if (check(value)) setLive(true);\n          }}\n          className={cn(\n            // 22px of top padding (23px with the border) clears the floated\n            // label (7px down, 12px text in a 16px line box, so done by 23px),\n            // so typed text and label never share a pixel. A fixed 20px line\n            // height keeps that math independent of the page's leading.\n            \"peer h-13 w-full rounded-xl border bg-background pt-[22px] pr-10 pb-2 pl-3.5 text-[15px]/5 text-foreground outline-hidden transition-[border-color] duration-150 ease-out\",\n            \"focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-1\",\n            invalid\n              ? \"border-destructive focus-visible:outline-destructive\"\n              : \"border-border focus-visible:outline-foreground\",\n          )}\n        />\n        {/* The label peels off the line one letter at a time, first letter\n            first, and settles back last letter first, like a sticker lifted\n            from its corner. The whole word scales from its top left corner\n            while each letter rises on its own delay, so nothing reflows. */}\n        <label\n          htmlFor={id}\n          data-floated={floated || undefined}\n          className={cn(\n            \"group/label pointer-events-none absolute top-4 left-3.5 origin-top-left text-[15px]/5 whitespace-nowrap select-none\",\n            \"transition-[scale,color] duration-150 ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-[color]\",\n            // Centered at 16px from the top, it shrinks to 80% (12px) while\n            // its letters rise 9px, to sit 7px from the top.\n            \"data-floated:scale-[0.8] data-floated:duration-200\",\n            invalid ? \"text-destructive\" : \"text-muted-foreground peer-focus:text-foreground\",\n          )}\n        >\n          <span className=\"sr-only\">{label}</span>\n          <span aria-hidden>\n            {letters.map((letter, i) => (\n              <span\n                key={i}\n                style={{\n                  transitionDelay: `${\n                    floated\n                      ? Math.min(i, STAGGER_CAP) * RISE_STAGGER\n                      : Math.min(letters.length - 1 - i, STAGGER_CAP) *\n                        SETTLE_STAGGER\n                  }ms`,\n                }}\n                className={cn(\n                  \"inline-block whitespace-pre\",\n                  \"transition-[translate] duration-150 ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none\",\n                  // 9px on screen is 11.25px before the 0.8 scale.\n                  \"group-data-floated/label:-translate-y-[11.25px] group-data-floated/label:duration-200\",\n                )}\n              >\n                {letter}\n              </span>\n            ))}\n          </span>\n        </label>\n        <motion.svg\n          aria-hidden\n          viewBox=\"0 0 16 16\"\n          fill=\"none\"\n          stroke=\"currentColor\"\n          strokeWidth={1.5}\n          strokeLinecap=\"round\"\n          strokeLinejoin=\"round\"\n          className=\"pointer-events-none absolute top-4 right-3.5 size-5 text-foreground\"\n          initial={false}\n          animate={\n            status === \"valid\"\n              ? { scale: 1, opacity: 1, filter: \"blur(0px)\" }\n              : reduceMotion\n                ? { scale: 1, opacity: 0, filter: \"blur(0px)\" }\n                : { scale: 0.25, opacity: 0, filter: \"blur(4px)\" }\n          }\n          transition={ICON_SWAP}\n        >\n          <path d=\"m3.5 8.5 3 3 6-7\" />\n        </motion.svg>\n      </div>\n\n      {/* Grid rows from 0fr to 1fr give a real height transition without\n          measuring. Opens in 200ms, closes in 150ms. */}\n      <div\n        className={cn(\n          \"grid transition-[grid-template-rows] ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none\",\n          invalid\n            ? \"grid-rows-[1fr] duration-200\"\n            : \"grid-rows-[0fr] duration-150\",\n        )}\n      >\n        <div className=\"min-h-0 overflow-hidden\">\n          <p\n            id={errorId}\n            aria-hidden={!invalid}\n            className={cn(\n              \"pt-2 pl-3.5 text-sm text-destructive transition-[opacity,translate] ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-[opacity]\",\n              invalid\n                ? \"translate-y-0 opacity-100 duration-200\"\n                : \"-translate-y-1 opacity-0 duration-150 motion-reduce:translate-y-0\",\n            )}\n          >\n            {message}\n          </p>\n        </div>\n      </div>\n      {/* Blur moves focus away, so the error needs its own announcement. */}\n      <span className=\"sr-only\" aria-live=\"polite\">\n        {invalid ? message : \"\"}\n      </span>\n    </div>\n  );\n}\n\n// Deliberately loose: the server is the real judge of an address.\nfunction validateEmail(value: string) {\n  const email = value.trim();\n  if (email === \"\") return \"Enter your email address.\";\n  if (!/^[^\\s@]+@[^\\s@]+\\.[^\\s@]{2,}$/.test(email))\n    return \"That doesn't look like an email address.\";\n  return null;\n}\n\nexport default function FloatingLabelDemo() {\n  return (\n    <form\n      className=\"flex w-[380px] max-w-full flex-col gap-4\"\n      noValidate\n      onSubmit={(e) => e.preventDefault()}\n    >\n      <FloatingLabel label=\"Full name\" name=\"name\" autoComplete=\"name\" />\n      <FloatingLabel\n        label=\"Email address\"\n        type=\"email\"\n        name=\"email\"\n        autoComplete=\"email\"\n        validate={validateEmail}\n      />\n    </form>\n  );\n}\n"},{"path":"hooks/use-reduced-motion.ts","type":"registry:hook","target":"hooks/use-reduced-motion.ts","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\n// Motion's useReducedMotion reads the media query on the very first client\n// render, but the server can't know it, so every component that renders\n// differently under reduced motion broke hydration for those users. This\n// reports false during hydration, matching the server HTML, then the real\n// preference straight after, and follows it if it changes.\nconst query = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribe(onChange: () => void) {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n"}],"categories":["inputs"],"docs":"From ui lab: https://lab.xevrion.dev/lab/floating-label"}