{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"flip-card","type":"registry:component","title":"Flip card","description":"Turns over in 3D to show what is on the back.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/flip-card.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useRef, useState } from \"react\";\nimport {\n  animate,\n  motion,\n  useMotionTemplate,\n  useMotionValue,\n  useSpring,\n  useTransform,\n} from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\n// Half a turn is a lot of travel for a physical object; under ~300ms it reads\n// as a snap rather than a card turning over, so this runs longer than most\n// UI. The small bounce lets it settle like something with weight.\nconst FLIP = { type: \"spring\", visualDuration: 0.55, bounce: 0.2 } as const;\n// A few degrees is enough to feel the card lean in; more and the text skews.\nconst MAX_TILT = 6;\n// Settles in about 300ms with no overshoot, so the lean feels heavy.\nconst FOLLOW = { stiffness: 300, damping: 30 };\n// How far the card rises toward you at the halfway point of a flip.\nconst LIFT_SCALE = 0.03;\n// Held down, the card gives a little under your finger.\nconst PRESS_SCALE = 0.96;\nconst PRESS = { duration: 0.15, ease: [0.23, 1, 0.32, 1] } as const;\n\nexport function FlipCard({\n  front,\n  back,\n  frontLabel = \"Show details\",\n  backLabel = \"Show front\",\n  className,\n}: {\n  front: React.ReactNode;\n  back: React.ReactNode;\n  frontLabel?: string;\n  backLabel?: string;\n  className?: string;\n}) {\n  const reduceMotion = useReducedMotion();\n  const [flipped, setFlipped] = useState(false);\n  const frontButton = useRef<HTMLButtonElement>(null);\n  const backButton = useRef<HTMLButtonElement>(null);\n  const moveFocus = useRef(false);\n\n  const flip = useMotionValue(0);\n  // Lives in the same transform as the flip. A CSS scale on a wrapper\n  // around the 3D card makes Safari flatten it into an opaque square for\n  // as long as the press lasts.\n  const press = useMotionValue(1);\n  const setPressed = (down: boolean) => {\n    const to = down ? PRESS_SCALE : 1;\n    if (reduceMotion) press.jump(to);\n    else animate(press, to, PRESS);\n  };\n\n  // Pointer position across the card, -1 to 1 on each axis.\n  const pointerX = useMotionValue(0);\n  const pointerY = useMotionValue(0);\n  const x = useSpring(pointerX, FOLLOW);\n  const y = useSpring(pointerY, FOLLOW);\n  // The half under the pointer tips toward you.\n  const tiltX = useTransform(y, (v) => -v * MAX_TILT);\n  const tiltY = useTransform(x, (v) => v * MAX_TILT);\n\n  // 0 when a face is flat to the viewer, 1 when the card is edge-on. Derived\n  // from the angle itself, so an interrupted flip lifts exactly as much as\n  // its current position warrants.\n  const lift = useTransform(flip, (v) =>\n    Math.abs(Math.sin((v * Math.PI) / 180)),\n  );\n  const scale = useTransform(\n    () => (1 + lift.get() * LIFT_SCALE) * press.get(),\n  );\n  // Tilt adds to the flip in world space, so the lean still follows the\n  // cursor when the back is showing.\n  const turn = useTransform(() => flip.get() + tiltY.get());\n  const transform = useMotionTemplate`rotateX(${tiltX}deg) rotateY(${turn}deg) scale(${scale})`;\n  // Reduced motion keeps the press, just without the turn.\n  const pressTransform = useMotionTemplate`scale(${press})`;\n\n  // Raised higher, the shadow falls further away, spreads and darkens.\n  const shadowY = useTransform(lift, (l) => 14 + l * 22);\n  const shadowScale = useTransform(\n    () => (0.92 + lift.get() * 0.08) * press.get(),\n  );\n  const shadowOpacity = useTransform(lift, (l) => 0.3 + l * 0.3);\n  const shadowTransform = useMotionTemplate`translateY(${shadowY}px) scale(${shadowScale})`;\n\n  useEffect(() => {\n    if (reduceMotion) {\n      flip.jump(0);\n      return;\n    }\n    // Starts from the live angle and velocity, so flipping again mid-turn\n    // reverses smoothly instead of restarting.\n    const controls = animate(flip, flipped ? 180 : 0, FLIP);\n    return () => controls.stop();\n  }, [flipped, reduceMotion, flip]);\n\n  // The face that was pressed turns inert, so focus follows to the other one.\n  useEffect(() => {\n    if (!moveFocus.current) return;\n    moveFocus.current = false;\n    (flipped ? backButton : frontButton).current?.focus({\n      preventScroll: true,\n    });\n  }, [flipped]);\n\n  const toggle = () => {\n    moveFocus.current = true;\n    setFlipped((f) => !f);\n  };\n\n  const face = \"absolute inset-0 rounded-3xl backface-hidden\";\n  // Reduced motion swaps faces with a short cross-fade in place of the turn.\n  const fade = \"transition-[opacity] duration-200 ease-out\";\n  const hitArea =\n    \"absolute inset-0 z-10 cursor-pointer rounded-[inherit] outline-hidden focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-4 focus-visible:outline-foreground\";\n\n  return (\n    <div\n      className={cn(\n        \"relative h-[420px] w-[min(320px,100%)] touch-manipulation select-none\",\n        className,\n      )}\n      onPointerDown={(e) => {\n        if (e.button === 0 && (e.target as Element).closest(\"button\")) {\n          setPressed(true);\n        }\n      }}\n      onPointerUp={() => setPressed(false)}\n      onPointerCancel={() => setPressed(false)}\n      onKeyDown={(e) => {\n        if (e.key === \" \" && !e.repeat) setPressed(true);\n      }}\n      onKeyUp={(e) => {\n        if (e.key === \" \") setPressed(false);\n      }}\n      onBlur={() => setPressed(false)}\n      onPointerMove={(e) => {\n        // Touch would fight the page scroll, so leaning is for mouse and pen.\n        if (reduceMotion || e.pointerType === \"touch\") return;\n        const rect = e.currentTarget.getBoundingClientRect();\n        pointerX.set(((e.clientX - rect.left) / rect.width) * 2 - 1);\n        pointerY.set(((e.clientY - rect.top) / rect.height) * 2 - 1);\n      }}\n      onPointerLeave={() => {\n        pointerX.set(0);\n        pointerY.set(0);\n        setPressed(false);\n      }}\n    >\n      <motion.div\n        aria-hidden\n        className=\"absolute inset-x-6 top-10 bottom-2 rounded-3xl bg-black blur-2xl\"\n        style={{ transform: shadowTransform, opacity: shadowOpacity }}\n      />\n      <div className=\"absolute inset-0 perspective-[1200px]\">\n        <motion.div\n          className=\"relative size-full transform-3d\"\n          style={{ transform: reduceMotion ? pressTransform : transform }}\n        >\n          <div\n            className={cn(\n              face,\n              reduceMotion && fade,\n              reduceMotion && flipped && \"opacity-0\",\n            )}\n            inert={flipped}\n            aria-hidden={flipped}\n          >\n            <button\n              ref={frontButton}\n              type=\"button\"\n              aria-label={frontLabel}\n              onClick={toggle}\n              className={hitArea}\n            />\n            {front}\n          </div>\n          <div\n            className={cn(\n              face,\n              reduceMotion ? fade : \"rotate-y-180\",\n              reduceMotion && !flipped && \"opacity-0\",\n            )}\n            inert={!flipped}\n            aria-hidden={!flipped}\n          >\n            <button\n              ref={backButton}\n              type=\"button\"\n              aria-label={backLabel}\n              onClick={toggle}\n              className={hitArea}\n            />\n            {back}\n          </div>\n        </motion.div>\n      </div>\n    </div>\n  );\n}\n\nfunction FlipHint({ children }: { children: React.ReactNode }) {\n  return (\n    <span className=\"flex items-center gap-1.5 text-[13px] font-medium\">\n      <svg\n        viewBox=\"0 0 16 16\"\n        className=\"size-4\"\n        fill=\"none\"\n        stroke=\"currentColor\"\n        strokeWidth={1.5}\n        strokeLinecap=\"round\"\n        strokeLinejoin=\"round\"\n        aria-hidden\n      >\n        <path d=\"M13.25 8a5.25 5.25 0 0 1-9.4 3.2M2.75 8a5.25 5.25 0 0 1 9.4-3.2\" />\n        <path d=\"M12.5 2.25v2.5H10M3.5 13.75v-2.5H6\" />\n      </svg>\n      {children}\n    </span>\n  );\n}\n\nconst DETAILS = [\n  [\"Plan\", \"Studio, yearly\"],\n  [\"Seats\", \"3 of 5 used\"],\n  [\"Storage\", \"42 of 100 GB\"],\n  [\"Renews\", \"12 Mar 2027\"],\n] as const;\n\nfunction Front() {\n  return (\n    <div className=\"flex size-full flex-col justify-between rounded-[inherit] bg-foreground p-6 text-background\">\n      <div className=\"flex items-baseline justify-between\">\n        <span className=\"text-[15px] font-semibold tracking-tight\">ui lab</span>\n        <span className=\"font-mono text-xs tabular-nums opacity-60\">\n          No. 0042\n        </span>\n      </div>\n      <div className=\"flex flex-col gap-2\">\n        <span className=\"text-[13px] font-medium opacity-60\">\n          Studio member\n        </span>\n        <span className=\"text-[40px] leading-[1.05] font-semibold tracking-[-0.03em]\">\n          Yash\n          <br />\n          Bavadiya\n        </span>\n      </div>\n      <div className=\"flex items-end justify-between\">\n        <div className=\"flex flex-col gap-0.5\">\n          <span className=\"text-xs opacity-60\">Member since</span>\n          <span className=\"text-sm font-medium tabular-nums\">April 2024</span>\n        </div>\n        <span className=\"opacity-60\">\n          <FlipHint>Details</FlipHint>\n        </span>\n      </div>\n    </div>\n  );\n}\n\nfunction Back() {\n  return (\n    <div className=\"flex size-full flex-col justify-between rounded-[inherit] bg-muted p-6 text-foreground ring-1 ring-border ring-inset\">\n      <div className=\"flex flex-col gap-1\">\n        <span className=\"text-[13px] font-medium text-muted-foreground\">Membership</span>\n        <span className=\"text-2xl font-semibold tracking-tight\">Studio</span>\n      </div>\n      <dl className=\"flex flex-col\">\n        {DETAILS.map(([term, value]) => (\n          <div\n            key={term}\n            className=\"flex items-baseline justify-between border-t border-border py-3 text-[15px]\"\n          >\n            <dt className=\"text-muted-foreground\">{term}</dt>\n            <dd className=\"font-medium tabular-nums\">{value}</dd>\n          </div>\n        ))}\n      </dl>\n      <div className=\"flex items-center justify-between text-muted-foreground\">\n        <span className=\"font-mono text-xs tabular-nums\">No. 0042</span>\n        <FlipHint>Front</FlipHint>\n      </div>\n    </div>\n  );\n}\n\nexport default function FlipCardDemo() {\n  return <FlipCard front={<Front />} back={<Back />} />;\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":["cards"],"docs":"From ui lab: https://lab.xevrion.dev/lab/flip-card"}