Compact status labels with soft color, precise icons, subtle surface detailing, and custom content.
Default
Variants
soft
outline
solid
Sizes
Icons
Composition
Live
Purpose
A compact label helps people scan a status or category such as “In progress” or “Shipped.”
Parts & Composition
Badge renders one root element (a span by default) with a label and an optional icon. Use iconPosition to place the icon at the start or end. The render prop can replace the root with an element such as a link or button; native props, refs, event handlers, and classes are merged onto that element. Preset icons are decorative, so the status text remains the accessible label.
API & Props
| Prop | Purpose |
|---|---|
status | neutral, info, progress, warning, success, or error; supplies the default label, icon, and semantic color. Defaults to neutral. |
children | Replaces the preset label. |
icon | Replaces the preset icon; pass null or false to omit the icon. |
iconPosition | Places the icon at start or end; defaults to start. |
variant | soft, outline, or solid; defaults to soft. |
size | xs, sm, md, or lg; defaults to md. |
animated | Spins the preset icon, typically for progress. A custom icon is not animated. |
render | Replaces the root element, for example with <a href="…" />. |
className | Adds or overrides root styling. |
| Native span props | Standard span attributes and event handlers are forwarded to the root. |
The root exposes data-slot="badge", data-status, data-variant, and data-size. Its inner label and icon expose data-slot="badge-label" and data-slot="badge-icon".
Theming, Layout & Responsiveness
Status colors use the library’s status tokens when provided, with the established status palette as a fallback. --badge-color, --badge-fill, and --badge-ink can be set on a Badge to adjust a custom tone. soft applies a low contrast status tint, outline uses a tinted border, and solid fills with the status color and paired foreground ink.
Badges use compact minimum heights and content-driven width. Labels can wrap when the available space is narrow. Sizes use shared control text and compact-height tokens:
| Size | Min height | Type | Icon |
|---|---|---|---|
xs | 20px | xs | 10px |
sm | 24px | xs | 12px |
md | 28px | sm | 14px |
lg | 32px | base | 16px |
Motion & Accessibility
When the displayed label changes, ValueTransition animates text updates and respects reduced motion. animated rotates only the preset icon and stops under reduced motion. Interactive roots passed through render receive shared focus, hover, and pressed-state styling; static badges remain non-interactive. Use role="status" and aria-live="polite" only when an asynchronously changing status should be announced. The decorative icon is hidden from assistive technology, so keep status meaning in the label.
Guidance for Coding Agents
When adding a compact status or category label, read this Info reference and import Badge from @/components/library/badge. Choose an existing semantic status, use children for application-specific text, and select soft, outline, or solid only when a different surface treatment is needed. Use the shared xs, sm, md, and lg size scale (md by default); use icon and iconPosition for a custom decorative icon. Use render for a navigational or actionable root and preserve its native semantics. Avoid one-off status keys or colors when the existing status tokens express the meaning. Reserve aria-live for updates people need announced, and keep the label meaningful without its icon. This library provides Badge as a styled wrapper rather than an SDK Badge part; for inherited UI SDK render behavior, consult the upstream Rendering and Parts and Composition references before extending it. Start with the closest Preview example on this page, then check those SDK references for advanced rendering behavior.
CLI installation
bunx --bun shadcn@latest add https://ui.devvarena.com/api/r/badgeimport { mergeProps, type RenderProp, renderElement } from '@ui-sdk/react/primitive';
import { cva, type VariantProps } from 'class-variance-authority';
import { Bell, CircleCheck, CircleDashed, CircleX, TriangleAlert } from 'lucide-react';
import type { ComponentProps, ReactNode } from 'react';
import { ValueTransition } from '@/hooks/use-value-transition';
import { compactControlMinHeights, controlTextSizes } from '@/lib/devvarena-ui';
import { cn } from '@/lib/utils';
/** Label (`--badge-color`), fill, and ink align with Alert tone tokens. */
const statuses = {
neutral: {
label: 'Status',
className:
'[--badge-color:var(--muted-foreground)] [--badge-fill:var(--muted-foreground)] [--badge-ink:white]',
},
info: {
label: 'Info',
icon: Bell,
className:
'[--badge-color:var(--status-info,var(--color-blue-600))] dark:[--badge-color:var(--status-info,var(--color-blue-400))] [--badge-fill:var(--status-info,var(--color-blue-500))] [--badge-ink:white]',
},
progress: {
label: 'In progress',
icon: CircleDashed,
className:
'[--badge-color:var(--status-progress,var(--color-violet-600))] dark:[--badge-color:var(--status-progress,var(--color-violet-400))] [--badge-fill:var(--status-progress,var(--color-violet-500))] [--badge-ink:white]',
},
warning: {
label: 'Warning',
icon: TriangleAlert,
className:
'[--badge-color:var(--status-warning,var(--status-pending,var(--color-yellow-800)))] dark:[--badge-color:var(--status-warning,var(--status-pending,var(--color-yellow-300)))] [--badge-fill:var(--status-warning,var(--status-pending,var(--color-yellow-500)))] [--badge-ink:white]',
},
success: {
label: 'Success',
icon: CircleCheck,
className:
'[--badge-color:var(--status-success,var(--color-green-700))] dark:[--badge-color:var(--status-success,var(--color-green-400))] [--badge-fill:var(--status-success,var(--color-green-500))] [--badge-ink:white]',
},
error: {
label: 'Error',
icon: CircleX,
className:
'[--badge-color:var(--status-error,var(--color-red-600))] dark:[--badge-color:var(--status-error,var(--color-red-400))] [--badge-fill:var(--status-error,var(--color-red-500))] [--badge-ink:white]',
},
} as const;
const badgeShadow =
'shadow-[inset_0_1px_0_rgb(255_255_255/0.45),0_1px_1.5px_rgb(0_0_0/0.14)] dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.22),0_1px_2px_rgb(0_0_0/0.4)]';
const badgeVariants = cva(
'group/badge inline-flex w-fit max-w-full min-w-0 items-center justify-center rounded-sm border border-transparent font-medium tracking-normal whitespace-normal select-none transition-[background-color,border-color,box-shadow,filter,translate] duration-150 ease-out [a&,button&]:cursor-pointer [a&,button&]:touch-manipulation motion-safe:[a&,button&]:active:translate-y-px motion-reduce:transition-none',
{
variants: {
status: {
neutral: statuses.neutral.className,
info: statuses.info.className,
progress: statuses.progress.className,
warning: statuses.warning.className,
success: statuses.success.className,
error: statuses.error.className,
},
variant: {
soft: '[--badge-tone:var(--badge-fill,var(--badge-color))] bg-[color-mix(in_oklab,var(--badge-tone)_10%,transparent)] dark:bg-[color-mix(in_oklab,var(--badge-tone)_16%,transparent)] text-[color:var(--badge-color)]',
outline:
'[--badge-tone:var(--badge-fill,var(--badge-color))] border-[color-mix(in_oklab,var(--badge-tone)_32%,var(--border))] bg-transparent text-[color:var(--badge-color)]',
solid: `[--badge-tone:var(--badge-fill,var(--badge-color))] border-[color-mix(in_oklab,var(--badge-tone),black_12%)] bg-[var(--badge-tone)] text-[color:var(--badge-ink,white)] ${badgeShadow}`,
},
size: {
xs: `${compactControlMinHeights.xs} ${controlTextSizes.xs} gap-1 px-1.5 leading-none [&_[data-slot=badge-icon]]:size-2.5`,
sm: `${compactControlMinHeights.sm} ${controlTextSizes.sm} gap-1 px-2 py-0.5 leading-none [&_[data-slot=badge-icon]]:size-3`,
md: `${compactControlMinHeights.md} text-xs gap-1.5 px-2 py-0.5 leading-none [&_[data-slot=badge-icon]]:size-3.5`,
lg: `${compactControlMinHeights.lg} ${controlTextSizes.lg} gap-2 px-3 py-1 leading-snug [&_[data-slot=badge-icon]]:size-4`,
},
},
compoundVariants: [
{
status: 'neutral',
variant: 'solid',
className: 'border-border bg-muted text-muted-foreground',
},
],
defaultVariants: { status: 'neutral', variant: 'soft', size: 'md' },
},
);
type BadgeStatus = keyof typeof statuses;
type BadgeSize = NonNullable<VariantProps<typeof badgeVariants>['size']>;
type BadgeVariant = NonNullable<VariantProps<typeof badgeVariants>['variant']>;
type BadgeState = { slot: 'badge'; status: BadgeStatus; variant: BadgeVariant; size: BadgeSize };
type BadgeProps = ComponentProps<'span'> &
Omit<VariantProps<typeof badgeVariants>, 'status' | 'size' | 'variant'> & {
/** Semantic status preset for its label, icon, and theme color. */
status?: BadgeStatus;
/** Override the preset icon. Pass null or false to omit it. */
icon?: ReactNode;
/** Place the icon before or after the label. */
iconPosition?: 'start' | 'end';
/** Rotate the preset icon, typically for the progress status. */
animated?: boolean;
size?: BadgeSize;
variant?: BadgeVariant;
/** Render the badge as another element, such as an anchor or button. */
render?: RenderProp<BadgeState>;
};
function Badge({
status = 'neutral',
variant = 'soft',
size = 'md',
icon,
iconPosition = 'start',
animated = false,
children,
className,
render,
...props
}: BadgeProps) {
const preset = statuses[status];
const DefaultIcon = 'icon' in preset ? preset.icon : null;
const content = icon !== undefined ? icon : DefaultIcon ? <DefaultIcon /> : null;
const label = children ?? preset.label;
const displayedLabel =
typeof label === 'string' || typeof label === 'number' ? (
<ValueTransition
value={label}
className="min-w-0 max-w-full flex-wrap [overflow-wrap:anywhere]"
/>
) : (
label
);
const indicator =
content === null || content === false ? null : (
<span
aria-hidden="true"
data-slot="badge-icon"
className={cn(
'inline-flex shrink-0 items-center justify-center [&>svg]:size-full [&>svg]:stroke-[1.75]',
animated &&
icon === undefined &&
DefaultIcon &&
'motion-safe:animate-spin motion-safe:[animation-duration:1.6s]',
)}
>
{content}
</span>
);
const state: BadgeState = { slot: 'badge', status, variant, size };
return renderElement(
'span',
mergeProps(props, {
'data-slot': 'badge',
'data-status': status,
'data-variant': variant,
'data-size': size,
className: cn(badgeVariants({ status, variant, size }), className),
children: (
<>
{iconPosition === 'start' && indicator}
<span data-slot="badge-label" className="min-w-0 [overflow-wrap:anywhere]">
{displayedLabel}
</span>
{iconPosition === 'end' && indicator}
</>
),
}),
render,
state,
);
}
export { Badge, type BadgeProps, type BadgeSize, type BadgeStatus, badgeVariants };
'use client';
import { type ComponentProps, useState } from 'react';
import { cn } from '@/lib/utils';
export type UseValueTransitionOptions = {
/** Whether characters animate when the value changes. Defaults to `true`. */
enabled?: boolean;
/** Roll direction. `auto` rolls up when a number grows (or for text), down when it shrinks. */
direction?: 'auto' | 'up' | 'down';
/** Delay in ms between consecutive changed characters. Defaults to `28`. */
stagger?: number;
/**
* Animation granularity:
* - `auto` (default): per-character for numeric values, whole-string for text.
* - `char`: always animate per-character.
* - `whole`: always animate the entire value as one unit.
*/
mode?: 'auto' | 'char' | 'whole';
};
export type TransitionChar = {
key: string;
char: string;
/** The character being replaced. Only set when this character should roll. */
prev?: string;
/** Transition delay in ms. */
delay: number;
};
const MAX_DELAY = 140;
const hasDigit = (text: string) => /\d/.test(text);
const isNumeric = (text: string) => hasDigit(text) && !/[a-zA-Z]/.test(text);
const toNumber = (text: string) => Number.parseFloat(text.replace(/[^\d.-]/g, ''));
/**
* Diffs `value` against its previous value and returns per-character data, so
* only the characters that actually changed roll, one after another.
*
* - Numbers align from the right (the ones digit stays the ones digit),
* text aligns from the left.
* - Pure derivation from state, with no effects or DOM reads, so it works for
* any value: numbers, formatted numbers, labels, statuses.
*/
export function useValueTransition(
value: string | number | null | undefined,
{
enabled = true,
direction = 'auto',
stagger = 28,
mode = 'auto',
}: UseValueTransitionOptions = {},
) {
const text = value == null ? '' : String(value);
const [state, setState] = useState({ text, prev: text });
if (state.text !== text) setState({ text, prev: state.text });
const numeric = isNumeric(state.text);
const perChar = mode === 'char' || (mode === 'auto' && numeric);
const dir: 1 | -1 =
direction === 'up'
? 1
: direction === 'down'
? -1
: numeric && hasDigit(state.prev) && toNumber(state.text) < toNumber(state.prev)
? -1
: 1;
if (!perChar) {
const changed = enabled && state.prev !== state.text;
const chars: TransitionChar[] = state.text
? [
{
key: `whole-${state.text}`,
char: state.text,
prev: changed ? state.prev : undefined,
delay: 0,
},
]
: [];
return { text: state.text, chars, dir };
}
const next = [...state.text];
const old = [...state.prev];
const offset = numeric ? old.length - next.length : 0;
const fromEmpty = state.prev === '' && state.text !== '';
// Stagger starts at the least significant end: ones digit first for numbers.
let rank = 0;
const chars: TransitionChar[] = new Array(next.length);
for (let step = 0; step < next.length; step++) {
const i = numeric ? next.length - 1 - step : step;
const char = next[i];
const prevChar = old[i + offset];
const shouldRoll = enabled && (fromEmpty || (prevChar !== undefined && prevChar !== char));
chars[i] = {
// Keyed by position + char: a changed character remounts (replaying the
// animation, even on rapid changes) while untouched ones stay mounted.
key: `${numeric ? next.length - i : i}-${char}`,
char,
prev: shouldRoll ? (prevChar ?? '') : undefined,
delay: shouldRoll ? Math.min(rank++ * stagger, MAX_DELAY) : 0,
};
}
return { text: state.text, chars, dir };
}
const motion =
'transition-[translate,opacity,filter] duration-300 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none';
export type ValueTransitionProps = Omit<ComponentProps<'span'>, 'children'> &
UseValueTransitionOptions & {
value: string | number | null | undefined;
/** Whether to apply a subtle blur during the transition. Defaults to `true`. */
blur?: boolean;
};
/**
* Drop-in display for any value: `<ValueTransition value={count} />`.
* Inherits font, size and color from its parent.
*/
export function ValueTransition({
value,
enabled,
direction,
stagger,
mode,
blur = true,
className,
...props
}: ValueTransitionProps) {
const { text, chars, dir } = useValueTransition(value, { enabled, direction, stagger, mode });
return (
<span
{...props}
className={cn(
'inline-flex overflow-hidden tabular-nums [mask-image:linear-gradient(to_bottom,transparent,#000_14%,#000_88%,transparent)]',
className,
)}
>
<span className="sr-only"> {text} </span>
<span aria-hidden="true" className="inline-flex">
{chars.map(({ key, char, prev, delay }) => (
<span
key={key}
className={cn(
'relative inline-block whitespace-pre leading-normal',
dir > 0 ? '[--d:1]' : '[--d:-1]',
)}
>
{prev === undefined ? (
char
) : (
<>
<span
style={{ transitionDelay: `${delay}ms` }}
className={cn(
'inline-block starting:translate-y-[calc(var(--d)*100%)] starting:opacity-0',
blur && 'starting:blur-[2px]',
motion,
)}
>
{char}
</span>
<span
aria-hidden="true"
style={{ transitionDelay: `${delay}ms` }}
className={cn(
'absolute inset-0 translate-y-[calc(var(--d)*-100%)] opacity-0 starting:translate-y-0 starting:opacity-100 motion-reduce:hidden',
blur && 'blur-[2px] starting:blur-none',
motion,
)}
>
{prev}
</span>
</>
)}
</span>
))}
</span>
</span>
);
}
import { cn } from '@/lib/utils';
type ClassValue = string | false | null | undefined;
type PartClassValue<State> = ClassValue | ((state: State) => ClassValue);
/** Composes static class names and UI-SDK state class functions into a single `className` prop. */
export function partClass<State>(...parts: PartClassValue<State>[]) {
if (parts.some((part) => typeof part === 'function')) {
return (state: State) =>
cn(...parts.map((part) => (typeof part === 'function' ? part(state) : part)));
}
return cn(...(parts as ClassValue[]));
}
export const surfacePadding = 'p-1 [--surface-padding:1.5rem] [--concentric-inset:0.25rem]';
export const surfaceRegionInset = 'p-[calc(var(--surface-padding,1rem)-0.5rem)]';
export const surfaceHeaderRadius = 'rounded-t-[max(0px,calc(var(--radius-lg,0.5rem)-0.25rem))]';
export const surfaceFooterRadius = 'rounded-b-[max(0px,calc(var(--radius-lg,0.5rem)-0.25rem))]';
/** Concentric inner radius (`outer - inset`); set `[--concentric-inset:0.125rem]` on `p-0.5` rails (defaults to `0.25rem` for `p-1`). */
export const concentricRadius =
'rounded-[max(0px,calc(var(--radius-lg,0.5rem)-var(--concentric-inset,0.25rem)))]';
export const surfaceBodyPadding =
'py-[max(0px,calc(var(--surface-padding,1rem)-1rem))] has-[>[data-slot=list]:not([data-variant=plain])]:p-0 has-[>[data-slot=list-items-container]]:p-0';
export type StandardControlSize = 'xs' | 'sm' | 'md' | 'lg';
/** Standard control heights (`28px / 32px / 40px / 48px`) for buttons, inputs, selects, tabs, and sliders. */
export const controlHeights = {
xs: 'h-7',
sm: 'h-8',
md: 'h-10',
lg: 'h-12',
} as const satisfies Record<StandardControlSize, string>;
/** Standard minimum control heights (`28px / 32px / 40px / 48px`) for expandable controls and menu items. */
export const controlMinHeights = {
xs: 'min-h-7',
sm: 'min-h-8',
md: 'min-h-10',
lg: 'min-h-12',
} as const satisfies Record<StandardControlSize, string>;
/** Standard control text sizes (`xs / xs / sm / base`) paired with `StandardControlSize`. */
export const controlTextSizes = {
xs: 'text-xs',
sm: 'text-xs',
md: 'text-sm',
lg: 'text-base',
} as const satisfies Record<StandardControlSize, string>;
/** Compact control heights (`1.25rem / 1.3rem / 1.625rem / 1.75rem`), one step smaller than standard, for switches and compact controls. */
export const compactControlHeights = {
xs: 'h-[1.3rem]',
sm: 'h-[1.4rem]',
md: 'h-[1.5rem]',
lg: 'h-[1.6rem]',
} as const satisfies Record<StandardControlSize, string>;
/** Compact minimum control heights (`1rem / 1.25rem / 1.5rem / 1.75rem`) for badges and tooltips. */
export const compactControlMinHeights = {
xs: 'min-h-[1.3rem]',
sm: 'min-h-[1.4rem]',
md: 'min-h-[1.5rem]',
lg: 'min-h-[1.6rem]',
} as const satisfies Record<StandardControlSize, string>;
/** Universal keyboard focus + invalid ring/border styles shared across controls. */
export const focusRing =
'touch-manipulation outline-none focus-visible:border-ring/30 transition-ring focus-visible:ring-3 focus-visible:ring-ring/15 focus-visible:brightness-[0.97] dark:focus-visible:brightness-[1.15] has-[:focus-visible]:border-ring/30 has-[:focus-visible]:ring-3 has-[:focus-visible]:ring-ring/15 has-[:focus-visible]:brightness-[0.97] dark:has-[:focus-visible]:brightness-[1.15] data-active:border-ring/30 data-active:ring-3 data-active:ring-ring/15 data-active:brightness-[0.97] dark:data-active:brightness-[1.15] data-open:border-ring/30 data-open:ring-3 data-open:ring-ring/15 data-open:brightness-[0.97] dark:data-open:brightness-[1.15] data-disabled:cursor-not-allowed data-disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/25 data-invalid:border-destructive data-invalid:ring-3 data-invalid:ring-destructive/25 has-[[data-invalid]]:border-destructive has-[[data-invalid]]:ring-3 has-[[data-invalid]]:ring-destructive/25 group-aria-invalid/control:border-destructive group-aria-invalid/control:ring-3 group-aria-invalid/control:ring-destructive/25 group-data-invalid/control:border-destructive group-data-invalid/control:ring-3 group-data-invalid/control:ring-destructive/25 group-has-[input[aria-invalid=true]]/control:border-destructive group-has-[input[aria-invalid=true]]/control:ring-3 group-has-[input[aria-invalid=true]]/control:ring-destructive/25 hover:brightness-[0.97] dark:hover:brightness-[1.15]';
/** Shared sliding highlight indicator base (pointer-safe, concentric inner radius inside rounded-lg containers, 200ms transition). */
export const slidingHighlight =
'pointer-events-none -z-10 rounded-[max(0px,calc(var(--radius-lg,0.5rem)-var(--concentric-inset,0.25rem)))] bg-primary/10 [clip-path:inset(0px_round_max(0px,calc(var(--radius-lg,0.5rem)-var(--concentric-inset,0.25rem))))] transition-[transform,width,height,opacity] duration-200 ease-out motion-reduce:transition-none';
export const textFieldSurfaces = {
filled: 'border-input bg-card text-card-foreground',
outline: 'border-input bg-transparent text-foreground dark:bg-transparent',
ghost: 'border-transparent bg-muted text-foreground shadow-none',
underline:
'rounded-none border-0 border-b-2 border-input bg-transparent px-0 text-foreground shadow-none focus-visible:border-ring focus-visible:ring-0 aria-invalid:ring-0 data-invalid:ring-0 dark:bg-transparent',
} as const;
export const textFieldUnderlineMotion =
'border-transparent! bg-origin-border bg-bottom bg-no-repeat [--underline-color:var(--primary)] [background-image:linear-gradient(var(--underline-color),var(--underline-color)),linear-gradient(var(--input),var(--input))] [background-size:0%_2px,100%_2px] focus:[background-size:100%_2px,100%_2px] aria-invalid:[--underline-color:var(--destructive)] data-invalid:[--underline-color:var(--destructive)] transition-[border-color,background-color,box-shadow,filter,background-size] duration-200 motion-reduce:transition-none';
/** Generic balanced icon & floating-label layout tokens shared across all text-field sizes. */
export const textFieldLayout = {
icon: 'size-4',
iconStart: 'start-3',
iconEnd: 'end-3',
padStart: 'ps-9',
padEnd: 'pe-9',
underlinePadStart: 'ps-7',
underlinePadEnd: 'pe-7',
floatingStart: 'start-2.5',
floatingWithIcon: 'start-8',
floatingUnderlineIcon: 'start-6',
} as const;
export const textFieldLabelSegmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
/** Clamps per-grapheme wave delay (ms) so total staggering stays within 300ms. */
export function clampWaveDelay(waveDelay: number, count: number): number {
return Math.max(
0,
Math.min(Number.isFinite(waveDelay) ? waveDelay : 24, 80, 300 / Math.max(1, count - 1)),
);
}
/** Shared scale/color transition for floating labels inside a `group/field` wrapper. */
export const textFieldLabelMotion =
'inline-block origin-left backdrop-blur-xs transition-[scale,color] duration-200 ease-out group-has-[input:focus]/field:scale-85 group-has-[input:not(:placeholder-shown)]/field:scale-85 rtl:origin-right motion-reduce:transition-none';
/** Resolves start/end padding for a text field when a leading or trailing icon is present. */
export function getTextFieldIconPadding(iconPosition: 'start' | 'end', underline: boolean): string {
if (iconPosition === 'start') {
return underline ? textFieldLayout.underlinePadStart : textFieldLayout.padStart;
}
return underline ? textFieldLayout.underlinePadEnd : textFieldLayout.padEnd;
}
/** Shared per-grapheme ripple transition for wave labels inside a `group/field` wrapper. */
export const textFieldWaveMotion =
'inline-block origin-left backdrop-blur-xs transition-[translate,scale,color] duration-200 ease-out group-has-[input:focus]/field:-translate-y-5 group-has-[input:focus]/field:scale-85 group-has-[input:focus]/field:text-primary group-has-[input:not(:placeholder-shown)]/field:-translate-y-5 group-has-[input:not(:placeholder-shown)]/field:scale-85 group-has-[input[aria-invalid=true]]/field:text-destructive rtl:origin-right motion-reduce:transition-none';