Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion src/Badge.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@ import React, { memo, forwardRef, type ReactNode, type CSSProperties } from "rea
import { symToStr } from "tsafe/symToStr";
import { assert } from "tsafe/assert";
import type { Equals } from "tsafe";
import type {
FrClassName,
FrIconClassName,
RiIconClassName
} from "./fr/generatedFromCss/classNames";
import { fr } from "./fr";
import { cx } from "./tools/cx";
import type { AlertProps } from "./Alert";
Expand All @@ -14,11 +19,21 @@ export type BadgeProps = {
severity?: AlertProps.Severity | "new";
small?: boolean;
noIcon?: boolean;
iconId?: FrIconClassName | RiIconClassName;
accentColor?: BadgeProps.AccentColor;
/** Default: "p" */
as?: "p" | "span";
children: NonNullable<ReactNode>;
};

export namespace BadgeProps {
type ExtractAccentColor<FrClassName> = FrClassName extends `fr-badge--${infer AccentColor}`
? AccentColor
: never;

export type AccentColor = ExtractAccentColor<FrClassName>;
}

/** @see <https://components.react-dsfr.codegouv.studio/?path=/docs/components-badge> */
export const Badge = memo(
forwardRef<HTMLDivElement, BadgeProps>((props, ref) => {
Expand All @@ -30,6 +45,8 @@ export const Badge = memo(
severity,
small: isSmall = false,
noIcon = false,
iconId,
accentColor,
children,
...rest
} = props;
Expand All @@ -49,7 +66,13 @@ export const Badge = memo(
"fr-badge",
severity !== undefined && `fr-badge--${severity}`,
{ "fr-badge--sm": isSmall },
{ "fr-badge--no-icon": noIcon || severity === undefined }
{
"fr-badge--no-icon":
noIcon || (severity === undefined && iconId === undefined)
},
severity === undefined && iconId,
severity === undefined && iconId && "fr-badge--icon-left", // actually, it's always left but we need it in order to have the icon rendering
severity === undefined && accentColor && `fr-badge--${accentColor}`
),
className
),
Expand Down
11 changes: 11 additions & 0 deletions stories/Badge.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -118,3 +118,14 @@ export const NewBadge = getStory(
"description": "Small new `Badge` with icon"
}
);

export const BadgeWithIconAndAccentColor = getStory(
{
"iconId": "fr-icon-checkbox-circle-line",
"accentColor": "purple-glycine",
"children": "Custom badge"
},
{
"description": "`Badge` with custom icon and accent color"
}
);