# Badge

Labels the state of something in one or two words, such as a task that is blocked or a project that is on track.

Status: Stable. Group: Feedback.

## When to use

- Task and project states in lists and boards: On track, Blocked, In review.
- Counts and short tags next to a heading or tab: 3 new, Beta.

## When not to use

- Someone clicks it to filter or to change the state. Use Segmented control instead.
- The message needs a sentence to explain it. Use Alert and toast instead.

## Scenarios

### Project health

Each project card on the dashboard carries one Badge: On track in success, At risk in warning, Blocked in error. The word says it; the colour repeats it.

### Unread messages

The Messages tab shows a small solid neutral Badge with the unread count, so it reads at a glance without adding another colour.

## Do and avoid

- Do: Name the state in one or two words: Blocked.
- Avoid: Write a sentence in a badge: This task cannot move until design signs off.
- Do: Keep the meaning in the word, with the tone as a second cue.
- Avoid: Rely on colour alone, such as a red dot with no text.

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `tone` | `'neutral' \| 'info' \| 'success' \| 'warning' \| 'error' \| 'feature'` | `'neutral'` | The state family: success for done or healthy, warning for at risk, error for blocked or failed, feature for new. |
| `variant` | `'soft' \| 'solid'` | `'soft'` | soft: strong text on the soft step. solid: on-action text on the strong step, for counts that must stand out. |
| `tint` | `'lime' \| 'pink' \| 'blue' \| 'violet'` |  | A pastel tint instead of a state tone: the tint fill with its own ink, for categories rather than states. Replaces tone and variant. |
| `size` | `'sm' \| 'md'` | `'md'` | Height 20 or 24 px. |
| `dot` | `boolean` | `false` | A 6 px dot before the label in the tone colour. Decorative, hidden from assistive tech. |
| `children` | `ReactNode` |  | The label: one or two words, or a number. |
| `...rest` | `HTMLAttributes<HTMLSpanElement>` |  | Any span attribute: id, title, or aria-label for a bare number such as 3 unread. |

## Anatomy

1. Pill (`data-part="root"`): Radius full (the same pill family as Chip), soft or strong state fill or a pastel tint, 8 px side padding at md, 24 px tall.
2. Dot (`data-part="dot"`): Optional 6 px circle in the tone colour, 6 px before the label.
3. Label (`data-part="label"`): Label 13/16 at weight 600 (caption 12/16 at sm), never wraps.

## Motion

| Interaction | Property | Duration | Easing | From the keyboard |
| --- | --- | --- | --- | --- |
| Tone change, such as In review to Done | background-color, color | quick | out | Same, colour only. |
| Label change | old label out over the new one: opacity, blur 4 px, scale .9 | quick | out | Same; a badge is never changed by its own key press. |
| Count change | translate 60 %: in from below when it went up, from above when it went down; blur and opacity | quick | out | Same. |

## Accessibility

| Keys | Action |
| --- | --- |
| None | A badge is not interactive. Put links and buttons next to it, not inside it. |

- Plain text in a span, read in reading order with what it labels.
- The dot is aria-hidden; the word carries the meaning.
- For a bare number, add context with aria-label, such as aria-label="3 unread messages".

## Code

### Badge.tsx

