Components / ActionsStable

Button

Starts an action: saves, creates, sends or confirms. One primary button per view.

View as Markdown

Playground

Code

Button.tsx
'use client'
import { useLayoutEffect, useRef, useState, type ButtonHTMLAttributes, type MouseEvent, type ReactNode, type Ref } from 'react'

// Nacre Button. React plus Tailwind classes only; import nacre-theme.css (Resources, Tokens) once in your app.
// Motion: colour quick 160 out on hover, press scales to .97 (pointer only, motion-safe), spinner one turn per slow.
// Action swap: when the label changes (or swapKey does), the old icon and label blur out and the new ones blur in on
// top of each other (200 out, opacity, blur 4 px, scale .96), so the change reads as one morph. Loading to success:
// the label blurs away for the spinner, and the spinner shrinks into a check that draws in left to right (clip-path,
// base 240). A trailing icon leans 2 px on hover. Keyboard presses swap at once; reduced motion or an ancestor with
// [data-nacre-motion="off"]: no movement.

export type ButtonVariant = 'primary' | 'secondary' | 'ghost' | 'danger'
export type ButtonSize = 'sm' | 'md' | 'lg'
export type ButtonShape = 'pill' | 'round'

type ButtonBase = ButtonHTMLAttributes<HTMLButtonElement> & {
  variant?: ButtonVariant
  size?: ButtonSize
  loading?: boolean
  /** The action finished: a check replaces the spinner (or the label). Announce the result elsewhere too. */
  success?: boolean
  leading?: ReactNode
  trailing?: ReactNode
  /** Changing it plays the action swap. Default: the label, when it is plain text. */
  swapKey?: string
  ref?: Ref<HTMLButtonElement>
}

// shape="round" is a circle for one icon (a header action): the icon is the child and aria-label is required.
export type ButtonProps = ButtonBase & ({ shape?: 'pill' } | { shape: 'round'; 'aria-label': string })

const base =
  'group/button relative inline-flex shrink-0 cursor-pointer select-none items-center justify-center rounded-full font-ui font-[600] whitespace-nowrap ' +
  'transition-[color,background-color,border-color,scale] duration-(--nx-dur-quick) ease-out ' +
  'focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus ' +
  'motion-safe:active:not-focus-visible:scale-[.97] disabled:cursor-not-allowed aria-disabled:cursor-progress'

const variants: Record<ButtonVariant, string> = {
  primary: 'bg-action text-on-action enabled:hover:bg-action-hover disabled:bg-sunken disabled:text-fg-disabled disabled:shadow-[inset_0_0_0_1px_var(--nx-line-subtle)]',
  secondary: 'border border-line bg-secondary text-fg-strong enabled:hover:border-line-strong disabled:border-line-subtle disabled:text-fg-disabled',
  ghost: 'text-fg-strong enabled:hover:bg-line-subtle disabled:text-fg-disabled',
  danger: 'bg-error-strong text-on-action enabled:hover:bg-error disabled:bg-sunken disabled:text-fg-disabled disabled:shadow-[inset_0_0_0_1px_var(--nx-line-subtle)]',
}

// Round: 32, 40 and 48 px circles. A secondary round button is the white header action: hairline ring and shadow-1.
const roundSizes: Record<ButtonSize, string> = { sm: 'size-8', md: 'size-10', lg: 'size-12' }
const roundSecondary = 'border border-line-subtle bg-secondary text-fg-strong shadow-1 enabled:hover:border-line disabled:text-fg-disabled disabled:shadow-none'

const sizes: Record<ButtonSize, string> = {
  sm: 'h-8 px-3 text-label',
  md: 'h-10 px-4 text-label',
  lg: 'h-12 px-5 text-body-lg',
}

/** Reduced motion, or an ancestor that switched motion off, means no movement. */
function motionOk(el: Element): boolean {
  return !window.matchMedia('(prefers-reduced-motion: reduce)').matches && !el.closest('[data-nacre-motion="off"]')
}

/** A duration token in ms, read from CSS so a slowed-down parent slows this too. */
function tokenMs(el: Element, name: string, fallback: number): number {
  const v = getComputedStyle(el).getPropertyValue(name).trim()
  const n = parseFloat(v)
  if (!Number.isFinite(n)) return fallback
  return v.endsWith('ms') ? n : v.endsWith('s') ? n * 1000 : n
}

const BLURRED = { opacity: 0, filter: 'blur(4px)', transform: 'scale(.96)' }
const CLEAR = { opacity: 1, filter: 'blur(0px)', transform: 'none' }

