Skip to content

Morphing Modal

One panel morphs between inner views with a blur cross-fade.

Installation

CLI

npx shadcn@latest add https://hantui-theta.vercel.app/r/morphing-modal.json

Manual

  1. Install the dependencies

    npm install clsx lucide-react motion radix-ui tailwind-merge
  2. Add the shared helpers

    Components use cn() from lib/utils.ts and the motion tokens below. See Installation if you have not set them up yet.

    lib/motion.ts
    import type { Transition, Variants } from "motion/react";
    
    /** Durations in seconds. */
    export const duration = {
      instant: 0.1,
      quick: 0.18,
      base: 0.28,
      slow: 0.45,
    } as const;
    
    /** Cubic-bezier curves. */
    export const ease = {
      /** Entering, UI response. */
      out: [0.22, 1, 0.36, 1],
      /** Moving on screen. */
      inOut: [0.65, 0, 0.35, 1],
      /** Sheets and the mobile menu. */
      drawer: [0.32, 0.72, 0, 1],
    } as const;
    
    /** Everyday UI: presses, icon swaps, popovers and modals. Exits run at `exitFactor` of the enter. */
    export const ui = {
      press: { scale: 0.96, duration: 0.12 },
      icon: { type: "spring", duration: 0.3, bounce: 0 },
      popover: { duration: 0.18, ease: ease.out },
      modal: { duration: 0.24, ease: ease.out },
      exitFactor: 0.6,
    } as const;
    
    /** Once-per-visit motion on the landing page: hero letters, the reel and the afterimage. */
    export const kinetic = {
      heroLetter: { duration: 0.6, ease: ease.out },
      /** Delay per letter, eased so the wave slows toward the end. */
      heroStep: 0.035,
      reelSwap: { type: "spring", duration: 0.5, bounce: 0.1 },
      /** Two afterimages: lag in seconds and opacity of each. */
      ghost: { lag: [0.04, 0.09], opacity: [0.14, 0.06] },
    } as const;
    
    /** Spring presets. */
    export const spring = {
      snappy: { type: "spring", stiffness: 500, damping: 30 },
      smooth: { type: "spring", stiffness: 260, damping: 26 },
      bouncy: { type: "spring", stiffness: 300, damping: 15 },
    } as const satisfies Record<string, Transition>;
    
    /** Stagger between siblings, in seconds (0.03–0.06). */
    export const stagger = {
      tight: 0.03,
      base: 0.045,
      loose: 0.06,
    } as const;
    
    /** Blur + fade + y-offset. Falls back to a plain fade under reduced motion. */
    export function enterVariants(reduceMotion?: boolean | null, y = 8): Variants {
      if (reduceMotion) {
        return {
          hidden: { opacity: 0 },
          visible: { opacity: 1, transition: { duration: duration.base } },
          exit: { opacity: 0, transition: { duration: duration.quick } },
        };
      }
      return {
        hidden: { opacity: 0, y, filter: "blur(4px)" },
        visible: {
          opacity: 1,
          y: 0,
          filter: "blur(0px)",
          transition: { duration: duration.base, ease: ease.out },
        },
        exit: {
          opacity: 0,
          y: -y / 2,
          filter: "blur(4px)",
          transition: { duration: duration.quick, ease: ease.out },
        },
      };
    }
    
    /** Scale 0.96 → 1 for popovers, menus and dialogs. */
    export function overlayVariants(reduceMotion?: boolean | null): Variants {
      if (reduceMotion) {
        return {
          hidden: { opacity: 0 },
          visible: { opacity: 1, transition: { duration: duration.quick } },
          exit: { opacity: 0, transition: { duration: duration.instant } },
        };
      }
      return {
        hidden: { opacity: 0, scale: 0.96, filter: "blur(2px)" },
        visible: {
          opacity: 1,
          scale: 1,
          filter: "blur(0px)",
          transition: { duration: duration.quick, ease: ease.out },
        },
        exit: {
          opacity: 0,
          scale: 0.96,
          filter: "blur(2px)",
          transition: { duration: duration.instant + 0.02, ease: ease.out },
        },
      };
    }
    
    /** Parent variants that stagger their children in. */
    export function staggerVariants(gap: number = stagger.base, delayChildren = 0): Variants {
      return {
        hidden: {},
        visible: { transition: { staggerChildren: gap, delayChildren } },
        exit: { transition: { staggerChildren: gap / 2, staggerDirection: -1 } },
      };
    }
  3. Copy the source

    components/ui/morphing-modal/morphing-modal.tsx
    "use client";
    
    import { useEffect, useRef, useState, type ReactNode } from "react";
    import { AnimatePresence, motion, useReducedMotion } from "motion/react";
    import { Dialog } from "radix-ui";
    import { X } from "lucide-react";
    import { cn } from "@/lib/utils";
    import { duration, ease, overlayVariants } from "@/lib/motion";
    
    export interface MorphingModalProps {
      /** Controlled open state. */
      open?: boolean;
      /** Initial open state when uncontrolled. @default false */
      defaultOpen?: boolean;
      /** Called when the modal opens or closes. */
      onOpenChange?: (open: boolean) => void;
      /** Element that opens the modal, e.g. a button. */
      trigger?: ReactNode;
      /** Key of the current view. Changing it morphs the panel to the new view's height. @default "default" */
      view?: string;
      /** Heading of the current view; also the dialog's accessible name. */
      title: ReactNode;
      /** Supporting text under the title. */
      description?: ReactNode;
      /** Body of the current view. */
      children?: ReactNode;
      /** Show the close button in the corner. @default true */
      showClose?: boolean;
      /** Classes for the panel, e.g. a max width. */
      className?: string;
    }
    
    // The panel's height change and its scale-in share one spring.
    const LAYOUT = { type: "spring", stiffness: 380, damping: 34 } as const;
    
    export function MorphingModal({
      open,
      defaultOpen = false,
      onOpenChange,
      trigger,
      view = "default",
      title,
      description,
      children,
      showClose = true,
      className,
    }: MorphingModalProps) {
      const [internalOpen, setInternalOpen] = useState(defaultOpen);
      const isOpen = open ?? internalOpen;
      const reduceMotion = useReducedMotion();
      const viewRef = useRef<HTMLDivElement>(null);
      const previousView = useRef(view);
    
      const setOpen = (next: boolean) => {
        if (open === undefined) setInternalOpen(next);
        onOpenChange?.(next);
      };
    
      // When the view changes, the focused control has usually unmounted; move focus into the new view.
      useEffect(() => {
        if (previousView.current === view) return;
        previousView.current = view;
        const frame = requestAnimationFrame(() => {
          const target = viewRef.current?.querySelector<HTMLElement>("[data-autofocus]") ?? viewRef.current;
          target?.focus({ preventScroll: true });
        });
        return () => cancelAnimationFrame(frame);
      }, [view]);
    
      const layout = reduceMotion ? { duration: 0 } : LAYOUT;
    
      return (
        <Dialog.Root open={isOpen} onOpenChange={setOpen}>
          {trigger ? <Dialog.Trigger asChild>{trigger}</Dialog.Trigger> : null}
          <AnimatePresence>
            {isOpen ? (
              <Dialog.Portal forceMount>
                <Dialog.Overlay asChild forceMount>
                  <motion.div
                    className="fixed inset-0 z-50 bg-zinc-950/25 backdrop-blur-[2px]"
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    exit={{ opacity: 0 }}
                    transition={{ duration: duration.base }}
                  />
                </Dialog.Overlay>
                <div className="pointer-events-none fixed inset-0 z-50 flex items-center justify-center p-4">
                  {/* Radix links the description automatically; only opt out when there is none. */}
                  <Dialog.Content asChild forceMount {...(description ? {} : { "aria-describedby": undefined })}>
                    <motion.div
                      layout
                      variants={overlayVariants(reduceMotion)}
                      initial="hidden"
                      animate="visible"
                      exit="exit"
                      transition={{ layout }}
                      style={{ borderRadius: 20 }}
                      className={cn(
                        "pointer-events-auto relative w-full max-w-md overflow-hidden border border-border bg-popover text-popover-foreground shadow-xl outline-none",
                        className,
                      )}
                    >
                      <AnimatePresence mode="popLayout" initial={false}>
                        <motion.div
                          key={view}
                          ref={viewRef}
                          tabIndex={-1}
                          layout="position"
                          initial={reduceMotion ? { opacity: 0 } : { opacity: 0, scale: 0.98, filter: "blur(6px)" }}
                          animate={{ opacity: 1, scale: 1, filter: "blur(0px)" }}
                          exit={
                            reduceMotion
                              ? { opacity: 0, transition: { duration: duration.instant } }
                              : { opacity: 0, scale: 0.98, filter: "blur(6px)", transition: { duration: duration.quick } }
                          }
                          transition={{ duration: duration.base, ease: ease.out, layout }}
                          className="p-6 outline-none"
                        >
                          <Dialog.Title className="pr-8 text-lg font-semibold tracking-tight text-foreground">{title}</Dialog.Title>
                          {description ? (
                            <Dialog.Description className="mt-1.5 text-sm leading-6 text-muted-foreground">{description}</Dialog.Description>
                          ) : null}
                          {children ? <div className="mt-5">{children}</div> : null}
                        </motion.div>
                      </AnimatePresence>
                      {showClose ? (
                        <Dialog.Close
                          aria-label="Close"
                          className="absolute top-3.5 right-3.5 inline-flex size-8 cursor-pointer items-center justify-center rounded-full text-muted-foreground outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
                        >
                          <X className="size-4" aria-hidden="true" />
                        </Dialog.Close>
                      ) : null}
                    </motion.div>
                  </Dialog.Content>
                </div>
              </Dialog.Portal>
            ) : null}
          </AnimatePresence>
        </Dialog.Root>
      );
    }

