Components / FeedbackStable

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.

View as Markdown

Playground

On track

Code

Badge.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>
  )
}

Usage

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.

Choose something else when

In the Nacre workspace

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 don't

  • DoName the state in one or two words: Blocked.

    Don'tWrite a sentence in a badge: This task cannot move until design signs off.

  • DoKeep the meaning in the word, with the tone as a second cue.

    Don'tRely on colour alone, such as a red dot with no text.

Anatomy

On track
  1. Pill. 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. Optional 6 px circle in the tone colour, 6 px before the label.
  3. Label. Label 13/16 at weight 600 (caption 12/16 at sm), never wraps.

API

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

Motion

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

Accessibility

Keyboard

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

ARIA and semantics

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

Contrast

Soft neutral labelneutral-strong on neutral-softLight 12.38:1Dark 10.47:1Needs 4.5:1
Soft info labelinfo-strong on info-softLight 6.81:1Dark 8.02:1Needs 4.5:1
Soft success labelsuccess-strong on success-softLight 5.58:1Dark 9.70:1Needs 4.5:1
Soft warning labelwarning-strong on warning-softLight 5.14:1Dark 9.53:1Needs 4.5:1
Soft error labelerror-strong on error-softLight 4.74:1Dark 8.72:1Needs 4.5:1
Soft feature labelfeature-strong on feature-softLight 5.14:1Dark 8.40:1Needs 4.5:1
Solid neutral labelon-action on neutral-strongLight 14.89:1Dark 15.10:1Needs 4.5:1
Solid info labelon-action on info-strongLight 8.72:1Dark 10.89:1Needs 4.5:1
Solid success labelon-action on success-strongLight 6.56:1Dark 14.53:1Needs 4.5:1
Solid warning labelon-action on warning-strongLight 6.33:1Dark 13.26:1Needs 4.5:1
Solid error labelon-action on error-strongLight 6.00:1Dark 11.68:1Needs 4.5:1
Solid feature labelon-action on feature-strongLight 6.83:1Dark 11.23:1Needs 4.5:1