{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"card-number-reveal","type":"registry:component","title":"Card number reveal","description":"Rolls the hidden digits in when you press the eye, then hides them again when the ring runs out.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/card-number-reveal.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useRef, useState } from \"react\";\nimport { animate, motion, useMotionValue, useTransform } from \"motion/react\";\nimport { usePreviewPlay } from \"@/lib/preview-play\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\n// After Nitish Khagwal's card number reveal (https://x.com/nitishkmrk): the\n// number stays masked until you press the eye, the eye turns into the\n// copy button, and a ring around it runs down until the number hides again.\n\ntype State = \"masked\" | \"shown\" | \"copied\";\n\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\n// Each hidden digit rolls a beat after the one before it, so the number\n// reads as being written out left to right rather than switched on.\nconst STAGGER = 0.03;\nconst ROLL_IN = { duration: 0.32, ease: EASE_OUT };\n// Leaving is quicker and softer than arriving.\nconst ROLL_OUT = { duration: 0.2, ease: EASE_OUT };\n// Long enough to read sixteen digits and copy them, short enough that a\n// number left on screen puts itself away.\nconst SHOWN_FOR = 5000;\n// How long the check holds before the number hides.\nconst COPIED_FOR = 1200;\n// How much of the number stays visible at each end.\nconst KEEP = 4;\n\nexport function CardNumberReveal({\n  number,\n  shownFor = SHOWN_FOR,\n  className,\n}: {\n  number: string;\n  shownFor?: number;\n  className?: string;\n}) {\n  const reduceMotion = useReducedMotion();\n  const play = usePreviewPlay();\n  const [own, setOwn] = useState<State>(\"masked\");\n  // The index card acts the whole thing out on its own state, so a show\n  // never leaves the real one half revealed.\n  const [show, setShow] = useState<State>(\"masked\");\n  const state = play ? show : own;\n  const shown = state !== \"masked\";\n\n  const digits = number.replace(/\\D/g, \"\");\n  const groups = digits.match(/.{1,4}/g) ?? [];\n  const last = digits.slice(-KEEP);\n\n  const ring = useMotionValue(1);\n  const ringOpacity = useTransform(ring, [0, 0.02], [0, 1]);\n  const numberRef = useRef<HTMLSpanElement>(null);\n\n  // Shown: the ring runs down, then the number hides. Copied: the check\n  // holds for a moment, then the same.\n  useEffect(() => {\n    const set = play ? setShow : setOwn;\n    if (state === \"shown\") {\n      ring.jump(1);\n      const controls = animate(ring, 0, {\n        duration: shownFor / 1000,\n        ease: \"linear\",\n        onComplete: () => set(\"masked\"),\n      });\n      // A soft light passes over the digits once they've landed, the moment\n      // the number reads as whole.\n      const glint = reduceMotion\n        ? undefined\n        : numberRef.current?.animate(\n            [{ maskPosition: \"100% 0\" }, { maskPosition: \"0% 0\" }],\n            {\n              duration: 900,\n              delay: (KEEP * 2 * STAGGER + ROLL_IN.duration) * 1000,\n              easing: \"cubic-bezier(0.65, 0, 0.35, 1)\",\n            },\n          );\n      return () => {\n        controls.stop();\n        glint?.cancel();\n      };\n    }\n    if (state === \"copied\") {\n      const timer = setTimeout(() => set(\"masked\"), COPIED_FOR);\n      return () => clearTimeout(timer);\n    }\n  }, [state, play, shownFor, reduceMotion, ring]);\n\n  // The card's show: someone reaches for the eye, copies, and lets it hide.\n  // It never touches the clipboard.\n  useEffect(() => {\n    if (!play) return;\n    const timers: ReturnType<typeof setTimeout>[] = [];\n    const loop = () => {\n      timers.push(setTimeout(() => setShow(\"shown\"), 500));\n      timers.push(setTimeout(() => setShow(\"copied\"), 2300));\n      timers.push(setTimeout(loop, 4600));\n    };\n    loop();\n    return () => {\n      timers.forEach(clearTimeout);\n      setShow(\"masked\");\n    };\n  }, [play]);\n\n  const reveal = () => setOwn(\"shown\");\n\n  const copy = async () => {\n    // Confirm on press: the write is near instant, and waiting for it makes\n    // the click feel ignored.\n    setOwn(\"copied\");\n    try {\n      await navigator.clipboard.writeText(digits);\n    } catch {\n      setOwn(\"shown\");\n    }\n  };\n\n  let hidden = -1;\n\n  return (\n    <div\n      className={cn(\n        // 10px around the 40px button keeps the radii concentric (22 = 12 +\n        // 10) and leaves room for the ring that sits outside it.\n        \"flex h-[60px] max-w-full items-center gap-5 rounded-[22px] bg-background pr-2.5 pl-6 shadow-raised\",\n        className,\n      )}\n    >\n      <span className=\"sr-only\">\n        {shown\n          ? `Card number ${groups.join(\" \")}`\n          : `Card number ending in ${last}`}\n      </span>\n      <span\n        ref={numberRef}\n        aria-hidden\n        // The glint is a dimmer band in a mask three times the width of the\n        // number, slid across it once. At rest the band sits off the end.\n        className=\"flex gap-[0.45em] text-[20px] font-medium tracking-[0.02em] whitespace-nowrap tabular-nums [mask-image:linear-gradient(90deg,black_40%,rgb(0_0_0/0.25)_50%,black_60%)] [mask-position:100%_0] [mask-size:300%_100%]\"\n      >\n        {groups.map((group, g) => (\n          <span key={g} className=\"flex\">\n            {[...group].map((digit, d) => {\n              const index = g * 4 + d;\n              const masked = index >= KEEP && index < digits.length - KEEP;\n              if (!masked) return <span key={d}>{digit}</span>;\n              hidden += 1;\n              return (\n                <Rolling\n                  key={d}\n                  digit={digit}\n                  shown={shown}\n                  delay={hidden * STAGGER}\n                  reduceMotion={reduceMotion}\n                />\n              );\n            })}\n          </span>\n        ))}\n      </span>\n\n      <span className=\"relative shrink-0\">\n        {/* The countdown, drawn around the button from the top centre, 5px\n            out so it reads as a ring around it rather than its border. */}\n        <motion.svg\n          aria-hidden\n          viewBox=\"0 0 50 50\"\n          className=\"pointer-events-none absolute -inset-[5px] size-[50px] text-green-500\"\n          initial={false}\n          animate={{ opacity: state === \"shown\" ? 1 : 0 }}\n          transition={{ duration: 0.15 }}\n        >\n          <motion.path\n            d=\"M25 1H33A16 16 0 0 1 49 17V33A16 16 0 0 1 33 49H17A16 16 0 0 1 1 33V17A16 16 0 0 1 17 1Z\"\n            fill=\"none\"\n            stroke=\"currentColor\"\n            strokeWidth={2}\n            strokeLinecap=\"round\"\n            style={{ pathLength: ring, opacity: ringOpacity }}\n          />\n        </motion.svg>\n        <button\n          type=\"button\"\n          aria-label={\n            state === \"masked\"\n              ? \"Show card number\"\n              : state === \"shown\"\n                ? \"Copy card number\"\n                : \"Copied\"\n          }\n          // A press reveals and a second press copies. Never on hover: a card\n          // number shouldn't show just because the cursor passed over it.\n          onClick={() => {\n            if (own === \"masked\") reveal();\n            else if (own === \"shown\") copy();\n          }}\n          // Green is the one accent: it means the number is out and safe to\n          // take, and solid green means it's taken.\n          className={cn(\n            \"relative grid size-10 touch-manipulation place-items-center rounded-[12px] outline-hidden transition-[background-color,color,scale] duration-200 ease-out focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-[6px] focus-visible:outline-foreground active:scale-[0.96] motion-reduce:transition-[background-color,color]\",\n            state === \"masked\" &&\n              \"bg-muted text-foreground hover:bg-foreground/10\",\n            state === \"shown\" &&\n              \"bg-green-500/15 text-green-600 dark:text-green-400\",\n            state === \"copied\" && \"bg-green-500 text-white\",\n          )}\n        >\n          <span aria-hidden className=\"grid\">\n            <Glyph on={state === \"masked\"} reduceMotion={reduceMotion}>\n              <path d=\"M1.75 8s2.25-4.5 6.25-4.5S14.25 8 14.25 8 12 12.5 8 12.5 1.75 8 1.75 8Z\" />\n              <circle cx=\"8\" cy=\"8\" r=\"2\" />\n            </Glyph>\n            <Glyph on={state === \"shown\"} reduceMotion={reduceMotion}>\n              <rect x=\"5.25\" y=\"5.25\" width=\"8\" height=\"8\" rx=\"1.75\" />\n              <path d=\"M10.75 5.25V4.5A1.75 1.75 0 0 0 9 2.75H4.5A1.75 1.75 0 0 0 2.75 4.5V9a1.75 1.75 0 0 0 1.75 1.75h.75\" />\n            </Glyph>\n            <Glyph on={state === \"copied\"} reduceMotion={reduceMotion}>\n              <path d=\"m3.5 8.5 3 3 6-7\" />\n            </Glyph>\n          </span>\n        </button>\n      </span>\n\n      <span className=\"sr-only\" aria-live=\"polite\">\n        {state === \"shown\"\n          ? \"Card number shown\"\n          : state === \"copied\"\n            ? \"Card number copied\"\n            : \"\"}\n      </span>\n    </div>\n  );\n}\n\n// One hidden digit: the cross and the digit share a cell, and whichever is\n// arriving drops in from above while the other falls out below.\nfunction Rolling({\n  digit,\n  shown,\n  delay,\n  reduceMotion,\n}: {\n  digit: string;\n  shown: boolean;\n  delay: number;\n  reduceMotion: boolean;\n}) {\n  const arrive = reduceMotion\n    ? { opacity: 1 }\n    : {\n        opacity: 1,\n        y: [\"-0.6em\", \"0em\"],\n        filter: [\"blur(4px)\", \"blur(0px)\"],\n      };\n  const leave = reduceMotion\n    ? { opacity: 0 }\n    : { opacity: 0, y: \"0.6em\", filter: \"blur(4px)\" };\n  const fade = { duration: 0.15 };\n  return (\n    <span className=\"inline-grid w-[1ch] justify-items-center\">\n      <motion.span\n        className=\"col-start-1 row-start-1\"\n        initial={false}\n        animate={shown ? arrive : leave}\n        transition={\n          reduceMotion ? fade : { ...(shown ? ROLL_IN : ROLL_OUT), delay }\n        }\n      >\n        {digit}\n      </motion.span>\n      <motion.span\n        className=\"col-start-1 row-start-1 text-muted-foreground\"\n        initial={false}\n        animate={shown ? leave : arrive}\n        transition={\n          reduceMotion ? fade : { ...(shown ? ROLL_OUT : ROLL_IN), delay }\n        }\n      >\n        ×\n      </motion.span>\n    </span>\n  );\n}\n\nfunction Glyph({\n  on,\n  reduceMotion,\n  children,\n}: {\n  on: boolean;\n  reduceMotion: boolean;\n  children: React.ReactNode;\n}) {\n  return (\n    <motion.svg\n      viewBox=\"0 0 16 16\"\n      className=\"col-start-1 row-start-1 size-[18px]\"\n      fill=\"none\"\n      stroke=\"currentColor\"\n      strokeWidth={1.5}\n      strokeLinecap=\"round\"\n      strokeLinejoin=\"round\"\n      initial={false}\n      animate={\n        on\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={{ type: \"spring\", duration: 0.3, bounce: 0 }}\n    >\n      {children}\n    </motion.svg>\n  );\n}\n\nexport default function CardNumberRevealDemo() {\n  return <CardNumberReveal number=\"4485 1996 2057 7516\" />;\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"},{"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"}],"cssVars":{"light":{"shadow-raised":"0 0 0 1px oklch(0 0 0 / 0.06), 0 1px 2px oklch(0 0 0 / 0.06), 0 6px 16px -6px oklch(0 0 0 / 0.12)"},"dark":{"shadow-raised":"0 0 0 1px oklch(1 0 0 / 0.08), 0 1px 2px oklch(0 0 0 / 0.4), 0 6px 16px -6px oklch(0 0 0 / 0.6)"},"theme":{"shadow-raised":"var(--shadow-raised)"}},"categories":["data"],"docs":"From ui lab: https://lab.xevrion.dev/lab/card-number-reveal"}