Hold Action Button
Hold to confirm while a liquid fill rises, or let go early to cancel.
Preview
"use client";
import { useState } from "react";
import { HoldActionButton } from "@/components/motion/hold-action-button";
export function HoldActionButtonPreview() {
const [confirmed, setConfirmed] = useState(false);
return (
<div className="flex flex-col items-center justify-center gap-3">
<HoldActionButton
onHoldComplete={() => {
setConfirmed(true);
window.setTimeout(() => setConfirmed(false), 1800);
}}
>
Hold for vertical fill
</HoldActionButton>
<HoldActionButton
type="horizontal"
onHoldComplete={() => {
setConfirmed(true);
window.setTimeout(() => setConfirmed(false), 1800);
}}
>
Hold for horizontal fill
</HoldActionButton>
<p className="h-4 text-xs text-muted-foreground" aria-live="polite">
{confirmed ? "Action confirmed" : "Release early to cancel"}
</p>
</div>
);
}
"use client";
// beui.dev/components/motion/expanding-arrow-button/hold-action
import { type HTMLMotionProps, motion, useReducedMotion } from "motion/react";
import {
forwardRef,
type KeyboardEvent,
type PointerEvent,
type ReactNode,
useRef,
useState,
} from "react";
import { EASE_OUT, SPRING_PRESS } from "@/lib/ease";
import { useMessages } from "@/lib/i18n";
import {
capturePointer,
releasePointer,
TOUCH_GESTURE_CLASS,
} from "@/lib/touch";
import { cn } from "@/lib/utils";
/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */
export const holdActionButtonMessages = {
holding: "Keep holding",
complete: "Done",
};
export type HoldActionButtonMessages = typeof holdActionButtonMessages;
export interface HoldActionButtonProps extends Omit<
HTMLMotionProps<"button">,
| "children"
| "type"
| "onClick"
| "onPointerDown"
| "onPointerUp"
| "onPointerCancel"
| "onPointerLeave"
| "onPointerMove"
| "onKeyDown"
| "onKeyUp"
> {
children: ReactNode;
/** Fill rises from the bottom or sweeps in from the left. Default: "vertical" */
type?: "vertical" | "horizontal";
/** Label shown while the button is held. Default: "Keep holding" */
holdingLabel?: ReactNode;
/** Label shown once the hold completes. Default: "Done" */
completeLabel?: ReactNode;
/** How long the button must be held to complete (ms). Default: 1600 */
holdDuration?: number;
/** Called once when the fill finishes while still held. */
onHoldComplete?: () => void;
/** Classes merged onto the fill layer, e.g. to change its color. */
fillClassName?: string;
/** Classes merged onto the label wrapper. */
labelClassName?: string;
/** Override any built-in string. */
labels?: Partial<HoldActionButtonMessages>;
}
export const HoldActionButton = forwardRef<
HTMLButtonElement,
HoldActionButtonProps
>(function HoldActionButton(
{
children,
type = "vertical",
holdingLabel,
completeLabel,
holdDuration = 1600,
onHoldComplete,
fillClassName,
labelClassName,
className,
disabled,
labels,
onBlur,
...rest
},
ref,
) {
const t = useMessages("holdActionButton", holdActionButtonMessages, labels);
const reduce = useReducedMotion();
const completedRef = useRef(false);
const [holding, setHolding] = useState(false);
const [completed, setCompleted] = useState(false);
const startHold = () => {
if (disabled || holding) return;
completedRef.current = false;
setCompleted(false);
setHolding(true);
};
const cancelHold = () => {
setHolding(false);
setCompleted(false);
};
const handlePointerDown = (event: PointerEvent<HTMLButtonElement>) => {
if (event.button !== 0) return;
// Start first: capture is a convenience, and a browser that refuses it
// must not take the hold down with it.
startHold();
capturePointer(event.currentTarget, event.pointerId);
};
const handlePointerUp = (event: PointerEvent<HTMLButtonElement>) => {
releasePointer(event.currentTarget, event.pointerId);
cancelHold();
};
const handlePointerLeave = (event: PointerEvent<HTMLButtonElement>) => {
// Only reached when the capture below was refused: a captured pointer gets
// no boundary events at all. A finger does not get this reading either way
// — WebKit fires leave repeatedly for a touch that never moved, which
// would cancel every hold on the frame it started.
if (event.pointerType !== "touch") cancelHold();
};
const handlePointerMove = (event: PointerEvent<HTMLButtonElement>) => {
// Leaving the button abandons the hold, and while the pointer is captured
// nothing announces that: no boundary events, and `touch-none` means a
// finger sliding off cannot scroll and so cannot cancel either. Measure it
// instead — off the button ends the hold, wherever the pointer then goes.
if (!holding) return;
const rect = event.currentTarget.getBoundingClientRect();
const outside =
event.clientX < rect.left ||
event.clientX > rect.right ||
event.clientY < rect.top ||
event.clientY > rect.bottom;
if (outside) cancelHold();
};
const handleKeyDown = (event: KeyboardEvent<HTMLButtonElement>) => {
if ((event.key === " " || event.key === "Enter") && !event.repeat) {
event.preventDefault();
startHold();
}
};
const handleKeyUp = (event: KeyboardEvent<HTMLButtonElement>) => {
if (event.key === " " || event.key === "Enter") {
event.preventDefault();
cancelHold();
}
};
const handleFillComplete = () => {
if (!holding || completedRef.current) return;
completedRef.current = true;
setCompleted(true);
onHoldComplete?.();
};
const accessibleName = typeof children === "string" ? children : undefined;
const active = holding || completed;
const activeTransform =
type === "horizontal" ? "translateX(0%)" : "translateY(0%)";
const idleTransform =
type === "horizontal" ? "translateX(-100%)" : "translateY(115%)";
return (
<motion.button
ref={ref}
type="button"
disabled={disabled}
aria-label={accessibleName}
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
onPointerCancel={cancelHold}
onPointerLeave={handlePointerLeave}
onKeyDown={handleKeyDown}
onKeyUp={handleKeyUp}
onBlur={(event) => {
// A key held while focus leaves never delivers its keyup here.
cancelHold();
onBlur?.(event);
}}
onContextMenu={(event) => event.preventDefault()}
whileTap={reduce || disabled ? undefined : { scale: 0.98 }}
transition={SPRING_PRESS}
className={cn(
"relative inline-grid h-16 min-w-72 touch-none place-items-center overflow-hidden rounded-[var(--hold-radius)] bg-primary px-8 text-primary-foreground",
"[--hold-radius:9999px]",
TOUCH_GESTURE_CLASS,
"outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 focus-visible:ring-offset-background",
"disabled:pointer-events-none disabled:opacity-50",
className,
)}
{...rest}
>
{/* Safari hands the fill its own compositing layer and then stops
applying the button's rounded overflow clip to it, so the liquid
bleeds past the corners. clip-path survives compositing. It lives on
this static layer rather than the button so it never cuts the focus
ring, and reads the same radius so the two cannot drift apart. */}
<span
aria-hidden="true"
className="pointer-events-none absolute inset-0 [clip-path:inset(0_round_var(--hold-radius))]"
>
<motion.span
aria-hidden="true"
initial={false}
animate={
reduce
? { opacity: active ? 1 : 0, transform: "none" }
: {
opacity: 1,
transform: active ? activeTransform : idleTransform,
}
}
transition={
active
? { duration: holdDuration / 1000, ease: "linear" }
: { duration: reduce ? 0.15 : 0.24, ease: EASE_OUT }
}
onAnimationComplete={handleFillComplete}
className={cn(
"absolute inset-0 bg-sky-400 will-change-[opacity,transform]",
fillClassName,
)}
>
{!reduce ? (
type === "horizontal" ? (
<motion.svg
viewBox="0 0 24 240"
preserveAspectRatio="none"
aria-hidden="true"
animate={{
transform: active ? "translateY(-50%)" : "translateY(0%)",
}}
transition={{
duration: 1.1,
ease: "linear",
repeat: active ? Number.POSITIVE_INFINITY : 0,
}}
className="absolute -right-5 top-0 h-[200%] w-6 text-sky-400"
>
<path
d="M0 0h12C2 20 2 40 12 60s10 40 0 60-10 40 0 60 10 40 0 60H0Z"
fill="currentColor"
/>
</motion.svg>
) : (
<motion.svg
viewBox="0 0 240 24"
preserveAspectRatio="none"
aria-hidden="true"
animate={{
transform: active ? "translateX(-50%)" : "translateX(0%)",
}}
transition={{
duration: 1.1,
ease: "linear",
repeat: active ? Number.POSITIVE_INFINITY : 0,
}}
className="absolute -top-5 left-0 h-6 w-[200%] text-sky-400"
>
<path
d="M0 12C20 2 40 2 60 12s40 10 60 0 40-10 60 0 40 10 60 0v12H0Z"
fill="currentColor"
/>
</motion.svg>
)
) : null}
</motion.span>
</span>
<span
className={cn(
"relative z-10 grid place-items-center text-base font-medium tracking-[-0.01em]",
labelClassName,
)}
>
<motion.span
animate={{ opacity: active ? 0 : 1 }}
transition={{ duration: reduce ? 0 : 0.12, ease: EASE_OUT }}
className="col-start-1 row-start-1"
>
{children}
</motion.span>
<motion.span
aria-hidden={!holding || completed}
animate={{ opacity: holding && !completed ? 1 : 0 }}
transition={{ duration: reduce ? 0 : 0.12, ease: EASE_OUT }}
className="col-start-1 row-start-1"
>
{holdingLabel ?? t("holding")}
</motion.span>
<motion.span
aria-hidden={!completed}
animate={{ opacity: completed ? 1 : 0 }}
transition={{ duration: reduce ? 0 : 0.12, ease: EASE_OUT }}
className="col-start-1 row-start-1"
>
{completeLabel ?? t("complete")}
</motion.span>
</span>
</motion.button>
);
});
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],
);
}
// Shared touch primitives. iOS and iPadOS run their own gestures on top of the
// page — the long-press selection callout and the selection it drags in with
// it — and they win: once the platform claims a touch it cancels ours
// mid-gesture, so a press-and-hold or a drag simply dies. Surfaces that own
// their gesture have to opt out.
//
// What the two classes below cover, precisely:
// - `-webkit-touch-callout: none` stops iOS's long-press callout. WebKit-only:
// it is not a property other engines have, so it is inert everywhere else.
// - `user-select: none` stops the long-press selection on every engine,
// Android included, and stops a drag from painting a selection under the
// cursor. It is inherited, so it reaches every descendant — which is why the
// two classes differ only in whether they apply it unconditionally.
// What neither covers:
// - Chrome for Android's long-press menu on a link or an image. No CSS
// suppresses it; a gesture surface that wraps one needs its own
// `onContextMenu` with `preventDefault()`.
// - The native drag of an `<img>` or `<a>` descendant. `-webkit-user-drag` is
// not inherited and plain divs and buttons are not drag sources, so setting
// it on the surface does nothing — the child itself needs `draggable={false}`.
/**
* Classes for a surface that *is* the control: a thumb, a drum, a stage, a
* handle, a hold button. Selection is suppressed on every input, because a
* drag that highlights the control's own label is wrong on a mouse too.
* Compose with `touch-none` when the surface also owns the scroll axis — leave
* it off when the page must still scroll from there.
*/
export const TOUCH_GESTURE_CLASS = "select-none [-webkit-touch-callout:none]";
/**
* The same opt-out for a gesture surface that wraps content the consumer owns:
* a scroller, a context-menu trigger, a sheet header, a list row. Selection is
* suppressed only where the platform runs its own press gestures — a coarse
* pointer — so a mouse user can still select and copy that content. If the
* gesture itself would paint a selection under the cursor, add `select-none`
* for the duration of the gesture rather than reaching for
* `TOUCH_GESTURE_CLASS`.
*
* `pointer: coarse` describes the *primary* pointer and nothing else, so a
* hybrid machine reads it wrong in both directions: a tablet with a mouse
* plugged in keeps touch as primary and loses mouse selection, and a laptop
* with a touchscreen keeps the mouse as primary and leaves selection live
* under a finger. No media query can answer per interaction — the query is
* about the device, and the question is about the gesture in progress. The
* default stays here because it is right on the machines that are one thing or
* the other, and losing a selection is a nuisance; where the miss costs a
* *gesture* instead, the surface pairs it with `holdSelection` on the press.
*/
export const TOUCH_GESTURE_CONTENT_CLASS =
"[-webkit-touch-callout:none] pointer-coarse:select-none";
/**
* Suppress selection on `element` for as long as a gesture is running on it,
* whatever the primary pointer of the machine happens to be. Returns the
* release. Inline, so it wins over the class above and is gone again the
* moment the gesture ends.
*
* For the press gestures a native selection would otherwise steal — a
* long-press that opens a menu. Elsewhere prefer the classes: a surface that
* takes selection away for the whole session is a surface whose text nobody
* can copy.
*/
export function holdSelection(element: HTMLElement) {
element.style.setProperty("user-select", "none");
element.style.setProperty("-webkit-user-select", "none");
return () => {
element.style.removeProperty("user-select");
element.style.removeProperty("-webkit-user-select");
};
}
/**
* Pointer capture, best effort. WebKit throws `NotFoundError` when the pointer
* is already gone by the time the handler runs — routine on iOS, where the
* system can claim the touch first — and an uncaught throw takes the rest of
* the handler, the gesture included, down with it. Touch pointers carry
* implicit capture anyway, so losing it is never fatal.
*/
export function capturePointer(element: Element, pointerId: number) {
try {
element.setPointerCapture(pointerId);
} catch {
// Pointer is no longer active — implicit capture still applies on touch.
}
}
/** Release a capture taken with `capturePointer`, ignoring a stale pointer. */
export function releasePointer(element: Element, pointerId: number) {
try {
if (element.hasPointerCapture(pointerId)) {
element.releasePointerCapture(pointerId);
}
} catch {
// Capture was already dropped by the browser.
}
}
/**
* Whether this event came from a pointer that is *hovering*: not a touch, and
* not currently pressed. Which input the user is holding right now is not
* something a device capability can answer — a touchscreen laptop hovers and
* taps, and iPadOS reports a fine hovering pointer for a finger — so both
* paths stay live and each handler branches on the event it was given.
*
* A pen resting on the glass is making contact, not hovering: `buttons` is the
* tell, and it sends a pen tap down the same route a finger takes.
*
* This answers what an *enter* asks. A leave is the other half of a pair and
* has to be read against the enter that started it — `useHoverGesture` in
* `lib/hooks/use-hover-gesture` does that, and hover surfaces should use it
* rather than asking this question twice.
*/
export const isHoveringPointer = (event: {
pointerType: string;
buttons: number;
}) => event.pointerType !== "touch" && event.buttons === 0;
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/components/motion/expanding-arrow-button/hold-action
import { type HTMLMotionProps, motion, useReducedMotion } from "motion/react";
import {
forwardRef,
type KeyboardEvent,
type PointerEvent,
type ReactNode,
useRef,
useState,
} from "react";
import { EASE_OUT, SPRING_PRESS } from "@/lib/ease";
import { useMessages } from "@/lib/i18n";
import {
capturePointer,
releasePointer,
TOUCH_GESTURE_CLASS,
} from "@/lib/touch";
import { cn } from "@/lib/utils";
/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */
export const holdActionButtonMessages = {
holding: "Keep holding",
complete: "Done",
};
export type HoldActionButtonMessages = typeof holdActionButtonMessages;
export interface HoldActionButtonProps extends Omit<
HTMLMotionProps<"button">,
| "children"
| "type"
| "onClick"
| "onPointerDown"
| "onPointerUp"
| "onPointerCancel"
| "onPointerLeave"
| "onPointerMove"
| "onKeyDown"
| "onKeyUp"
> {
children: ReactNode;
/** Fill rises from the bottom or sweeps in from the left. Default: "vertical" */
type?: "vertical" | "horizontal";
/** Label shown while the button is held. Default: "Keep holding" */
holdingLabel?: ReactNode;
/** Label shown once the hold completes. Default: "Done" */
completeLabel?: ReactNode;
/** How long the button must be held to complete (ms). Default: 1600 */
holdDuration?: number;
/** Called once when the fill finishes while still held. */
onHoldComplete?: () => void;
/** Classes merged onto the fill layer, e.g. to change its color. */
fillClassName?: string;
/** Classes merged onto the label wrapper. */
labelClassName?: string;
/** Override any built-in string. */
labels?: Partial<HoldActionButtonMessages>;
}
export const HoldActionButton = forwardRef<
HTMLButtonElement,
HoldActionButtonProps
>(function HoldActionButton(
{
children,
type = "vertical",
holdingLabel,
completeLabel,
holdDuration = 1600,
onHoldComplete,
fillClassName,
labelClassName,
className,
disabled,
labels,
onBlur,
...rest
},
ref,
) {
const t = useMessages("holdActionButton", holdActionButtonMessages, labels);
const reduce = useReducedMotion();
const completedRef = useRef(false);
const [holding, setHolding] = useState(false);
const [completed, setCompleted] = useState(false);
const startHold = () => {
if (disabled || holding) return;
completedRef.current = false;
setCompleted(false);
setHolding(true);
};
const cancelHold = () => {
setHolding(false);
setCompleted(false);
};
const handlePointerDown = (event: PointerEvent<HTMLButtonElement>) => {
if (event.button !== 0) return;
// Start first: capture is a convenience, and a browser that refuses it
// must not take the hold down with it.
startHold();
capturePointer(event.currentTarget, event.pointerId);
};
const handlePointerUp = (event: PointerEvent<HTMLButtonElement>) => {
releasePointer(event.currentTarget, event.pointerId);
cancelHold();
};
const handlePointerLeave = (event: PointerEvent<HTMLButtonElement>) => {
// Only reached when the capture below was refused: a captured pointer gets
// no boundary events at all. A finger does not get this reading either way
// — WebKit fires leave repeatedly for a touch that never moved, which
// would cancel every hold on the frame it started.
if (event.pointerType !== "touch") cancelHold();
};
const handlePointerMove = (event: PointerEvent<HTMLButtonElement>) => {
// Leaving the button abandons the hold, and while the pointer is captured
// nothing announces that: no boundary events, and `touch-none` means a
// finger sliding off cannot scroll and so cannot cancel either. Measure it
// instead — off the button ends the hold, wherever the pointer then goes.
if (!holding) return;
const rect = event.currentTarget.getBoundingClientRect();
const outside =
event.clientX < rect.left ||
event.clientX > rect.right ||
event.clientY < rect.top ||
event.clientY > rect.bottom;
if (outside) cancelHold();
};
const handleKeyDown = (event: KeyboardEvent<HTMLButtonElement>) => {
if ((event.key === " " || event.key === "Enter") && !event.repeat) {
event.preventDefault();
startHold();
}
};
const handleKeyUp = (event: KeyboardEvent<HTMLButtonElement>) => {
if (event.key === " " || event.key === "Enter") {
event.preventDefault();
cancelHold();
}
};
const handleFillComplete = () => {
if (!holding || completedRef.current) return;
completedRef.current = true;
setCompleted(true);
onHoldComplete?.();
};
const accessibleName = typeof children === "string" ? children : undefined;
const active = holding || completed;
const activeTransform =
type === "horizontal" ? "translateX(0%)" : "translateY(0%)";
const idleTransform =
type === "horizontal" ? "translateX(-100%)" : "translateY(115%)";
return (
<motion.button
ref={ref}
type="button"
disabled={disabled}
aria-label={accessibleName}
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
onPointerCancel={cancelHold}
onPointerLeave={handlePointerLeave}
onKeyDown={handleKeyDown}
onKeyUp={handleKeyUp}
onBlur={(event) => {
// A key held while focus leaves never delivers its keyup here.
cancelHold();
onBlur?.(event);
}}
onContextMenu={(event) => event.preventDefault()}
whileTap={reduce || disabled ? undefined : { scale: 0.98 }}
transition={SPRING_PRESS}
className={cn(
"relative inline-grid h-16 min-w-72 touch-none place-items-center overflow-hidden rounded-[var(--hold-radius)] bg-primary px-8 text-primary-foreground",
"[--hold-radius:9999px]",
TOUCH_GESTURE_CLASS,
"outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 focus-visible:ring-offset-background",
"disabled:pointer-events-none disabled:opacity-50",
className,
)}
{...rest}
>
{/* Safari hands the fill its own compositing layer and then stops
applying the button's rounded overflow clip to it, so the liquid
bleeds past the corners. clip-path survives compositing. It lives on
this static layer rather than the button so it never cuts the focus
ring, and reads the same radius so the two cannot drift apart. */}
<span
aria-hidden="true"
className="pointer-events-none absolute inset-0 [clip-path:inset(0_round_var(--hold-radius))]"
>
<motion.span
aria-hidden="true"
initial={false}
animate={
reduce
? { opacity: active ? 1 : 0, transform: "none" }
: {
opacity: 1,
transform: active ? activeTransform : idleTransform,
}
}
transition={
active
? { duration: holdDuration / 1000, ease: "linear" }
: { duration: reduce ? 0.15 : 0.24, ease: EASE_OUT }
}
onAnimationComplete={handleFillComplete}
className={cn(
"absolute inset-0 bg-sky-400 will-change-[opacity,transform]",
fillClassName,
)}
>
{!reduce ? (
type === "horizontal" ? (
<motion.svg
viewBox="0 0 24 240"
preserveAspectRatio="none"
aria-hidden="true"
animate={{
transform: active ? "translateY(-50%)" : "translateY(0%)",
}}
transition={{
duration: 1.1,
ease: "linear",
repeat: active ? Number.POSITIVE_INFINITY : 0,
}}
className="absolute -right-5 top-0 h-[200%] w-6 text-sky-400"
>
<path
d="M0 0h12C2 20 2 40 12 60s10 40 0 60-10 40 0 60 10 40 0 60H0Z"
fill="currentColor"
/>
</motion.svg>
) : (
<motion.svg
viewBox="0 0 240 24"
preserveAspectRatio="none"
aria-hidden="true"
animate={{
transform: active ? "translateX(-50%)" : "translateX(0%)",
}}
transition={{
duration: 1.1,
ease: "linear",
repeat: active ? Number.POSITIVE_INFINITY : 0,
}}
className="absolute -top-5 left-0 h-6 w-[200%] text-sky-400"
>
<path
d="M0 12C20 2 40 2 60 12s40 10 60 0 40-10 60 0 40 10 60 0v12H0Z"
fill="currentColor"
/>
</motion.svg>
)
) : null}
</motion.span>
</span>
<span
className={cn(
"relative z-10 grid place-items-center text-base font-medium tracking-[-0.01em]",
labelClassName,
)}
>
<motion.span
animate={{ opacity: active ? 0 : 1 }}
transition={{ duration: reduce ? 0 : 0.12, ease: EASE_OUT }}
className="col-start-1 row-start-1"
>
{children}
</motion.span>
<motion.span
aria-hidden={!holding || completed}
animate={{ opacity: holding && !completed ? 1 : 0 }}
transition={{ duration: reduce ? 0 : 0.12, ease: EASE_OUT }}
className="col-start-1 row-start-1"
>
{holdingLabel ?? t("holding")}
</motion.span>
<motion.span
aria-hidden={!completed}
animate={{ opacity: completed ? 1 : 0 }}
transition={{ duration: reduce ? 0 : 0.12, ease: EASE_OUT }}
className="col-start-1 row-start-1"
>
{completeLabel ?? t("complete")}
</motion.span>
</span>
</motion.button>
);
});
className?stringClasses merged onto the root element.
—labels?Partial<{ holding: string; complete: string; }>Override any built-in string.
—type?"vertical" | "horizontal"Fill rises from the bottom or sweeps in from the left. Default: "vertical"
verticallabelClassName?stringClasses merged onto the label wrapper.
—holdingLabel?ReactNodeLabel shown while the button is held. Default: "Keep holding"
—completeLabel?ReactNodeLabel shown once the hold completes. Default: "Done"
—holdDuration?numberHow long the button must be held to complete (ms). Default: 1600
1600onHoldComplete?(() => void)Called once when the fill finishes while still held.
—fillClassName?stringClasses merged onto the fill layer, e.g. to change its color.
—Action Swap
CTA button and slot primitives for swapping text and icons with blur motion.
Expandable Control
Click-to-expand button and chip controls that reveal a label or trailing action through spring layout continuity.
Card
Composable card with header, title, description, action, content and footer parts. Outlined or muted surfaces, standard or compact spacing, and an opt-in selectable state with press feedback that composes with Checkbox, Radio and Button.
Updated