Skip to main content

Icon Morph

Zero-dependency SVG stroke icon morphing with optimal stroke matching, rotation and mirror detection, ink draw-in/out, and velocity motion blur.

x-mark
Select an icon to morph

Customize

Duration (ms)680
Motion blur (px)5

Installation

npx shadcn@latest add @kinetic/icon-morph

To parse raw SVG strings from your own icon set at runtime or build time, also add the svg-to-paths helper:

npx shadcn@latest add @kinetic/svg-to-paths

Usage

Pass an icons map (name -> d[]) and control the active key through icon. Switching icon morphs smoothly even when triggered rapidly mid-flight.

"use client";

import { useState } from "react";
import { IconMorph, type IconMorphIconSet } from "@/components/kinetic/icons/icon-morph";

const MENU_ICONS: IconMorphIconSet = {
  menu: ["M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5"],
  close: ["M6 18 18 6M6 6l12 12"],
};

interface MenuToggleProps {
  readonly open: boolean;
  readonly onToggle: () => void;
}

export function MenuToggle({ open, onToggle }: MenuToggleProps) {
  return (
    <button
      type="button"
      onClick={onToggle}
      aria-label={open ? "Close navigation" : "Open navigation"}
      className="inline-flex size-9 items-center justify-center rounded-md border border-border"
    >
      <IconMorph icon={open ? "close" : "menu"} icons={MENU_ICONS} className="size-5" />
    </button>
  );
}

Bring your own icons

IconMorphEngine does not ship or lock you into a specific icon pack. It expects outline stroke icons drawn on a 24x24 viewBox with strokeWidth={1.5} and rounded caps and joins.

Install any MIT outline set such as heroicons and extract path strings with svgToPaths:

import { svgToPaths } from "@/components/kinetic/icons/svg-to-paths";
import type { IconMorphIconSet } from "@/components/kinetic/icons/icon-morph";

const rawHeart = `<svg viewBox="0 0 24 24"><path d="M21 8.25c0-2.485-2.099-4.5-4.688-4.5-1.935 0-3.597 1.126-4.312 2.733-.715-1.607-2.377-2.733-4.313-2.733C5.1 3.75 3 5.765 3 8.25c0 7.22 9 12 9 12s9-4.78 9-12Z"/></svg>`;
const rawCheck = `<svg viewBox="0 0 24 24"><path d="m4.5 12.75 6 6 9-13.5"/></svg>`;

export const MY_ICONS: IconMorphIconSet = {
  heart: svgToPaths(rawHeart),
  check: svgToPaths(rawCheck),
};