export function Button({
  variant = 'primary',
  size = 'md',
  shape = 'pill',
  loading = false,
  success = false,
  leading,
  trailing,
  swapKey,
  type = 'button',
  className = '',
  onClick,
  children,
  ref,
  ...rest
}: ButtonProps) {
  const root = useRef<HTMLButtonElement>(null)
  const label = useRef<HTMLSpanElement>(null)
  const outgoing = useRef<HTMLSpanElement>(null)
  const busy = loading || success
  const round = shape === 'round'
  const content = (
    <>
      {leading && <span data-part="leading" aria-hidden="true" className="inline-flex size-4 shrink-0 items-center justify-center">{leading}</span>}
      {children}
      {trailing && (
        <span data-part="trailing" aria-hidden="true" className="inline-flex size-4 shrink-0 items-center justify-center transition-[translate] duration-(--nx-dur-quick) ease-out motion-safe:group-hover/button:group-enabled/button:translate-x-0.5">
          {trailing}
        </span>
      )}
    </>
  )
  const key = swapKey ?? (typeof children === 'string' || typeof children === 'number' ? String(children) : undefined)

  // Action swap: remember what was shown when the key changes; the leaving copy is drawn over the new one until it
  // has blurred out. A change mid-swap replaces the leaving copy (the newest old state is what the eye last saw).
  const [shown, setShown] = useState({ key, node: content })
  const [leaving, setLeaving] = useState<{ node: ReactNode; n: number } | null>(null)
  if (shown.key !== key) {
    setShown({ key, node: content })
    setLeaving({ node: shown.node, n: (leaving?.n ?? 0) + 1 })
  }

  useLayoutEffect(() => {
    const b = root.current
    const out = outgoing.current
    const inn = label.current
    if (!leaving || !b || !out || !inn) return
    const keys = document.activeElement === b && b.matches(':focus-visible')
    if (keys || !motionOk(b)) return setLeaving(null)
    const opts: KeyframeAnimationOptions = { duration: tokenMs(b, '--nx-dur-quick', 160) * 1.25, easing: 'cubic-bezier(.23, 1, .32, 1)' }
    out.animate([CLEAR, BLURRED], { ...opts, fill: 'forwards' }).finished.then(() => setLeaving((l) => (l?.n === leaving.n ? null : l)), () => {})
    inn.animate([BLURRED, CLEAR], opts)
  }, [leaving])

  // Loading keeps the variant's look (not the disabled look) and blocks a second click.
  const click = (e: MouseEvent<HTMLButtonElement>) => {
    if (busy) {
      e.preventDefault()
      return
    }
    onClick?.(e)
  }
  return (
    <button
      ref={(el) => {
        root.current = el
        if (typeof ref === 'function') ref(el)
        else if (ref) ref.current = el
      }}
      type={type}
      aria-busy={loading || undefined}
      aria-disabled={busy || undefined}
      onClick={click}
      data-part="root"
      className={`${base} ${round && variant === 'secondary' ? roundSecondary : variants[variant]} ${round ? roundSizes[size] : sizes[size]} ${className}`}
      {...rest}
    >
      {busy && (
        <span data-part="status" aria-hidden="true" className="absolute inset-0 grid place-items-center">
          <svg
            data-part="spinner"
            viewBox="0 0 16 16"
            fill="none"
            stroke="currentColor"
            strokeWidth="1.5"
            strokeLinecap="round"
            className={`col-start-1 row-start-1 size-4 transition-[opacity,scale,filter] duration-(--nx-dur-quick) ease-out motion-safe:animate-spin ${success ? 'scale-50 opacity-0 blur-[2px]' : ''}`}
          >
            <path d="M8 1.75a6.25 6.25 0 1 0 6.25 6.25" />
          </svg>
          <svg
            data-part="check"
            viewBox="0 0 16 16"
            fill="none"
            stroke="currentColor"
            strokeWidth="1.75"
            strokeLinecap="round"
            strokeLinejoin="round"
            className={`col-start-1 row-start-1 size-4 transition-[clip-path,opacity] delay-75 duration-(--nx-dur-base) ease-out ${success ? '[clip-path:inset(0)]' : '[clip-path:inset(0_100%_0_0)] opacity-0'}`}
          >
            <path d="M3.5 8.5l3 3 6-7" />
          </svg>
        </span>
      )}
      <span
        ref={label}
        data-part="label"
        className={`inline-flex items-center gap-2 transition-[opacity,filter,scale] duration-(--nx-dur-quick) ease-out ${busy ? 'scale-[.96] opacity-0 blur-[2px]' : ''}`}
      >
        {content}
      </span>
      {leaving && (
        <span ref={outgoing} aria-hidden="true" data-part="label-out" className="pointer-events-none absolute inset-0 flex overflow-hidden rounded-[inherit] items-center justify-center gap-2">
          {leaving.node}
        </span>
      )}
    </button>
  )
}

Usage

