{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "flip-card",
  "title": "Flip Card",
  "description": "A card with two faces that turns over in 3D on hover, from a trigger, or from a prop.",
  "dependencies": [
    "@radix-ui/react-slot"
  ],
  "registryDependencies": [
    "@corsair-ui/utils",
    "@corsair-ui/use-media-query"
  ],
  "files": [
    {
      "path": "registry/default/ui/flip-card.tsx",
      "content": "\"use client\";\n\nimport { Slot } from \"@radix-ui/react-slot\";\nimport {\n  createContext,\n  useCallback,\n  useContext,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n  type ComponentProps,\n  type CSSProperties,\n  type MouseEvent,\n  type Ref,\n} from \"react\";\n\nimport { useMediaQuery } from \"@/registry/default/hooks/use-media-query\";\nimport { cn } from \"@/registry/default/lib/utils\";\n\nfunction mergeRefs<T>(...refs: (Ref<T> | undefined)[]) {\n  return (node: T | null) => {\n    for (const ref of refs) {\n      if (typeof ref === \"function\") ref(node);\n      else if (ref) ref.current = node;\n    }\n  };\n}\n\ntype FlipCardTriggerMode = \"hover\" | \"click\" | \"manual\";\ntype FlipCardAxis = \"x\" | \"y\";\ntype FlipCardSide = \"front\" | \"back\";\n\ninterface FlipCardContextValue {\n  flipped: boolean;\n  toggle: () => void;\n  trigger: FlipCardTriggerMode;\n  axis: FlipCardAxis;\n  duration: number;\n  easing: string;\n  id: string;\n}\n\nconst FlipCardContext = createContext<FlipCardContextValue | null>(null);\n\nfunction useFlipCard(part: string) {\n  const context = useContext(FlipCardContext);\n  if (!context) throw new Error(`${part} must be used inside <FlipCard>.`);\n  return context;\n}\n\n// A tap on one of these is the control's own business, not a request to flip.\nconst INTERACTIVE =\n  \"a[href], button, input, select, textarea, label, summary, [role='button'], [role='link'], [contenteditable='true']\";\nconst TABBABLE =\n  \"a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex='-1'])\";\n\n/** The face of this card (not of a nested one) on the given side. */\nfunction faceOf(root: HTMLElement, side: FlipCardSide) {\n  return root.querySelector<HTMLElement>(`:scope > [data-slot=\"flip-card-${side}\"]`);\n}\n\n/** Where focus goes when the face holding it turns away: a trigger first, then anything tabbable. */\nfunction focusTarget(root: HTMLElement, face: HTMLElement) {\n  const own = (element: Element) => element.closest('[data-slot=\"flip-card\"]') === root;\n  const triggers = [...face.querySelectorAll<HTMLElement>('[data-slot=\"flip-card-trigger\"]')];\n  return triggers.find(own) ?? [...face.querySelectorAll<HTMLElement>(TABBABLE)].find(own) ?? null;\n}\n\ninterface FlipCardProps extends ComponentProps<\"div\"> {\n  /** Whether the back is showing (controlled). */\n  flipped?: boolean;\n  /** Whether the back shows at first (uncontrolled). */\n  defaultFlipped?: boolean;\n  /** Called with the next value whenever a trigger, or a tap in hover mode, asks to flip. */\n  onFlippedChange?: (flipped: boolean) => void;\n  /**\n   * What turns the card. \"hover\": the pointer over it or focus inside it, with\n   * CSS alone; on touch screens a tap toggles. \"click\": only a FlipCardTrigger.\n   * \"manual\": nothing on the card itself, drive it with `flipped`.\n   */\n  trigger?: FlipCardTriggerMode;\n  /** \"y\" turns it like a page, \"x\" tips it over its horizontal axis. */\n  axis?: FlipCardAxis;\n  /** How long the turn takes, in ms. */\n  duration?: number;\n  /** Distance to the viewer, in px: lower values give a deeper 3D turn. */\n  perspective?: number;\n  /** CSS timing function of the turn. */\n  easing?: string;\n}\n\n/**\n * A card with two faces that turns over in 3D: stickers that flip on hover,\n * a weekly grid whose cells turn one after another, tiles in a bento. Both\n * faces sit in the same grid cell, so the card takes the size of the larger\n * one and does not jump. Only `transform` and `opacity` animate; with\n * `prefers-reduced-motion` the faces crossfade instead of turning.\n *\n * `trigger=\"hover\"` (default) is CSS: the card turns while the pointer is\n * over it or focus is inside it, so it works without JavaScript. On touch\n * screens (`hover: none`) a tap on the card toggles it; taps on links and\n * buttons inside are left alone. Both faces stay readable and focusable in\n * this mode, since hovering only changes how they are shown: screen readers\n * read the front then the back, and tabbing to a link on the back turns the\n * card so it is visible. Put links and buttons on the back, not the front: a\n * focused control on the front would turn away. `data-state` follows the\n * tap / `flipped` state, not the hover.\n *\n * `trigger=\"click\"` and `\"manual\"` are state driven: the face turned away is\n * `inert` and `aria-hidden`, so it cannot be reached or read, and when it held\n * focus, focus moves to the first trigger (or control) on the face that\n * turned up. In \"click\" mode give each face a FlipCardTrigger. In \"manual\"\n * mode the card listens to nothing: set `flipped` yourself (a\n * FlipCardTrigger still reports through `onFlippedChange`).\n *\n * @example\n * // Hover\n * <FlipCard className=\"size-40\">\n *   <FlipCardFront className=\"bg-card rounded-xl border\">\n *     <img src=\"/sticker.png\" alt=\"Parrot sticker\" className=\"size-full object-contain\" />\n *   </FlipCardFront>\n *   <FlipCardBack className=\"bg-primary text-primary-foreground rounded-xl p-4\">\n *     <a href=\"/stickers/parrot\">Get this sticker</a>\n *   </FlipCardBack>\n * </FlipCard>\n *\n * @example\n * // Click, with a trigger on each face\n * <FlipCard trigger=\"click\" className=\"w-72\">\n *   <FlipCardFront asChild>\n *     <Card>\n *       <CardHeader><CardTitle>Plan</CardTitle></CardHeader>\n *       <CardFooter>\n *         <FlipCardTrigger asChild><Button variant=\"outline\">Show details</Button></FlipCardTrigger>\n *       </CardFooter>\n *     </Card>\n *   </FlipCardFront>\n *   <FlipCardBack asChild>\n *     <Card>\n *       <CardContent>Everything in the plan…</CardContent>\n *       <CardFooter>\n *         <FlipCardTrigger asChild><Button variant=\"ghost\">Back</Button></FlipCardTrigger>\n *       </CardFooter>\n *     </Card>\n *   </FlipCardBack>\n * </FlipCard>\n *\n * @example\n * // Manual: a weekly grid the consumer staggers\n * const [revealed, setRevealed] = useState(0);\n * useEffect(() => {\n *   if (revealed >= days.length) return;\n *   const timer = setTimeout(() => setRevealed((count) => count + 1), 120);\n *   return () => clearTimeout(timer);\n * }, [revealed]);\n * <div className=\"grid grid-cols-7 gap-2\">\n *   {days.map((day, index) => (\n *     <FlipCard key={day.label} trigger=\"manual\" flipped={index < revealed}>\n *       <FlipCardFront className=\"bg-muted rounded-md p-2\">{day.label}</FlipCardFront>\n *       <FlipCardBack className=\"bg-card rounded-md border p-2\">{day.value}</FlipCardBack>\n *     </FlipCard>\n *   ))}\n * </div>\n */\nfunction FlipCard({\n  flipped: flippedProp,\n  defaultFlipped = false,\n  onFlippedChange,\n  trigger = \"hover\",\n  axis = \"y\",\n  duration = 600,\n  perspective = 1000,\n  easing = \"cubic-bezier(0.16, 1, 0.3, 1)\",\n  id: idProp,\n  className,\n  style,\n  ref,\n  children,\n  ...props\n}: FlipCardProps) {\n  const generatedId = useId();\n  const id = idProp ?? generatedId;\n  const [uncontrolled, setUncontrolled] = useState(defaultFlipped);\n  const controlled = flippedProp !== undefined;\n  const flipped = controlled ? flippedProp : uncontrolled;\n\n  const root = useRef<HTMLDivElement>(null);\n  const mergedRef = useMemo(() => mergeRefs(ref, root), [ref]);\n  // Set when a flip is requested while focus is inside, so a face that turns\n  // away does not strand it even if the browser has already blurred it.\n  const focusWasInside = useRef(false);\n\n  const toggle = useCallback(() => {\n    focusWasInside.current = root.current?.contains(document.activeElement) ?? false;\n    const next = !flipped;\n    if (!controlled) setUncontrolled(next);\n    onFlippedChange?.(next);\n  }, [controlled, flipped, onFlippedChange]);\n\n  // Touch screens have no hover: a tap on the card toggles it instead. A\n  // listener rather than onClick, since the card itself is not a control;\n  // keyboard users turn it through focus.\n  const cannotHover = useMediaQuery(\"(hover: none)\");\n  useEffect(() => {\n    const node = root.current;\n    if (trigger !== \"hover\" || !cannotHover || !node) return;\n    const handleClick = (event: globalThis.MouseEvent) => {\n      if (event.defaultPrevented) return;\n      const control = (event.target as Element | null)?.closest(INTERACTIVE);\n      if (control && node.contains(control)) return;\n      toggle();\n    };\n    node.addEventListener(\"click\", handleClick);\n    return () => node.removeEventListener(\"click\", handleClick);\n  }, [trigger, cannotHover, toggle]);\n\n  // When the face holding focus turns away (and becomes inert), move focus to the one that turned up.\n  useLayoutEffect(() => {\n    const wasInside = focusWasInside.current;\n    focusWasInside.current = false;\n    const node = root.current;\n    if (trigger === \"hover\" || !node) return;\n    const hidden = faceOf(node, flipped ? \"front\" : \"back\");\n    const visible = faceOf(node, flipped ? \"back\" : \"front\");\n    if (!hidden || !visible) return;\n    const active = document.activeElement;\n    const stranded =\n      (active !== null && hidden.contains(active)) ||\n      (wasInside && (active === null || active === document.body));\n    if (stranded) focusTarget(node, visible)?.focus();\n  }, [flipped, trigger]);\n\n  const context = useMemo(\n    () => ({ flipped, toggle, trigger, axis, duration, easing, id }),\n    [flipped, toggle, trigger, axis, duration, easing, id]\n  );\n\n  return (\n    <FlipCardContext.Provider value={context}>\n      <div\n        ref={mergedRef}\n        id={id}\n        data-slot=\"flip-card\"\n        data-state={flipped ? \"flipped\" : \"unflipped\"}\n        data-trigger={trigger}\n        data-axis={axis}\n        className={cn(\n          // --flip-card-turn is 0 for the front and 1 for the back; the faces turn,\n          // fade and stack from it. `perspective` also makes the root a stacking\n          // context, so the faces' z-index stays inside the card.\n          \"group/flip-card grid [--flip-card-turn:0] data-[state=flipped]:[--flip-card-turn:1]\",\n          trigger === \"hover\" &&\n            \"focus-within:[--flip-card-turn:1] [@media(hover:hover)]:hover:[--flip-card-turn:1]\",\n          className\n        )}\n        style={{ perspective: `${perspective}px`, ...style }}\n        {...props}\n      >\n        {children}\n      </div>\n    </FlipCardContext.Provider>\n  );\n}\n\n// Whole class names, so Tailwind finds them. The front turns 0 → 180deg, the\n// back -180 → 0deg, both the same way round.\nconst ROTATION: Record<FlipCardAxis, Record<FlipCardSide, string>> = {\n  y: {\n    front: \"motion-safe:[transform:rotateY(calc(var(--flip-card-turn)*180deg))]\",\n    back: \"motion-safe:[transform:rotateY(calc(var(--flip-card-turn)*180deg_-_180deg))]\",\n  },\n  x: {\n    front: \"motion-safe:[transform:rotateX(calc(var(--flip-card-turn)*180deg))]\",\n    back: \"motion-safe:[transform:rotateX(calc(var(--flip-card-turn)*180deg_-_180deg))]\",\n  },\n};\n\n// Reduced motion: no turn, the face that is away fades out instead.\nconst CROSSFADE: Record<FlipCardSide, string> = {\n  front: \"motion-reduce:[opacity:calc(1_-_var(--flip-card-turn))]\",\n  back: \"motion-reduce:[opacity:var(--flip-card-turn)]\",\n};\n\n// The face towards the reader sits on top, so it takes the clicks even when\n// the other one is only faded out (reduced motion) or turned by hover.\nconst STACKING: Record<FlipCardSide, string> = {\n  front: \"[z-index:calc(1_-_var(--flip-card-turn))]\",\n  back: \"[z-index:var(--flip-card-turn)]\",\n};\n\ninterface FlipCardFaceProps extends ComponentProps<\"div\"> {\n  /** Render the single child element (a Card, for example) as the face instead of a div. */\n  asChild?: boolean;\n}\n\nfunction FlipCardFace({\n  side,\n  asChild = false,\n  className,\n  style,\n  ...props\n}: FlipCardFaceProps & { side: FlipCardSide }) {\n  const { flipped, trigger, axis, duration, easing } = useFlipCard(\n    side === \"front\" ? \"FlipCardFront\" : \"FlipCardBack\"\n  );\n  // Only state-driven modes hide the face that is away; in hover mode both stay readable.\n  const away = trigger !== \"hover\" && flipped === (side === \"front\");\n  const Comp = asChild ? Slot : \"div\";\n  return (\n    <Comp\n      data-slot={`flip-card-${side}`}\n      data-side={side}\n      data-state={flipped ? \"flipped\" : \"unflipped\"}\n      aria-hidden={away || undefined}\n      inert={away || undefined}\n      className={cn(\n        \"col-start-1 row-start-1 transition-[transform,opacity] [backface-visibility:hidden]\",\n        ROTATION[axis][side],\n        CROSSFADE[side],\n        STACKING[side],\n        className\n      )}\n      style={\n        {\n          transitionDuration: `${duration}ms`,\n          transitionTimingFunction: easing,\n          ...style,\n        } as CSSProperties\n      }\n      {...props}\n    />\n  );\n}\n\n/** The side that shows first. */\nfunction FlipCardFront(props: FlipCardFaceProps) {\n  return <FlipCardFace side=\"front\" {...props} />;\n}\n\n/** The side that turns up when the card flips. */\nfunction FlipCardBack(props: FlipCardFaceProps) {\n  return <FlipCardFace side=\"back\" {...props} />;\n}\n\ninterface FlipCardTriggerProps extends ComponentProps<\"button\"> {\n  /** Render the single child element (your own Button) as the trigger. */\n  asChild?: boolean;\n}\n\n/**\n * A button that turns the card over. `aria-pressed` says whether the back is\n * showing and `aria-controls` points at the card (pass your own to change it).\n * With `trigger=\"click\"`, put one on each face (\"Show details\" / \"Back\").\n */\nfunction FlipCardTrigger({ asChild = false, onClick, ...props }: FlipCardTriggerProps) {\n  const { flipped, toggle, id } = useFlipCard(\"FlipCardTrigger\");\n  const Comp = asChild ? Slot : \"button\";\n  return (\n    <Comp\n      type={asChild ? undefined : \"button\"}\n      aria-controls={id}\n      {...props}\n      data-slot=\"flip-card-trigger\"\n      data-state={flipped ? \"flipped\" : \"unflipped\"}\n      aria-pressed={flipped}\n      onClick={(event: MouseEvent<HTMLButtonElement>) => {\n        onClick?.(event);\n        if (!event.defaultPrevented) toggle();\n      }}\n    />\n  );\n}\n\nexport {\n  FlipCard,\n  FlipCardBack,\n  FlipCardFront,\n  FlipCardTrigger,\n  type FlipCardFaceProps,\n  type FlipCardProps,\n  type FlipCardTriggerProps,\n};\n",
      "type": "registry:ui"
    }
  ],
  "categories": [
    "creative"
  ],
  "type": "registry:ui"
}