Preview
"use client";
import { StatusIcon } from "@/components/motion/status-icon";
export function StatusIconUsage() {
return <StatusIcon status="success" />;
}
"use client";
// beui.dev/micro-interactions/status-icon
import {
type AnimationPlaybackControls,
animate,
motion,
useAnimationFrame,
useMotionValue,
useReducedMotion,
} from "motion/react";
import { type ComponentProps, useEffect, useRef } from "react";
import { EASE_IN_OUT, EASE_OUT, SPRING_SWAP } from "@/lib/ease";
import { useMessages } from "@/lib/i18n";
import { cn } from "@/lib/utils";
export type StatusIconStatus = "idle" | "syncing" | "success" | "warning" | "error";
/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */
export const statusIconMessages = {
idle: "Idle",
syncing: "Syncing",
success: "Done",
warning: "Needs attention",
error: "Failed",
};
export type StatusIconMessages = typeof statusIconMessages;
export interface StatusIconProps extends Omit<ComponentProps<"span">, "children"> {
/** Which state to show. The icon morphs from one state to the next. Default: "idle" */
status?: StatusIconStatus;
/** Width and height in px. Default: 20 */
size?: number;
/** Hides the icon from assistive technology, for when nearby text already says the status. Default: false */
decorative?: boolean;
/** Override any built-in string, e.g. for translation. */
labels?: Partial<StatusIconMessages>;
}
const COLOR: Record<StatusIconStatus, string> = {
idle: "text-muted-foreground/45",
syncing: "text-foreground",
success: "text-emerald-500",
warning: "text-amber-500",
error: "text-rose-500",
};
// The arc turns like a wheel: syncing spins it up to a steady speed, and when
// the work settles it coasts on with the speed it had and eases to a stop at
// the top. Its length breathes while it turns, like a system spinner.
const SPEED = 420; // degrees per second at full spin
const SPIN_UP = { duration: 0.4, ease: EASE_OUT } as const;
// Coasting: an ease-out quad starts at twice its average speed, so a coast of
// COAST_S seconds over (speed × COAST_S / 2) degrees leaves at exactly the
// speed the wheel had and slows to rest. A full ring hides its angle, so the
// stop can be anywhere. The curve is easeOutQuad, local because its starting
// slope (2) is what makes the hand-off seamless.
const COAST_S = 0.42;
const COAST_EASE = [0.5, 1, 0.89, 1] as const;
const BREATH = {
duration: 1.4,
ease: EASE_IN_OUT,
repeat: Number.POSITIVE_INFINITY,
repeatType: "reverse",
} as const;
const ARC_SHORT = 0.16;
const ARC_LONG = 0.62;
// Settling is one motion, not three steps: the ring closes as the arc slows,
// the fill swells in while it finishes, and the mark draws as the fill lands.
const CLOSE = { type: "spring", duration: 0.5, bounce: 0 } as const;
const FILL = { ...SPRING_SWAP, delay: 0.1 } as const;
const MARK_IN = { duration: 0.24, ease: EASE_OUT, delay: 0.18 } as const;
const OPEN = { duration: 0.3, ease: EASE_OUT } as const;
const OUT = { duration: 0.14, ease: EASE_OUT } as const;
/**
* One status icon that morphs instead of swapping glyphs. Syncing turns an arc
* whose length breathes. On success, warning or error the arc carries on from
* wherever it is and sweeps round to close the ring, the ring fills in that
* state's colour with a small spring, and a white check, exclamation or cross
* draws in. Going back to syncing empties it and the arc opens again. Idle is
* a faint ring.
*/
export function StatusIcon({
status = "idle",
size = 20,
decorative = false,
labels,
className,
...props
}: StatusIconProps) {
const t = useMessages("statusIcon", statusIconMessages, labels);
const reduce = useReducedMotion() ?? false;
const syncing = status === "syncing";
const settled = status === "success" || status === "warning" || status === "error";
// The arc's angle, spin speed and length are driven by hand, so every change
// starts from where the arc really is and how fast it is really turning.
const rotate = useMotionValue(0);
const speed = useMotionValue(0);
const spinning = useRef(false);
const length = useMotionValue(settled ? 1 : ARC_SHORT);
const arcOpacity = useMotionValue(syncing || settled ? 1 : 0);
const running = useRef<AnimationPlaybackControls[]>([]);
// While spinning, the angle advances by the current speed every frame, so
// speeding up and slowing down are just changes to `speed`.
useAnimationFrame((_, delta) => {
if (!spinning.current) return;
rotate.set(rotate.get() + (speed.get() * Math.min(delta, 50)) / 1000);
});
// Bumped on every state change, so a step queued by an older state is dropped.
const sessionRef = useRef(0);
useEffect(() => {
const session = ++sessionRef.current;
for (const controls of running.current) controls.stop();
running.current = [];
const run = (controls: AnimationPlaybackControls) => running.current.push(controls);
// Hand the wheel's momentum to a coast that eases it to rest.
const coast = () => {
const velocity = spinning.current ? speed.get() : 0;
spinning.current = false;
speed.set(0);
if (velocity <= 0) return;
run(
animate(rotate, rotate.get() + (velocity * COAST_S) / 2, {
duration: COAST_S,
ease: COAST_EASE,
}),
);
};
if (syncing) {
run(animate(arcOpacity, 1, OUT));
if (reduce) {
length.set(0.3);
return;
}
// Spin up from whatever speed it has, never from a standing jolt.
speed.set(spinning.current ? speed.get() : Math.max(0, rotate.getVelocity()));
spinning.current = true;
run(animate(speed, SPEED, SPIN_UP));
// Coming from a closed ring, the arc first opens to its short length,
// then starts breathing.
run(
animate(length, ARC_SHORT, {
...OPEN,
onComplete: () => {
if (session !== sessionRef.current) return;
run(animate(length, [ARC_SHORT, ARC_LONG], BREATH));
},
}),
);
} else if (settled) {
run(animate(arcOpacity, 1, OUT));
if (reduce) {
length.set(1);
return;
}
coast();
run(animate(length, 1, { ...CLOSE, velocity: length.getVelocity() }));
} else {
run(animate(arcOpacity, 0, OUT));
if (!reduce) coast();
}
return () => {
for (const controls of running.current) controls.stop();
};
}, [syncing, settled, reduce, rotate, speed, length, arcOpacity]);
useEffect(
() => () => {
spinning.current = false;
},
[],
);
// A mark draws while its state is shown and fades away when it leaves.
const mark = (shown: boolean) => ({
initial: false as const,
animate: reduce
? { opacity: shown ? 1 : 0 }
: { pathLength: shown ? 1 : 0, opacity: shown ? 1 : 0 },
transition: reduce ? { duration: 0.12 } : shown ? MARK_IN : OUT,
});
const frame = {
"data-status": status,
className: cn(
"inline-grid shrink-0 place-items-center transition-colors duration-200",
COLOR[status],
className,
),
style: { width: size, height: size },
...props,
};
const icon = (
<>
{/* The arc gets an svg of its own and turns as a whole. An svg element's
box is the full 24×24 icon, so it spins round the true centre; a
group inside one would turn round the centre of the arc's own
bounding box, which moves as the arc changes length. */}
<motion.svg
aria-hidden="true"
viewBox="0 0 24 24"
fill="none"
style={{ rotate }}
className="col-start-1 row-start-1 size-full overflow-visible"
>
<motion.circle
cx="12"
cy="12"
r="9.5"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
transform="rotate(-90 12 12)"
style={{ pathLength: length, opacity: arcOpacity }}
/>
</motion.svg>
<svg
aria-hidden="true"
viewBox="0 0 24 24"
fill="none"
className="col-start-1 row-start-1 size-full overflow-visible"
>
{/* Idle: a faint ring. */}
<motion.circle
cx="12"
cy="12"
r="9.5"
stroke="currentColor"
strokeWidth="2"
initial={false}
animate={{ opacity: status === "idle" ? 0.9 : 0 }}
transition={OUT}
/>
{/* The fill: pops in once the ring has closed, from the icon's centre
(a full circle's own box shares that centre). */}
<motion.circle
cx="12"
cy="12"
r="10.5"
fill="currentColor"
initial={false}
animate={reduce ? { opacity: settled ? 1 : 0 } : { opacity: settled ? 1 : 0, scale: settled ? 1 : 0.6 }}
transition={settled ? (reduce ? { duration: 0.15 } : FILL) : OUT}
/>
{/* Marks, drawn in white on the fill. */}
<motion.path
d="M7.8 12.3l2.8 2.8 5.6-5.8"
stroke="white"
strokeWidth="2.2"
strokeLinecap="round"
strokeLinejoin="round"
{...mark(status === "success")}
/>
<motion.path
d="M12 7.4v5.2"
stroke="white"
strokeWidth="2.2"
strokeLinecap="round"
{...mark(status === "warning")}
/>
<motion.path
d="M12 16.3v.01"
stroke="white"
strokeWidth="2.6"
strokeLinecap="round"
{...mark(status === "warning")}
/>
<motion.path
d="M9.2 9.2l5.6 5.6M14.8 9.2l-5.6 5.6"
stroke="white"
strokeWidth="2.2"
strokeLinecap="round"
{...mark(status === "error")}
/>
</svg>
</>
);
return decorative ? (
<span aria-hidden="true" {...frame}>
{icon}
</span>
) : (
<span role="img" aria-label={t(status)} {...frame}>
{icon}
</span>
);
}
Add it with the shadcn CLI, or copy the source manually.
npx shadcn add https://beui.dev/r/theme.json. Theme setupInstall dependencies
npm i clsx motion tailwind-mergeAdd util files
// Shared motion tokens. Easing curves mirror the CSS custom properties in
// globals.css; springs are the canonical physics used across components.
// Strong custom variants — defaults like `ease-in`/`ease-out` feel weak.
export const EASE_OUT = [0.16, 1, 0.3, 1] as const;
/** Accelerating curve for things that fall (a dropped ball, a toppled block). Not for UI entrances. */
export const EASE_IN = [0.55, 0, 1, 0.45] as const;
export const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;
export const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;
/** CSS string form of EASE_OUT for inline style transitions. */
export const EASE_OUT_CSS = "cubic-bezier(0.16, 1, 0.3, 1)";
/** Press feedback on buttons and other tappable surfaces. */
export const SPRING_PRESS = {
type: "spring",
stiffness: 500,
damping: 30,
mass: 0.6,
} as const;
/** Content swaps — label/icon slots trading places inside a control. */
export const SPRING_SWAP = {
type: "spring",
stiffness: 460,
damping: 30,
mass: 0.55,
} as const;
/** Overlay panel entrances — modals and sheets summoned by pointer. */
export const SPRING_PANEL = {
type: "spring",
stiffness: 420,
damping: 40,
mass: 0.5,
} as const;
/** Shared-layout glides — pills, indicators and panels morphing between positions. */
export const SPRING_LAYOUT = {
type: "spring",
stiffness: 360,
damping: 32,
mass: 0.6,
} as const;
/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). */
export const SPRING_MOUSE = {
stiffness: 200,
damping: 15,
mass: 0.3,
} as const;
/** Dragged handles and fills (sliders) — critically damped `useSpring` config,
* so the value follows the pointer butterily and never rebounds off an end. */
export const SPRING_GLIDE = {
stiffness: 700,
damping: 50,
mass: 0.5,
} as const;
/** Shared-surface morphs: a trigger growing into its panel and back on one
* weighted spring, so opening and closing travel the same path. */
export const SPRING_MORPH = {
type: "spring",
duration: 0.5,
bounce: 0.22,
} as const;
"use client";
import {
createContext,
type ReactNode,
useCallback,
useContext,
useMemo,
} from "react";
/**
* A component's messages. Plain strings with `{name}` placeholders, so a
* dictionary stays JSON-serializable and can be passed from a server layout.
* There are no plural forms: write messages that read correctly for any count.
*/
export type Messages = Record<string, string>;
/** A language file: component namespace → any subset of that component's messages. */
export type LocaleMessages = Record<string, Partial<Messages>>;
type LocaleContextValue = {
locale?: string;
messages: LocaleMessages;
};
const NO_MESSAGES: LocaleMessages = {};
const LocaleContext = createContext<LocaleContextValue>({ messages: NO_MESSAGES });
/** Without a locale, digits stay plain so server and client render the same text. */
export function formatNumber(value: number, locale?: string) {
return locale ? new Intl.NumberFormat(locale).format(value) : String(value);
}
export interface LocaleProviderProps {
/** BCP 47 tag, e.g. `de`, `pt-BR`. Drives `Intl` number formatting. */
locale: string;
/**
* Component namespace → translated strings. Missing keys fall back to English.
* Pass a stable object (a module constant, imported JSON or a memoized value):
* a new object each render gives every translated component a new `t`.
*/
messages?: LocaleMessages;
children: ReactNode;
}
export function LocaleProvider({ locale, messages = NO_MESSAGES, children }: LocaleProviderProps) {
const value = useMemo(() => ({ locale, messages }), [locale, messages]);
return <LocaleContext.Provider value={value}>{children}</LocaleContext.Provider>;
}
export function useLocale(): { locale?: string } {
return { locale: useContext(LocaleContext).locale };
}
/**
* Resolves a component's strings: `labels` prop, then the provider's
* messages for `namespace`, then the component's English `defaults`.
* Numbers passed as values are formatted for the provider's locale.
*/
export function useMessages<T extends Messages>(
namespace: string,
defaults: T,
labels?: Partial<T>,
) {
const { locale, messages } = useContext(LocaleContext);
const provided = messages[namespace];
// Inline `labels={{ … }}` is a new object every render. Keying it by content
// keeps `t` one identity until a label changes, so effects and memos that
// depend on `t` don't re-run per render, and render-time reads never lag.
const labelsKey = labels ? JSON.stringify(labels) : "";
const stableLabels = useMemo(
() => (labelsKey ? (JSON.parse(labelsKey) as Partial<T>) : undefined),
[labelsKey],
);
return useCallback(
(key: keyof T & string, values?: Record<string, string | number>) => {
const template = stableLabels?.[key] ?? provided?.[key] ?? defaults[key];
if (!values) return template;
return template.replace(/\{(\w+)\}/g, (match, name: string) => {
const value = values[name];
if (value === undefined) return match;
return typeof value === "number" ? formatNumber(value, locale) : value;
});
},
[defaults, stableLabels, locale, provided],
);
}
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
Copy the source code
"use client";
// beui.dev/micro-interactions/status-icon
import {
type AnimationPlaybackControls,
animate,
motion,
useAnimationFrame,
useMotionValue,
useReducedMotion,
} from "motion/react";
import { type ComponentProps, useEffect, useRef } from "react";
import { EASE_IN_OUT, EASE_OUT, SPRING_SWAP } from "@/lib/ease";
import { useMessages } from "@/lib/i18n";
import { cn } from "@/lib/utils";
export type StatusIconStatus = "idle" | "syncing" | "success" | "warning" | "error";
/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */
export const statusIconMessages = {
idle: "Idle",
syncing: "Syncing",
success: "Done",
warning: "Needs attention",
error: "Failed",
};
export type StatusIconMessages = typeof statusIconMessages;
export interface StatusIconProps extends Omit<ComponentProps<"span">, "children"> {
/** Which state to show. The icon morphs from one state to the next. Default: "idle" */
status?: StatusIconStatus;
/** Width and height in px. Default: 20 */
size?: number;
/** Hides the icon from assistive technology, for when nearby text already says the status. Default: false */
decorative?: boolean;
/** Override any built-in string, e.g. for translation. */
labels?: Partial<StatusIconMessages>;
}
const COLOR: Record<StatusIconStatus, string> = {
idle: "text-muted-foreground/45",
syncing: "text-foreground",
success: "text-emerald-500",
warning: "text-amber-500",
error: "text-rose-500",
};
// The arc turns like a wheel: syncing spins it up to a steady speed, and when
// the work settles it coasts on with the speed it had and eases to a stop at
// the top. Its length breathes while it turns, like a system spinner.
const SPEED = 420; // degrees per second at full spin
const SPIN_UP = { duration: 0.4, ease: EASE_OUT } as const;
// Coasting: an ease-out quad starts at twice its average speed, so a coast of
// COAST_S seconds over (speed × COAST_S / 2) degrees leaves at exactly the
// speed the wheel had and slows to rest. A full ring hides its angle, so the
// stop can be anywhere. The curve is easeOutQuad, local because its starting
// slope (2) is what makes the hand-off seamless.
const COAST_S = 0.42;
const COAST_EASE = [0.5, 1, 0.89, 1] as const;
const BREATH = {
duration: 1.4,
ease: EASE_IN_OUT,
repeat: Number.POSITIVE_INFINITY,
repeatType: "reverse",
} as const;
const ARC_SHORT = 0.16;
const ARC_LONG = 0.62;
// Settling is one motion, not three steps: the ring closes as the arc slows,
// the fill swells in while it finishes, and the mark draws as the fill lands.
const CLOSE = { type: "spring", duration: 0.5, bounce: 0 } as const;
const FILL = { ...SPRING_SWAP, delay: 0.1 } as const;
const MARK_IN = { duration: 0.24, ease: EASE_OUT, delay: 0.18 } as const;
const OPEN = { duration: 0.3, ease: EASE_OUT } as const;
const OUT = { duration: 0.14, ease: EASE_OUT } as const;
/**
* One status icon that morphs instead of swapping glyphs. Syncing turns an arc
* whose length breathes. On success, warning or error the arc carries on from
* wherever it is and sweeps round to close the ring, the ring fills in that
* state's colour with a small spring, and a white check, exclamation or cross
* draws in. Going back to syncing empties it and the arc opens again. Idle is
* a faint ring.
*/
export function StatusIcon({
status = "idle",
size = 20,
decorative = false,
labels,
className,
...props
}: StatusIconProps) {
const t = useMessages("statusIcon", statusIconMessages, labels);
const reduce = useReducedMotion() ?? false;
const syncing = status === "syncing";
const settled = status === "success" || status === "warning" || status === "error";
// The arc's angle, spin speed and length are driven by hand, so every change
// starts from where the arc really is and how fast it is really turning.
const rotate = useMotionValue(0);
const speed = useMotionValue(0);
const spinning = useRef(false);
const length = useMotionValue(settled ? 1 : ARC_SHORT);
const arcOpacity = useMotionValue(syncing || settled ? 1 : 0);
const running = useRef<AnimationPlaybackControls[]>([]);
// While spinning, the angle advances by the current speed every frame, so
// speeding up and slowing down are just changes to `speed`.
useAnimationFrame((_, delta) => {
if (!spinning.current) return;
rotate.set(rotate.get() + (speed.get() * Math.min(delta, 50)) / 1000);
});
// Bumped on every state change, so a step queued by an older state is dropped.
const sessionRef = useRef(0);
useEffect(() => {
const session = ++sessionRef.current;
for (const controls of running.current) controls.stop();
running.current = [];
const run = (controls: AnimationPlaybackControls) => running.current.push(controls);
// Hand the wheel's momentum to a coast that eases it to rest.
const coast = () => {
const velocity = spinning.current ? speed.get() : 0;
spinning.current = false;
speed.set(0);
if (velocity <= 0) return;
run(
animate(rotate, rotate.get() + (velocity * COAST_S) / 2, {
duration: COAST_S,
ease: COAST_EASE,
}),
);
};
if (syncing) {
run(animate(arcOpacity, 1, OUT));
if (reduce) {
length.set(0.3);
return;
}
// Spin up from whatever speed it has, never from a standing jolt.
speed.set(spinning.current ? speed.get() : Math.max(0, rotate.getVelocity()));
spinning.current = true;
run(animate(speed, SPEED, SPIN_UP));
// Coming from a closed ring, the arc first opens to its short length,
// then starts breathing.
run(
animate(length, ARC_SHORT, {
...OPEN,
onComplete: () => {
if (session !== sessionRef.current) return;
run(animate(length, [ARC_SHORT, ARC_LONG], BREATH));
},
}),
);
} else if (settled) {
run(animate(arcOpacity, 1, OUT));
if (reduce) {
length.set(1);
return;
}
coast();
run(animate(length, 1, { ...CLOSE, velocity: length.getVelocity() }));
} else {
run(animate(arcOpacity, 0, OUT));
if (!reduce) coast();
}
return () => {
for (const controls of running.current) controls.stop();
};
}, [syncing, settled, reduce, rotate, speed, length, arcOpacity]);
useEffect(
() => () => {
spinning.current = false;
},
[],
);
// A mark draws while its state is shown and fades away when it leaves.
const mark = (shown: boolean) => ({
initial: false as const,
animate: reduce
? { opacity: shown ? 1 : 0 }
: { pathLength: shown ? 1 : 0, opacity: shown ? 1 : 0 },
transition: reduce ? { duration: 0.12 } : shown ? MARK_IN : OUT,
});
const frame = {
"data-status": status,
className: cn(
"inline-grid shrink-0 place-items-center transition-colors duration-200",
COLOR[status],
className,
),
style: { width: size, height: size },
...props,
};
const icon = (
<>
{/* The arc gets an svg of its own and turns as a whole. An svg element's
box is the full 24×24 icon, so it spins round the true centre; a
group inside one would turn round the centre of the arc's own
bounding box, which moves as the arc changes length. */}
<motion.svg
aria-hidden="true"
viewBox="0 0 24 24"
fill="none"
style={{ rotate }}
className="col-start-1 row-start-1 size-full overflow-visible"
>
<motion.circle
cx="12"
cy="12"
r="9.5"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
transform="rotate(-90 12 12)"
style={{ pathLength: length, opacity: arcOpacity }}
/>
</motion.svg>
<svg
aria-hidden="true"
viewBox="0 0 24 24"
fill="none"
className="col-start-1 row-start-1 size-full overflow-visible"
>
{/* Idle: a faint ring. */}
<motion.circle
cx="12"
cy="12"
r="9.5"
stroke="currentColor"
strokeWidth="2"
initial={false}
animate={{ opacity: status === "idle" ? 0.9 : 0 }}
transition={OUT}
/>
{/* The fill: pops in once the ring has closed, from the icon's centre
(a full circle's own box shares that centre). */}
<motion.circle
cx="12"
cy="12"
r="10.5"
fill="currentColor"
initial={false}
animate={reduce ? { opacity: settled ? 1 : 0 } : { opacity: settled ? 1 : 0, scale: settled ? 1 : 0.6 }}
transition={settled ? (reduce ? { duration: 0.15 } : FILL) : OUT}
/>
{/* Marks, drawn in white on the fill. */}
<motion.path
d="M7.8 12.3l2.8 2.8 5.6-5.8"
stroke="white"
strokeWidth="2.2"
strokeLinecap="round"
strokeLinejoin="round"
{...mark(status === "success")}
/>
<motion.path
d="M12 7.4v5.2"
stroke="white"
strokeWidth="2.2"
strokeLinecap="round"
{...mark(status === "warning")}
/>
<motion.path
d="M12 16.3v.01"
stroke="white"
strokeWidth="2.6"
strokeLinecap="round"
{...mark(status === "warning")}
/>
<motion.path
d="M9.2 9.2l5.6 5.6M14.8 9.2l-5.6 5.6"
stroke="white"
strokeWidth="2.2"
strokeLinecap="round"
{...mark(status === "error")}
/>
</svg>
</>
);
return decorative ? (
<span aria-hidden="true" {...frame}>
{icon}
</span>
) : (
<span role="img" aria-label={t(status)} {...frame}>
{icon}
</span>
);
}
"use client";
import { useInView, useReducedMotion } from "motion/react";
import { createContext, type RefObject, useContext, useEffect, useRef, useState } from "react";
/**
* Lets a parent decide when previews play. The micro interactions gallery
* provides it, so its cards start still and play only from their play
* button. Without it a preview plays on its own.
*/
export const AutoplayContext = createContext<{ playing: boolean } | null>(null);
/**
* Plays a preview: calls `tick` every `interval` ms while the stage is on
* screen and the tab is visible. Under an AutoplayContext it plays only
* while `playing` is set; on its own it plays unless someone is hovering or
* focused inside it. Off entirely with reduced motion. Spread the returned
* props on the element that wraps the preview.
*/
export function useAutoplay(tick: () => void, interval: number) {
const ref = useRef<HTMLDivElement>(null);
const inView = useInView(ref as RefObject<Element>, { amount: 0.5 });
const reduce = useReducedMotion();
const control = useContext(AutoplayContext);
const [paused, setPaused] = useState(false);
// The latest tick, so the timer never restarts when the callback changes.
const tickRef = useRef(tick);
useEffect(() => {
tickRef.current = tick;
});
const running = control ? control.playing : !paused;
useEffect(() => {
if (!inView || !running || reduce) return;
// The first step plays right away, so pressing play answers at once.
if (control) tickRef.current();
const id = window.setInterval(() => {
if (document.visibilityState === "visible") tickRef.current();
}, interval);
return () => window.clearInterval(id);
}, [inView, running, reduce, interval, control]);
return {
ref,
onPointerEnter: () => setPaused(true),
onPointerLeave: () => setPaused(false),
onFocus: () => setPaused(true),
onBlur: () => setPaused(false),
};
}
"use client";
import {
type AnimationPlaybackControls,
animate,
type HTMLMotionProps,
motion,
useMotionValue,
useReducedMotion,
useTransform,
} from "motion/react";
import { type CSSProperties, type ReactNode, useLayoutEffect, useRef } from "react";
import { EASE_OUT, SPRING_MORPH } from "@/lib/ease";
import { cn } from "@/lib/utils";
// The bottom edge glides to the new size; a little quicker when shrinking,
// since the content inside has already gone.
const GROW = { duration: 0.3, ease: EASE_OUT } as const;
const SHRINK = { duration: 0.24, ease: EASE_OUT } as const;
export interface ClipResizeFrameProps extends Omit<HTMLMotionProps<"div">, "children" | "style"> {
style?: CSSProperties;
/**
* Which size follows the content. "y": the bottom edge glides as the height
* changes. "x": both ends glide in or out from the centre as the width
* changes, on a morph spring, for pills and chips. Default: "y"
*/
axis?: "x" | "y";
/**
* With axis "y", which edge moves. "top" is for a panel anchored at its
* bottom, such as a list opening above an input: its top edge glides and its
* content stays against the bottom. Default: "bottom"
*/
edge?: "top" | "bottom";
/** Outer corner radius in px. The surface inside uses one less. */
radius?: number;
/** Classes for the content box (padding goes here). */
contentClassName?: string;
children: ReactNode;
}
/**
* A bordered card whose bottom edge glides when its content grows or shrinks,
* without animating height. The layout changes at once; a clip on the card
* hides the difference and slides it away. The border is the 1px gap between
* two clipped layers (the frame in the border colour, the surface inside it),
* so the bottom line travels with the edge instead of being clipped off.
*/
export function ClipResizeFrame({
axis = "y",
edge = "bottom",
radius = 16,
className,
contentClassName,
style,
children,
...props
}: ClipResizeFrameProps) {
const reduce = useReducedMotion() ?? false;
const horizontal = axis === "x";
const fromTop = !horizontal && edge === "top";
const surfaceRef = useRef<HTMLDivElement>(null);
const contentRef = useRef<HTMLDivElement>(null);
// How much of the surface (px) is hidden right now: at the moving edge, or
// split evenly between the two ends.
const gap = useMotionValue(0);
const clip = (value: number, round: number) =>
horizontal
? `inset(0 ${value / 2}px 0 ${value / 2}px round ${round}px)`
: fromTop
? `inset(${value}px 0 0 0 round ${round}px)`
: `inset(0 0 ${value}px 0 round ${round}px)`;
const frameClip = useTransform(gap, (value) =>
Math.abs(value) > 0.5 ? clip(value, radius) : "none",
);
const surfaceClip = useTransform(gap, (value) =>
Math.abs(value) > 0.5 ? clip(value, radius - 1) : "none",
);
useLayoutEffect(() => {
const surface = surfaceRef.current;
const content = contentRef.current;
if (!surface || !content || typeof ResizeObserver === "undefined") return;
const measure = () => (horizontal ? content.offsetWidth : content.offsetHeight);
const side = horizontal ? "width" : "height";
let last = measure();
// While shrinking, the surface keeps its old size so the edge has
// somewhere to glide from; null when the surface sizes to its content.
let held: number | null = null;
let controls: AnimationPlaybackControls | undefined;
const release = () => {
held = null;
surface.style[side] = "";
gap.set(0);
};
// Runs after layout and before paint, so the held size lands in the
// same frame as the content change: the edge never jumps.
const observer = new ResizeObserver(() => {
const next = measure();
if (next === last) return;
const visible = (held ?? last) - gap.get();
last = next;
controls?.stop();
if (reduce) {
release();
return;
}
const from = Math.max(next, visible);
held = from > next ? from : null;
surface.style[side] = held === null ? "" : `${held}px`;
gap.set(from - visible);
controls = animate(gap, from - next, {
...(horizontal ? SPRING_MORPH : next < visible ? SHRINK : GROW),
// The edge has reached the content: hand the size back to layout.
onComplete: () => {
if (held !== null) release();
},
});
});
observer.observe(content);
return () => {
observer.disconnect();
controls?.stop();
};
}, [gap, reduce, horizontal]);
return (
<motion.div
{...props}
style={{ ...style, borderRadius: radius, clipPath: frameClip }}
className={cn("bg-border p-px", horizontal && "w-fit", className)}
>
<motion.div
ref={surfaceRef}
style={{ borderRadius: radius - 1, clipPath: surfaceClip }}
// Held wider than its content while shrinking, the surface keeps the
// content centred, so the two ends close in on it evenly.
// Held taller than its content, a top-edge surface keeps the content
// against its anchored bottom.
className={cn(
"overflow-hidden bg-background",
horizontal && "flex justify-center",
fromTop && "flex flex-col justify-end",
)}
>
<div ref={contentRef} className={cn(horizontal && "w-max shrink-0", contentClassName)}>
{children}
</div>
</motion.div>
</motion.div>
);
}
"use client";
import {
ActionSwapButton,
ActionSwapIcon,
ActionSwapText,
type ActionSwapButtonProps,
type ActionSwapIconProps,
type ActionSwapTextProps,
} from "./action-swap";
export type {
ActionSwapButtonSize,
ActionSwapButtonVariant,
ActionSwapItem,
} from "./action-swap";
export type ActionSwapRollButtonProps = Omit<ActionSwapButtonProps, "animation">;
export type ActionSwapRollTextProps = Omit<ActionSwapTextProps, "animation">;
export type ActionSwapRollIconProps = Omit<ActionSwapIconProps, "animation">;
export function ActionSwapRollButton(props: ActionSwapRollButtonProps) {
return <ActionSwapButton {...props} animation="roll" />;
}
export function ActionSwapRollText(props: ActionSwapRollTextProps) {
return <ActionSwapText {...props} animation="roll" />;
}
export function ActionSwapRollIcon(props: ActionSwapRollIconProps) {
return <ActionSwapIcon {...props} animation="roll" />;
}
"use client";
import { AnimatePresence, type HTMLMotionProps, motion, useReducedMotion, type Variants } from "motion/react";
import type { ReactNode } from "react";
import { useState } from "react";
import { EASE_OUT, SPRING_LAYOUT, SPRING_PRESS, SPRING_SWAP } from "@/lib/ease";
import { cn } from "@/lib/utils";
export type ActionSwapItem = {
/** Unique key, used as the button's value. */
id: string;
/** Text shown on the button while this item is active. Hidden when `iconOnly`. */
label: ReactNode;
/** Icon shown before the label while this item is active. */
icon?: ReactNode;
/** Accessible name while active. Falls back to a string label when `iconOnly`. */
ariaLabel?: string;
};
export type ActionSwapButtonVariant = "primary" | "secondary" | "outline" | "ghost";
export type ActionSwapButtonSize = "sm" | "md" | "lg" | "icon";
export type ActionSwapAnimation = "blur" | "roll" | "cascade";
/** Animations with a single-element variant set (cascade animates per letter). */
type CoreAnimation = "blur" | "roll";
export interface ActionSwapButtonProps extends Omit<
HTMLMotionProps<"button">,
"children" | "onChange"
> {
/** States the button steps through, each with a label and optional icon. */
items: ActionSwapItem[];
/** The id of the shown item, for controlled use. */
value?: string;
/** The initial item id when uncontrolled. Default: the first item. */
defaultValue?: string;
/** Called with the next item's id and the item when a press advances it. */
onValueChange?: (value: string, item: ActionSwapItem) => void;
/** Visual style of the button. Default: "secondary" */
variant?: ActionSwapButtonVariant;
/** Button height and padding. Default: "md" */
size?: ActionSwapButtonSize;
/** How the label and icon swap between items. Default: "blur" */
animation?: ActionSwapAnimation;
/** Show only the icon and use the label as the accessible name. Default: true for size "icon" */
iconOnly?: boolean;
/** Advance to the next item on each press, wrapping at the end. Default: true */
cycle?: boolean;
}
export interface ActionSwapTextProps {
/** Key for the current text; a new value plays the swap. */
value: string;
children: ReactNode;
/** How the old text leaves and the new text enters. Default: "blur" */
animation?: ActionSwapAnimation;
/** Classes merged onto the root element. */
className?: string;
}
export interface ActionSwapIconProps {
/** Key for the current icon; a new value plays the swap. */
value: string;
children: ReactNode;
/** How the old icon leaves and the new one enters. "cascade" plays as "roll". Default: "blur" */
animation?: ActionSwapAnimation;
/** Classes merged onto the root element. */
className?: string;
}
// The arriving layer springs in, so a second press mid-swap bends it toward
// the new target instead of restarting. The leaving layer is a little quicker,
// still long enough to cross the arrival so the swap reads as one morph.
const BLUR_TRANSITION = SPRING_SWAP;
const BLUR_EXIT_TRANSITION = { duration: 0.16, ease: EASE_OUT } as const;
const ROLL_TRANSITION = SPRING_SWAP;
const ROLL_EXIT_TRANSITION = { duration: 0.14, ease: EASE_OUT } as const;
// A light blur softens the crossing without smearing small glyphs.
const SWAP_BLUR = "blur(2px)";
const ROLL_BLUR = "blur(3px)";
// Cascade rolls the label one letter at a time, left to right. The leaving
// and landing strings overlap as independent layers (no shared cells), so
// proportional glyph widths never jitter. Exits cascade at half the enter
// stagger so the tail of the old label lingers briefly.
const CASCADE_STAGGER = 0.025;
const CASCADE_LETTER_VARIANTS: Variants = {
initial: { opacity: 0, y: "105%", filter: ROLL_BLUR },
animate: (delay: number = 0) => ({
opacity: 1,
y: "0%",
filter: "blur(0px)",
transition: { ...SPRING_SWAP, delay },
}),
exit: (delay: number = 0) => ({
opacity: 0,
y: "-105%",
filter: ROLL_BLUR,
transition: { duration: 0.16, ease: EASE_OUT, delay: delay * 0.5 },
}),
};
const TEXT_VARIANTS: Record<CoreAnimation, Variants> = {
blur: {
initial: { opacity: 0, scale: 0.9, filter: SWAP_BLUR },
animate: {
opacity: 1,
scale: 1,
filter: "blur(0px)",
transition: BLUR_TRANSITION,
},
exit: {
opacity: 0,
scale: 0.96,
filter: SWAP_BLUR,
transition: BLUR_EXIT_TRANSITION,
},
},
roll: {
initial: { opacity: 0, y: "90%", filter: ROLL_BLUR },
animate: {
opacity: 1,
y: "0%",
filter: "blur(0px)",
transition: ROLL_TRANSITION,
},
exit: {
opacity: 0,
y: "-90%",
filter: ROLL_BLUR,
transition: ROLL_EXIT_TRANSITION,
},
},
};
const ICON_VARIANTS: Record<CoreAnimation, Variants> = {
blur: {
initial: { opacity: 0, scale: 0.25, filter: SWAP_BLUR },
animate: {
opacity: 1,
scale: 1,
filter: "blur(0px)",
transition: BLUR_TRANSITION,
},
exit: {
opacity: 0,
scale: 0.25,
filter: SWAP_BLUR,
transition: BLUR_EXIT_TRANSITION,
},
},
roll: {
initial: { opacity: 0, y: 12, filter: ROLL_BLUR },
animate: {
opacity: 1,
y: 0,
filter: "blur(0px)",
transition: ROLL_TRANSITION,
},
exit: {
opacity: 0,
y: -12,
filter: ROLL_BLUR,
transition: ROLL_EXIT_TRANSITION,
},
},
};
const VARIANT_CLASS: Record<ActionSwapButtonVariant, string> = {
primary: "bg-primary text-primary-foreground hover:bg-primary/90",
secondary: "border border-border bg-card text-foreground hover:border-border",
outline: "border border-border bg-transparent text-foreground hover:bg-muted/60",
ghost: "text-muted-foreground hover:bg-muted/60 hover:text-foreground",
};
const SIZE_CLASS: Record<ActionSwapButtonSize, string> = {
sm: "h-8 gap-1.5 rounded-full px-3 text-xs",
md: "h-10 gap-2 rounded-full px-4 text-sm",
lg: "h-12 gap-2.5 rounded-full px-5 text-base",
icon: "h-10 w-10 rounded-full",
};
export function ActionSwapText({
value,
children,
animation = "blur",
className,
}: ActionSwapTextProps) {
const reduce = useReducedMotion();
// Cascade needs a plain string to split into letters; non-string content
// and reduced motion fall back to the closest single-element animation.
const label = typeof children === "string" ? children : null;
const cascade = animation === "cascade" && label !== null && !reduce;
const coreAnimation: CoreAnimation =
animation === "cascade" ? "roll" : animation;
return (
<span
className={cn(
"relative -my-[0.08em] inline-block max-w-full whitespace-nowrap py-[0.08em] align-bottom",
className,
)}
style={{
clipPath: "inset(0 -999px)",
WebkitClipPath: "inset(0 -999px)",
}}
>
<span
aria-hidden
className="invisible inline-block whitespace-nowrap"
>
{cascade
? label.split("").map((char, index) => (
<span
// biome-ignore lint/suspicious/noArrayIndexKey: position is the slot identity.
key={index}
className="inline-block whitespace-pre"
>
{char}
</span>
))
: children}
</span>
{cascade ? (
<>
{/* Letters are decorative fragments; readers get the whole label. */}
<span className="sr-only">{label}</span>
<AnimatePresence initial={false}>
<motion.span
key={`cascade-${value}`}
aria-hidden
initial="initial"
animate="animate"
exit="exit"
className="absolute left-0 top-[0.08em] inline-block whitespace-pre"
>
{label.split("").map((char, i) => (
<motion.span
// biome-ignore lint/suspicious/noArrayIndexKey: position is the slot identity — the letter at a position is exactly what rolls.
key={i}
custom={i * CASCADE_STAGGER}
variants={CASCADE_LETTER_VARIANTS}
// Own states: a label that swaps away and straight back
// re-enters mid-exit, and only owned targets are restored.
initial="initial"
animate="animate"
exit="exit"
className="inline-block whitespace-pre will-change-[opacity,filter,transform]"
>
{char}
</motion.span>
))}
</motion.span>
</AnimatePresence>
</>
) : (
<AnimatePresence initial={false}>
<motion.span
key={`${animation}-${value}`}
variants={TEXT_VARIANTS[coreAnimation]}
initial={reduce ? false : "initial"}
animate={reduce ? { opacity: 1, filter: "blur(0px)", scale: 1, y: 0 } : "animate"}
exit={reduce ? undefined : "exit"}
// Truncation lives on the layer that holds the text — the layer
// moves as a whole, so clipping it never eats the roll.
className="absolute left-0 top-[0.08em] inline-block max-w-full truncate will-change-[opacity,filter,transform]"
>
{children}
</motion.span>
</AnimatePresence>
)}
</span>
);
}
export function ActionSwapIcon({
value,
children,
animation = "blur",
className,
}: ActionSwapIconProps) {
const reduce = useReducedMotion();
// Icons are single elements — cascade maps to its closest motion, roll.
const coreAnimation: CoreAnimation =
animation === "cascade" ? "roll" : animation;
return (
<span className={cn("relative inline-grid shrink-0 place-items-center overflow-hidden", className)}>
<AnimatePresence mode="popLayout" initial={false}>
<motion.span
key={`${animation}-${value}`}
aria-hidden
variants={ICON_VARIANTS[coreAnimation]}
initial={reduce ? false : "initial"}
animate={reduce ? { opacity: 1, filter: "blur(0px)", scale: 1, y: 0 } : "animate"}
exit={reduce ? undefined : "exit"}
className="col-start-1 row-start-1 inline-flex items-center justify-center will-change-[opacity,filter,transform]"
>
{children}
</motion.span>
</AnimatePresence>
</span>
);
}
export function ActionSwapButton({
items,
value,
defaultValue,
onValueChange,
variant = "secondary",
size = "md",
animation = "blur",
iconOnly = size === "icon",
cycle = true,
className,
disabled,
onClick,
style,
...rest
}: ActionSwapButtonProps) {
const reduce = useReducedMotion();
const [internalValue, setInternalValue] = useState(defaultValue ?? items[0]?.id);
const currentValue = value ?? internalValue;
const activeIndex = Math.max(0, items.findIndex((item) => item.id === currentValue));
const activeItem = items[activeIndex] ?? items[0];
const hasIcon = items.some((item) => item.icon);
const nextItem = cycle && items.length > 0 ? items[(activeIndex + 1) % items.length] : undefined;
if (!activeItem) return null;
const accessibleLabel = activeItem.ariaLabel ?? (iconOnly && typeof activeItem.label === "string" ? activeItem.label : undefined);
const layoutTransition = reduce ? { duration: 0 } : SPRING_LAYOUT;
return (
<motion.button
type="button"
disabled={disabled}
// A label of a different length resizes the button: glide the width on
// the soft layout spring, and only when the value changes, so unrelated
// page reflow never animates the button.
layout
layoutDependency={activeItem.id}
whileTap={reduce || disabled ? undefined : { scale: 0.97 }}
transition={{ ...SPRING_PRESS, layout: layoutTransition }}
// Layout animations only correct a radius set inline.
style={{ borderRadius: 9999, ...style }}
className={cn(
"inline-flex items-center justify-center overflow-hidden font-medium transition-colors",
"disabled:pointer-events-none disabled:opacity-50",
VARIANT_CLASS[variant],
SIZE_CLASS[size],
className,
)}
aria-label={accessibleLabel}
onClick={(event) => {
onClick?.(event);
if (event.defaultPrevented || disabled || !cycle || !nextItem) return;
if (value === undefined) setInternalValue(nextItem.id);
onValueChange?.(nextItem.id, nextItem);
}}
{...rest}
>
{/* Position-only layout keeps the contents from stretching with the
button while its width glides. */}
{hasIcon ? (
<motion.span
layout="position"
layoutDependency={activeItem.id}
transition={layoutTransition}
className="inline-flex shrink-0"
>
<ActionSwapIcon value={activeItem.id} animation={animation} className="h-4 w-4">
{activeItem.icon ?? null}
</ActionSwapIcon>
</motion.span>
) : null}
{!iconOnly ? (
<motion.span
layout="position"
layoutDependency={activeItem.id}
transition={layoutTransition}
className="inline-flex min-w-0 max-w-full"
>
<ActionSwapText value={activeItem.id} animation={animation}>
{activeItem.label}
</ActionSwapText>
</motion.span>
) : null}
</motion.button>
);
}
status?"error" | "success" | "idle" | "warning" | "syncing"Which state to show. The icon morphs from one state to the next. Default: "idle"
idlesize?numberWidth and height in px. Default: 20
20decorative?booleanHides the icon from assistive technology, for when nearby text already says the status. Default: false
falselabels?Partial<{ idle: string; syncing: string; success: string; warning: string; error: string; }>Override any built-in string, e.g. for translation.
—className?stringClasses merged onto the root element.
—Refresh Button
Arrows that wind back, spin up into a breathing spinner arc, then coast to land upright and hand over to a check as Refresh morphs to Updated.
Delete Button
A bin button that opens into a cross and a tick to confirm, then a spinner while it deletes, then a drawn check with Deleted.
Copy Button
Copies text and confirms it: the pill tints, the icon blurs into a check that draws its stroke, and Copy morphs letter by letter into Copied.
Updated