{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"caps-lock-warning","type":"registry:component","title":"Caps lock warning","description":"A small caps lock key with its light on slides into the field when caps is on.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/caps-lock-warning.tsx","type":"registry:component","content":"\"use client\";\n\nimport {\n  useEffect,\n  useId,\n  useRef,\n  useState,\n  type KeyboardEvent,\n  type PointerEvent,\n} from \"react\";\nimport { motion } from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\nimport { usePreviewPlay } from \"@/lib/preview-play\";\n\nconst ICON_SWAP = { type: \"spring\", duration: 0.3, bounce: 0 } as const;\n\nexport function CapsLockPasswordField({\n  label = \"Password\",\n  name = \"password\",\n  autoComplete = \"current-password\",\n  capsLock,\n  className,\n}: {\n  label?: string;\n  name?: string;\n  autoComplete?: string;\n  /** Caps Lock state tracked elsewhere (say, app-wide). When set, it\n   * replaces the field's own detection and shows without focus. */\n  capsLock?: boolean;\n  className?: string;\n}) {\n  const id = useId();\n  const hintId = `${id}-caps`;\n  const reduceMotion = useReducedMotion();\n  const [caps, setCaps] = useState(false);\n  const [focused, setFocused] = useState(false);\n  const [shown, setShown] = useState(false);\n\n  // Every key and pointer event carries the lock state, including the\n  // Caps Lock key's own events, so the field stays right without polling.\n  const read = (e: KeyboardEvent | PointerEvent) => {\n    const on = e.getModifierState(\"CapsLock\");\n    setCaps((prev) => (prev === on ? prev : on));\n  };\n\n  // Only while typing here: a warning for a field you aren't in is noise.\n  const warn = capsLock ?? (caps && focused);\n\n  return (\n    <div className={cn(\"grid w-[min(320px,100%)] gap-1.5\", className)}>\n      <label htmlFor={id} className=\"text-sm font-medium text-foreground\">\n        {label}\n      </label>\n      <div className=\"relative\">\n        <input\n          id={id}\n          name={name}\n          type={shown ? \"text\" : \"password\"}\n          autoComplete={autoComplete}\n          spellCheck={false}\n          aria-describedby={warn ? hintId : undefined}\n          onKeyDown={read}\n          onKeyUp={read}\n          onPointerDown={read}\n          onFocus={() => setFocused(true)}\n          onBlur={() => setFocused(false)}\n          // Right padding is fixed for both the keycap and the button, so\n          // the text never shifts when the keycap arrives.\n          className=\"h-10 w-full rounded-lg border border-border bg-background pr-[84px] pl-3 text-[15px] text-foreground shadow-[0_1px_2px_oklch(0_0_0/0.04)] outline-hidden transition-[border-color,box-shadow] duration-150 ease-out placeholder:text-muted-foreground focus-visible:border-foreground/40 focus-visible:shadow-[0_0_0_3px_color-mix(in_oklch,var(--foreground)_10%,transparent)]\"\n        />\n\n        <div className=\"pointer-events-none absolute inset-y-0 right-10 flex items-center\">\n          <motion.span\n            aria-hidden\n            initial={false}\n            animate={\n              warn\n                ? {\n                    opacity: 1,\n                    x: 0,\n                    filter: \"blur(0px)\",\n                    transition: { type: \"spring\", duration: 0.35, bounce: 0.15 },\n                  }\n                : {\n                    opacity: 0,\n                    x: reduceMotion ? 0 : 8,\n                    filter: reduceMotion ? \"blur(0px)\" : \"blur(3px)\",\n                    // Leaves quicker and without the bounce.\n                    transition: { duration: 0.15, ease: [0.23, 1, 0.32, 1] },\n                  }\n            }\n            className=\"relative flex h-[22px] w-[30px] flex-col justify-between rounded-[5px] border border-border bg-background px-[4px] pt-[3px] pb-[3px] shadow-[0_2px_0_0_var(--border)] dark:bg-muted\"\n          >\n            <span\n              className={cn(\n                \"block size-[4px] rounded-full transition-[background-color,box-shadow] duration-300 ease-out\",\n                // The LED is lit hardware, so it is a raw green: it means\n                // \"on\" in both themes, like the light on a real keyboard.\n                warn\n                  ? \"bg-[#30d158] shadow-[0_0_4px_1px_#30d15888]\"\n                  : \"bg-border\",\n              )}\n            />\n            {/* The caps lock glyph: an outlined up arrow over a bar. */}\n            <svg\n              viewBox=\"0 0 12 10\"\n              className=\"h-[9px] w-[11px] self-center text-foreground/70\"\n              fill=\"none\"\n              stroke=\"currentColor\"\n              strokeWidth={1.1}\n              strokeLinejoin=\"round\"\n              strokeLinecap=\"round\"\n            >\n              <path d=\"M6 1 2 5h2v1.5h4V5h2L6 1Z\" />\n              <path d=\"M4 8.75h4\" />\n            </svg>\n          </motion.span>\n        </div>\n\n        <button\n          type=\"button\"\n          aria-label={shown ? \"Hide password\" : \"Show password\"}\n          aria-controls={id}\n          aria-pressed={shown}\n          onClick={() => setShown((s) => !s)}\n          // Keeps focus in the field so the caret and caps state survive.\n          onPointerDown={(e) => e.preventDefault()}\n          className=\"absolute top-1 right-1 flex size-8 touch-manipulation items-center justify-center rounded-md text-muted-foreground outline-hidden transition-[scale,color,background-color] duration-150 ease-out hover:bg-muted hover:text-foreground focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-foreground active:scale-[0.96]\"\n        >\n          <span className=\"grid\" aria-hidden>\n            <EyeGlyph visible={!shown} reduceMotion={reduceMotion} slash={false} />\n            <EyeGlyph visible={shown} reduceMotion={reduceMotion} slash />\n          </span>\n        </button>\n      </div>\n\n      {/* Fixed-height row so the form never jumps when the hint appears. */}\n      <p id={hintId} className=\"relative h-5 text-[13px] text-muted-foreground\">\n        {/* Visible text never empties, so it can fade out whole. */}\n        <span\n          aria-hidden\n          className={cn(\n            \"absolute inset-0 transition-[opacity,filter,translate] ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-[opacity]\",\n            warn\n              ? \"translate-y-0 opacity-100 filter-none duration-200\"\n              : \"-translate-y-0.5 opacity-0 blur-[2px] duration-150 motion-reduce:translate-y-0 motion-reduce:filter-none\",\n          )}\n        >\n          Caps Lock is on\n        </span>\n        <span className=\"sr-only\" aria-live=\"polite\">\n          {warn ? \"Caps Lock is on\" : \"\"}\n        </span>\n      </p>\n    </div>\n  );\n}\n\nfunction EyeGlyph({\n  visible,\n  slash,\n  reduceMotion,\n}: {\n  visible: boolean;\n  slash: boolean;\n  reduceMotion: boolean | null;\n}) {\n  return (\n    <motion.svg\n      viewBox=\"0 0 16 16\"\n      className=\"col-start-1 row-start-1 size-4\"\n      fill=\"none\"\n      stroke=\"currentColor\"\n      strokeWidth={1.5}\n      strokeLinecap=\"round\"\n      strokeLinejoin=\"round\"\n      initial={false}\n      animate={\n        visible\n          ? { opacity: 1, scale: 1, filter: \"blur(0px)\" }\n          : reduceMotion\n            ? { opacity: 0 }\n            : { opacity: 0, scale: 0.25, filter: \"blur(4px)\" }\n      }\n      transition={ICON_SWAP}\n    >\n      <path d=\"M1.5 8S4 3.5 8 3.5 14.5 8 14.5 8 12 12.5 8 12.5 1.5 8 1.5 8Z\" />\n      <circle cx=\"8\" cy=\"8\" r=\"2\" />\n      {slash && <path d=\"m2.5 2.5 11 11\" />}\n    </motion.svg>\n  );\n}\n\n// Index card hover: someone types a password, hits Caps Lock partway\n// through, sees the key light up, turns it off and carries on. Times are ms\n// from the start of each run.\nconst SCRIPT: [number, string | boolean][] = [\n  [300, \"s\"], [420, \"u\"], [540, \"n\"],\n  [900, true],\n  [1250, \"S\"], [1370, \"E\"], [1490, \"T\"],\n  [2400, false],\n  [2750, \"4\"], [2870, \"2\"],\n];\nconst RUN_MS = 5200;\nconst ERASE_AT = 3900;\n// Held backspace speed.\nconst ERASE_STEP = 45;\n\nexport default function CapsLockWarningDemo() {\n  const play = usePreviewPlay();\n  const wrap = useRef<HTMLDivElement>(null);\n  const [caps, setCaps] = useState(false);\n  const erase = useRef<ReturnType<typeof setInterval>>(undefined);\n\n  useEffect(() => {\n    if (!play) return;\n    const input = wrap.current?.querySelector(\"input\");\n    if (!input) return;\n    // Typed straight into the DOM: the field is uncontrolled, and a preview\n    // never takes focus or touches real keys.\n    const eraseAll = () => {\n      clearInterval(erase.current);\n      erase.current = setInterval(() => {\n        input.value = input.value.slice(0, -1);\n        if (!input.value) clearInterval(erase.current);\n      }, ERASE_STEP);\n    };\n    clearInterval(erase.current);\n    input.value = \"\";\n    let timers: ReturnType<typeof setTimeout>[] = [];\n    const run = () => {\n      timers = SCRIPT.map(([at, step]) =>\n        setTimeout(() => {\n          if (typeof step === \"boolean\") setCaps(step);\n          else input.value += step;\n        }, at),\n      );\n      timers.push(setTimeout(eraseAll, ERASE_AT), setTimeout(run, RUN_MS));\n    };\n    run();\n    return () => {\n      timers.forEach(clearTimeout);\n      // Unhovered: let go the way a person would, not all at once.\n      setCaps(false);\n      if (input.value) eraseAll();\n    };\n  }, [play]);\n\n  useEffect(() => () => clearInterval(erase.current), []);\n\n  return (\n    <div ref={wrap} className=\"contents\">\n      <CapsLockPasswordField capsLock={play ? caps : undefined} />\n    </div>\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"},{"path":"lib/preview-play.ts","type":"registry:lib","target":"lib/preview-play.ts","content":"\"use client\";\n\nimport { createContext, useContext } from \"react\";\n\n// Lets a demo know whether it's showing in an index card, and whether that\n// card is hovered or focused. Demos use it to act themselves out on hover:\n// a star button stars itself, a checkbox scribbles, and so on.\n//\n// null: not in a preview (the component's own page, or real use).\n// false: in a preview, at rest.\n// true: in a preview, being hovered or focused: play the show.\nexport const PreviewPlayContext = createContext<boolean | null>(null);\n\nexport function usePreviewPlay() {\n  return useContext(PreviewPlayContext);\n}\n"}],"categories":["inputs"],"docs":"From ui lab: https://lab.xevrion.dev/lab/caps-lock-warning"}