When to use

  • The main action of a form, dialog or page header: Create project, Save changes.
  • A second action next to the primary one, such as Cancel or Preview: the secondary variant.
  • A quiet action inside dense UI, such as a toolbar or a task row: the ghost variant.

Choose something else when

  • It takes the reader to another page: use a text link.
  • It switches between views of the same content: use Segmented control.
  • It turns a setting on or off: use Switch.

In the Nacre workspace

New project

The project sheet ends with Create project and Cancel. While the project saves, Create shows a spinner and keeps its width, so nothing in the sheet moves.

Delete a board

The confirm dialog uses the danger variant for Delete board, with Keep board as the secondary choice. Focus starts on Keep board.

Task row

Each row has a ghost Assign button that only takes a fill on hover, so a list of fifty tasks stays calm.

Do and don't

  • DoName the action with a verb and its object: Create project.

    Don'tUse labels that say nothing about the result, such as OK or Submit.

  • DoKeep one primary button per view and make the others secondary or ghost.

    Don'tPut two ink buttons side by side so the reader has to guess which one matters.

  • DoUse loading while the action runs, so the button keeps its width and ignores a second click.

    Don'tSwap the label for a longer waiting text that changes the width of the button.

  • DoSwap the label when the action changes its result, such as Copy link to Copied, and swap it back after a moment.

    Don'tSwap labels on hover or on a timer the person did not start.

Anatomy

  1. Container. A full pill. Its height comes from the size: 32, 40 or 48 px; padding 12, 16 or 20 px.
  2. Label. Geist 13/16 at weight 600 (16/24 at size lg), with optional 16 px icons 8 px away.

API

variantType 'primary' | 'secondary' | 'ghost' | 'danger'Default 'primary'Visual weight. Danger is only for actions that destroy something.
sizeType 'sm' | 'md' | 'lg'Default 'md'Height 32, 40 or 48 px.
shapeType 'pill' | 'round'Default 'pill'round is a circle for one icon, the header action: 32, 40 or 48 px by size, and as secondary it is white with a hairline ring and shadow 1. The icon is the child, and an aria-label is required.
loadingType booleanDefault falseShows a spinner, keeps the width and blocks clicks (aria-busy, aria-disabled) without the disabled look.
successType booleanDefault falseThe action finished: the spinner shrinks into a check that draws in. Keeps the name and the width and ignores clicks; announce the result elsewhere (a toast or status line).
swapKeyType stringDefault -Changing it plays the action swap. Defaults to the label when the label is plain text, so Copy link to Copied swaps on its own.
leadingType ReactNodeDefault -A 16 px icon before the label. Hidden from assistive tech.
trailingType ReactNodeDefault -A 16 px icon after the label. Hidden from assistive tech.
typeType 'button' | 'submit' | 'reset'Default 'button'Button by default, so it never submits a form by accident.
disabledType booleanDefault falseNot available right now. Explain why nearby; a disabled button cannot show a tooltip on focus.
...restType ButtonHTMLAttributesDefault -Any native button attribute, such as onClick, form or aria-label.

Motion

HoverProperty background-color, border-colorDuration quick 160Easing outKeyboard Focus shows the ring at once.
PressProperty scale to .97Duration quick 160Easing outKeyboard Enter and Space do not scale.
Loading spinnerProperty rotate, a loop, one turn per slowDuration slow 520Easing linearKeyboard Same. Stops with reduced motion.
Label to spinnerProperty opacity, blur 2 px, scale .96Duration quick 160Easing outKeyboard Same, the button is reporting work.
Spinner to checkProperty scale .5 and blur out; clip-path draws the checkDuration base 240Easing outKeyboard Same.
Action swapProperty opacity, blur 4 px, scale .96, old over newDuration quick 160Easing outKeyboard Enter or Space swaps at once.
Trailing icon on hoverProperty translate 2 pxDuration quick 160Easing outKeyboard None: focus does not move it.

Accessibility

Keyboard

Tab
Moves focus to the button.
Enter or Space
Runs the action.

ARIA and semantics

  • A native button element, so it is focusable and announced as a button without extra roles.
  • Loading sets aria-busy and aria-disabled: the button stays focusable and announced, but ignores clicks.
  • An icon-only button needs aria-label; the icons themselves are hidden from assistive tech.

Contrast

Primary labelon-action on actionLight 17.74:1Dark 17.30:1Needs 4.5:1
Primary label on hoveron-action on action-hoverLight 13.72:1Dark 19.01:1Needs 4.5:1
Secondary labelfg-strong on secondaryLight 19.01:1Dark 14.96:1Needs 4.5:1
Danger labelon-action on error-strongLight 6.00:1Dark 11.68:1Needs 4.5:1
Danger label on hoveron-action on errorLight 4.78:1Dark 6.35:1Needs 4.5:1
Focus ringfocus on pageLight 3.74:1Dark 13.14:1Needs 3:1