{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"icon-morph","type":"registry:component","title":"Icon morph","description":"One icon becoming another: blur pop, direction-aware turn, card flip, or strokes that draw themselves. Fast toggling never jumps.","author":"Hairline UI","dependencies":[],"files":[{"path":"registry/icon-morph.tsx","type":"registry:component","content":"// Hairline UI · icon-morph · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { EASE_OUT, EASE_THROW, INTERACTION_FOCUS, INTERACTION_PRESS, useInteractionReducedMotion } from \"./ui-interaction-motion\";\n\n/* ─────────────────────────────────────────────────────────\n * ICON MORPH: one icon becoming another\n *\n *   blur     the old icon shrinks into a 3px blur while the new\n *            one pops out of it with a slight overshoot\n *   rotate   a quarter turn that keeps its direction: forward\n *            turns clockwise, back turns the other way\n *   flip     a card turn: the old icon goes edge-on, the new one\n *            comes round from behind\n *   draw     the new icon's strokes draw themselves, one after\n *            another, as the old one blurs away\n *\n * Every change starts from wherever the last one is, so fast\n * toggling never jumps. Two icons (from/to + active) or any\n * number (icons + value). Reduced motion gets a short crossfade.\n * ───────────────────────────────────────────────────────── */\n\nexport type IconMorphMode = \"blur\" | \"rotate\" | \"flip\" | \"draw\" | \"scale\";\n\nexport interface IconMorphProps extends Omit<React.HTMLAttributes<HTMLSpanElement>, \"children\"> {\n  /** Shown while `active` is false. */\n  from?: React.ReactNode;\n  /** Shown while `active` is true. */\n  to?: React.ReactNode;\n  active?: boolean;\n  /** Any number of icons by name; `value` picks one. Order sets the direction of rotate and flip. */\n  icons?: Record<string, React.ReactNode>;\n  value?: string;\n  /** How the icons trade places. \"scale\" is the old name for \"blur\". */\n  mode?: IconMorphMode;\n  /** Box size in px. */\n  size?: number;\n}\n\ntype Pose = { opacity: string; transform: string; filter: string };\n\nconst SHOWN: Pose = { opacity: \"1\", transform: \"none\", filter: \"blur(0px)\" };\nconst STROKES = \"path, line, polyline, polygon, circle, rect, ellipse\";\n\nfunction hidden(mode: IconMorphMode, dir: number, leaving: boolean): Pose {\n  const side = leaving ? dir : -dir;\n  if (mode === \"rotate\") return { opacity: \"0\", transform: `rotate(${90 * side}deg) scale(0.5)`, filter: \"blur(2px)\" };\n  if (mode === \"flip\") return { opacity: \"0\", transform: `rotateY(${90 * side}deg)`, filter: \"blur(0px)\" };\n  if (mode === \"draw\") return { opacity: \"0\", transform: \"scale(0.85)\", filter: \"blur(3px)\" };\n  return { opacity: \"0\", transform: \"scale(0.6)\", filter: \"blur(3px)\" };\n}\n\n/**\n * Where a layer starts from. Mid-animation, that's wherever it is now (so a fast toggle turns\n * back instead of jumping); at rest, the pose it held before this render flipped its opacity.\n */\nfunction startPose(el: HTMLElement, rest: Pose): Pose {\n  if (!el.getAnimations().some((a) => a.playState === \"running\")) return rest;\n  const style = getComputedStyle(el);\n  return { opacity: style.opacity, transform: style.transform, filter: style.filter === \"none\" ? \"blur(0px)\" : style.filter };\n}\n\nfunction animateLayer(el: HTMLElement, mode: IconMorphMode, dir: number, entering: boolean, reduced: boolean) {\n  const from = startPose(el, entering ? hidden(mode, dir, false) : SHOWN);\n  el.getAnimations().forEach((a) => a.cancel());\n  el.querySelectorAll<SVGElement>(STROKES).forEach((s) => s.getAnimations().forEach((a) => a.cancel()));\n\n  if (reduced) {\n    el.animate([{ opacity: from.opacity }, { opacity: entering ? \"1\" : \"0\" }], { duration: 160, easing: \"ease-out\" });\n    return;\n  }\n\n  if (!entering) {\n    if (mode === \"flip\") el.animate([from, hidden(mode, dir, true)], { duration: 170, easing: \"cubic-bezier(0.5,0,0.75,0)\" });\n    else el.animate([from, hidden(mode, dir, true)], { duration: 200, easing: EASE_OUT });\n    return;\n  }\n\n  if (mode === \"flip\") {\n    // Waits until the old face is edge-on, then comes round from behind.\n    const wait = Number(from.opacity) < 0.02;\n    el.animate(wait ? [{ ...from, offset: 0 }, { ...from, offset: 0.34, easing: EASE_OUT }, { ...SHOWN, offset: 1 }] : [from, SHOWN], {\n      duration: wait ? 500 : 340,\n      easing: wait ? \"linear\" : EASE_OUT,\n    });\n    return;\n  }\n  el.animate([{ opacity: from.opacity, filter: from.filter }, { opacity: \"1\", filter: \"blur(0px)\" }], { duration: mode === \"draw\" ? 180 : 260, easing: EASE_OUT });\n  el.animate([{ transform: from.transform }, { transform: \"none\" }], { duration: mode === \"rotate\" ? 480 : 440, easing: EASE_THROW });\n  if (mode !== \"draw\") return;\n  el.querySelectorAll<SVGGeometryElement>(STROKES).forEach((stroke, i) => {\n    const length = typeof stroke.getTotalLength === \"function\" ? stroke.getTotalLength() : 0;\n    if (!length) return;\n    stroke.animate([{ strokeDasharray: `${length}`, strokeDashoffset: `${length}` }, { strokeDasharray: `${length}`, strokeDashoffset: \"0\" }], {\n      duration: 420,\n      delay: 40 + Math.min(i, 5) * 60,\n      easing: EASE_OUT,\n      fill: \"backwards\",\n    });\n  });\n}\n\nexport function IconMorph({ from, to, active = false, icons, value, mode = \"blur\", size = 16, className = \"\", style, ...props }: IconMorphProps) {\n  const reduced = useInteractionReducedMotion();\n  const layers = React.useMemo<[string, React.ReactNode][]>(() => (icons ? Object.entries(icons) : [[\"from\", from], [\"to\", to]]), [icons, from, to]);\n  const key = icons ? (value ?? layers[0]?.[0]) : active ? \"to\" : \"from\";\n  const refs = React.useRef(new Map<string, HTMLSpanElement>());\n  const shownRef = React.useRef(key);\n  const kind: IconMorphMode = mode === \"scale\" ? \"blur\" : mode;\n\n  React.useLayoutEffect(() => {\n    const prev = shownRef.current;\n    if (prev === key) return;\n    shownRef.current = key;\n    const order = layers.map(([k]) => k);\n    const dir = order.indexOf(key) >= order.indexOf(prev) ? 1 : -1;\n    const leaving = refs.current.get(prev);\n    const entering = refs.current.get(key);\n    if (leaving) animateLayer(leaving, kind, dir, false, reduced);\n    if (entering) animateLayer(entering, kind, dir, true, reduced);\n  }, [key, layers, kind, reduced]);\n\n  return (\n    <span\n      aria-hidden=\"true\"\n      className={`relative inline-flex shrink-0 items-center justify-center ${className}`}\n      style={{ width: size, height: size, perspective: kind === \"flip\" ? 240 : undefined, ...style }}\n      {...props}\n    >\n      {layers.map(([k, node]) => (\n        <span\n          key={k}\n          ref={(el) => {\n            if (el) refs.current.set(k, el);\n            else refs.current.delete(k);\n          }}\n          className=\"absolute inset-0 flex items-center justify-center [backface-visibility:hidden] [&_svg]:size-full\"\n          style={{ opacity: k === key ? 1 : 0, willChange: \"transform, opacity\" }}\n        >\n          {node}\n        </span>\n      ))}\n    </span>\n  );\n}\n\nexport interface IconMorphButtonProps extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, \"children\"> {\n  from: React.ReactNode;\n  to: React.ReactNode;\n  active?: boolean;\n  defaultActive?: boolean;\n  onActiveChange?: (next: boolean) => void;\n  mode?: IconMorphMode;\n  /** sm 28px, md 36px, lg 40px. */\n  size?: \"sm\" | \"md\" | \"lg\";\n  variant?: \"outline\" | \"ghost\" | \"solid\";\n  /** Accessible name; the pressed state is announced with it. */\n  label: string;\n}\n\nconst BUTTON_SIZES = { sm: { box: \"size-7\", icon: 14 }, md: { box: \"size-9\", icon: 16 }, lg: { box: \"size-10\", icon: 18 } };\n\nconst BUTTON_TONES = {\n  outline: \"bg-card text-foreground shadow-[inset_0_0_0_1px_var(--border)] hover:bg-accent\",\n  ghost: \"bg-transparent text-muted-foreground hover:bg-accent hover:text-foreground\",\n  solid: \"bg-primary text-primary-foreground hover:bg-primary/90\",\n};\n\nexport function IconMorphButton({\n  from,\n  to,\n  active: controlled,\n  defaultActive = false,\n  onActiveChange,\n  mode = \"blur\",\n  size = \"md\",\n  variant = \"outline\",\n  label,\n  className = \"\",\n  onClick,\n  ...props\n}: IconMorphButtonProps) {\n  const [inner, setInner] = React.useState(defaultActive);\n  const active = controlled ?? inner;\n  const s = BUTTON_SIZES[size];\n\n  return (\n    <button\n      type=\"button\"\n      aria-label={label}\n      aria-pressed={active}\n      onClick={(e) => {\n        onClick?.(e);\n        if (e.defaultPrevented) return;\n        if (controlled === undefined) setInner(!active);\n        onActiveChange?.(!active);\n      }}\n      className={`inline-flex shrink-0 select-none items-center justify-center rounded-full cursor-pointer disabled:cursor-default disabled:opacity-45 ${s.box} ${BUTTON_TONES[variant]} ${INTERACTION_PRESS} ${INTERACTION_FOCUS} ${className}`}\n      {...props}\n    >\n      <IconMorph from={from} to={to} active={active} mode={mode} size={s.icon} />\n    </button>\n  );\n}\n\nexport default IconMorph;\n"},{"path":"registry/ui-interaction-motion.ts","type":"registry:component","content":"// Hairline UI · icon-morph · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n'use client';\n\nimport * as React from 'react';\n\nexport const EASE_OUT = 'cubic-bezier(0.16, 1, 0.3, 1)';\nexport const EASE_SETTLE = 'cubic-bezier(0.22, 1.18, 0.36, 1)';\n/** Thrown things (indicators, thumbs): a slight overshoot on transform only. */\nexport const EASE_THROW = 'cubic-bezier(0.34, 1.36, 0.64, 1)';\n/**\n * The press every button primitive shares: a 3% give that eases in and settles back.\n * Tailwind v4's scale-* writes the `scale` property, so `scale` has to be in the list\n * or the press snaps.\n */\nexport const INTERACTION_PRESS =\n  'transition-[background-color,color,box-shadow,opacity,scale] duration-200 ease-[cubic-bezier(0.16,1,0.3,1)] active:scale-[0.97] motion-reduce:transition-none motion-reduce:active:scale-100';\nexport const INTERACTION_FOCUS ='focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background';\n\nconst query = '(prefers-reduced-motion: reduce)';\nconst subscribe = (notify: () => void) => {\n  const media = window.matchMedia(query);\n  media.addEventListener('change', notify);\n  return () => media.removeEventListener('change', notify);\n};\nexport const useInteractionReducedMotion = () => React.useSyncExternalStore(subscribe, () => window.matchMedia(query).matches, () => false);\n\nexport function useInteractionActivity<T extends Element>() {\n  const ref = React.useRef<T>(null);\n  const [visible, setVisible] = React.useState(false);\n  const [hidden, setHidden] = React.useState(false);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const observer = new IntersectionObserver(([entry]) => setVisible(entry.isIntersecting));\n    observer.observe(el);\n    const visibility = () => setHidden(document.hidden);\n    visibility(); document.addEventListener('visibilitychange', visibility);\n    return () => { observer.disconnect(); document.removeEventListener('visibilitychange', visibility); };\n  }, []);\n  return { ref, active: visible && !hidden };\n}\n\nexport function interactionIcon(on: boolean, reduced: boolean): React.CSSProperties {\n  return { opacity: on ? 1 : 0, transform: on ? 'none' : 'scale(0.6)', filter: on ? 'blur(0px)' : 'blur(3px)', transition: reduced ? 'none' : `opacity 220ms ${EASE_OUT}, transform 380ms ${EASE_OUT}, filter 220ms ${EASE_OUT}` };\n}\n\n/** A raised object: one tight contact shadow, one short ambient, a hairline of light on its top edge. */\nexport const MATERIAL_LIFT =\n  'shadow-[0_1px_1.5px_rgb(0_0_0/0.07),0_3px_8px_-2px_rgb(0_0_0/0.1),inset_0_0.5px_0_rgb(255_255_255/0.8)] dark:shadow-[0_1px_2px_rgb(0_0_0/0.5),0_4px_10px_-2px_rgb(0_0_0/0.35),inset_0_0.5px_0_rgb(255_255_255/0.1)]';\n/** A trough something sits in, shaded from above, lit along its bottom edge. */\nexport const MATERIAL_RECESS =\n  'shadow-[inset_0_1px_2.5px_rgb(0_0_0/0.09),inset_0_-0.5px_0_rgb(255_255_255/0.7)] dark:shadow-[inset_0_1px_3px_rgb(0_0_0/0.45),inset_0_-0.5px_0_rgb(255_255_255/0.07)]';\n\nexport type SpringConfig = { stiffness: number; damping: number; mass?: number };\nexport interface Spring {\n  get(): number;\n  getVelocity(): number;\n  getTarget(): number;\n  /** Aim somewhere new from wherever it is now, keeping its speed. */\n  set(target: number): void;\n  /** Add speed (units per second), on top of what it already has. */\n  push(velocity: number): void;\n  /** Be there now, at rest. */\n  jump(value: number): void;\n  configure(config: SpringConfig): void;\n  stop(): void;\n}\n\n// Every moving spring on the page shares one frame loop, which sleeps when the last one rests. Each spring's onFrame runs\n// once per frame after all of them have stepped, so several springs that draw one shape paint it once.\nconst SPRING_STEP = 1 / 240;\ntype Running = { step: () => void };\nconst runningSprings = new Set<Running>();\nconst springPainters = new Set<() => void>();\nlet springFrame = 0;\nlet springLast = 0;\nlet springSpare = 0;\n\nfunction springTick(now: number) {\n  // A hidden tab stops the frames, so the first one back must not count the whole gap as time passed.\n  springSpare += Math.min((now - springLast) / 1000, 0.05);\n  springLast = now;\n  while (springSpare >= SPRING_STEP) {\n    runningSprings.forEach((spring) => spring.step());\n    springSpare -= SPRING_STEP;\n  }\n  const painters = [...springPainters];\n  springPainters.clear();\n  painters.forEach((paint) => paint());\n  springFrame = runningSprings.size ? requestAnimationFrame(springTick) : 0;\n}\n\nfunction wakeSprings(spring: Running) {\n  runningSprings.add(spring);\n  if (springFrame) return;\n  springSpare = 0;\n  springFrame = requestAnimationFrame((now) => {\n    springLast = now - 1000 / 60;\n    springTick(now);\n  });\n}\n\n/**\n * A spring that carries its speed: re-aim it mid-flight and it curves on from where it is, push it while it swings and the\n * push adds to the swing. Use it for anything that can be interrupted; a curve restarts from a standstill every time.\n * `onFrame` should write straight to the DOM. `precision` is how close counts as there, in the value's own units.\n */\nexport function createSpring(initial: number, config: SpringConfig, onFrame: () => void, precision = 0.01): Spring {\n  let value = initial;\n  let velocity = 0;\n  let target = initial;\n  let { stiffness, damping, mass = 1 } = config;\n  const running: Running = {\n    step() {\n      velocity += ((-stiffness * (value - target) - damping * velocity) / mass) * SPRING_STEP;\n      value += velocity * SPRING_STEP;\n      if (Math.abs(value - target) < precision && Math.abs(velocity) < precision * 10) {\n        value = target;\n        velocity = 0;\n        runningSprings.delete(running);\n      }\n      springPainters.add(onFrame);\n    },\n  };\n  return {\n    get: () => value,\n    getVelocity: () => velocity,\n    getTarget: () => target,\n    set(next) {\n      if (next === target && !runningSprings.has(running)) return;\n      target = next;\n      wakeSprings(running);\n    },\n    push(speed) {\n      velocity += speed;\n      wakeSprings(running);\n    },\n    jump(next) {\n      value = next;\n      target = next;\n      velocity = 0;\n      runningSprings.delete(running);\n      onFrame();\n    },\n    configure(next) {\n      ({ stiffness, damping, mass = 1 } = next);\n    },\n    stop() {\n      runningSprings.delete(running);\n    },\n  };\n}\n\n/** Sample recent movement rather than averaging a long drag and losing its release velocity. */\nexport type PointerSample = { x: number; time: number };\nexport function samplePointer(samples: PointerSample[], x: number, time: number) {\n  samples.push({ x, time });\n  while (samples.length > 2 && time - samples[0].time > 100) samples.shift();\n}\nexport function releaseVelocity(samples: PointerSample[], now: number) {\n  if (samples.length < 2 || now - samples[samples.length - 1].time > 100) return 0;\n  const first = samples[0], last = samples[samples.length - 1];\n  return (last.x - first.x) / Math.max(1, last.time - first.time);\n}\n\n/** Smooth Apple/rational rubber-band curve: continuous exponential-like resistance without linear kinks. */\nexport function rubberBand(overshoot: number, dimension = 320, constant = 0.55): number {\n  const d = dimension || 320;\n  const abs = Math.abs(overshoot);\n  return Math.sign(overshoot) * (1 - 1 / ((abs * constant) / d + 1)) * d;\n}\n\n/** Projects resting travel from release velocity (velocity in px/ms; time in seconds). */\nexport function projectInertia(distance: number, velocity: number, time = 0.12): number {\n  return distance + velocity * 1000 * time;\n}\n\n/** Smooths incoming release velocity toward a boundary so springs don't slam or clip into walls. */\nexport function softenVelocity(velocity: number, distanceToTarget: number, factor = 10): number {\n  const maxAllowed = Math.abs(distanceToTarget) * factor;\n  return Math.sign(velocity) * Math.min(Math.abs(velocity), maxAllowed);\n}\n\n/** A damped spring sampled by WAAPI: tuned for organic lightness with a hint of life (3% breath). */\nexport function springFrames(\n  from: number,\n  to: number,\n  velocity = 0,\n  duration = 480,\n  config: { omega?: number; damping?: number; steps?: number } = {},\n) {\n  const { omega = 16, damping = 0.74, steps = 36 } = config;\n  const damped = omega * Math.sqrt(Math.max(0.001, 1 - damping * damping));\n  const displacement = from - to;\n  const coefficient = (velocity * 1000 + damping * omega * displacement) / damped;\n  return Array.from({ length: steps + 1 }, (_, i) => {\n    const t = (i / steps) * (duration / 1000);\n    const value = to + Math.exp(-damping * omega * t) * (displacement * Math.cos(damped * t) + coefficient * Math.sin(damped * t));\n    return { value: i === steps ? to : value, offset: i / steps };\n  });\n}\n\n"}],"css":{},"docs":"Docs and live preview: https://hairlineui.com/ui/icon-morph. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}