For larger sets, pre-extract the d[] arrays during your build (for example, reading node_modules/heroicons/24/outline/*.svg into JSON) and lazy-load the map only on routes that need the full catalog.

Note: svgToPaths expects un-transformed stroke geometry on a 0 0 24 24 viewBox. It ignores transform attributes and does not rescale other viewBoxes, emitting a warning when either is detected.

If you attach CSS filter utilities (such as drop-shadow-*) to IconMorph, set blurPx={0} so the engine never writes inline style.filter mid-morph; when blurPx > 0, inline style.filter is cleared back to "" once the transition settles. IconMorph locks viewBox="0 0 24 24", fill="none", and stroke="currentColor" on the root <svg> (overriding any stroke, fill, or viewBox passed through SVG props), so style stroke color with className utilities such as text-*. Use the imperative ref (set / morphTo) when not simultaneously driving the active icon via the controlled icon prop.

How it works

  1. Lazy subpath parsing: Each icon is parsed on first use into dense polylines, splitting multi-move paths and compressed arc flags while preserving tiny dots and merging collinear joints.
  2. Global stroke matching: A Hungarian assignment pairs source and target strokes by topology (open, closed, or dot), Procrustes shape distance, centroid proximity, and length ratio.
  3. Rotation and mirror detection: Similarity Procrustes with ICP refinement identifies whole-icon rotations, coin flips, and rotating inner subgroups inside stationary shells (such as cloud-arrow-up to cloud-arrow-down or arrow-down to arrow-down-circle).
  4. Ink draw-in and draw-out: Unmatched strokes draw out from the nearest anchor or retract cleanly instead of teleporting, while fill="split" divides long strokes when two icons share little topology.

Accessibility

  • Without a label prop, IconMorph renders aria-hidden="true" for decorative icons inside labeled buttons.
  • Passing label sets role="img" and aria-label={label} for standalone status icons.
  • Reduced motion and document tempo sync reactively through useMotionPreferences(). Under reduced motion, IconMorph snaps immediately to the target paths with zero blur and still calls onComplete.
  • During SSR, IconMorph renders the initial icon's static <path> elements so icons appear before hydration with no layout shift.

API Reference

IconMorph

React adapter around IconMorphEngine with SSR static fallback paths, reactive tempo and reduced-motion sync, and imperative handle. Locks viewBox="0 0 24 24", fill="none", and stroke="currentColor" (style color via text-* classes).

PropTypeDefaultDescription
iconstring-Active icon key from icons. Changing this prop morphs smoothly from the current visual state.
iconsReadonly<Record<string, readonly string[]>>-Map of icon names to arrays of SVG path d strings on a 24x24 stroke grid.
durationMsnumber680Base morph duration in milliseconds before speed and document tempo scaling.
blurPxnumber5Peak velocity-coupled motion blur radius in pixels. Engine writes inline style.filter while blur is active and clears it when settled; set 0 to disable blur and preserve CSS filter utilities like drop-shadow-* throughout the morph.
easing"spring" | "fluid" | "snappy""spring"Motion curve preset with matched analytic velocity profile.
fill"split" | "grow""split"Strategy when stroke counts differ: split divides long strokes dynamically; grow crossfades shared shells and draws extras.
staggerbooleantrueApplies a capped spatial wave delay across strokes (synchronized within rotating groups).
smartbooleantrueDetects global or subgroup rotation, scaling, and mirror flips via Procrustes + ICP.
arcbooleantrueCurves linear stroke travel along a subtle radial arc away from the icon center.
drawbooleantrueDraws unmatched new strokes in and retracts surplus strokes out along their path length.
pointsnumber72Resampled vertex count per stroke.
strokeWidthnumber1.5SVG strokeWidth applied directly on the root svg element.
speednumber1Local playback speed multiplier (clamped to 0.25..4).
onComplete() => void-Callback fired once a morph finishes and blur settles (or immediately under reduced motion). Not called when interrupted mid-flight by another morph, set(), or unmount.
labelstring-Accessible image label. When set, applies role="img" and aria-label; when omitted, sets aria-hidden="true".
refReact.Ref<IconMorphHandle>-Exposes imperative set(name) and morphTo(name) methods. Intended for imperative control when not simultaneously driving the active icon through the controlled icon prop.

IconMorphEngine

Framework-agnostic core engine exported from @kinetic/icon-morph-engine with zero React or framework imports.

PropTypeDefaultDescription
set(name)(name: string) => void-Cancels any in-flight morph and snaps immediately to the target icon.
to(name)(name: string) => void-Morphs smoothly from the live intermediate geometry to the target icon.
addIcons(more)(more: IconMorphIconSet) => void-Merges additional icon definitions and invalidates caches only for changed keys.
update(partial)(partial: Partial<IconMorphEngineOptions>) => void-Updates timing, blur, curve, reducedMotion, tempo, or sampler options in place.
destroy()() => void-Cancels rAF, removes managed path nodes, clears caches, and releases the ref-counted probe SVG.

svgToPaths

DOM-free parser exported from @kinetic/svg-to-paths that extracts normalized path d strings from raw SVG markup. Expects un-transformed paths on a 0 0 24 24 viewBox.

PropTypeDefaultDescription
svgstring-Raw SVG string containing path, line, circle, ellipse, rect, polyline, or polygon elements.
options{ readonly onWarning?: (message: string) => void }-Optional warning handler called when transform attributes or non-24x24 viewBoxes are detected (defaults to console.warn).

Icons: Heroicons, MIT