```tsx
'use client'
import { useLayoutEffect, useRef, useState, type HTMLAttributes, type ReactNode, type Ref } from 'react'

// Nacre Badge: the state of something in one or two words, or a count, as a round pill (same family as Chip); tint
// swaps the state tone for one of the four pastel tints. React plus Tailwind classes only; needs
// nacre-theme.css. Motion: a tone change crossfades its colours, quick 160 out. A label change (In review to Done) is
// one morph: the old label blurs out over the new one while the new one blurs in (opacity, blur 4 px, scale .9, quick
// 160 out). A count rolls: the new number comes in from below when it went up and from above when it went down, the
// old one leaves the other way. A change mid-swap takes over from what is shown. Reduced motion or
// [data-nacre-motion="off"]: the label changes at once. Not interactive.

export type BadgeTone = 'neutral' | 'info' | 'success' | 'warning' | 'error' | 'feature'
export type BadgeVariant = 'soft' | 'solid'
export type BadgeSize = 'sm' | 'md'
export type BadgeTint = 'lime' | 'pink' | 'blue' | 'violet'

export type BadgeProps = HTMLAttributes<HTMLSpanElement> & {
  tone?: BadgeTone
  variant?: BadgeVariant
  size?: BadgeSize
  /** A pastel tint instead of a state tone: the tint fill with its own ink. Replaces tone and variant. */
  tint?: BadgeTint
  dot?: boolean
  ref?: Ref<HTMLSpanElement>
}

// Soft: strong text on the soft step. Solid: on-action text on the strong step (white in light, ink in dark).
const tones: Record<BadgeVariant, Record<BadgeTone, string>> = {
  soft: {
    neutral: 'bg-neutral-soft text-neutral-strong',
    info: 'bg-info-soft text-info-strong',
    success: 'bg-success-soft text-success-strong',
    warning: 'bg-warning-soft text-warning-strong',
    error: 'bg-error-soft text-error-strong',
    feature: 'bg-feature-soft text-feature-strong',
  },
  solid: {
    neutral: 'bg-neutral-strong text-on-action',
    info: 'bg-info-strong text-on-action',
    success: 'bg-success-strong text-on-action',
    warning: 'bg-warning-strong text-on-action',
    error: 'bg-error-strong text-on-action',
    feature: 'bg-feature-strong text-on-action',
  },
}

const tints: Record<BadgeTint, string> = {
  lime: 'bg-tint-lime text-tint-lime-ink',
  pink: 'bg-tint-pink text-tint-pink-ink',
  blue: 'bg-tint-blue text-tint-blue-ink',
  violet: 'bg-tint-violet text-tint-violet-ink',
}

const dots: Record<BadgeTone, string> = {
  neutral: 'bg-neutral',
  info: 'bg-info',
  success: 'bg-success',
  warning: 'bg-warning',
  error: 'bg-error',
  feature: 'bg-feature',
}

const sizes: Record<BadgeSize, string> = { sm: 'h-6 gap-1 px-2.5 text-caption', md: 'h-7 gap-1.5 px-3 text-label' }

function motionOk(el: Element): boolean {
  return !window.matchMedia('(prefers-reduced-motion: reduce)').matches && !el.closest('[data-nacre-motion="off"]')
}

const textOf = (n: ReactNode) => (typeof n === 'string' || typeof n === 'number' ? String(n) : undefined)

export function Badge({ tone = 'neutral', variant = 'soft', size = 'md', tint, dot = false, className = '', children, ref, ...rest }: BadgeProps) {
  const label = useRef<HTMLSpanElement>(null)
  const old = useRef<HTMLSpanElement>(null)
  // Remember what was shown; when the text changes, the old copy is drawn over the new one until it has gone.
  const key = textOf(children)
  const [shown, setShown] = useState({ key, node: children as ReactNode })
  const [leaving, setLeaving] = useState<{ node: ReactNode; dir: number; n: number } | null>(null)
  if (shown.key !== key) {
    const a = Number(shown.key)
    const b = Number(key)
    const dir = shown.key !== undefined && key !== undefined && Number.isFinite(a) && Number.isFinite(b) ? Math.sign(b - a) : 0
    setShown({ key, node: children })
    setLeaving({ node: shown.node, dir, n: (leaving?.n ?? 0) + 1 })
  }
  useLayoutEffect(() => {
    const inn = label.current
    const out = old.current
    if (!leaving || !inn || !out) return
    if (!motionOk(inn)) return setLeaving(null)
    const y = leaving.dir * 60
    const opts = { duration: 160, easing: 'cubic-bezier(.23, 1, .32, 1)' }
    out.animate([{ opacity: 1, filter: 'blur(0px)', transform: 'none' }, { opacity: 0, filter: 'blur(4px)', transform: `translateY(${-y}%) scale(.9)` }], { ...opts, fill: 'forwards' })
      .finished.then(() => setLeaving((l) => (l?.n === leaving.n ? null : l)), () => {})
    inn.animate([{ opacity: 0, filter: 'blur(4px)', transform: `translateY(${y}%) scale(.9)` }, { opacity: 1, filter: 'blur(0px)', transform: 'none' }], opts)
  }, [leaving])
  return (
    <span
      ref={ref}
      data-part="root"
      className={`inline-flex shrink-0 items-center rounded-full font-[600] whitespace-nowrap transition-colors duration-(--nx-dur-quick) ease-out ${leaving ? 'overflow-hidden' : ''} ${sizes[size]} ${tint ? tints[tint] : tones[variant][tone]} ${className}`}
      {...rest}
    >
      {dot && <span data-part="dot" aria-hidden="true" className={`size-1.5 shrink-0 rounded-full ${tint || variant === 'solid' ? 'bg-current' : dots[tone]}`} />}
      {/* Old and new share one grid cell, so they line up while they cross. */}
      <span className="inline-grid">
        <span ref={label} className="col-start-1 row-start-1" data-part="label">{children}</span>
        {leaving && <span ref={old} aria-hidden="true" className="pointer-events-none col-start-1 row-start-1">{leaving.node}</span>}
      </span>
    </span>
  )
}
```

## HTML

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

```html
<span data-part="root" class="inline-flex shrink-0 items-center rounded-full font-[600] whitespace-nowrap transition-colors duration-(--nx-dur-quick) ease-out  h-7 gap-1.5 px-3 text-label bg-success-soft text-success-strong ">
  <span data-part="dot" aria-hidden="true" class="size-1.5 shrink-0 rounded-full bg-success"></span>
  <span class="inline-grid">
    <span class="col-start-1 row-start-1" data-part="label">On track</span>
  </span>
</span>
```

## Related

- [Tabs](https://enxm.me/services/design-systems/nacre/components/tabs)
- [Avatar](https://enxm.me/services/design-systems/nacre/components/avatar)
- [Alert and toast](https://enxm.me/services/design-systems/nacre/components/alert)
