{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "morphing-dialog",
  "title": "Morphing dialog",
  "description": "A service card expands into a booking dialog, with its image, title and price flying into place through a shared-layout spring, then folds back into the card on Esc or backdrop click.",
  "dependencies": [
    "lucide-react",
    "motion"
  ],
  "registryDependencies": [
    "https://goodui.dev/r/goodui-motion.json",
    "https://goodui.dev/r/locale.json"
  ],
  "files": [
    {
      "path": "registry/components/overlays/morphing-dialog.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { AnimatePresence, MotionConfig, motion, useDragControls, useMotionValue, useReducedMotion, useTransform, type DragControls, type MotionValue, type PanInfo, type Transition } from \"motion/react\"\nimport { X } from \"lucide-react\"\nimport { cn } from \"@/lib/utils\"\nimport { useLabels } from \"@/lib/goodui-locale\"\nimport { GooduiTokens, ease, spring } from \"@/lib/goodui-motion\"\n\nconst SPRING: Transition = spring.morph\n/** Drag-to-dismiss thresholds, the same as vaul: px/s and a fraction of the dialog's height. */\nconst FLICK_VELOCITY = 400\nconst CLOSE_FRACTION = 0.25\nconst FOCUSABLE =\n  'a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex=\"-1\"])'\n\nfunction useControllable<T>(value: T | undefined, defaultValue: T, onChange?: (v: T) => void) {\n  const [inner, setInner] = React.useState(defaultValue)\n  const controlled = value !== undefined\n  const current = controlled ? value : inner\n  const set = React.useCallback(\n    (v: T) => {\n      if (!controlled) setInner(v)\n      onChange?.(v)\n    },\n    [controlled, onChange],\n  )\n  return [current, set] as const\n}\n\ntype DialogContextValue = {\n  open: boolean\n  setOpen: (open: boolean) => void\n  uid: string\n  titleId: string\n  descriptionId: string\n  triggerRef: React.RefObject<HTMLButtonElement | null>\n  /** True from opening until the card has flown back into place, so it stays above its neighbours. */\n  lifted: boolean\n  setLifted: (lifted: boolean) => void\n  /** Whether a MorphingDialogDescription is mounted, so aria-describedby never points at a missing element. */\n  hasDescription: boolean\n  setHasDescription: (has: boolean) => void\n  /** Vertical drag offset of the dialog; the backdrop thins out with it. */\n  dragY: MotionValue<number>\n  dragControls: DragControls\n  reduce: boolean\n}\n\nconst DialogContext = React.createContext<DialogContextValue | null>(null)\nconst InContentContext = React.createContext(false)\n\nfunction useDialog() {\n  const ctx = React.useContext(DialogContext)\n  if (!ctx) throw new Error(\"MorphingDialog parts must be used inside <MorphingDialog>\")\n  return ctx\n}\n\nexport type MorphingDialogProps = {\n  /** Controlled open state. Pair with onOpenChange. */\n  open?: boolean\n  /** Initial open state when uncontrolled. */\n  defaultOpen?: boolean\n  /** Called with the next state when the trigger, Esc, the backdrop or a close control opens or closes it. */\n  onOpenChange?: (open: boolean) => void\n  /** Transition for the shared-layout morph. Reduced motion always snaps. */\n  transition?: Transition\n  children: React.ReactNode\n}\n\n/**\n * A card that expands into a dialog. Media, title and subtitle placed in both the trigger and the content\n * travel between the two with a shared-layout animation.\n *\n * The dialog is `position: fixed` without a portal, so keep it out of ancestors that set `transform`/`filter`.\n * For the morph to keep rounded corners, set the radius with `style={{ borderRadius }}` instead of a class.\n */\nexport function MorphingDialog({ open: openProp, defaultOpen = false, onOpenChange, transition, children }: MorphingDialogProps) {\n  const reduce = useReducedMotion() ?? false\n  const [open, setOpen] = useControllable(openProp, defaultOpen, onOpenChange)\n  const [lifted, setLifted] = React.useState(open)\n  const [hasDescription, setHasDescription] = React.useState(false)\n  const uid = React.useId()\n  const triggerRef = React.useRef<HTMLButtonElement | null>(null)\n  const wasOpen = React.useRef(open)\n  const dragY = useMotionValue(0)\n  const dragControls = useDragControls()\n\n  React.useEffect(() => {\n    if (open) setLifted(true)\n    if (!open && wasOpen.current) triggerRef.current?.focus({ preventScroll: true })\n    wasOpen.current = open\n    if (!open) return\n    const prev = document.body.style.overflow\n    document.body.style.overflow = \"hidden\"\n    const onKey = (e: KeyboardEvent) => {\n      if (e.key === \"Escape\") {\n        e.preventDefault()\n        setOpen(false)\n      }\n    }\n    document.addEventListener(\"keydown\", onKey)\n    return () => {\n      document.body.style.overflow = prev\n      document.removeEventListener(\"keydown\", onKey)\n    }\n  }, [open, setOpen])\n\n  const value = React.useMemo(\n    () => ({ open, setOpen, uid, titleId: `${uid}-title`, descriptionId: `${uid}-desc`, triggerRef, lifted, setLifted, hasDescription, setHasDescription, dragY, dragControls, reduce }),\n    [open, setOpen, uid, lifted, hasDescription, dragY, dragControls, reduce],\n  )\n\n  return (\n    <DialogContext.Provider value={value}>\n      <GooduiTokens />\n      <MotionConfig transition={reduce ? { duration: 0 } : (transition ?? SPRING)}>{children}</MotionConfig>\n    </DialogContext.Provider>\n  )\n}\n\nexport type MorphingDialogTriggerProps = Omit<React.ComponentProps<typeof motion.button>, \"ref\">\n\n/** The collapsed card. A real button: Enter or Space opens the dialog. */\nexport function MorphingDialogTrigger({ className, style, children, onClick, ...props }: MorphingDialogTriggerProps) {\n  const { open, setOpen, uid, triggerRef, lifted, setLifted } = useDialog()\n  return (\n    <motion.button\n      ref={triggerRef}\n      type=\"button\"\n      layoutId={`${uid}-card`}\n      aria-haspopup=\"dialog\"\n      aria-expanded={open}\n      onClick={(e) => {\n        onClick?.(e)\n        if (!e.defaultPrevented) setOpen(true)\n      }}\n      onLayoutAnimationComplete={() => {\n        if (!open) setLifted(false)\n      }}\n      className={cn(\n        \"pc-press pc-press-soft relative block w-full cursor-pointer overflow-hidden bg-card text-start text-card-foreground shadow-[var(--pc-e1)] outline-none focus-visible:ring-3 focus-visible:ring-ring/50\",\n        className,\n      )}\n      style={{ borderRadius: 16, zIndex: lifted ? 40 : undefined, ...style }}\n      {...props}\n    >\n      {children}\n    </motion.button>\n  )\n}\n\nexport type MorphingDialogContainerProps = {\n  /** Classes for the fixed layer that centers the dialog (padding, alignment). */\n  className?: string\n  /** Classes for the backdrop. */\n  backdropClassName?: string\n  children: React.ReactNode\n}\n\n/** Backdrop and centering layer. Clicking the backdrop closes the dialog. */\nexport function MorphingDialogContainer({ className, backdropClassName, children }: MorphingDialogContainerProps) {\n  const { open, setOpen, dragY } = useDialog()\n  const fade = useTransform(dragY, [0, 320], [1, 0.35])\n  return (\n    <AnimatePresence initial={false}>\n      {open && (\n        <motion.div key=\"pc-morphing-dialog\" className={cn(\"fixed inset-0 z-50 grid place-items-center p-4 sm:p-6\", className)}>\n          <motion.div style={{ opacity: fade }} className=\"absolute inset-0\">\n            <motion.div\n              aria-hidden=\"true\"\n              className={cn(\"absolute inset-0 bg-black/30 dark:bg-black/55\", backdropClassName)}\n              initial={{ opacity: 0 }}\n              animate={{ opacity: 1 }}\n              exit={{ opacity: 0 }}\n              transition={{ duration: 0.2 }}\n              onClick={() => setOpen(false)}\n            />\n          </motion.div>\n          {children}\n        </motion.div>\n      )}\n    </AnimatePresence>\n  )\n}\n\nexport type MorphingDialogContentProps = Omit<React.ComponentProps<typeof motion.div>, \"ref\"> & {\n  /** Drag the media or the grip down to close, with a flick or past a quarter of the height. Off with reduced motion. */\n  dragToDismiss?: boolean\n}\n\n/** The expanded dialog. Focus moves inside and is trapped until it closes. */\nexport function MorphingDialogContent({ className, style, children, onKeyDown, dragToDismiss = true, ...props }: MorphingDialogContentProps) {\n  const { uid, titleId, descriptionId, hasDescription, setOpen, dragY, dragControls, reduce } = useDialog()\n  const ref = React.useRef<HTMLDivElement>(null)\n  const drag = dragToDismiss && !reduce\n  const lean = useTransform(dragY, [0, 400], [1, 0.94])\n\n  // Reset here, not on release: the morph home starts from where the finger left it.\n  React.useEffect(() => () => dragY.jump(0), [dragY])\n\n  const onDragEnd = (_: unknown, info: PanInfo) => {\n    const height = ref.current?.offsetHeight ?? 400\n    if (info.velocity.y > FLICK_VELOCITY || info.offset.y > height * CLOSE_FRACTION) setOpen(false)\n  }\n\n  React.useEffect(() => {\n    const el = ref.current\n    if (!el) return\n    const first = el.querySelector<HTMLElement>(\"[data-autofocus]\") ?? el.querySelector<HTMLElement>(FOCUSABLE)\n    ;(first ?? el).focus({ preventScroll: true })\n  }, [])\n\n  const trap = (e: React.KeyboardEvent<HTMLDivElement>) => {\n    onKeyDown?.(e)\n    if (e.key !== \"Tab\" || !ref.current) return\n    const items = Array.from(ref.current.querySelectorAll<HTMLElement>(FOCUSABLE))\n    if (!items.length) return e.preventDefault()\n    const first = items[0]!\n    const last = items[items.length - 1]!\n    const active = document.activeElement\n    if (e.shiftKey && (active === first || active === ref.current)) {\n      e.preventDefault()\n      last.focus()\n    } else if (!e.shiftKey && active === last) {\n      e.preventDefault()\n      first.focus()\n    }\n  }\n\n  return (\n    <InContentContext.Provider value={true}>\n      <GooduiTokens />\n      <motion.div\n        ref={ref}\n        layoutId={`${uid}-card`}\n        drag={drag ? \"y\" : false}\n        dragControls={dragControls}\n        dragListener={false}\n        dragConstraints={{ top: 0, bottom: 0 }}\n        dragElastic={{ top: 0.04, bottom: 0.65 }}\n        dragMomentum={false}\n        dragTransition={{ bounceStiffness: 500, bounceDamping: 40 }}\n        onDragEnd={onDragEnd}\n        role=\"dialog\"\n        aria-modal=\"true\"\n        aria-labelledby={titleId}\n        aria-describedby={hasDescription ? descriptionId : undefined}\n        tabIndex={-1}\n        onKeyDown={trap}\n        className={cn(\n          \"relative z-10 flex max-h-[calc(100dvh-2rem)] w-full max-w-lg flex-col overflow-hidden bg-card text-card-foreground shadow-[var(--pc-e3)] outline-none\",\n          className,\n        )}\n        style={{ borderRadius: 24, y: dragY, scale: lean, ...style }}\n        {...props}\n      >\n        {drag && (\n          <span\n            aria-hidden=\"true\"\n            onPointerDown={(e) => dragControls.start(e)}\n            className=\"absolute inset-x-0 top-0 z-[5] flex h-6 cursor-grab touch-none justify-center pt-2 active:cursor-grabbing\"\n          >\n            <span className=\"h-1 w-9 rounded-full bg-black/25 dark:bg-white/30\" />\n          </span>\n        )}\n        {children as React.ReactNode}\n      </motion.div>\n    </InContentContext.Provider>\n  )\n}\n\nexport type MorphingDialogPartProps = Omit<React.ComponentProps<typeof motion.div>, \"ref\" | \"layoutId\">\n\n/** Image or illustration area. Put the same media in the trigger and the content. */\nexport function MorphingDialogMedia({ className, onPointerDown, ...props }: MorphingDialogPartProps) {\n  const { uid, dragControls, reduce } = useDialog()\n  const inContent = React.useContext(InContentContext)\n  return (\n    <motion.div\n      layoutId={`${uid}-media`}\n      className={cn(\"relative block overflow-hidden\", inContent && !reduce && \"cursor-grab touch-none select-none active:cursor-grabbing\", className)}\n      onPointerDown={(e) => {\n        onPointerDown?.(e)\n        if (inContent && !reduce) dragControls.start(e)\n      }}\n      {...props}\n    />\n  )\n}\n\n/** Title; it becomes the dialog's accessible name inside the content. */\nexport function MorphingDialogTitle({ className, children }: { className?: string; children: React.ReactNode }) {\n  const { uid, titleId } = useDialog()\n  const inContent = React.useContext(InContentContext)\n  const shared = { layoutId: `${uid}-title`, layout: \"position\" as const }\n  return inContent ? (\n    <motion.h2 id={titleId} {...shared} className={cn(\"text-lg font-semibold tracking-tight\", className)}>\n      {children}\n    </motion.h2>\n  ) : (\n    <motion.span {...shared} className={cn(\"block font-semibold tracking-tight\", className)}>\n      {children}\n    </motion.span>\n  )\n}\n\nexport function MorphingDialogSubtitle({ className, children }: { className?: string; children: React.ReactNode }) {\n  const { uid } = useDialog()\n  return (\n    <motion.span layoutId={`${uid}-subtitle`} layout=\"position\" className={cn(\"block text-sm text-muted-foreground\", className)}>\n      {children}\n    </motion.span>\n  )\n}\n\n/** Content that only exists in the open dialog. It fades up once the card has started to grow. */\nexport function MorphingDialogDescription({ className, children, ...props }: MorphingDialogPartProps) {\n  const { descriptionId, setHasDescription, reduce } = useDialog()\n  React.useEffect(() => {\n    setHasDescription(true)\n    return () => setHasDescription(false)\n  }, [setHasDescription])\n  return (\n    <motion.div\n      id={descriptionId}\n      initial={reduce ? { opacity: 0 } : { opacity: 0, y: 10, filter: \"blur(4px)\" }}\n      animate={{ opacity: 1, y: 0, filter: \"blur(0px)\", transition: reduce ? { duration: 0 } : { delay: 0.1, duration: 0.28, ease: ease.out } }}\n      exit={reduce ? { opacity: 0, transition: { duration: 0 } } : { opacity: 0, filter: \"blur(4px)\", transition: { duration: 0.1 } }}\n      className={className}\n      {...props}\n    >\n      {children}\n    </motion.div>\n  )\n}\n\nexport type MorphingDialogLabels = { close: string }\nconst DEFAULT_LABELS: MorphingDialogLabels = { close: \"Close\" }\n\nexport type MorphingDialogCloseProps = React.ComponentProps<\"button\"> & {\n  /** Text for built-in controls and screen readers; pass translations here. */\n  labels?: Partial<MorphingDialogLabels>\n}\n\nexport function MorphingDialogClose({ className, children, onClick, labels, ...props }: MorphingDialogCloseProps) {\n  const { setOpen } = useDialog()\n  const l = useLabels(\"morphing-dialog\", DEFAULT_LABELS, labels)\n  return (\n    <button\n      type=\"button\"\n      aria-label={children ? undefined : l.close}\n      onClick={(e) => {\n        onClick?.(e)\n        if (!e.defaultPrevented) setOpen(false)\n      }}\n      className={cn(\n        \"pc-press absolute end-3 top-3 z-10 inline-flex size-8 items-center justify-center rounded-full bg-background/80 text-foreground shadow-[var(--pc-e1)] backdrop-blur transition-colors outline-none hover:bg-background focus-visible:ring-3 focus-visible:ring-ring/50 [&_svg]:size-4\",\n        className,\n      )}\n      {...props}\n    >\n      <GooduiTokens />\n      {children ?? <X />}\n    </button>\n  )\n}\n",
      "type": "registry:component",
      "target": "components/goodui/morphing-dialog.tsx"
    }
  ],
  "categories": [
    "components",
    "overlays"
  ],
  "type": "registry:component"
}