Variable Proximity
Text whose letters morph between variable-font axis values as the pointer gets close.
pnpm dlx shadcn@latest add @leo/variable-proximityProps
| Name | Type | Default | Description |
|---|---|---|---|
| className | string | undefined | - | |
| containerRef | MutableRefObject<HTMLElement | null> | null | undefined | - | Element whose box the pointer is measured against. Defaults to the component's own root. |
| falloff | undefined | "linear" | "exponential" | "gaussian" | - | |
| fromFontVariationSettings | string | undefined | - | |
| initialPosition | VariableProximityInitialPosition | undefined | - | Resting pointer position as fractions of the container (0-1), used until the first pointer move. |
| label | string | undefined | - | |
| onClick | (() => void) | undefined | - | |
| radius | number | undefined | - | |
| style | CSSProperties | undefined | - | Merged over the default `fontFamily` ("Roboto Flex"). The consumer must load a variable font that supports every axis used in `fromFontVariationSettings` and `toFontVariationSettings`; otherwise the settings have no visible effect. |
| toFontVariationSettings | string | undefined | - |
Dependencies
- motion@^12.23.12
Source
"use client";
import { motion } from "motion/react";
import {
type CSSProperties,
forwardRef,
type HTMLAttributes,
type MutableRefObject,
useCallback,
useEffect,
useMemo,
useRef,
} from "react";
import { cn } from "@/lib/utils";
function useAnimationFrame(callback: () => void) {
useEffect(() => {
let frameId: number;
const loop = () => {
callback();
frameId = requestAnimationFrame(loop);
};
frameId = requestAnimationFrame(loop);
return () => cancelAnimationFrame(frameId);
}, [callback]);
}
export interface VariableProximityInitialPosition {
x: number;
y: number;
}
function useMousePositionRef(
getContainer: () => HTMLElement | null,
initialPosition: VariableProximityInitialPosition | undefined,
) {
const positionRef = useRef({ x: 0, y: 0 });
// The resting position is resolved after mount because it needs the container's size.
const initialX = initialPosition?.x;
const initialY = initialPosition?.y;
useEffect(() => {
if (initialX === undefined || initialY === undefined) return;
const container = getContainer();
if (!container) return;
const rect = container.getBoundingClientRect();
positionRef.current = { x: rect.width * initialX, y: rect.height * initialY };
}, [getContainer, initialX, initialY]);
useEffect(() => {
const updatePosition = (x: number, y: number) => {
const container = getContainer();
if (container) {
const rect = container.getBoundingClientRect();
positionRef.current = { x: x - rect.left, y: y - rect.top };
} else {
positionRef.current = { x, y };
}
};
const handleMouseMove = (ev: MouseEvent) => updatePosition(ev.clientX, ev.clientY);
const handleTouchMove = (ev: TouchEvent) => {
const touch = ev.touches[0];
updatePosition(touch.clientX, touch.clientY);
};
window.addEventListener("mousemove", handleMouseMove);
window.addEventListener("touchmove", handleTouchMove);
return () => {
window.removeEventListener("mousemove", handleMouseMove);
window.removeEventListener("touchmove", handleTouchMove);
};
}, [getContainer]);
return positionRef;
}
const DEFAULT_FROM_SETTINGS = "'wght' 400";
const DEFAULT_TO_SETTINGS = "'wght' 900";
export interface VariableProximityProps extends HTMLAttributes<HTMLSpanElement> {
label?: string;
fromFontVariationSettings?: string;
toFontVariationSettings?: string;
/** Element whose box the pointer is measured against. Defaults to the component's own root. */
containerRef?: MutableRefObject<HTMLElement | null> | null;
radius?: number;
falloff?: "linear" | "exponential" | "gaussian";
/** Resting pointer position as fractions of the container (0-1), used until the first pointer move. */
initialPosition?: VariableProximityInitialPosition;
className?: string;
onClick?: () => void;
/**
* Merged over the default `fontFamily` ("Roboto Flex"). The consumer must load a variable font that
* supports every axis used in `fromFontVariationSettings` and `toFontVariationSettings`; otherwise
* the settings have no visible effect.
*/
style?: CSSProperties;
}
const VariableProximity = forwardRef<HTMLSpanElement, VariableProximityProps>((props, ref) => {
const {
label = "Hover over these letters",
fromFontVariationSettings = DEFAULT_FROM_SETTINGS,
toFontVariationSettings = DEFAULT_TO_SETTINGS,
containerRef,
radius = 50,
falloff = "linear",
initialPosition,
className,
onClick,
style,
...restProps
} = props;
const rootRef = useRef<HTMLSpanElement | null>(null);
const setRootRef = useCallback(
(el: HTMLSpanElement | null) => {
rootRef.current = el;
if (typeof ref === "function") ref(el);
else if (ref) ref.current = el;
},
[ref],
);
const getContainer = useCallback(() => containerRef?.current ?? rootRef.current, [containerRef]);
const letterRefs = useRef<(HTMLSpanElement | null)[]>([]);
const interpolatedSettingsRef = useRef<string[]>([]);
const mousePositionRef = useMousePositionRef(getContainer, initialPosition);
const lastPositionRef = useRef<{ x: number | null; y: number | null }>({ x: null, y: null });
const parsedSettings = useMemo(() => {
const parseSettings = (settingsStr: string) =>
new Map(
settingsStr
.split(",")
.map((s) => s.trim())
.map((s) => {
const [name, value] = s.split(" ");
return [name.replace(/['"]/g, ""), parseFloat(value)];
}),
);
const fromSettings = parseSettings(fromFontVariationSettings);
const toSettings = parseSettings(toFontVariationSettings);
return Array.from(fromSettings.entries()).map(([axis, fromValue]) => ({
axis,
fromValue,
toValue: toSettings.get(axis) ?? fromValue,
}));
}, [fromFontVariationSettings, toFontVariationSettings]);
const calculateDistance = (x1: number, y1: number, x2: number, y2: number) =>
Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2);
const calculateFalloff = (distance: number) => {
const norm = Math.min(Math.max(1 - distance / radius, 0), 1);
switch (falloff) {
case "exponential":
return norm ** 2;
case "gaussian":
return Math.exp(-((distance / (radius / 2)) ** 2) / 2);
default:
return norm;
}
};
useAnimationFrame(() => {
const container = getContainer();
if (!container) return;
const { x, y } = mousePositionRef.current;
if (lastPositionRef.current.x === x && lastPositionRef.current.y === y) {
return;
}
lastPositionRef.current = { x, y };
const containerRect = container.getBoundingClientRect();
letterRefs.current.forEach((letterRef, index) => {
if (!letterRef) return;
const rect = letterRef.getBoundingClientRect();
const letterCenterX = rect.left + rect.width / 2 - containerRect.left;
const letterCenterY = rect.top + rect.height / 2 - containerRect.top;
const distance = calculateDistance(
mousePositionRef.current.x,
mousePositionRef.current.y,
letterCenterX,
letterCenterY,
);
if (distance >= radius) {
letterRef.style.fontVariationSettings = fromFontVariationSettings;
return;
}
const falloffValue = calculateFalloff(distance);
const newSettings = parsedSettings
.map(({ axis, fromValue, toValue }) => {
const interpolatedValue = fromValue + (toValue - fromValue) * falloffValue;
return `'${axis}' ${interpolatedValue}`;
})
.join(", ");
interpolatedSettingsRef.current[index] = newSettings;
letterRef.style.fontVariationSettings = newSettings;
});
});
const words = label.split(" ");
let letterIndex = 0;
return (
// biome-ignore lint/a11y/noStaticElementInteractions: onClick is a pass-through for consumers; the text itself is not a control
// biome-ignore lint/a11y/useKeyWithClickEvents: onClick is a pass-through for consumers; the text itself is not a control
<span
ref={setRootRef}
onClick={onClick}
style={{
display: "inline",
fontFamily: '"Roboto Flex", sans-serif',
...style,
}}
className={cn(className)}
{...restProps}
>
{words.map((word, wordIndex) => (
// biome-ignore lint/suspicious/noArrayIndexKey: words are static positions of the label and may repeat
<span key={wordIndex} className="inline-block whitespace-nowrap">
{word.split("").map((letter) => {
const currentLetterIndex = letterIndex++;
return (
<motion.span
key={currentLetterIndex}
ref={(el) => {
letterRefs.current[currentLetterIndex] = el;
}}
style={{
display: "inline-block",
fontVariationSettings: interpolatedSettingsRef.current[currentLetterIndex],
}}
aria-hidden="true"
>
{letter}
</motion.span>
);
})}
{wordIndex < words.length - 1 && <span className="inline-block"> </span>}
</span>
))}
<span className="sr-only">{label}</span>
</span>
);
});
VariableProximity.displayName = "VariableProximity";
export { VariableProximity };
export default VariableProximity;