Usage

import { MorphingModal } from "@/components/ui/morphing-modal/morphing-modal";

export function Upgrade() {
  const [view, setView] = useState("plans");
  return (
    <MorphingModal
      trigger={<button>Upgrade</button>}
      view={view}
      title={view === "plans" ? "Choose a plan" : "Payment"}
    >
      {view === "plans" ? <Plans onNext={() => setView("payment")} /> : <Payment />}
    </MorphingModal>
  );
}

API reference

PropTypeDefaultDescription
openboolean–Controlled open state.
defaultOpenbooleanfalseInitial open state when uncontrolled.
onOpenChange(open: boolean) => void–Called when the modal opens or closes.
triggerReactNode–Element that opens the modal, e.g. a button.
viewstring"default"Key of the current view. Changing it morphs the panel to the new view's height.
title*ReactNode–Heading of the current view; also the dialog's accessible name.
descriptionReactNode–Supporting text under the title.
childrenReactNode–Body of the current view.
showClosebooleantrueShow the close button in the corner.
classNamestring–Classes for the panel, e.g. a max width.
  • Change the view prop to move between steps; the panel's height morphs with a Motion layout animation while the content cross-fades.
  • The panel has an inline 20px radius so its corners stay round mid-morph.

Accessibility

  • Built on Radix Dialog: focus is trapped inside, Escape and the close button dismiss it, page scroll is locked and focus returns to the trigger.
  • The title is the dialog's accessible name and the description is linked automatically.
  • When the view changes, focus moves to the element marked data-autofocus in the new view (or the view itself), so keyboard and screen reader users never land on <body>.
  • With reduced motion enabled, the panel resizes instantly and views cross-fade without blur or scale.