Button
An interactive button with multiple variants, sizes, icons, loading state, and Motion layout animation.
Installation
npx shadcn@latest add https://ui.mattdowney.com/r/button.jsonUsage
import { Button } from "@/components/ui/button"Examples
Default
Variants
Six fills. soft is the accent-tinted secondary that pairs with default, and subtle is its neutral version for toolbars. link paints no fill, so it ignores the size's height and sits on the text line.
Sizes
Four heights (24/28/32/40) plus three square icon sizes. An Input given the same size matches the button beside it in height and corner.
With Icon
Pass an element: it works anywhere, including from a Server Component. A bare component reference (iconStart={Mail}) also works, but only from a Client Component, because a function cannot cross the server/client boundary.
Icon sizes
Pass iconStart or iconEnd and the icon sizes itself (12/14/14/16px across the four heights), with its side padding adjusted to match. Set iconSize only to override it.
With count
Pass count to add a count chip inside the button. It stays readable on every variant and through hover.
A count arriving
Flip the switch: the chip slides in and pops, then fades out faster when it clears, and the button widens and narrows with it instead of jumping. A count already there on load, or one that changes from 3 to 4, stays still. Pass null to clear it; 0 still shows a chip.
Bare and block
variant="bare" is a press target with no fill or label styling, for an avatar, a thumbnail or a run of copy; give it a radius so the focus ring fits. size="block" makes a whole cell or row the target, with no press scale. ghost + block adds the hover tint.
Loading
loading swaps the label for a spinner, blocks the click, and sets aria-busy. The box does not resize, so a row of buttons holds its layout. Each variant keeps its own hover fill while busy, so a loading button reads as the same button mid-press rather than turning into a different one.
API Reference
| Prop | Type | Default | Description |
|---|---|---|---|
| variant | "default" | "soft" | "ghost" | "destructive" | "subtle" | "link" | "bare" | "default" | Visual style of the button. soft is the accent-tinted secondary that pairs with default; subtle is its neutral equivalent for toolbars. link paints no fill, so it ignores the size's height and padding and sits on the text line at every size. bare is only a focus and press target around its child: no fill, no press scale, no label styling, no height or padding. |
| size | "default" | "xs" | "sm" | "lg" | "icon" | "icon-sm" | "icon-lg" | "inline" | "block" | "default" | Height and padding preset. icon (32px), icon-sm (24px), and icon-lg (40px) are square; inline flows with surrounding text; block is a whole cell or row (full width, height from its content, left-aligned, no press scale). variant="link" and variant="bare" take only the type scale from this, never the height or padding. |
| iconStart | TablerIcon | ReactNode | None | Icon rendered before the label. Prefer an element (<Mail />); a bare component (Mail) still works but cannot be passed from a Server Component. |
| iconEnd | TablerIcon | ReactNode | None | Icon rendered after the label. Prefer an element (<ChevronRight />); a bare component still works but cannot be passed from a Server Component. |
| iconSize | "xs" | "sm" | "default" | "lg" | "xl" | None | Overrides the icon size implied by size. |
| count | React.ReactNode | None | Count chip rendered after the label, tinted to match the variant. Going from null to a value, the chip arrives with a short slide and pop; back to null, it fades out. Its space opens and closes with it, so the button glides to its new width. Changes in between stay still. |
| countClassName | string | None | Extra classes for the count chip. |
| disabled | boolean | false | Dims the button to 50% with a not-allowed cursor. It keeps its rest fill, label and size under the pointer: no hover tint, no press. With asChild, the link also gets aria-disabled and leaves the tab order. |
| loading | boolean | false | Locks in the variant's hover styling and blocks clicks at once. After about 200ms the label rises out as a centered spinner rises in, and the reverse when it ends; a shorter load shows no spinner. The button's size never changes. |
| layoutAnimation | boolean | false | Motion layout animation on content changes. Set false to prevent glitches on rapid state changes; disabled automatically under reduced motion. |
| type | "button" | "submit" | "reset" | "button" | Button never submits a form on its own. Pass type="submit" on the one that should. |
| asChild | boolean | false | Renders the child element instead of a <button>, merging classes and injecting icons, count, and spinner into it. |
variant"default" | "soft" | "ghost" | "destructive" | "subtle" | "link" | "bare" = "default"Visual style of the button. soft is the accent-tinted secondary that pairs with default; subtle is its neutral equivalent for toolbars. link paints no fill, so it ignores the size's height and padding and sits on the text line at every size. bare is only a focus and press target around its child: no fill, no press scale, no label styling, no height or padding. |
size"default" | "xs" | "sm" | "lg" | "icon" | "icon-sm" | "icon-lg" | "inline" | "block" = "default"Height and padding preset. icon (32px), icon-sm (24px), and icon-lg (40px) are square; inline flows with surrounding text; block is a whole cell or row (full width, height from its content, left-aligned, no press scale). variant="link" and variant="bare" take only the type scale from this, never the height or padding. |
iconStartTablerIcon | ReactNodeIcon rendered before the label. Prefer an element (<Mail />); a bare component (Mail) still works but cannot be passed from a Server Component. |
iconEndTablerIcon | ReactNodeIcon rendered after the label. Prefer an element (<ChevronRight />); a bare component still works but cannot be passed from a Server Component. |
iconSize"xs" | "sm" | "default" | "lg" | "xl"Overrides the icon size implied by size. |
countReact.ReactNodeCount chip rendered after the label, tinted to match the variant. Going from null to a value, the chip arrives with a short slide and pop; back to null, it fades out. Its space opens and closes with it, so the button glides to its new width. Changes in between stay still. |
| countClassNamestringExtra classes for the count chip. |
disabledboolean = falseDims the button to 50% with a not-allowed cursor. It keeps its rest fill, label and size under the pointer: no hover tint, no press. With asChild, the link also gets aria-disabled and leaves the tab order. |
| loadingboolean = falseLocks in the variant's hover styling and blocks clicks at once. After about 200ms the label rises out as a centered spinner rises in, and the reverse when it ends; a shorter load shows no spinner. The button's size never changes. |
layoutAnimationboolean = falseMotion layout animation on content changes. Set false to prevent glitches on rapid state changes; disabled automatically under reduced motion. |
type"button" | "submit" | "reset" = "button"Button never submits a form on its own. Pass type="submit" on the one that should. |
asChildboolean = falseRenders the child element instead of a <button>, merging classes and injecting icons, count, and spinner into it. |
"use client"
import * as React from "react"
import { motion, useReducedMotion } from "motion/react"
import { cn } from "@/registry/lib/utils"
import { renderIconProp, type IconProp } from "@/registry/lib/icon-prop"
import { CountArrival } from "@/registry/lib/count-arrival"
import { Spinner } from "@/registry/ui/spinner"
// The cva lives in its own module with NO "use client", so a Server Component
// can call `buttonVariants()` to paint a link as a button. Calling it through
// THIS module fails the production build: every export of a client module is a
// client reference, and a re-export is one too. See button-variants.ts.
import { buttonVariants, buttonGap, buttonIconSidePadding, type ButtonVariantProps } from "@/registry/ui/button-variants"
const iconSizeClasses = {
xs: "[&_svg]:!size-3",
sm: "[&_svg]:!size-3.5",
default: "", // uses variant default
lg: "[&_svg]:!size-5",
xl: "[&_svg]:!size-6",
} as const
/** Button's icon props take an ELEMENT or a bare component. See IconProp for
* which to reach for and why the element form is the one that works from a
* Server Component. */
type ButtonIcon = IconProp
/** Paint an icon prop in either form, tagging it with its position and giving
* it the loading swap's classes for the current phase. The two-form detection
* is shared with Input in `registry/lib/icon-prop`: it is the part that is easy
* to get wrong. */
function renderIcon(
icon: ButtonIcon | undefined,
position: "start" | "end",
faceClassName: string
) {
return renderIconProp(icon, {
"data-position": position,
className: faceClassName,
})
}
// THE LOADING SWAP, the same move as SwapButton's label swap. The face going
// away rises 4px, blurs 2px and fades; the face coming in rises from 4px
// below, sharpening and fading in. Both run at once on the small role, so
// there is never an empty frame. In: the label, icons and count leave, the
// spinner arrives. Out: the spinner leaves, the label, icons and count arrive.
// `translate` and `filter`, never `scale`: every Tabler glyph already carries
// `scale` for the kit's optical correction. Reduced motion keeps the fade only.
//
// A load goes through five phases:
// rest not loading. The label is `contents`, so the button lays out
// its children exactly as if the label span were not there.
// armed loading, inside the 200ms wait. Nothing moves; the label turns
// into a box of its own (laid out the same, see `labelBox`) so
// it has something to fade, and the spinner waits below, unseen.
// spinning the swap in. The label and its icons and count rise out.
// held the label has gone, and is snapped below with no transition,
// so that when loading ends it rises in rather than dropping.
// out loading ended. The spinner rises out while the label rises in;
// the spinner stays mounted until its fade ends, then `rest`.
// A load that ends while `armed` goes straight to `rest`: no spinner, no move.
type LoadPhase = "rest" | "armed" | "spinning" | "held" | "out"
const faceMove =
"transition-[opacity,translate,filter] duration-small ease-small motion-reduce:transition-[opacity]"
const faceShown = cn(faceMove, "opacity-100")
const faceLeaving = cn(faceMove, "opacity-0 motion-safe:-translate-y-1 motion-safe:blur-2xs")
const faceWaiting = "transition-none opacity-0 motion-safe:translate-y-1 motion-safe:blur-2xs"
// Which state the label's side (label, icons, count) is in for each phase.
const labelFace: Record<LoadPhase, string> = {
rest: faceShown,
// `transition-none`, not shown: the label has only just become a box, and
// nothing should run on the frame it does.
armed: "transition-none opacity-100",
spinning: faceLeaving,
held: faceWaiting,
out: faceShown,
}
// The spinner's state for each phase. It is not mounted at `rest`.
const spinnerFace: Record<LoadPhase, string> = {
rest: faceWaiting,
armed: faceWaiting,
spinning: faceShown,
held: faceShown,
out: faceLeaving,
}
// How long to wait for a fade's `transitionend` before moving on anyway. It
// only fires late: a role retuned to no duration sends no event at all, and
// this keeps the phase from sticking. Moving on late is harmless (the label
// snaps below a little later, or the hidden spinner unmounts a little later).
const SWAP_FALLBACK_MS = 600
type ButtonProps = Omit<React.ComponentProps<"button">, "onDrag" | "onDragStart" | "onDragEnd" | "onAnimationStart"> &
ButtonVariantProps & {
asChild?: boolean
iconStart?: ButtonIcon
iconEnd?: ButtonIcon
/** A count shown in a chip after the label. */
count?: React.ReactNode
countClassName?: string
/** @deprecated Use `count`. */
badge?: React.ReactNode
/** @deprecated Use `countClassName`. */
badgeClassName?: string
iconSize?: keyof typeof iconSizeClasses
loading?: boolean
/** Opt IN to Framer Motion layout animation (the button glides to its new
* position when surrounding layout changes). Off by default: with it on,
* ANY page reflow (a grid changing column count, a sibling unmounting, a
* filter re-render) sent every visible button sliding independently of
* its container, reading as a layout-shift glitch. */
layoutAnimation?: boolean
}
// @use-when any action the user can take, including a clickable thing whose
// face is not a button's: an avatar, a thumbnail, a run of text, a drag grip, a
// whole table cell or row (`variant="bare"`, and `size="block"` for the cell).
// To render a LINK as a button from a
// Server Component, paint the anchor with `buttonVariants` from
// `button-variants`: `asChild` runs React.Children.only, which children
// handed across the RSC boundary do not survive, so it throws at request
// time. `asChild` is correct inside a client component.
function Button({
className,
variant,
size,
iconSize,
count: countProp,
countClassName: countClassNameProp,
badge,
badgeClassName,
asChild = false,
iconStart,
iconEnd,
loading = false,
layoutAnimation = false,
disabled,
onClick,
children,
type,
...props
}: ButtonProps) {
const shouldReduceMotion = useReducedMotion()
// The spinner waits ~200ms after `loading` starts, so a load that finishes
// at once never flashes it. The button still holds its loading fill, cursor
// and `aria-busy` from the first frame; only the swap of label for spinner
// is delayed. Phases are described above `LoadPhase`. A change of `loading`
// moves the phase during render (React's pattern for state that follows a
// prop); the rest move on a timer or at the end of a fade.
const [phase, setPhase] = React.useState<LoadPhase>(loading ? "armed" : "rest")
const [wasLoading, setWasLoading] = React.useState(loading)
if (loading !== wasLoading) {
setWasLoading(loading)
setPhase(loading ? "armed" : phase === "spinning" || phase === "held" ? "out" : "rest")
}
React.useEffect(() => {
if (phase === "armed") {
const timer = setTimeout(() => setPhase("spinning"), 200)
return () => clearTimeout(timer)
}
if (phase === "spinning" || phase === "out") {
const next = phase === "spinning" ? "held" : "rest"
const timer = setTimeout(() => setPhase(next), SWAP_FALLBACK_MS)
return () => clearTimeout(timer)
}
}, [phase])
// A fade on the face that is leaving has ended: move on. Only the element's
// own opacity counts, not a transition bubbling up from inside it.
const onFadeEnd = (from: LoadPhase, to: LoadPhase) => (e: React.TransitionEvent) => {
if (e.target !== e.currentTarget || e.propertyName !== "opacity") return
setPhase((p) => (p === from ? to : p))
}
const swapping = phase !== "rest"
const count = countProp ?? badge
const countClassName = countClassNameProp ?? badgeClassName
// When loading, allow pointer events (for hover states) but block clicks
const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
if (loading) {
e.preventDefault();
return;
}
onClick?.(e);
};
// The icon side gets 2px LESS padding than the label side, and that reduction
// TRACKS THE SIZE RAMP. It used to be a flat `pl-3`/`pr-3` (12px) at every
// size, which balanced only at `sm`: against the ramp's own 8/12/16/20 label
// padding it was 4px too tight at `xs` (icon side wider than label side, the
// asymmetry reversed) and 8px too loose at `lg` (icon crammed to the edge, a
// visible right-heavy button). A flat value cannot balance a scaling one.
//
// Why 2px and not symmetric: icons vary wildly in how much of their 24-box
// they fill. A full-bleed glyph (mail, inbox) insets ~0.9u, a directional one
// (chevron 7.9u, arrow 3.9u) carries its own edge whitespace that padding
// cannot remove. Symmetric padding balances the full-bleed case dead-on but
// leaves a trailing chevron +4-5px right-heavy; a 2px reduction is the value
// that holds BOTH archetypes inside a +1.7 to +3.0px band across the whole
// ramp. Measured, not eyeballed: see the icon-fill table in the reference doc.
//
// Icon-only sizes (`icon`, `icon-sm`, `icon-lg`) and `inline` are skipped:
// no label means no side to balance against, and padding a fixed square box
// shoves the glyph off-centre inside the hover highlight. The table lives in
// button-variants.ts so SwapButton applies the same trim.
const sizePad = buttonIconSidePadding[size ?? "default"]
const iconPaddingClasses = sizePad
? cn(iconStart && sizePad.start, iconEnd && sizePad.end)
: undefined
const resolvedVariant = variant ?? "default"
// Loading holds the variant's OWN hover fill, so a busy button reads as the
// same button mid-press rather than as a different variant. `default` used to
// lock in a transparent accent-bordered box, which no variant rests in, so a
// busy primary read as a different button. `soft` and `subtle` had no
// loading state at all.
//
// CLASSES, NOT INLINE STYLES. These were inline accent-alias `var()` reads
// for specificity they never needed: a class appended after the variant's
// lands later in the same layer and wins on its own, and tailwind-merge drops
// the fill it replaces. Inline styles were also actively WRONG, because
// `--color-*` is an `@theme inline` alias declared once at `:root`. A custom
// property resolves where it is DECLARED, so the value froze against the root
// palette and never saw a scope below it: a d-a-r-k island (`SiteHeader`
// surface="hero" adds that class to a descendant) or a consumer scoping the
// kit under a class over their own root palette both got root colors.
// Utilities do not have this problem: `bg-accent` compiles to `var(--accent)`,
// which re-resolves at each element. Never read `var(--color-<semantic>)`
// from component source; the numbered scale is fine, declared not aliased.
// Going through `buttonClasses` also fixes `asChild`, which never received
// the inline styles at all and so had no loading state in any variant.
const loadingClasses = !loading
? undefined
: {
default: "bg-accent-600 text-accent-foreground",
soft: "bg-accent-200 dark:bg-accent-800 text-accent-800 dark:text-accent-200",
ghost: "bg-accent-100 dark:bg-accent-800 text-accent-700 dark:text-accent-200",
destructive: "bg-destructive-600 text-destructive-foreground",
"ghost-destructive":
"bg-destructive-100 dark:bg-destructive-800 text-destructive-700 dark:text-destructive-200",
"soft-destructive":
"bg-destructive-200 dark:bg-destructive-700 text-destructive-800 dark:text-destructive-100",
subtle: "bg-neutral-500/15 text-foreground",
// `link` paints no fill in any state, so there is nothing to hold. The
// spinner inherits the text color and reads on its own.
link: undefined,
// `bare` paints nothing, so there is no fill to hold either.
bare: undefined,
}[resolvedVariant]
const buttonClasses = cn(
buttonVariants({ variant, size, className }),
"group/button",
iconSize && iconSizeClasses[iconSize],
iconPaddingClasses,
loading && "pointer-events-auto cursor-wait",
// Last, so tailwind-merge drops the rest fill it replaces. It also outranks
// a caller's `className` fill, which is correct: loading is a state the
// component owns, and it lasts only as long as the flag.
loadingClasses
)
// The count is a DATUM, not a state. Every chip is OPAQUE and carries the
// strongest contrast available against its own button, which is why none of
// them carry a hover rule: an opaque chip cannot be swallowed when the
// button's fill shifts underneath it, so the number stays equally readable
// at the moment the pointer lands on it.
// `tabular-nums` keeps a changing count from resizing the button.
const countClasses = cn(
"inline-flex items-center justify-center min-w-4 h-4 rounded-full px-1 text-2xs font-medium tabular-nums transition-[color,background-color,opacity,translate,filter] duration-small ease-small motion-reduce:transition-[color,background-color,opacity]",
// Accent-FILLED buttons invert the chip to the foreground color, because
// accent-on-accent fails contrast.
resolvedVariant === "default" && "bg-accent-foreground text-accent",
resolvedVariant === "destructive" &&
"bg-destructive-foreground text-destructive-600",
// The transparent destructive button takes a solid destructive chip, the
// same relationship ghost has to its accent chip below.
(resolvedVariant === "ghost-destructive" || resolvedVariant === "soft-destructive") &&
"bg-destructive text-destructive-foreground dark:bg-destructive-400 dark:text-destructive-950",
// Accent-tinted and transparent buttons get a solid accent chip. This is
// the tabs.tsx active-tab counter exactly: that chip sits on the same
// accent-100/900 tint the `soft` button uses, and a pale chip on a pale
// surface reads as lost rather than as a count.
// The chip tracks the LABEL, one accent per control: a chip a step off its
// own label reads as two different blues, and the counter must never be the
// dimmer of the two. Light stays accent-500 for both. DARK moved to 400 for
// both when the tint went to accent-800, and the chip had to follow or it
// would have been the dimmer one. Its text inverts to accent-950 there,
// because accent-foreground on an accent-400 fill is only 3.09:1; on the
// accent-500 fill light mode still uses, the same near-white is 5.0:1.
// Change the label's accent step and you must change the chip's with it.
(resolvedVariant === "soft" || resolvedVariant === "ghost") && "bg-accent text-accent-foreground dark:bg-accent-400 dark:text-accent-950",
// The neutral button keeps a neutral chip: an accent-colored count would
// inject accent into the one variant that deliberately has none. Sits
// between the button's own rest and hover washes so it reads on both.
// The alpha chip needs a SOLID step once the page goes near-black:
// neutral-500/20 over an already-dim button lands 1.26:1 against it, so the
// disc vanishes and only the digit floats, reading as broken next to five
// solid chips. A near-black surface has too little range left for the disc
// to be a strong shape AND carry a strong digit at once, so the digit wins:
// neutral-600 puts the disc at 2.38:1 with the number still at 6.42:1.
// (Bare "d-a-r-k" as a word is avoided here on purpose: verify-registry
// scans raw quoted spans, and an apostrophe in a nearby comment turns this
// block into a fake string literal, tripping its site-only-class check.)
(resolvedVariant === "subtle" || resolvedVariant === "bare") && "bg-neutral-500/20 dark:bg-neutral-600 text-foreground",
countClassName
)
// The row's own flex gap, so the count's slot can cancel it while closed
// (see CountArrival). The icon-only sizes carry no gap.
const countGap =
size && size in buttonGap
? buttonGap[size as keyof typeof buttonGap]
: size === "inline"
? "gap-1"
: size === "block"
? "gap-2"
: size == null
? buttonGap.default
: "gap-0"
// At rest the label hands its box back to the button (`contents`), so the
// button's own flex row lays out the children: its gap, its centring, and a
// caller's truncation all behave as if the span were not there. While a load
// runs it needs a box of its own, because opacity, translate and filter do
// nothing on a `contents` element. That box is laid out to match: a flex row
// with the button's own gap for this size, centred on the cross axis like
// the button, and free to shrink (`min-w-0`). A label of plain text, or of
// several children, sits in the same place either way, so becoming a box
// and handing it back moves no pixel.
const labelClasses = cn(
"[color:inherit] [line-height:inherit] [letter-spacing:inherit]",
swapping ? cn("inline-flex min-w-0 items-center", countGap, labelFace[phase]) : "contents"
)
// The icons and the count follow the label. The count keeps its own color
// transition, so it takes only the state, not `faceMove`; at `rest` and
// `out` it is at its resting place and rises back to it.
const iconFace = labelFace[phase]
const countFace = {
rest: undefined,
armed: undefined,
spinning: "opacity-0 motion-safe:-translate-y-1 motion-safe:blur-2xs",
held: "transition-none opacity-0 motion-safe:translate-y-1 motion-safe:blur-2xs",
out: undefined,
}[phase]
// One overlay for both render paths. It mounts when a load starts, waiting
// below, rises in once the delay has passed, and stays mounted after the
// load ends until it has risen out.
const spinnerOverlay = swapping ? (
<span
className={cn(
"absolute inset-0 flex items-center justify-center [color:inherit]",
spinnerFace[phase]
)}
onTransitionEnd={onFadeEnd("out", "rest")}
>
<Spinner />
</span>
) : null
const renderContent = (label: React.ReactNode) => (
<>
{renderIcon(iconStart, "start", iconFace)}
<span className={labelClasses} onTransitionEnd={onFadeEnd("spinning", "held")}>
{label}
</span>
<CountArrival count={count} gap={countGap} className={cn(countClasses, countFace)} />
{renderIcon(iconEnd, "end", iconFace)}
{spinnerOverlay}
</>
)
// When using asChild, clone the child element and inject icons into its children
if (asChild) {
const child = React.Children.only(children) as React.ReactElement<{
className?: string
children?: React.ReactNode
}>
return React.cloneElement(child, {
...props,
// A caller's own `type` still reaches the child, but the `button` default
// below is not applied: an <a> or Link must not get a `type` attribute.
...(type ? { type } : {}),
// `disabled` is inert on non-button children (e.g. an <a>/<Link>), so also
// block interaction the way that works on any element. aria-busy is only
// meaningful while loading.
disabled,
...(disabled ? { "aria-disabled": true, tabIndex: -1 } : {}),
...(loading ? { "aria-busy": true } : {}),
className: cn(buttonClasses, disabled && "pointer-events-none", child.props.className),
"data-slot": "button",
children: renderContent(child.props.children),
} as React.Attributes & { className: string; children: React.ReactNode; "data-slot": string; disabled?: boolean; "aria-busy"?: boolean })
}
return (
<motion.button
data-slot="button"
// Defaults to "button" so a Button inside a form never submits it by
// accident (the HTML default is "submit"). A Button that should submit
// says `type="submit"`; a caller's own type always wins.
type={type ?? "button"}
className={buttonClasses}
disabled={disabled}
aria-busy={loading}
onClick={handleClick}
layout={layoutAnimation && !shouldReduceMotion ? "position" : false}
// motion-role-exempt: Motion's layout transition runs in JS and cannot read
// the role tokens. These are the small role's values (150ms, the same curve
// as ease-small), written out.
transition={{ duration: shouldReduceMotion ? 0 : 0.15, ease: [0, 0, 0.2, 1] }}
{...props}
>
{renderContent(children)}
</motion.button>
)
}
// `buttonVariants` is re-exported for the client components that already import
// it from here. In a SERVER component import it from the `button-variants`
// sibling module instead: this module is a client module, so the re-export is a
// client reference and calling it on the server throws. (The sibling is named
// rather than given as a path, because the path differs upstream and in an
// installed project, and only the import statements get rewritten on install.)
// rsc-reexport: buttonVariants -> button-variants
// kept for existing client call sites; server callers import the sibling
export { Button, buttonVariants }
export type { ButtonProps, ButtonIcon }import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/registry/lib/utils"
// ICON STROKE IS A FUNCTION OF THE LABEL'S FONT WEIGHT, not of the component.
//
// A Tabler glyph is stroked in a 24-unit viewBox, so the ink it actually paints
// is `strokeWidth * iconSize / 24` px. Type ink is measurable the same way:
// Geist's stem is 0.084em at weight 400, 0.106 at 500, 0.128 at 600. Set the two
// equal and Tabler's default stroke of 2 turns out to BE Geist Regular
// (24 * 0.084 = 2.02) when the icon box matches the font size. That is the
// calibration point the whole ramp hangs off, and it is why nothing here needed
// a stroke until now: at regular weight the default was already right.
//
// Button labels are `font-semibold`, and 600 wants 2.7-3.1. Every button in the
// kit was therefore pairing Semibold text with Regular-weight icons, two weight
// steps apart, which is the "icons look wrong" report this came from.
//
// The ceiling is set by counters, not by the stroke. Rasterising the shipped
// icon set, `Trash2`'s lid counter is the tightest thing in it and clears
// exactly `(3.94 - strokeWidth) * iconSize / 24` px. At the old 12px box that
// left 0.97px at stroke 2, i.e. no headroom at all: raising stroke alone just
// fills the counter in. Growing the box buys the headroom back, so the two moves
// have to happen together. 14px at 2.25 lands 89% of the way to the Semibold
// target and OPENS the tightest counter slightly (0.99px), so nothing in the set
// clogs relative to what already shipped.
//
// The stroke is a token rather than a literal because it is a property of the
// TYPEFACE. Swap Geist for something with a different stem and this is the knob
// that re-matches the icons; `--stroke-icon` (regular-weight contexts) and
// `--stroke-icon-action` (a semibold control label) both ship from `base`.
// The gap between a labelled button's icon and its label, per size. One table,
// read by the size strings below AND by SwapButton, which stacks its own
// icon-and-label pairs inside the label and so never sits in Button's flex
// row. A copy of these numbers anywhere else drifts the first time one moves.
const buttonGap = {
default: "gap-1.5",
xs: "gap-1",
sm: "gap-1",
lg: "gap-1.5",
} as const
// The icon side of a labelled button gets 2px LESS padding than the label side,
// scaled with the size; button.tsx explains the measurement. Shared for the same
// reason as `buttonGap`: SwapButton draws its icons itself, so it applies this
// trim by hand, and it has to be the same trim.
const buttonIconSidePadding: Record<string, { start: string; end: string }> = {
xs: { start: "ps-1.5", end: "pe-1.5" }, // label px-2 (8) -> 6
sm: { start: "ps-2.5", end: "pe-2.5" }, // label px-3 (12) -> 10
default: { start: "ps-3.5", end: "pe-3.5" }, // label px-4 (16) -> 14
lg: { start: "ps-4.5", end: "pe-4.5" }, // label px-5 (20) -> 18
}
const buttonVariantsBase = cva(
// `rotate-[0.0001deg]` keeps the label on the same render path at rest and
// pressed. Chrome snaps resting text to whole pixels but draws a transformed
// box at its true position, so the press scale used to hop the label about
// 1px. Any press-scaled kit part carries the same rotate.
"relative inline-flex items-center justify-center shrink-0 select-none cursor-pointer rotate-[0.0001deg] transition-[transform,color,background-color,border-color] duration-small ease-small motion-reduce:transition-[color,background-color,border-color] disabled:opacity-50 disabled:cursor-not-allowed disabled:active:scale-100 outline-none focus-visible:ring-ring-focus focus-visible:ring-[3px] [&_svg]:[stroke-width:var(--stroke-icon-action)]",
// DISABLED NEVER HOVERS. `disabled:opacity-50` alone left every variant's
// hover fill, hover label and press scale live, so a disabled ghost lit a
// washed-out accent chip under the pointer and read as broken. Each variant
// below restates its REST fill and label under `disabled:hover:`, and again
// under `dark:disabled:hover:` wherever it has a `dark:hover:` (the kit's
// `dark` variant is `:is(.dark, .dark *)`, which adds a class of specificity
// and sorts late, so a light reset loses to a dark hover), and the base string
// holds the press at `disabled:active:scale-100`. A reset, not a
// `not-disabled:hover:` gate on the hover itself: the gate adds a pseudo-class
// to every hover rule, so a caller's own `hover:` override in `className`
// (CopyButton, Calendar, Alert's dismiss X) would silently lose to it. The
// reset only outranks anything while the button is disabled.
// `verify-registry` (rule 9) fails a variant whose hover has no reset.
// An `asChild` link that is disabled gets `pointer-events-none` in
// button.tsx, so it never hovers at all.
{
variants: {
variant: {
// Primary: accent background, one step further from the page on hover.
// It does NOT invert to a bordered/transparent state, which would make
// the hovered primary read as a different button. Mirrors `destructive`,
// which shifts its fill this way.
//
// Both themes rest on the accent (500) and dim one step (600) on
// hover. The accent is the action colour, so the resting button shows
// it as picked; a dark theme that rested on 600 painted every primary
// button a shade off the colour the site is built around.
// Change either step and re-check the loading fill in button.tsx, which
// holds the hover fill so a busy button reads as mid-press.
default:
"bg-accent text-accent-foreground border border-transparent text-xs font-semibold hover:bg-accent-600 disabled:hover:bg-accent active:scale-[0.98]",
// Soft: accent-tinted fill, i.e. the `ghost` hover state made permanent.
// The secondary that pairs with `default`: it carries the accent tint so
// the two read as one family, but it has no border and no saturated
// fill, so it never competes with the primary or mimics its shape.
// Same tint pair as the kit's selected state (accent-100/accent-800).
// The label sits two steps off the plain accent, onto the tint:
// accent-500 on accent-100 is only 4:1, accent-700 clears 5.9:1 (dark:
// accent-200 on accent-800, 6.4:1). On hover the fill moves one step
// (light accent-200, dark accent-700) and the label moves one step with
// it: accent-800 on accent-200 is 6.4:1, dark accent-100 on accent-700
// 5.9:1. Ghost's hover fill is the resting tint, so it takes the
// resting label.
soft:
"bg-accent-100 dark:bg-accent-800 text-accent-700 dark:text-accent-200 border border-transparent text-xs font-semibold hover:bg-accent-200 hover:text-accent-800 dark:hover:bg-accent-700 dark:hover:text-accent-100 disabled:hover:bg-accent-100 disabled:hover:text-accent-700 dark:disabled:hover:bg-accent-800 dark:disabled:hover:text-accent-200 active:scale-[0.98]",
// Ghost: transparent with accent background on hover
ghost:
"bg-transparent text-foreground text-xs font-semibold hover:bg-accent-100 dark:hover:bg-accent-800 hover:text-accent-700 dark:hover:text-accent-200 disabled:hover:bg-transparent disabled:hover:text-foreground dark:disabled:hover:bg-transparent dark:disabled:hover:text-foreground active:scale-[0.98]",
// Destructive: solid destructive fill, one step darker on hover
destructive:
"bg-destructive text-destructive-foreground border border-transparent text-xs font-semibold hover:bg-destructive-600 disabled:hover:bg-destructive active:scale-[0.98]",
// Ghost-destructive: `ghost`'s shape in the destructive hue, for the
// quiet delete in a dialog footer or menu. It exists because the
// alternative was recoloring `ghost`'s label at the call site, which
// paints ghost's ACCENT hover fill under a destructive label: two
// semantic hues on one control at the exact moment the pointer lands
// on it. Hue is the variant's to own, so fill and label move together
// here the same way they do on every other variant. At rest the label sits
// on the page, so it keeps its own steps (600, dark 400); on hover it
// lands on the tint and takes ghost's label (700, dark 200).
"ghost-destructive":
"bg-transparent text-destructive-600 dark:text-destructive-400 text-xs font-semibold hover:bg-destructive-100 dark:hover:bg-destructive-800 hover:text-destructive-700 dark:hover:text-destructive-200 disabled:hover:bg-transparent disabled:hover:text-destructive-600 dark:disabled:hover:bg-transparent dark:disabled:hover:text-destructive-400 active:scale-[0.98]",
// Soft-destructive: `soft`'s tinted fill in the destructive hue, for
// the one delete in a row of soft peers (a page title row's actions).
// A peer set shares one weight class, so a ghost delete among soft
// buttons read as the odd one out: bare red text where its neighbours
// carry a fill. Same steps as `soft` (100/800 rest, 200/700 hover, labels 700/200 rest and 800/100 hover).
"soft-destructive":
"bg-destructive-100 dark:bg-destructive-800 text-destructive-700 dark:text-destructive-200 border border-transparent text-xs font-semibold hover:bg-destructive-200 hover:text-destructive-800 dark:hover:bg-destructive-700 dark:hover:text-destructive-100 disabled:hover:bg-destructive-100 disabled:hover:text-destructive-700 dark:disabled:hover:bg-destructive-800 dark:disabled:hover:text-destructive-200 active:scale-[0.98]",
// Subtle: tinted neutral surface for toolbar buttons
subtle:
"bg-neutral-500/10 text-foreground border border-transparent text-xs font-semibold hover:bg-neutral-500/15 disabled:hover:bg-neutral-500/10 active:scale-[0.98]",
// Link: inline text link for card headers and inline contexts
// Its BOX lives in the compound rule below, not here: a variant string
// is emitted before the size variant, so `h-auto p-0` written here is
// silently overwritten by whatever height and padding the size carries.
// The press scale rides the base string's transition list (it already
// covers colour and has the reduced-motion guard), so `link` no longer
// sets a colour-only transition of its own, which would have replaced
// that list and left the release snapping.
link: "bg-transparent text-muted-foreground text-sm normal-case font-normal tracking-normal hover:text-foreground disabled:hover:text-muted-foreground active:scale-[0.98] cursor-pointer",
// Bare: only a focus, press and disabled target around its child. No
// fill at any state, no press scale, no label styling (type, weight and
// colour come from the child), left-aligned. For something clickable
// whose face is not a button's: an avatar, a thumbnail, a run of copy,
// a badge, a drag grip, or a whole cell or row (add `size="block"`). It
// has no box of its own; the compound rule below zeroes the height and
// padding the size would add. Shape the focus ring with a radius on
// `className` (`rounded-full` around an avatar).
bare: "bg-transparent text-start",
},
// Radius lives HERE, not on the variants, because it is a function of
// height, and it reads from the ACTION ramp rather than the shared radius
// ladder. Roundness is only ever seen as a fraction of the box, so four
// heights wearing one corner value are four different shapes: 12px is 3/8
// of the 32px default and exactly half of the 24px xs, and half IS a pill.
// Snapping the short sizes to the nearest ladder rung trades that for a
// default that reads rounder than every button beside it. Each
// `rounded-action-*` rung is 3/8 of its own height instead, so all four
// sizes read as one shape. Change a height, re-derive its radius.
// Side padding steps a constant 4px across the ramp (8/12/16/20). It
// used to end on 24, which made the last step twice every other one and
// left `lg` looking loose next to `default`.
//
// TOUCH TARGETS. The four full-size rungs grow their BOX to 44px on a
// coarse pointer (WCAG 2.5.5), and carry the matching 44px corner with
// them: a height change owes a radius change in the same edit, so the
// touch rung reads as the same shape the mouse rung does. Growing the box
// is the right mechanism here rather than `.tap-target`, whose inset
// overlay is documented as unsafe next to another interactive control,
// and a Button sits next to another Button constantly (dialog footers,
// toolbars, table row actions). `min-h`/`min-w` rather than a fixed 44,
// so a long label or a tall wrapped one still grows past it.
//
// The three SHORT rungs (`xs`, `sm`, `icon-sm`) deliberately do not grow.
// A caller reaches for them because the row is dense, so tripling a 24px
// control's area would reflow exactly the layouts that chose it and would
// be fought back with `className` at every call site, which is worse than
// no rule at all. They stay at or above the 24px floor of WCAG 2.5.8, and
// the components that ship them in a real touch row already opt in by
// hand: Kebab grows its 28px square to 44 on coarse. A dense row that
// wants a thumb target asks for one.
//
// ICON BOX steps 12 / 14 / 14 / 16 against labels of 11 / 12 / 13 / 14px.
// It is not a straight `iconSize = fontSize`, because the stroke set on
// the base string above is one value and the ink it paints scales with the
// BOX, so the box is what tunes each rung onto its label: at 2.25 the three
// rungs paint 1.13 / 1.31 / 1.50px against Semibold targets of 1.24 / 1.36
// / 1.47 / 1.58, i.e. 90 / 97 / 89 / 95%. `xs` and `icon-sm` hold at 12px
// even though 14 would score better, because the box is 24px: a 14px glyph
// fills more than half of it and the size exists for dense rows. The
// icon-only rungs match the labelled rung of their own HEIGHT (icon-sm to
// xs, icon to default, icon-lg to lg) so a toolbar mixing the two reads as
// one row rather than two glyph sizes.
size: {
default:
`h-8 px-4 rounded-action pointer-coarse:min-h-11 pointer-coarse:min-w-11 pointer-coarse:rounded-action-xl [&_svg]:size-3.5 [&_svg]:shrink-0 ${buttonGap.default}`,
xs: `h-6 px-2 rounded-action-xs text-2xs [&_svg]:size-3 [&_svg]:shrink-0 ${buttonGap.xs}`,
sm: `h-7 px-3 rounded-action-sm text-1xs [&_svg]:size-3.5 [&_svg]:shrink-0 ${buttonGap.sm}`,
lg: `h-10 px-5 rounded-action-lg pointer-coarse:min-h-11 pointer-coarse:min-w-11 pointer-coarse:rounded-action-xl text-sm [&_svg]:size-4 [&_svg]:shrink-0 ${buttonGap.lg}`,
icon: "size-8 rounded-action pointer-coarse:size-11 pointer-coarse:rounded-action-xl [&_svg]:size-3.5",
"icon-sm": "size-6 rounded-action-xs [&_svg]:size-3",
// Square counterpart to `lg`, so a 40px control row (lg Button, lg Nav,
// lg Tabs) can carry an icon-only action without breaking its height.
// Glyph matches `lg`'s size-3.5 rather than `icon`'s size-3.
"icon-lg": "size-10 rounded-action-lg pointer-coarse:size-11 pointer-coarse:rounded-action-xl [&_svg]:size-4",
// Inline: for text buttons that flow with content. Its box is the text
// line (~20px), so it takes the smallest rung: a `ghost` inline button
// still paints a hover fill, and that fill needs a corner.
inline:
"h-auto px-0 rounded-sm gap-1 [&_svg]:size-3.5 [&_svg]:shrink-0",
// Block: the whole target is a cell or a row. Full width, height from
// its content, content left-aligned, and it never scales on press (a
// large block shrinking under the finger reads as a glitch, so the
// compound rule below cancels the variant's scale). Pair it with
// `bare` for a cell that paints its own states, or `ghost` for one that
// takes the accent tint on hover. Like `link` and `inline` it keeps its
// natural height on a coarse pointer, since it is already a large target.
block:
"h-auto w-full min-w-0 justify-start rounded-md px-3 py-2 text-start gap-2 [&_svg]:size-3.5 [&_svg]:shrink-0",
},
},
// `link` paints no fill at any state, so its box is the text line, not the
// size variant's height. Taking that height's corner would wrap a ~20px run
// of text in a 12px focus ring. Compound rules are emitted after the size
// variant, so this wins on merge whatever size is passed.
// The HEIGHT and PADDING belong here for the same reason the radius does,
// and they used to sit in the `link` variant string, where they never once
// applied: a bare `variant="link"` shipped a 32px box with 16px of side
// padding, and only `size="inline"` undid it. Nobody reaching for `link`
// wants a 32px box, so the variant no longer asks for a size to behave.
// It opts OUT of the touch growth for the same reason: a link runs inside a
// sentence, and a sentence whose link is 44px tall has a 44px line box, so
// the paragraph around it reflows on every phone. The text line is the
// target for a link, and prose is not a control row.
compoundVariants: [
{
variant: ["link"],
className:
// Stroke drops back to the regular-weight token for the same reason
// the box does: `link` is the one variant that sets `font-normal`, so
// the action stroke would make its glyph heavier than the word it sits
// in. At 14px text and a 14px box, plain 2 is already a 99% match.
"h-auto p-0 rounded-sm pointer-coarse:rounded-sm pointer-coarse:min-h-0 pointer-coarse:min-w-0 [&_svg]:[stroke-width:var(--stroke-icon)]",
},
// `bare` has no label of its own, so the icon stroke is the regular one
// (its child sets the type), at every size.
{
variant: ["bare"],
className: "[&_svg]:[stroke-width:var(--stroke-icon)]",
},
// `bare` has no box: it takes the child's size. The icon-only sizes keep
// their square, because that square IS the target (a drag grip).
{
variant: ["bare"],
size: ["default", "xs", "sm", "lg", "inline", "block"],
className: "h-auto p-0 pointer-coarse:min-h-0 pointer-coarse:min-w-0",
},
{
size: ["block"],
className: "active:scale-100",
},
],
defaultVariants: {
variant: "default",
size: "default",
},
}
)
type ButtonVariantProps = VariantProps<typeof buttonVariantsBase>
// MERGED, NOT JUST CONCATENATED. `cva` joins its variant strings and compound
// rules as plain text, so `link` at the default size came out as
// `h-8 px-4 ... h-auto p-0`. Tailwind emits `px-4` AFTER `p-0` (a longhand
// sorts after its shorthand), so the padding the link rule zeroes came back and
// a bare `<Link className={buttonVariants({ variant: "link" })}>` sat 16px short
// of the edge it was aligned to. `Button` never showed it because it runs the
// same string through `cn()`. The documented Server Component idiom skips that
// step, so the merge happens here, and both paths now produce the same classes.
function buttonVariants(props?: Parameters<typeof buttonVariantsBase>[0]) {
return cn(buttonVariantsBase(props))
}
// NO "use client" IN THIS FILE, ON PURPOSE..
//
// `button.tsx` is a client module (it uses Motion and `useReducedMotion`), and
// under React Server Components EVERY export of a client module becomes a client
// reference: it can be rendered, or passed as a prop, but never CALLED on the
// server. So the standard idiom for painting a link as a button
//
// <Link className={buttonVariants({ variant: "ghost" })} />
//
// failed the production build from any App Router page, which is a Server
// Component by default:
//
// Attempted to call buttonVariants() from the server but buttonVariants is on
// the client.
//
// Re-exporting it from `button.tsx` does NOT fix this, because the re-export is
// itself a client reference. The variants have to live in their own module with
// no directive, which both graphs can then import. Import from HERE in a Server
// Component; `button.tsx` re-exports it for the client callers that already do.
//
// This warning sits at the BOTTOM of the file, which looks odd and is
// deliberate. The shadcn CLI reprints every file it installs and loses the
// comments around the import block, so the same words written at the top of
// the file reached nobody they were written for, on every pull. Down here they
// survive. `verify:registry` fails the build if a comment leads this file.
export { buttonVariants, buttonGap, buttonIconSidePadding }
export type { ButtonVariantProps }