← All proposals

Badge

An extension of the PDS Badge: one new prop, as ('span' | 'kbd', default 'span').

Extends a PDS componentOpen in Storybook

proposals/Badge/Badge.tsx102 lines · View on GitHub
import { ComponentPropsWithoutRef, ReactNode } from 'react';

import {
	BadgeColor,
	BadgeSize,
	Icon,
	IconSize,
	PDSIcon,
} from '@pantheon-systems/pds-toolkit-react';

import { mergeClasses } from '../_base/Button/utils';

import './badge.css';

/**
 * Maps each badge size to the closest-fitting Icon size, so a badge's icon
 * never has to be requested directly by consumers.
 */
const iconSizes: Record<BadgeSize, IconSize> = {
	xs: 'xs',
	s: 'xs',
	m: 'm',
};

/**
 * Badge component props
 */
export interface BadgeProps extends ComponentPropsWithoutRef<'span'> {
	/**
	 * The element to render. `kbd` is for a keyboard key (for example the Esc
	 * hint on a search field), so the badge itself is the key.
	 */
	as?: 'kbd' | 'span';
	/**
	 * Additional class names
	 */
	className?: string;
	/**
	 * Badge color
	 */
	color: BadgeColor;
	/**
	 * Optional leading icon. Sized to fit the badge's `size` and always
	 * colored to match the badge's foreground color.
	 */
	iconName?: PDSIcon;
	/**
	 * Let a long label wrap onto multiple lines within its container instead
	 * of staying on one line and overflowing.
	 */
	isWrappable?: boolean;
	/**
	 * Badge text or content.
	 */
	label: ReactNode;
	/**
	 * Badge size
	 */
	size?: BadgeSize;
}

/**
 * Badge UI component
 */
export const Badge = ({
	as: Element = 'span',
	className,
	color = 'brand-muted',
	iconName,
	isWrappable = false,
	label,
	size = 's',
	...props
}: BadgeProps) => {
	const baseClass = 'pds-badge';
	const colorClass = `${baseClass}--${color}`;
	const sizeClass = `${baseClass}--${size}`;
	const wrappableClass = isWrappable ? `${baseClass}--wrappable` : null;

	return (
		<Element
			className={mergeClasses([
				baseClass,
				colorClass,
				sizeClass,
				wrappableClass,
				className ?? '',
			])}
			{...props}
		>
			{iconName && (
				<Icon
					className={`${baseClass}__icon`}
					iconName={iconName}
					size={iconSizes[size]}
				/>
			)}
			<span className={`${baseClass}__label`}>{label}</span>
		</Element>
	);
};