Button
The base button with press feedback, sound and several variants.
- #arc
- #component
- #button
- #action
- #loading
- #variant
Install
One command installs the files and packages this item needs.
npx shadcn@latest add https://dsui.vercel.app/r/button.jsonFiles
components/arc/button/button.module.csscomponents/arc/button/button.tsx
npm packages
motion@^14.2.0
Registry items it pulls in
Source
View as Markdown/* Press scale is driven by Motion (whileTap) alone, so transform never gets a CSS transition here. */
.button { position: relative; display: inline-flex; min-height: var(--control-height-md); align-items: center; justify-content: center; gap: var(--space-2); border: 1px solid transparent; border-radius: var(--radius-control); padding: 0 var(--space-4); font: inherit; font-size: var(--label-md); font-weight: var(--label-weight); line-height: var(--leading-body); white-space: nowrap; cursor: pointer; -webkit-tap-highlight-color: transparent; transition: color var(--duration-fast) var(--ease-standard), background var(--duration-fast) var(--ease-standard), border-color var(--duration-fast) var(--ease-standard), opacity var(--duration-fast) var(--ease-standard), box-shadow var(--duration-fast) var(--ease-standard); }
.button:disabled { cursor: not-allowed; }
.button[aria-busy="true"] { cursor: progress; }
/* Anchors of floating layers never scale: Radix opens on pointerdown and would measure a shrunken trigger. */
.button:is([aria-haspopup]:not([aria-haspopup="false"]), [data-state], [role="combobox"]) { transform: none !important; }
/* The slot's width follows the incoming label on a spring. The label stays centered and may overflow evenly while the slot catches up;
the outgoing label pops out of flow against the slot itself, so it keeps its place instead of following the new content box. */
.labelSlot { position: relative; display: inline-flex; min-width: 0; align-items: center; justify-content: center; transition: opacity var(--duration-fast) var(--ease-standard); }
.labelSlot[data-morphing] { clip-path: inset(-50% calc(var(--space-3) * -1)); }
.labelContent { display: inline-flex; flex: none; align-items: center; }
.labelPhase { display: inline-flex; align-items: center; justify-content: center; gap: var(--space-2); white-space: nowrap; }
.labelPhase svg { flex: none; }
/* A face with a color of its own casts that color; the plain surfaces (secondary, ghost) keep the neutral shadow. */
.primary { color: var(--accent-foreground); background: var(--accent); border-color: var(--accent); box-shadow: var(--shadow-accent-resting); }
.secondary { color: var(--foreground); background: var(--surface); border-color: var(--border); }
.ghost { color: var(--text-secondary); background: transparent; border-color: transparent; }
.accent { color: var(--highlight-foreground); background: var(--highlight); border-color: var(--highlight); box-shadow: var(--shadow-highlight-resting); }
.danger { color: var(--danger); background: var(--surface); border-color: var(--border); }
/* Disabled keeps the shape on a muted fill with a faded ink label, the same in every variant, so it reads as a button that is off. */
.primary:disabled, .accent:disabled, .secondary:disabled, .ghost:disabled, .danger:disabled { color: color-mix(in oklab, var(--foreground) 55%, transparent); background: var(--border); border-color: transparent; box-shadow: none; }
@media (hover: hover) and (pointer: fine) {
.primary:hover:not(:disabled) { opacity: .91; box-shadow: var(--shadow-accent-raised); }
.accent:hover:not(:disabled) { opacity: .91; box-shadow: var(--shadow-highlight-raised); }
.secondary:hover:not(:disabled) { background: var(--surface-muted); box-shadow: var(--shadow-resting); }
.ghost:hover:not(:disabled) { color: var(--foreground); background: var(--accent-subtle); }
.danger:hover:not(:disabled) { border-color: var(--danger); background: var(--surface-muted); box-shadow: var(--shadow-danger-resting); }
}
/* Color feedback on press, so touch and menu triggers (which never scale) still answer the finger. */
.primary:active:not(:disabled) { background: var(--accent-strong); border-color: var(--accent-strong); box-shadow: var(--shadow-accent-resting); }
.accent:active:not(:disabled) { opacity: .84; }
.secondary:active:not(:disabled) { color: var(--foreground); background: var(--surface-muted); border-color: var(--border-strong); }
.ghost:active:not(:disabled) { color: var(--accent-strong); background: var(--accent-subtle); }
.danger:active:not(:disabled) { border-color: var(--danger); background: var(--surface-muted); }
.sm { min-height: var(--control-height-sm); padding-inline: var(--space-3); font-size: var(--label-sm); }
.md { min-height: var(--control-height-md); }
.lg { min-height: var(--control-height-lg); padding-inline: var(--space-5); font-size: var(--label-lg); }
.loader { position: absolute; left: 50%; top: 50%; display: grid; width: var(--space-4); height: var(--space-4); margin: calc(var(--space-4) / -2); }
.spinner { border: 1.5px solid currentColor; border-right-color: transparent; border-radius: 50%; animation: spin .7s linear infinite; }
.loadingLabel { opacity: 0; }
@keyframes spin { to { transform: rotate(360deg); } }
@media (prefers-reduced-motion: reduce) { .button { transition: none; } .labelSlot { transition: opacity var(--duration-instant) linear; } .spinner { animation-duration: .01ms; animation-iteration-count: 1; } }
"use client";
import { forwardRef, isValidElement, useCallback, useEffect, useLayoutEffect, useRef } from "react";
import type { ButtonHTMLAttributes, ReactNode, Ref, RefObject } from "react";
import { AnimatePresence, animate, motion, useIsPresent, useMotionValue } from "motion/react";
import { useReducedMotion } from "../lib/use-reduced-motion";
import type { TargetAndTransition, Variants } from "motion/react";
import { motionTokens } from "../lib/motion-tokens";
import styles from "./button.module.css";
import { playUiSound } from "../sound/play";
export type ButtonVariant = "primary" | "secondary" | "ghost" | "accent" | "danger";
export type ButtonSize = "sm" | "md" | "lg";
export interface ButtonProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, "onDrag" | "onDragEnd" | "onDragStart" | "onAnimationStart"> {
variant?: ButtonVariant;
size?: ButtonSize;
loading?: boolean;
/** Skip the click sound, for a button that already makes its own sound. */
silent?: boolean;
}
/** Icon buttons press a little deeper, wide buttons a little less, so every size reads as the same push. */
const pressVariants: Variants = {
pressed: (button: RefObject<HTMLButtonElement | null>) => {
const width = button.current?.offsetWidth ?? 0;
return { scale: width > 220 ? .985 : width && width <= 48 ? .96 : .97, transition: { duration: motionTokens.duration.instant, ease: [...motionTokens.ease.standard] } };
},
};
const rest: TargetAndTransition = { opacity: 1, y: 0, scale: 1, filter: "blur(0px)" };
/** Text rises about .3em out of a soft blur; the outgoing label lifts away a little faster. */
const textIn: TargetAndTransition = { opacity: 0, y: 4, filter: `blur(${motionTokens.blur.soft}px)` };
const textOut: TargetAndTransition = { opacity: 0, y: -3, filter: `blur(${motionTokens.blur.soft}px)`, transition: { duration: motionTokens.duration.fast, ease: [...motionTokens.ease.standard] } };
const iconIn: TargetAndTransition = { opacity: 0, scale: .6, filter: `blur(${motionTokens.blur.subtle}px)` };
const iconOut: TargetAndTransition = { opacity: 0, scale: .6, filter: `blur(${motionTokens.blur.subtle}px)`, transition: { duration: motionTokens.duration.fast, ease: [...motionTokens.ease.standard] } };
const fadeIn: TargetAndTransition = { ...rest, opacity: 0 };
const fadeOut: TargetAndTransition = { opacity: 0, transition: { duration: motionTokens.duration.instant } };
/** Scale rides the spring; opacity and blur tween so blur never overshoots below zero. */
const iconEnter = { ...motionTokens.spring.snappy, opacity: { duration: motionTokens.duration.fast, ease: [...motionTokens.ease.enter] }, filter: { duration: motionTokens.duration.fast, ease: [...motionTokens.ease.enter] } } as const;
/** A key for the label content: text plus element names, so a new label or icon crossfades while prop-only updates stay in place. */
function labelKey(node: ReactNode): string {
if (node == null || typeof node === "boolean") return "";
if (typeof node === "string" || typeof node === "number" || typeof node === "bigint") return String(node);
if (Array.isArray(node)) return node.map(labelKey).join("");
if (!isValidElement(node)) return "";
const type = node.type as string | { displayName?: string; name?: string };
return `<${typeof type === "string" ? type : type?.displayName ?? type?.name ?? ""}>${labelKey((node.props as { children?: ReactNode }).children)}`;
}
/** Springs the slot to the natural width of the incoming label when it changes, so a new label never snaps the button's size.
* The outgoing label is popped out of flow at once, so it never holds the old width. Other resizes (a late web font, a parent reflow) jump straight to the new width, so nothing wobbles on first paint. */
function useMorphWidth(content: RefObject<HTMLElement | null>, key: string, reduced: boolean) {
const width = useMotionValue<number | "auto">("auto");
const lastKey = useRef(key), armedUntil = useRef(0);
useLayoutEffect(() => {
if (lastKey.current === key) return;
lastKey.current = key;
armedUntil.current = performance.now() + 700;
}, [key]);
useEffect(() => {
const node = content.current, slot = node?.parentElement;
if (!node || !slot || typeof ResizeObserver === "undefined") return;
let measured = false;
const observer = new ResizeObserver(([entry]) => {
if (!entry) return;
const next = entry.contentRect.width;
if (!next || !measured || reduced || performance.now() > armedUntil.current) { measured = next > 0; width.jump(next || "auto"); delete slot.dataset.morphing; return; }
slot.dataset.morphing = "";
animate(width, next, { ...motionTokens.spring.morph, onComplete: () => { delete slot.dataset.morphing; } });
});
observer.observe(node);
return () => observer.disconnect();
}, [content, reduced, width]);
return width;
}
function LabelPhase({ children, icon, reduced, ref }: { children: ReactNode; icon: boolean; reduced: boolean; ref?: Ref<HTMLSpanElement> }) {
const present = useIsPresent();
return <motion.span ref={ref} className={styles.labelPhase} aria-hidden={present ? undefined : true} initial={reduced ? fadeIn : icon ? iconIn : textIn} animate={rest} exit={reduced ? fadeOut : icon ? iconOut : textOut} transition={reduced ? { duration: motionTokens.duration.instant } : icon ? iconEnter : { duration: motionTokens.duration.standard, ease: [...motionTokens.ease.enter] }}>{children}</motion.span>;
}
export const Button = forwardRef<HTMLButtonElement, ButtonProps>(function Button(
{ className, variant = "primary", size = "md", loading = false, silent = false, disabled, children, onClick, ...props },
ref,
) {
const reduceMotion = useReducedMotion() ?? false;
const buttonRef = useRef<HTMLButtonElement | null>(null);
const contentRef = useRef<HTMLSpanElement>(null);
const key = labelKey(children);
const width = useMorphWidth(contentRef, key, reduceMotion);
const setRefs = useCallback((node: HTMLButtonElement | null) => {
buttonRef.current = node;
if (typeof ref === "function") ref(node); else if (ref) ref.current = node;
}, [ref]);
// A trigger that anchors a menu, popover, or dialog keeps its rect still while pressed, so the layer never measures a scaled anchor.
// Radix triggers (asChild) pass aria-haspopup or data-state through; the stylesheet repeats the guard.
const popup = props["aria-haspopup"];
const anchorsLayer = (popup !== undefined && popup !== false && popup !== "false") || props.role === "combobox" || (props as Record<string, unknown>)["data-state"] !== undefined;
const inert = disabled || loading || props["aria-disabled"] === true || props["aria-disabled"] === "true";
const classes = [styles.button, styles[variant], styles[size], className].filter(Boolean).join(" ");
return (
<motion.button
ref={setRefs}
tabIndex={props.tabIndex ?? 0}
className={classes}
disabled={disabled}
aria-busy={loading || undefined}
custom={buttonRef}
variants={pressVariants}
whileTap={reduceMotion || anchorsLayer || inert ? undefined : "pressed"}
transition={motionTokens.spring.snappy}
{...props}
// Loading keeps the button focusable (a disabled button would drop keyboard focus mid-action) and swallows presses instead.
aria-disabled={loading || props["aria-disabled"] || undefined}
onClick={loading ? event => event.preventDefault() : event => { if (!silent) playUiSound("click"); onClick?.(event); }}
>
<AnimatePresence initial={false}>
{loading ? <motion.span key="loader" className={styles.loader} aria-hidden="true" initial={reduceMotion ? { opacity: 0 } : { opacity: 0, scale: .6 }} animate={{ opacity: 1, scale: 1 }} exit={reduceMotion ? fadeOut : { ...iconOut, scale: .8 }} transition={reduceMotion ? { duration: motionTokens.duration.instant } : iconEnter}><span className={styles.spinner} /></motion.span> : null}
</AnimatePresence>
<motion.span className={[styles.labelSlot, loading ? styles.loadingLabel : ""].filter(Boolean).join(" ")} style={{ width }}>
<span ref={contentRef} className={styles.labelContent}>
<AnimatePresence mode="popLayout" initial={false}>
<LabelPhase key={key} icon={!/\S/.test(key.replace(/<[^>]*>/g, ""))} reduced={reduceMotion}>{children}</LabelPhase>
</AnimatePresence>
</span>
</motion.span>
</motion.button>
);
});
Button.displayName = "Button";
export default Button;
Used by
- Button linkComponent
An anchor that looks like the Button, for navigation that has to stay a real link.
- Comment composerBlock
The box for writing a comment, with the room left, the button and the notice.
- Contact sectionBlock
A contact section offering a validated form, channel list, or offices with live local time.
- Cookie consentComponent
A consent banner with per-category cookie preferences that can be reopened.
- CTA sectionBlock
A call to action section in centered, split, and dismissible banner variants.
- Empty statesBlock
Four animated empty states, such as no results and offline, each with a local action.
- Generative UIComponent
Draws a screen an AI model wrote in OpenUI or json-render with dsui components.
- Hero sectionBlock
A full-screen hero in centered, split, and minimal variants with animated visuals.
- Centered loginBlock
A centered sign-in and sign-up flow with passkey, email code, and social providers.
- Logo marqueeBlock
A scrolling strip of brand logos in full color or monochrome.
- Page headerBlock
A page header with breadcrumbs and actions that condenses on scroll and folds overflow.
- Plan comparisonBlock
A two-plan comparison with a monthly and yearly billing switch.
- Settings panelBlock
A drawer that gathers sound, color mode, season theme, text size and motion, and takes extra groups such as language or account.
- Sign inBlock
A stepwise sign-in with email code, passkey, and social providers.
- Signup formBlock
A validated signup form with social providers that morphs into a confirmation.
- Site footerBlock
A site footer in columns, minimal, and large logo variants with an optional newsletter.
- Theme switchComponent
A button that toggles light and dark themes with a rotating icon swap.