# Button

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

Status: Stable. Group: Actions.

## 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.

## When not to use

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

## Scenarios

### 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 avoid

- Do: Name the action with a verb and its object: Create project.
- Avoid: Use labels that say nothing about the result, such as OK or Submit.
- Do: Keep one primary button per view and make the others secondary or ghost.
- Avoid: Put two ink buttons side by side so the reader has to guess which one matters.
- Do: Use loading while the action runs, so the button keeps its width and ignores a second click.
- Avoid: Swap the label for a longer waiting text that changes the width of the button.
- Do: Swap the label when the action changes its result, such as Copy link to Copied, and swap it back after a moment.
- Avoid: Swap labels on hover or on a timer the person did not start.

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `variant` | `'primary' \| 'secondary' \| 'ghost' \| 'danger'` | `'primary'` | Visual weight. Danger is only for actions that destroy something. |
| `size` | `'sm' \| 'md' \| 'lg'` | `'md'` | Height 32, 40 or 48 px. |
| `shape` | `'pill' \| 'round'` | `'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. |
| `loading` | `boolean` | `false` | Shows a spinner, keeps the width and blocks clicks (aria-busy, aria-disabled) without the disabled look. |
| `success` | `boolean` | `false` | The 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). |
| `swapKey` | `string` |  | 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. |
| `leading` | `ReactNode` |  | A 16 px icon before the label. Hidden from assistive tech. |
| `trailing` | `ReactNode` |  | A 16 px icon after the label. Hidden from assistive tech. |
| `type` | `'button' \| 'submit' \| 'reset'` | `'button'` | Button by default, so it never submits a form by accident. |
| `disabled` | `boolean` | `false` | Not available right now. Explain why nearby; a disabled button cannot show a tooltip on focus. |
| `...rest` | `ButtonHTMLAttributes` |  | Any native button attribute, such as onClick, form or aria-label. |

## Anatomy

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

## Motion

| Interaction | Property | Duration | Easing | From the keyboard |
| --- | --- | --- | --- | --- |
| Hover | background-color, border-color | quick | out | Focus shows the ring at once. |
| Press | scale to .97 | quick | out | Enter and Space do not scale. |
| Loading spinner | rotate, a loop, one turn per slow | slow | linear | Same. Stops with reduced motion. |
| Label to spinner | opacity, blur 2 px, scale .96 | quick | out | Same, the button is reporting work. |
| Spinner to check | scale .5 and blur out; clip-path draws the check | base | out | Same. |
| Action swap | opacity, blur 4 px, scale .96, old over new | quick | out | Enter or Space swaps at once. |
| Trailing icon on hover | translate 2 px | quick | out | None: focus does not move it. |

## Accessibility

| Keys | Action |
| --- | --- |
| Tab | Moves focus to the button. |
| Enter or Space | Runs the action. |

- 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.

## Code

### Button.tsx

```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>
  )
}
```

## HTML

The default example as plain HTML, for any stack. Needs nacre-theme.css.

```html
<button type="button" data-part="root" class="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 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)] h-10 px-4 text-label ">
  <span data-part="label" class="inline-flex items-center gap-2 transition-[opacity,filter,scale] duration-(--nx-dur-quick) ease-out ">Create project</span>
</button>
```

## Related

- [Switch](https://enxm.me/services/design-systems/nacre/components/switch)
- [Segmented control](https://enxm.me/services/design-systems/nacre/components/segmented-control)
- [Tabs](https://enxm.me/services/design-systems/nacre/components/tabs)
