{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"copy-email","type":"registry:component","title":"Copy email","description":"Click the address and its letters flip, one by one, into \"Copied to clipboard\".","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/copy-email.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useRef, useState } 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\ntype Status = \"idle\" | \"copied\" | \"failed\";\n\n// One letter's flip. Each letter starts a beat after its left neighbour,\n// so the message reads as a wave running through the address.\nconst FLIP = { duration: 0.22, ease: [0.23, 1, 0.32, 1] } as const;\nconst STAGGER = 0.018;\n// The box eases to its new width over the same span the wave takes to\n// cross it. Width (not scale) on purpose: the neighbours should reflow.\nconst WIDTH_MS = 320;\n\nexport function CopyEmail({\n  email,\n  copiedText = \"Copied to clipboard\",\n  // Long enough to read the confirmation, short enough to feel returned.\n  resetAfter = 1600,\n  display,\n  className,\n}: {\n  email: string;\n  copiedText?: string;\n  resetAfter?: number;\n  /** Shows this state instead of the button's own, without copying or\n   * announcing anything (a copy confirmed elsewhere, a demo). */\n  display?: Status;\n  className?: string;\n}) {\n  const reduceMotion = useReducedMotion();\n  const [own, setStatus] = useState<Status>(\"idle\");\n  const status = display ?? own;\n  const timer = useRef<ReturnType<typeof setTimeout>>(undefined);\n  const attempt = useRef(0);\n\n  useEffect(() => () => clearTimeout(timer.current), []);\n\n  const show = (next: Exclude<Status, \"idle\">) => {\n    setStatus(next);\n    clearTimeout(timer.current);\n    timer.current = setTimeout(() => setStatus(\"idle\"), resetAfter);\n  };\n\n  const copy = async () => {\n    const id = ++attempt.current;\n    // Confirm on press; the write is near instant and waiting makes the\n    // click feel ignored.\n    show(\"copied\");\n    try {\n      if (!navigator.clipboard) throw new Error(\"Clipboard unavailable\");\n      await navigator.clipboard.writeText(email);\n    } catch {\n      if (id === attempt.current) show(\"failed\");\n    }\n  };\n\n  const shown =\n    status === \"copied\" ? copiedText : status === \"failed\" ? \"Couldn't copy\" : email;\n  // Every text shares these slots; the extras sit blank at the tail and\n  // are clipped by the animating width.\n  const slots = Math.max(email.length, copiedText.length, 13);\n\n  return (\n    <span className={cn(\"inline-flex items-center gap-1\", className)}>\n      <span className=\"group/copy relative inline-flex\">\n        <button\n          type=\"button\"\n          onClick={copy}\n          aria-label={`Copy email address ${email}`}\n          className=\"relative flex h-9 touch-manipulation items-center rounded-md px-2 font-mono text-sm text-foreground outline-hidden transition-[scale,background-color] duration-150 ease-out select-none hover:bg-muted focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-solid focus-visible:outline-foreground active:scale-[0.96] motion-reduce:transition-[background-color]\"\n        >\n          <span\n            aria-hidden\n            className=\"flex overflow-hidden transition-[width] ease-[cubic-bezier(0.77,0,0.175,1)] motion-reduce:transition-none\"\n            style={{\n              width: `${shown.length}ch`,\n              transitionDuration: `${WIDTH_MS}ms`,\n              // Room for the flip's perspective to read as depth.\n              perspective: 240,\n            }}\n          >\n            {Array.from({ length: slots }, (_, i) => (\n              <Letter\n                key={i}\n                char={shown[i] ?? \" \"}\n                delay={i * STAGGER}\n                reduceMotion={reduceMotion}\n              />\n            ))}\n          </span>\n        </button>\n\n        {/* A whisper of what the click does. Hidden once the text itself\n            is saying something, and never on touch, where hover lies. */}\n        <span\n          aria-hidden\n          className={cn(\n            \"pointer-events-none absolute bottom-full left-1/2 mb-1 -translate-x-1/2 translate-y-0.5 rounded-full bg-foreground px-2 py-0.5 text-xs font-medium whitespace-nowrap text-background opacity-0\",\n            \"transition-[opacity,translate] duration-100 ease-out [@media(hover:hover)]:group-hover/copy:translate-y-0 [@media(hover:hover)]:group-hover/copy:opacity-100 [@media(hover:hover)]:group-hover/copy:delay-300 [@media(hover:hover)]:group-hover/copy:duration-150\",\n            status !== \"idle\" && \"invisible\",\n          )}\n        >\n          Click to copy\n        </span>\n      </span>\n\n      <a\n        href={`mailto:${email}`}\n        aria-label={`Email ${email}`}\n        className=\"relative flex size-7 touch-manipulation items-center justify-center rounded-md text-muted-foreground outline-hidden transition-[scale,color,background-color] duration-150 ease-out after:absolute after:-inset-1.5 hover:bg-muted hover:text-foreground focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-foreground active:scale-[0.96]\"\n      >\n        <svg\n          aria-hidden\n          viewBox=\"0 0 16 16\"\n          className=\"size-3.5\"\n          fill=\"none\"\n          stroke=\"currentColor\"\n          strokeWidth={1.5}\n          strokeLinecap=\"round\"\n          strokeLinejoin=\"round\"\n        >\n          <path d=\"M5 11 11 5M6 5h5v5\" />\n        </svg>\n      </a>\n\n      <span className=\"sr-only\" aria-live=\"polite\">\n        {own === \"copied\" ? \"Copied to clipboard\" : own === \"failed\" ? \"Couldn't copy\" : \"\"}\n      </span>\n    </span>\n  );\n}\n\nfunction Letter({\n  char,\n  delay,\n  reduceMotion,\n}: {\n  char: string;\n  delay: number;\n  reduceMotion: boolean | null;\n}) {\n  // Two faces: the letter on show, and the one it is leaving. Keying the\n  // pair on the char restarts the flip only for slots that change.\n  const [faces, setFaces] = useState({ now: char, was: char });\n  if (faces.now !== char) setFaces({ now: char, was: faces.now });\n\n  const changed = faces.now !== faces.was;\n  return (\n    <span className=\"relative inline-block w-[1ch] shrink-0 whitespace-pre [transform-style:preserve-3d]\">\n      <motion.span\n        key={`in-${faces.now}-${faces.was}`}\n        className=\"block origin-[50%_50%_-0.5em] backface-hidden\"\n        initial={\n          changed\n            ? reduceMotion\n              ? { opacity: 0 }\n              : { rotateX: -90, opacity: 0 }\n            : false\n        }\n        animate={{ rotateX: 0, opacity: 1 }}\n        transition={{ ...FLIP, delay: reduceMotion ? 0 : delay }}\n      >\n        {faces.now}\n      </motion.span>\n      {changed ? (\n        <motion.span\n          key={`out-${faces.now}-${faces.was}`}\n          aria-hidden\n          className=\"absolute inset-0 block origin-[50%_50%_-0.5em] backface-hidden\"\n          initial={{ rotateX: 0, opacity: 1 }}\n          animate={reduceMotion ? { opacity: 0 } : { rotateX: 90, opacity: 0 }}\n          transition={{ ...FLIP, delay: reduceMotion ? 0 : delay }}\n        >\n          {faces.was}\n        </motion.span>\n      ) : null}\n    </span>\n  );\n}\n\n// The index card's show: a click a moment after the cursor arrives, the\n// confirmation for as long as a real one lasts, then a calm beat.\nconst SHOW_CLICK = 500;\nconst SHOW_HOLD = 1600;\nconst SHOW_REST = 1800;\n\nexport default function CopyEmailDemo() {\n  const play = usePreviewPlay();\n  const [display, setDisplay] = useState<Status>();\n\n  useEffect(() => {\n    if (play !== true) return;\n    let timer: ReturnType<typeof setTimeout>;\n    const click = (wait: number) => {\n      timer = setTimeout(() => {\n        // Only the letters change; the real clipboard is never touched.\n        setDisplay(\"copied\");\n        timer = setTimeout(() => {\n          setDisplay(\"idle\");\n          click(SHOW_REST);\n        }, SHOW_HOLD);\n      }, wait);\n    };\n    click(SHOW_CLICK);\n    // Unhovering flips the letters back to the address.\n    return () => {\n      clearTimeout(timer);\n      setDisplay(undefined);\n    };\n  }, [play]);\n\n  return (\n    // Fixed width and left-aligned so the address never moves under the\n    // cursor; only the arrow slides as the text grows. In an index card the\n    // box is narrowed to halfway between the resting (248px) and copied\n    // (290px) widths and kept on one line, so the centred card is off by\n    // only ~10px either way.\n    <div\n      className={cn(\n        \"flex flex-wrap items-center gap-x-2 text-sm text-muted-foreground\",\n        play === null ? \"w-[min(340px,100%)]\" : \"w-[269px] flex-nowrap whitespace-nowrap\",\n      )}\n    >\n      <span>Say hello at</span>\n      <CopyEmail\n        email=\"hi@xevrion.dev\"\n        display={display}\n        className={play === null ? undefined : \"shrink-0\"}\n      />\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":["text"],"docs":"From ui lab: https://lab.xevrion.dev/lab/copy-email"}