{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "morph",
  "title": "Morph",
  "description": "One surface becomes another: shared-layout surfaces without bounce, content that travels without stretching, a box-shadow rim that stays 1px, and parts that rise in after the surface.",
  "dependencies": [
    "motion"
  ],
  "devDependencies": [],
  "registryDependencies": [
    "utils",
    "https://reactmotionkit.com/r/motion-presets.json",
    "https://reactmotionkit.com/r/motion-kit.json",
    "https://reactmotionkit.com/r/beats.json",
    "https://reactmotionkit.com/r/compose-refs.json"
  ],
  "files": [
    {
      "path": "lib/morph.tsx",
      "content": "\"use client\"\n\nimport {\n  cancelFrame,\n  frame,\n  type HTMLMotionProps,\n  LayoutGroup,\n  motion,\n  type MotionValue,\n  type Transition,\n  useIsPresent,\n  useMotionValue,\n} from \"motion/react\"\nimport {\n  createContext,\n  type ReactNode,\n  useCallback,\n  useContext,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\"\n\nimport { cascade, type CascadeOptions } from \"@/lib/beats\"\nimport { composeRefs } from \"@/lib/compose-refs\"\nimport type { MotionTokens, Temperament } from \"@/lib/motion\"\nimport { useMotionKit } from \"@/lib/motion-kit\"\nimport { cn } from \"@/lib/utils\"\n\n/**\n * The morph (\"il morphing\"), the third shape of the MotionKit shape language\n * (docs/plan/SHAPE-LANGUAGE.md): one surface becomes another. A button becomes its\n * popover, a search field becomes the command palette, a toast's icon disc becomes the\n * toast, a skeleton block becomes the content it stood for. The Morphing Dialog is the\n * reference; this is its grammar for everything smaller than a dialog:\n *\n * - one `MorphSurface` on each side shares a layout id, so Motion flies the box from one\n *   to the other and crossfades the two looks;\n * - the surface never bounces: a bouncing box re-wraps its text twice and can cross the\n *   screen edge. It takes the temperament's duration and nothing else of its character;\n * - text travels in `MorphContent` (`layout=\"position\"`): its box moves, letters never stretch;\n * - the rim and shadow are a `box-shadow` list held in the `--morph-rim` variable and\n *   counter-scaled every frame of a flight (Motion's own correction skips shadow lists), so\n *   a 1px line stays 1px while a CSS border would stretch with the box. The surface's\n *   `box-shadow` itself composes that variable with Tailwind's ring and shadow utilities: a\n *   consumer's `focus-visible:ring-*` halo draws next to the rim instead of being replaced;\n * - parts that exist on one side only arrive in a `MorphRise` cascade after the surface,\n *   and leave in the first 40% of the way back.\n *\n * `solid` (opt-in) is the family rule for surfaces that must never read as an empty tile: the\n * surface always draws a rim and a fill while it flies, clips its content to its corners, and\n * its `MorphContent` arrives from 35% of the morph and leaves in the first 40% of the way back,\n * the same beats as `MorphRise`.\n *\n * Render the growing side inside `AnimatePresence` so the way back is animated too. When\n * the origin must stay visible under the destination (a field under its list), give it\n * `ghost`: a copy of its look flies and the real element stays.\n */\n\n/**\n * Who is flying right now. The ghost copy is visible while any flight of the group is on\n * (the destination arriving, the ghost flying back, or both when closed mid-way); at rest it\n * is invisible. A surface ends its flight when its layout animation completes or when it\n * unmounts, and the end of the flight that started last ends them all: an interrupted flight\n * whose completion never comes (a flight back cut by a reopen, a panel closed before its\n * arrival started) cannot leave the ghost visible over the origin.\n */\ninterface Flight {\n  addGhost: (opacity: MotionValue<number>) => () => void\n  /** A surface whose rim is counter-scaled while any flight of the group is on. */\n  addRim: (rim: RimCorrection) => () => void\n  start: (owner: object) => void\n  end: (owner: object) => void\n}\n\nfunction createFlight(): Flight {\n  const ghosts = new Set<MotionValue<number>>()\n  const rims = new Set<RimCorrection>()\n  const flying = new Set<object>()\n  let latest: object | null = null\n  return {\n    addGhost: (opacity) => {\n      ghosts.add(opacity)\n      return () => {\n        ghosts.delete(opacity)\n      }\n    },\n    addRim: (rim) => {\n      rims.add(rim)\n      if (flying.size > 0) rim.begin(\"flight\")\n      return () => {\n        rims.delete(rim)\n      }\n    },\n    start: (owner) => {\n      const idle = flying.size === 0\n      flying.add(owner)\n      latest = owner\n      if (!idle) return\n      ghosts.forEach((opacity) => {\n        opacity.set(1)\n      })\n      rims.forEach((rim) => {\n        rim.begin(\"flight\")\n      })\n    },\n    end: (owner) => {\n      if (!flying.delete(owner)) return\n      if (owner === latest) {\n        flying.clear()\n        latest = null\n      }\n      if (flying.size > 0) return\n      ghosts.forEach((opacity) => {\n        opacity.set(0)\n      })\n      rims.forEach((rim) => {\n        rim.finish(\"flight\")\n      })\n    },\n  }\n}\n\n/** The CSS variable that holds a surface's rim; the surface's `box-shadow` reads it. */\nconst RIM_VAR = \"--morph-rim\"\n\n/*\n * The surface's box-shadow: Tailwind's shadow slot carries the rim, so `ring-*`,\n * `inset-ring-*` and `ring-offset-*` utilities on the same element (a focus halo) compose\n * with it as they do with any `shadow-*`. A consumer `shadow-*` class would replace the rim.\n */\nconst RIM_CLASS = \"shadow-[var(--morph-rim)]\"\n\n/*\n * What a `solid` surface draws when the consumer gives no rim or fill: a 1px line in the\n * shadcn border colour and the popover surface, so the flying box is never a rimless,\n * see-through tile. A consumer `rim` or `bg-*` class replaces them.\n */\nconst SOLID_RIM = \"0 0 0 1px var(--border)\"\nconst SOLID_FILL = \"bg-popover\"\n\n/** Splits a CSS list on the commas outside parentheses (`rgb(0 0 0/0.2)` stays whole). */\nfunction splitTopLevel(value: string, separator: RegExp) {\n  const parts: string[] = []\n  let depth = 0\n  let current = \"\"\n  for (const char of value) {\n    if (char === \"(\") depth++\n    else if (char === \")\") depth--\n    if (depth === 0 && separator.test(char)) {\n      if (current.trim()) parts.push(current.trim())\n      current = \"\"\n    } else current += char\n  }\n  if (current.trim()) parts.push(current.trim())\n  return parts\n}\n\nconst LENGTH = /^(-?\\d*\\.?\\d+)(px)?$/\n\n/**\n * A `box-shadow` list as it must be written on a box drawn at `scaleX` × `scaleY` so it\n * reads at its written size on screen: offsets divide by their axis' scale, blur and\n * spread by the mean scale (they apply to both axes), as Motion corrects a single shadow.\n */\nexport function counterScaleShadow(shadow: string, scaleX: number, scaleY: number) {\n  if (!(scaleX > 0) || !(scaleY > 0) || (scaleX === 1 && scaleY === 1)) return shadow\n  const mean = (scaleX + scaleY) / 2\n  const divisors = [scaleX, scaleY, mean, mean]\n  return splitTopLevel(shadow, /,/)\n    .map((layer) => {\n      let index = 0\n      return splitTopLevel(layer, /\\s/)\n        .map((token) => {\n          const match = LENGTH.exec(token)\n          const divisor = divisors[index]\n          if (!match?.[1] || divisor === undefined) return token\n          index++\n          return `${String(Number(match[1]) / divisor)}px`\n        })\n        .join(\" \")\n    })\n    .join(\", \")\n}\n\ntype RimSource = \"flight\" | \"self\"\n\ninterface RimCorrection {\n  begin: (source: RimSource) => void\n  finish: (source: RimSource) => void\n}\n\n/**\n * Keeps the rim of a scaled surface at its written size: while the surface is flying (its\n * own layout animation or a flight of its group), every frame after Motion has written the\n * projection transform, the rim variable is rewritten for the scale actually drawn. The\n * element's CSS transitions are paused meanwhile, so the box-shadow follows each frame.\n */\nfunction useRimCorrection(rim: string | undefined) {\n  const element = useRef<HTMLDivElement | null>(null)\n  const latestRim = useRef(rim)\n  const [correction] = useState(() => {\n    const sources = new Set<RimSource>()\n    let transition: string | null = null\n    const update = () => {\n      const node = element.current\n      const value = latestRim.current\n      if (!node || value === undefined || !node.offsetWidth || !node.offsetHeight) return\n      const box = node.getBoundingClientRect()\n      node.style.setProperty(\n        RIM_VAR,\n        counterScaleShadow(value, box.width / node.offsetWidth, box.height / node.offsetHeight),\n      )\n    }\n    const stop = () => {\n      cancelFrame(update)\n      const node = element.current\n      if (!node) return\n      if (latestRim.current !== undefined) node.style.setProperty(RIM_VAR, latestRim.current)\n      if (transition !== null) node.style.transition = transition\n      transition = null\n    }\n    const value: RimCorrection & { stop: () => void } = {\n      begin: (source) => {\n        if (latestRim.current === undefined) return\n        const idle = sources.size === 0\n        sources.add(source)\n        if (!idle) return\n        const node = element.current\n        if (node) {\n          transition = node.style.transition\n          node.style.transition = \"none\"\n        }\n        frame.postRender(update, true)\n      },\n      finish: (source) => {\n        if (!sources.delete(source) || sources.size > 0) return\n        stop()\n      },\n      stop: () => {\n        sources.clear()\n        stop()\n      },\n    }\n    return value\n  })\n  useLayoutEffect(() => {\n    latestRim.current = rim\n  }, [rim])\n  useLayoutEffect(\n    () => () => {\n      correction.stop()\n    },\n    [correction],\n  )\n  return { correction, element }\n}\n\ninterface MorphContextValue {\n  id: string\n  motion: MotionTokens\n  flight: Flight\n  /** Changes whenever a surface mounts into a live group: every part re-renders with it. */\n  revision: number\n  /** Called by a surface that mounted after the group: starts the morph (see `MorphGroup`). */\n  surfaceMounted: () => void\n  /** True once the group has mounted: a part rendered from then on is arriving. */\n  isLive: () => boolean\n}\n\nconst MorphContext = createContext<MorphContextValue | null>(null)\n\n/**\n * Set by a `solid` surface for its content: `arrival` when the surface mounted into a live\n * group (its content fades in from 35%), false when it was there from the first paint.\n */\nconst SolidContext = createContext<{ arrival: boolean } | null>(null)\n\nfunction useMorphContext(part: string) {\n  const context = useContext(MorphContext)\n  if (!context) throw new Error(`<${part}> must be inside <MorphGroup>.`)\n  return context\n}\n\n/** The spring of a morphing surface: the temperament's duration, no bounce (see above). */\nexport function morphTransition(motion: MotionTokens): Transition {\n  if (motion.reduced) return motion.fade\n  return { type: \"spring\", visualDuration: motion.seconds(motion.values.duration), bounce: 0 }\n}\n\nexport interface MorphGroupProps {\n  /** Motion character; defaults to the provider's, else `lively`. */\n  temperament?: Temperament\n  children: ReactNode\n}\n\n/**\n * Scope of one morph: the two surfaces inside it share a layout id. Put the origin (the\n * button, the field, the disc) and the destination (the panel, the card) both inside.\n */\nexport function MorphGroup({ temperament, children }: MorphGroupProps) {\n  const id = useId()\n  const motionKit = useMotionKit(temperament)\n  const [flight] = useState(createFlight)\n  const [revision, setRevision] = useState(0)\n  const mounted = useRef(false)\n  useLayoutEffect(() => {\n    mounted.current = true\n  }, [])\n  const surfaceMounted = useCallback(() => {\n    if (mounted.current) setRevision((current) => current + 1)\n  }, [])\n  const isLive = useCallback(() => mounted.current, [])\n  /*\n   * Motion only flies a shared layout id from a box it measured before the commit, and it\n   * measures a surface only when that surface re-renders. A destination that mounts on its\n   * own (its open state lives in a sibling, the origin is memoised) would find no origin\n   * measurement and appear in place. So a surface mounting into a live group re-renders\n   * every part of the group in the same frame, before paint: the origin's box is measured\n   * (it has not moved) and the flight starts from it.\n   */\n  const value = useMemo(\n    () => ({\n      id,\n      motion: motionKit,\n      flight,\n      revision,\n      surfaceMounted,\n      isLive,\n    }),\n    [id, motionKit, flight, revision, surfaceMounted, isLive],\n  )\n  return (\n    <MorphContext value={value}>\n      <LayoutGroup id={id}>{children}</LayoutGroup>\n    </MorphContext>\n  )\n}\n\n/** Resolved motion tokens and the surface transition of the enclosing `MorphGroup`. */\nexport function useMorph() {\n  const { motion: motionKit } = useMorphContext(\"useMorph\")\n  return { motion: motionKit, transition: morphTransition(motionKit) }\n}\n\nexport interface MorphSurfaceProps extends HTMLMotionProps<\"div\"> {\n  /** Corner radius in px. Inline, so Motion can keep the corners round while the box flies. */\n  radius?: number\n  /**\n   * Rim and shadow as a `box-shadow` list, e.g. `\"0 0 0 1px var(--border), 0 8px 24px -12px rgb(0 0 0/0.2)\"`.\n   * Drawn this way they stay 1px while the surface is scaled. They take Tailwind's shadow\n   * slot, so ring utilities on the surface (`focus-visible:ring-[3px]`, `has-[:focus-visible]:ring-*`)\n   * draw beside them; do not add a `shadow-*` class to a surface that has a rim.\n   */\n  rim?: string\n  /**\n   * Keeps this surface visible and in the layout while the other one exists: a field that\n   * must stay focused under its list, a thumb under its value bubble, a button under its\n   * menu. The surface renders as a plain element and a ghost copy of its look (background,\n   * radius, rim: not its content) carries the layout id and flies instead, the Morphing\n   * Dialog's technique in one prop. The copy is drawn under this surface's content and only\n   * while a morph is in flight; at rest it is invisible and inert. Without it, Motion hides\n   * this surface while the other one exists, and the two read as one object that moved.\n   */\n  ghost?: boolean\n  /**\n   * Opt-in. The surface always draws its rim and fill during the morph (default rim\n   * `0 0 0 1px var(--border)` and `bg-popover` when none is given), clips its content to\n   * its corners (`overflow-hidden`), and its `MorphContent` (without `slot`) fades in from\n   * 35% of the morph when the surface arrives and out in the first 40% when it leaves. On\n   * a `ghost` origin only the flying copy takes the default rim and fill; the origin's own\n   * look and content are untouched. Default `false`: the surface behaves as before.\n   */\n  solid?: boolean\n}\n\n/**\n * A surface that morphs into (or from) the other `MorphSurface` of the group. Give it the\n * padding, background and the `rim`; put text in `MorphContent` and one-side-only parts in\n * `MorphRise`. Avoid CSS `border` on it.\n */\nexport function MorphSurface({\n  radius = 12,\n  rim,\n  ghost = false,\n  solid = false,\n  className,\n  style,\n  transition,\n  ref,\n  children,\n  ...props\n}: MorphSurfaceProps) {\n  const { id, motion: motionKit, flight, surfaceMounted, isLive } = useMorphContext(\"MorphSurface\")\n  const surfaceTransition = transition ?? morphTransition(motionKit)\n  const [token] = useState(() => ({}))\n  const ghostOpacity = useMotionValue(0)\n  const present = useIsPresent()\n  // Set while this surface is arriving (mounted or re-entering): its next flight is the morph.\n  const arriving = useRef(false)\n  // Whether this surface mounted into a live group: then its solid content is arriving.\n  const [solidContent] = useState(() => (solid && !ghost ? { arrival: isLive() } : null))\n  // The rim of the element that flies (the surface itself, or its ghost copy).\n  const flightRim = rim ?? (solid ? SOLID_RIM : undefined)\n  const flightFill = solid ? SOLID_FILL : undefined\n  const { correction, element } = useRimCorrection(flightRim)\n  const rimLook = rim === undefined ? undefined : RIM_CLASS\n  const rimStyle = rim === undefined ? undefined : { [RIM_VAR]: rim }\n  const flightRimLook = flightRim === undefined ? undefined : RIM_CLASS\n  const flightRimStyle = flightRim === undefined ? undefined : { [RIM_VAR]: flightRim }\n\n  useLayoutEffect(() => {\n    surfaceMounted()\n  }, [surfaceMounted])\n  useLayoutEffect(() => {\n    if (ghost) return flight.addGhost(ghostOpacity)\n    return () => {\n      flight.end(token)\n    }\n  }, [ghost, flight, ghostOpacity, token])\n  useLayoutEffect(() => flight.addRim(correction), [flight, correction])\n  useLayoutEffect(() => {\n    if (present) arriving.current = true\n  }, [present])\n\n  if (ghost) {\n    return (\n      <motion.div\n        ref={ref}\n        data-slot=\"morph-surface\"\n        data-ghost\n        className={cn(\"relative\", rimLook, className)}\n        // The copy sits under the content (z -1 inside an isolated surface): the origin's\n        // text and icons stay visible over it while it leaves and when it lands back.\n        style={{ borderRadius: radius, ...rimStyle, isolation: \"isolate\", ...style }}\n        {...props}\n      >\n        {children as ReactNode}\n        {/* The copy that flies: the surface's look at the surface's box, invisible at rest. */}\n        <motion.div\n          ref={element}\n          aria-hidden\n          data-slot=\"morph-ghost\"\n          layoutId={`${id}-surface`}\n          layout\n          transition={surfaceTransition}\n          onLayoutAnimationStart={() => {\n            flight.start(token)\n            props.onLayoutAnimationStart?.()\n          }}\n          onLayoutAnimationComplete={() => {\n            flight.end(token)\n            props.onLayoutAnimationComplete?.()\n          }}\n          className={cn(\n            flightFill,\n            flightRimLook,\n            className,\n            \"pointer-events-none absolute inset-0\",\n          )}\n          style={{ borderRadius: radius, ...flightRimStyle, opacity: ghostOpacity, zIndex: -1 }}\n        />\n      </motion.div>\n    )\n  }\n  return (\n    <motion.div\n      ref={composeRefs(ref, element)}\n      data-slot=\"morph-surface\"\n      layoutId={`${id}-surface`}\n      layout\n      transition={surfaceTransition}\n      className={cn(\"relative\", flightFill, flightRimLook, solid && \"overflow-hidden\", className)}\n      style={{ borderRadius: radius, ...flightRimStyle, ...style }}\n      {...props}\n      onLayoutAnimationStart={() => {\n        // Only the arrival is a morph from the ghost; later resizes of this surface are not.\n        if (arriving.current) flight.start(token)\n        arriving.current = false\n        // A resize scales the surface too: its rim is corrected for every layout animation.\n        correction.begin(\"self\")\n        props.onLayoutAnimationStart?.()\n      }}\n      onLayoutAnimationComplete={() => {\n        flight.end(token)\n        correction.finish(\"self\")\n        props.onLayoutAnimationComplete?.()\n      }}\n    >\n      {solidContent ? (\n        <SolidContext value={solidContent}>{children as ReactNode}</SolidContext>\n      ) : (\n        children\n      )}\n    </motion.div>\n  )\n}\n\nexport interface MorphContentProps extends HTMLMotionProps<\"div\"> {\n  /**\n   * Parts with the same `slot` on both sides travel as one (a label that becomes a\n   * title). Without it the content only moves with its surface, never stretching.\n   */\n  slot?: string\n}\n\n/**\n * Content inside a surface: its box travels (`layout=\"position\"`), its letters are never\n * stretched. The same `slot` on both sides makes the two texts one travelling text.\n */\nexport function MorphContent({ slot, className, transition, ...props }: MorphContentProps) {\n  const { id, motion: motionKit } = useMorphContext(\"MorphContent\")\n  const solid = useContext(SolidContext)\n  const surfaceTransition = transition ?? morphTransition(motionKit)\n  /*\n   * Inside a `solid` surface, unslotted content keeps the cascade's beats (it is the\n   * cascade's first part, without the rise): in from 35% of the morph, out in the first\n   * 40% of the way back. A slotted text travels as one shared element instead, whose\n   * opacity Motion crossfades itself, so it keeps the default.\n   */\n  const timed = solid !== null && !slot\n  const beats = timed ? cascade(motionKit, 0) : null\n  const exitTransition = beats ? (beats.exit.transition ?? beats.transition) : undefined\n  return (\n    <motion.div\n      data-slot=\"morph-content\"\n      layoutId={slot ? `${id}-${slot}` : undefined}\n      layout=\"position\"\n      transition={\n        beats ? { ...surfaceTransition, opacity: { ...beats.transition } } : surfaceTransition\n      }\n      {...(beats\n        ? {\n            initial: solid?.arrival ? { opacity: 0 } : false,\n            animate: { opacity: 1 },\n            exit: { opacity: 0, transition: exitTransition },\n          }\n        : {})}\n      className={cn(\"relative\", className)}\n      {...props}\n    />\n  )\n}\n\nexport interface MorphRiseProps\n  extends Omit<HTMLMotionProps<\"div\">, \"initial\" | \"animate\" | \"exit\">, CascadeOptions {\n  /** Position in the cascade: each part starts a stagger step after the previous one. */\n  index?: number\n}\n\n/**\n * A part that exists on one side only (a list under the morphed button, a close\n * button). It rises in after the surface, one stagger step per `index`, and leaves in the\n * first 40% of the way back. Needs `AnimatePresence` above the surface for the exit.\n */\nexport function MorphRise({\n  index = 0,\n  after,\n  maxTotal,\n  from,\n  className,\n  ...props\n}: MorphRiseProps) {\n  const { motion: motionKit } = useMorphContext(\"MorphRise\")\n  const beats = cascade(motionKit, index, { after, maxTotal, from })\n  return (\n    <motion.div\n      data-slot=\"morph-rise\"\n      initial={beats.initial}\n      animate={beats.animate}\n      exit={beats.exit}\n      transition={beats.transition}\n      className={cn(\"relative\", className)}\n      {...props}\n    />\n  )\n}\n",
      "type": "registry:lib"
    }
  ],
  "meta": {
    "tier": "free",
    "collection": "interface",
    "needsImage": false,
    "addedAt": "2026-10-16",
    "tags": [
      "shape",
      "morph",
      "shared-layout",
      "popover"
    ],
    "tech": [],
    "presets": [],
    "keyboard": [],
    "heavy": false
  },
  "categories": [
    "internal"
  ],
  "type": "registry:lib"
}