{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"expanding-card","type":"registry:component","title":"Expanding card","description":"Grows from its slot into a detail view and folds back when you are done.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/expanding-card.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useId, useRef, useState } from \"react\";\nimport { AnimatePresence, LayoutGroup, motion } from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\nexport type ExpandingCardItem = {\n  id: string;\n  title: string;\n  meta: string;\n  summary: string;\n  detail: string;\n};\n\n// No bounce: a card overshooting its own slot reads as a glitch, not play.\nconst MORPH = { type: \"spring\", duration: 0.35, bounce: 0 } as const;\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\n// Held until the morph has visibly settled, so the paragraph never shows\n// while its box is still being scaled and can't appear to reflow.\nconst DETAIL_DELAY = 0.25;\n// Closing is quicker to read, so the card's summary returns a little sooner.\nconst RETURN_DELAY = 0.2;\n// The radius grows with the surface: 18px suits an 80px card, 24px the\n// larger dialog, and Motion animates between them.\nconst CARD_RADIUS = 18;\nconst DIALOG_RADIUS = 24;\n\nexport function ExpandingCards({\n  items,\n  className,\n}: {\n  items: ExpandingCardItem[];\n  className?: string;\n}) {\n  const reduceMotion = !!useReducedMotion();\n  const group = useId();\n  const [openId, setOpenId] = useState<string | null>(null);\n  // The card collapsing back rises above the fading backdrop and its\n  // siblings until it lands, then drops to the normal layer.\n  const [returningId, setReturningId] = useState<string | null>(null);\n  const cardRefs = useRef(new Map<string, HTMLButtonElement>());\n  const closeRef = useRef<HTMLButtonElement>(null);\n  const dialogRef = useRef<HTMLDivElement>(null);\n  const lastOpened = useRef<string | null>(null);\n\n  const open = openId ? items.find((item) => item.id === openId) : undefined;\n\n  const show = (id: string) => {\n    lastOpened.current = id;\n    setReturningId(null);\n    setOpenId(id);\n  };\n\n  const close = () => {\n    setReturningId(openId);\n    setOpenId(null);\n  };\n\n  useEffect(() => {\n    if (openId) {\n      closeRef.current?.focus({ preventScroll: true });\n      const onKey = (e: KeyboardEvent) => {\n        if (e.key !== \"Escape\") return;\n        e.preventDefault();\n        setReturningId(openId);\n        setOpenId(null);\n      };\n      document.addEventListener(\"keydown\", onKey);\n      return () => document.removeEventListener(\"keydown\", onKey);\n    }\n    // The card remounts in the commit that closes the dialog, so its ref is\n    // ready by the time this runs.\n    const id = lastOpened.current;\n    if (id) cardRefs.current.get(id)?.focus({ preventScroll: true });\n  }, [openId]);\n\n  // Keeps Tab inside the dialog, as aria-modal promises.\n  const trapTab = (e: React.KeyboardEvent) => {\n    if (e.key !== \"Tab\" || !dialogRef.current) return;\n    const focusable = Array.from(\n      dialogRef.current.querySelectorAll<HTMLElement>(\n        \"button, [href], input, textarea, select, [tabindex]:not([tabindex='-1'])\",\n      ),\n    );\n    if (focusable.length === 0) return;\n    const first = focusable[0];\n    const last = focusable[focusable.length - 1];\n    if (e.shiftKey && document.activeElement === first) {\n      e.preventDefault();\n      last.focus();\n    } else if (!e.shiftKey && document.activeElement === last) {\n      e.preventDefault();\n      first.focus();\n    }\n  };\n\n  // Without a layoutId there is nothing to morph, which is exactly the\n  // reduced motion path: the views simply cross-fade in place.\n  const shared = (key: string) => (reduceMotion ? undefined : key);\n  const titleId = `${group}-title`;\n\n  return (\n    <LayoutGroup id={group}>\n      <div className={cn(\"relative w-[400px] max-w-full\", className)}>\n        <ul className=\"flex flex-col gap-3\" inert={!!openId}>\n          {items.map((item) => (\n            <li key={item.id}>\n              {item.id === openId ? (\n                // Holds the slot at the card's exact size so the list never\n                // jumps, and marks where the card will return to.\n                <div\n                  aria-hidden\n                  className=\"bg-foreground/[0.03] shadow-[inset_0_0_0_1px_var(--border)]\"\n                  style={{ borderRadius: CARD_RADIUS }}\n                >\n                  <div className=\"invisible\">\n                    <CardFace item={item} />\n                  </div>\n                </div>\n              ) : (\n                <motion.button\n                  ref={(node) => {\n                    if (node) cardRefs.current.set(item.id, node);\n                    else cardRefs.current.delete(item.id);\n                  }}\n                  type=\"button\"\n                  aria-haspopup=\"dialog\"\n                  layoutId={shared(`card-${item.id}`)}\n                  // A crossfade would show the outgoing view squashed\n                  // mid-flight; one element morphing reads cleaner.\n                  layoutCrossfade={false}\n                  transition={MORPH}\n                  onClick={() => show(item.id)}\n                  onLayoutAnimationComplete={() =>\n                    setReturningId((id) => (id === item.id ? null : id))\n                  }\n                  // Radius lives in style so layout animation can correct it\n                  // for the scale instead of letting the corners stretch.\n                  style={{ borderRadius: CARD_RADIUS }}\n                  className={cn(\n                    \"relative block w-full touch-manipulation bg-muted text-left shadow-raised outline-hidden transition-[scale] duration-150 ease-out select-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-foreground active:scale-[0.96] motion-reduce:transition-none\",\n                    returningId === item.id && \"z-50\",\n                  )}\n                >\n                  <CardFace\n                    item={item}\n                    shared={shared}\n                    returning={returningId === item.id && !reduceMotion}\n                  />\n                </motion.button>\n              )}\n            </li>\n          ))}\n        </ul>\n\n        <AnimatePresence>\n          {open && (\n            <motion.div\n              key=\"backdrop\"\n              aria-hidden\n              className=\"fixed inset-0 z-40 bg-foreground/15 dark:bg-background/70\"\n              initial={{ opacity: 0 }}\n              animate={{\n                opacity: 1,\n                transition: { duration: 0.2, ease: EASE_OUT },\n              }}\n              // Leaves faster than it came so the returning card is the\n              // only thing the eye follows.\n              exit={{\n                opacity: 0,\n                transition: { duration: 0.15, ease: EASE_OUT },\n              }}\n              onClick={close}\n            />\n          )}\n        </AnimatePresence>\n\n        {/* Flex centres the dialog without a transform, which layout\n            animation would overwrite. It is wider than the list and\n            overflows both sides evenly. */}\n        <div className=\"pointer-events-none absolute inset-0 z-50 flex items-center justify-center\">\n          <AnimatePresence>\n            {open && (\n              <motion.div\n                key={open.id}\n                ref={dialogRef}\n                role=\"dialog\"\n                aria-modal=\"true\"\n                aria-labelledby={titleId}\n                layoutId={shared(`card-${open.id}`)}\n                layoutCrossfade={false}\n                transition={MORPH}\n                initial={reduceMotion ? { opacity: 0 } : undefined}\n                animate={\n                  reduceMotion\n                    ? {\n                        opacity: 1,\n                        transition: { duration: 0.15, ease: EASE_OUT },\n                      }\n                    : undefined\n                }\n                exit={\n                  reduceMotion\n                    ? {\n                        opacity: 0,\n                        transition: { duration: 0.1, ease: EASE_OUT },\n                      }\n                    : undefined\n                }\n                onKeyDown={trapTab}\n                style={{ borderRadius: DIALOG_RADIUS }}\n                className=\"pointer-events-auto w-[440px] max-w-[calc(100vw-2rem)] shrink-0 bg-muted p-6 shadow-raised\"\n              >\n                <div className=\"flex items-start justify-between gap-4\">\n                  <div className=\"flex flex-col items-start gap-1\">\n                    <motion.h2\n                      id={titleId}\n                      {...sharedText(shared(`title-${open.id}`))}\n                      className=\"text-[15px] font-medium text-foreground\"\n                    >\n                      {open.title}\n                    </motion.h2>\n                    <motion.p\n                      {...sharedText(shared(`meta-${open.id}`))}\n                      className=\"text-[13px] text-muted-foreground tabular-nums\"\n                    >\n                      {open.meta}\n                    </motion.p>\n                  </div>\n                  <Delayed reduceMotion={reduceMotion}>\n                    <button\n                      ref={closeRef}\n                      type=\"button\"\n                      aria-label=\"Close\"\n                      onClick={close}\n                      className={cn(\n                        \"relative -mt-2 -mr-2 flex size-8 touch-manipulation items-center justify-center rounded-full text-muted-foreground outline-hidden transition-[scale,color,background-color] duration-150 ease-out hover:bg-background hover:text-foreground focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-foreground active:scale-[0.96] motion-reduce:transition-[color,background-color]\",\n                        // Grows the hit area to 44px around the 32px circle.\n                        \"after:absolute after:-inset-1.5 after:rounded-full\",\n                      )}\n                    >\n                      <svg\n                        viewBox=\"0 0 16 16\"\n                        className=\"size-[18px]\"\n                        fill=\"none\"\n                        stroke=\"currentColor\"\n                        strokeWidth={1.5}\n                        strokeLinecap=\"round\"\n                        aria-hidden\n                      >\n                        <path d=\"m4.5 4.5 7 7M11.5 4.5l-7 7\" />\n                      </svg>\n                    </button>\n                  </Delayed>\n                </div>\n                {/* Not shared with the card: there the summary is cut off\n                    with an ellipsis, so flying it across would snap the\n                    hidden words in. It arrives with the detail instead. */}\n                <Delayed reduceMotion={reduceMotion}>\n                  <p className=\"mt-4 text-[15px] text-muted-foreground\">{open.summary}</p>\n                  <p className=\"mt-2.5 text-[15px] leading-6 text-pretty text-muted-foreground\">\n                    {open.detail}\n                  </p>\n                </Delayed>\n              </motion.div>\n            )}\n          </AnimatePresence>\n        </div>\n      </div>\n    </LayoutGroup>\n  );\n}\n\n// Text flies to its new spot by position only. Letting it scale with its\n// box would squash the glyphs whenever the box changes aspect.\nfunction sharedText(layoutId: string | undefined) {\n  return {\n    layoutId,\n    layoutCrossfade: false,\n    layout: \"position\" as const,\n    transition: MORPH,\n  };\n}\n\n// Content that only exists in the expanded view. It waits out the morph on\n// the way in, then comes into focus: the blur bridges nothing to text so it\n// reads as arriving rather than blinking on. On the way out the whole dialog\n// is swapped for the card at once, so it never needs an exit of its own.\nfunction Delayed({\n  reduceMotion,\n  children,\n}: {\n  reduceMotion: boolean;\n  children: React.ReactNode;\n}) {\n  return (\n    <motion.div\n      initial={\n        reduceMotion\n          ? { opacity: 0 }\n          : { opacity: 0, y: 4, filter: \"blur(4px)\" }\n      }\n      animate={{\n        opacity: 1,\n        y: 0,\n        filter: \"blur(0px)\",\n        transition: {\n          delay: reduceMotion ? 0 : DETAIL_DELAY,\n          duration: 0.25,\n          ease: EASE_OUT,\n        },\n      }}\n    >\n      {children}\n    </motion.div>\n  );\n}\n\nfunction CardFace({\n  item,\n  shared,\n  returning = false,\n}: {\n  item: ExpandingCardItem;\n  shared?: (key: string) => string | undefined;\n  returning?: boolean;\n}) {\n  // The invisible slot copy renders without layoutIds, so it can never\n  // compete with the real card for a shared element.\n  const Text = shared ? motion.span : \"span\";\n  const props = (key: string) =>\n    shared ? sharedText(shared(`${key}-${item.id}`)) : {};\n\n  return (\n    <span className=\"flex flex-col items-start gap-1.5 px-4.5 py-4\">\n      <span className=\"flex w-full items-baseline justify-between gap-4\">\n        <Text\n          {...props(\"title\")}\n          className=\"truncate text-[15px] font-medium text-foreground\"\n        >\n          {item.title}\n        </Text>\n        <Text\n          {...props(\"meta\")}\n          className=\"shrink-0 text-[13px] text-muted-foreground tabular-nums\"\n        >\n          {item.meta}\n        </Text>\n      </span>\n      {shared ? (\n        // Layout-aware so Motion corrects it for the card's scale; a plain\n        // child would stretch with the card as it shrinks back into its\n        // slot. It isn't shared with the dialog, so on the way back it\n        // comes into focus once the card has nearly landed.\n        <motion.span\n          layout=\"position\"\n          transition={MORPH}\n          initial={returning ? { opacity: 0, filter: \"blur(4px)\" } : false}\n          animate={{\n            opacity: 1,\n            filter: \"blur(0px)\",\n            transition: { delay: RETURN_DELAY, duration: 0.2, ease: EASE_OUT },\n          }}\n          className=\"max-w-full truncate text-sm text-muted-foreground\"\n        >\n          {item.summary}\n        </motion.span>\n      ) : (\n        <span className=\"max-w-full truncate text-sm text-muted-foreground\">\n          {item.summary}\n        </span>\n      )}\n    </span>\n  );\n}\n\nconst notes: ExpandingCardItem[] = [\n  {\n    id: \"layouts\",\n    title: \"Shared layouts\",\n    meta: \"Sep 18\",\n    summary: \"Cards morph into their detail view.\",\n    detail:\n      \"Give two elements the same layoutId and Motion animates one into the other, measuring both boxes and bridging them with transforms.\",\n  },\n  {\n    id: \"springs\",\n    title: \"Spring timing\",\n    meta: \"Aug 30\",\n    summary: \"Springs take a duration and bounce.\",\n    detail:\n      \"Describe a spring by how long it should feel and how much it should overshoot, instead of tuning stiffness and damping by hand.\",\n  },\n  {\n    id: \"motion\",\n    title: \"Reduced motion\",\n    meta: \"Aug 12\",\n    summary: \"Morphs become a plain swap.\",\n    detail:\n      \"When the system asks for less motion, the card and its detail view cross-fade in place with nothing flying across the screen.\",\n  },\n];\n\nexport default function ExpandingCardDemo() {\n  return <ExpandingCards items={notes} />;\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":["cards"],"docs":"From ui lab: https://lab.xevrion.dev/lab/expanding-card"}