Icon Morph
Zero-dependency SVG stroke icon morphing with optimal stroke matching, rotation and mirror detection, ink draw-in/out, and velocity motion blur.
Customize
Installation
npx shadcn@latest add @kinetic/icon-morphTo 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-pathsUsage
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
- 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.
- 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.
- 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-uptocloud-arrow-downorarrow-downtoarrow-down-circle). - 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
labelprop,IconMorphrendersaria-hidden="true"for decorative icons inside labeled buttons. - Passing
labelsetsrole="img"andaria-label={label}for standalone status icons. - Reduced motion and document tempo sync reactively through
useMotionPreferences(). Under reduced motion,IconMorphsnaps immediately to the target paths with zero blur and still callsonComplete. - During SSR,
IconMorphrenders 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).
| Prop | Type | Default | Description |
|---|---|---|---|
icon | string | - | Active icon key from icons. Changing this prop morphs smoothly from the current visual state. |
icons | Readonly<Record<string, readonly string[]>> | - | Map of icon names to arrays of SVG path d strings on a 24x24 stroke grid. |
durationMs | number | 680 | Base morph duration in milliseconds before speed and document tempo scaling. |
blurPx | number | 5 | Peak 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. |
stagger | boolean | true | Applies a capped spatial wave delay across strokes (synchronized within rotating groups). |
smart | boolean | true | Detects global or subgroup rotation, scaling, and mirror flips via Procrustes + ICP. |
arc | boolean | true | Curves linear stroke travel along a subtle radial arc away from the icon center. |
draw | boolean | true | Draws unmatched new strokes in and retracts surplus strokes out along their path length. |
points | number | 72 | Resampled vertex count per stroke. |
strokeWidth | number | 1.5 | SVG strokeWidth applied directly on the root svg element. |
speed | number | 1 | Local 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. |
label | string | - | Accessible image label. When set, applies role="img" and aria-label; when omitted, sets aria-hidden="true". |
ref | React.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.
| Prop | Type | Default | Description |
|---|---|---|---|
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.
| Prop | Type | Default | Description |
|---|---|---|---|
svg | string | - | 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