Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

refactor(web): Implement design-system PieChart (#17722)

Ben Bachem0328341f441f
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 41786349dc..d8ff6a4487 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -741,9 +741,15 @@ importers:
csv-parse:
specifier: ^7.0.2
version: 7.0.2
+ d3-scale:
+ specifier: ^4.0.2
+ version: 4.0.2
d3-selection:
specifier: ^3.0.0
version: 3.0.0
+ d3-shape:
+ specifier: ^3.2.0
+ version: 3.2.0
d3-zoom:
specifier: ^3.0.0
version: 3.0.0
@@ -961,9 +967,15 @@ importers:
'@types/cors':
specifier: ^2.8.19
version: 2.8.19
+ '@types/d3-scale':
+ specifier: ^4.0.9
+ version: 4.0.9
'@types/d3-selection':
specifier: ^3.0.11
version: 3.0.11
+ '@types/d3-shape':
+ specifier: ^3.2.0
+ version: 3.2.0
'@types/d3-zoom':
specifier: ^3.0.8
version: 3.0.8
@@ -6495,6 +6507,9 @@ packages:
resolution: {integrity: sha512-lae0iWfcDeR7qt7rA88BNiqdvPS5pFVPpo5OfjElwNaT2yyekbM0C9vK+yqBqEmHr6lDkRnYNoTBYlAgJa7a4w==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-kVd74ta9eof3eJOvbNd1vGKS/XERRyQbT26Og63hIsvDO84cjD5gEOhsXf26w3FSoNlPVz84DOFcKv/oou+fMw==}
+
resolution: {integrity: sha512-5xg9rC+wWL8kdDj153qZcsJ0FWiFt0J5RB6LYUNZjwSnesfblqrI/bJ1wBdJ8OQfncgbJG5+2F+qfqnqyzYxyg==}
@@ -18215,6 +18230,10 @@ snapshots:
dependencies:
'@types/d3-path': 3.1.1
+ '@types/[email protected]':
+ dependencies:
+ '@types/d3-path': 3.1.1
+
'@types/[email protected]': {}
'@types/[email protected]': {}
@@ -20549,17 +20568,6 @@ snapshots:
transitivePeerDependencies:
- supports-color
- dependencies:
- debug: 3.2.7([email protected])
- optionalDependencies:
- eslint-import-resolver-node: 0.3.10([email protected])
- transitivePeerDependencies:
- - supports-color
-
dependencies:
debug: 3.2.7([email protected])
@@ -20621,35 +20629,6 @@ snapshots:
- eslint-import-resolver-webpack
- supports-color
- dependencies:
- '@rtsao/scc': 1.1.0
- array-includes: 3.1.9
- array.prototype.findlastindex: 1.2.6
- array.prototype.flat: 1.3.3
- array.prototype.flatmap: 1.3.3
- debug: 3.2.7([email protected])
- doctrine: 2.1.0
- eslint-import-resolver-node: 0.3.10([email protected])
- hasown: 2.0.4
- is-core-module: 2.16.2
- is-glob: 4.0.3
- minimatch: 3.1.5
- object.fromentries: 2.0.8
- object.groupby: 1.0.3
- object.values: 1.2.1
- semver: 6.3.1
- string.prototype.trimend: 1.0.9
- tsconfig-paths: 3.15.0
- optionalDependencies:
- transitivePeerDependencies:
- - eslint-import-resolver-typescript
- - eslint-import-resolver-webpack
- - supports-color
-
dependencies:
aria-query: 5.3.2
diff --git a/web/eslint.config.mjs b/web/eslint.config.mjs
index b141957d71..a89eddb331 100644
--- a/web/eslint.config.mjs
+++ b/web/eslint.config.mjs
@@ -281,15 +281,16 @@ export default [
// Root design-system components follow `Name/Name.tsx`, optionally alongside
// `Name/Name.stories.tsx`. Files must be directly inside a PascalCase folder,
// match that folder's name, and expose a matching named runtime export. The
- // factories, table, and internal subtrees are domain-specific exceptions
+ // charts, factories, table, and internal subtrees are domain-specific exceptions
// with their own structure.
{
name: "langfuse/web/design-system-component-structure",
files: ["src/components/design-system/**/*.{ts,tsx}"],
- ignores: [
- "src/components/design-system/factories/**",
- "src/components/design-system/internal/**",
- "src/components/design-system/table/**",
+ ignores: [
+ "src/components/design-system/charts/**",
+ "src/components/design-system/factories/**",
+ "src/components/design-system/internal/**",
+ "src/components/design-system/table/**",
],
plugins: {
"check-file": checkFile,
@@ -322,10 +323,11 @@ export default [
{
name: "langfuse/web/design-system-component-exports",
files: ["src/components/design-system/*/*.{ts,tsx}"],
- ignores: [
- "src/components/design-system/**/*.stories.{ts,tsx}",
- "src/components/design-system/table/**",
- ],
+ ignores: [
+ "src/components/design-system/**/*.stories.{ts,tsx}",
+ "src/components/design-system/charts/**",
+ "src/components/design-system/table/**",
+ ],
rules: {
"@repo/filename-matches-export": "error",
"import/no-default-export": "error",
diff --git a/web/package.json b/web/package.json
index b963eeabdb..fa965dd166 100644
--- a/web/package.json
+++ b/web/package.json
@@ -118,7 +118,9 @@
"core-js": "^3.38.1",
"cors": "^2.8.6",
"csv-parse": "^7.0.2",
+ "d3-scale": "^4.0.2",
"d3-selection": "^3.0.0",
+ "d3-shape": "^3.2.0",
"d3-zoom": "^3.0.0",
"date-fns": "^3.6.0",
"dd-trace": "5.109.0",
@@ -194,6 +196,8 @@
"@types/chroma-js": "^3.1.2",
"@types/cors": "^2.8.19",
"@types/d3-selection": "^3.0.11",
+ "@types/d3-scale": "^4.0.9",
+ "@types/d3-shape": "^3.2.0",
"@types/d3-zoom": "^3.0.8",
"@types/lodash": "^4.17.24",
"@types/node": "24.3.0",
diff --git a/web/src/components/design-system/charts/ChartContainer.tsx b/web/src/components/design-system/charts/ChartContainer.tsx
new file mode 100644
index 0000000000..a4c987d3e8
--- /dev/null
+++ b/web/src/components/design-system/charts/ChartContainer.tsx
@@ -0,0 +1,24 @@
+"use client";
+
+import type { ReactNode } from "react";
+
+import { useElementSize } from "@/src/hooks/useElementSize";
+
+export function ChartContainer({
+ children,
+}: {
+ children: (size: { width: number; height: number }) => ReactNode;
+}) {
+ const [containerRef, containerSize] = useElementSize<HTMLDivElement>();
+ const width = containerSize?.width ?? 0;
+ const height = containerSize?.height ?? 0;
+
+ return (
+ <div
+ ref={containerRef}
+ className="relative h-full min-h-0 w-full min-w-0 text-xs"
+ >
+ {children({ width, height })}
+ </div>
+ );
+}
diff --git a/web/src/components/design-system/charts/ChartTooltip.tsx b/web/src/components/design-system/charts/ChartTooltip.tsx
new file mode 100644
index 0000000000..78bd782ac3
--- /dev/null
+++ b/web/src/components/design-system/charts/ChartTooltip.tsx
@@ -0,0 +1,176 @@
+"use client";
+
+import {
+ autoUpdate,
+ flip,
+ FloatingPortal,
+ offset,
+ shift,
+ useClientPoint,
+ useFloating,
+} from "@floating-ui/react";
+import {
+ useLayoutEffect,
+ useState,
+ type FocusEvent,
+ type PointerEvent,
+ type ReactNode,
+} from "react";
+
+import { useLayerContainer } from "@/src/context/LayerContext/LayerContext";
+
+export function ChartTooltip({
+ children,
+}: {
+ children: (controller: {
+ activeIndex: number | undefined;
+ getReferenceProps: (data: {
+ index: number;
+ label: string;
+ value: string;
+ color: string;
+ details?: { label: string; value: string }[];
+ }) => {
+ onPointerEnter: (event: PointerEvent<SVGElement>) => void;
+ onPointerMove: (event: PointerEvent<SVGElement>) => void;
+ onPointerLeave: () => void;
+ onFocus: (event: FocusEvent<SVGElement>) => void;
+ onBlur: () => void;
+ };
+ }) => ReactNode;
+}) {
+ const [activeTooltip, setActiveTooltip] = useState<{
+ index: number;
+ label: string;
+ value: string;
+ color: string;
+ details?: { label: string; value: string }[];
+ reference: SVGElement;
+ clientPoint?: { x: number; y: number };
+ placement: "left" | "right";
+ }>();
+
+ useLayoutEffect(() => {
+ if (activeTooltip && !activeTooltip.reference.isConnected) {
+ setActiveTooltip(undefined);
+ }
+ }, [activeTooltip, children]);
+
+ const layerContainer = useLayerContainer("tooltip");
+ const { context, floatingStyles, refs } = useFloating({
+ elements: { reference: activeTooltip?.reference },
+ placement: activeTooltip?.placement ?? "right",
+ strategy: "fixed",
+ middleware: [offset(12), flip(), shift({ padding: 8 })],
+ transform: false,
+ whileElementsMounted: autoUpdate,
+ });
+ useClientPoint(context, {
+ enabled: activeTooltip?.clientPoint !== undefined,
+ x: activeTooltip?.clientPoint?.x,
+ y: activeTooltip?.clientPoint?.y,
+ });
+
+ const getReferenceProps = (data: {
+ index: number;
+ label: string;
+ value: string;
+ color: string;
+ details?: { label: string; value: string }[];
+ }) => {
+ const showAtPointer = (event: PointerEvent<SVGElement>) => {
+ const { clientX, clientY, currentTarget } = event;
+ const chartBounds =
+ currentTarget.ownerSVGElement?.getBoundingClientRect();
+ setActiveTooltip({
+ ...data,
+ reference: currentTarget,
+ clientPoint: { x: clientX, y: clientY },
+ placement:
+ chartBounds && clientX < chartBounds.left + chartBounds.width / 2
+ ? "left"
+ : "right",
+ });
+ };
+
+ return {
+ onPointerEnter: showAtPointer,
+ onPointerMove: showAtPointer,
+ onPointerLeave: () => setActiveTooltip(undefined),
+ onFocus: (event: FocusEvent<SVGElement>) => {
+ const sliceBounds = event.currentTarget.getBoundingClientRect();
+ const chartBounds =
+ event.currentTarget.ownerSVGElement?.getBoundingClientRect();
+ setActiveTooltip({
+ ...data,
+ reference: event.currentTarget,
+ placement:
+ chartBounds &&
+ sliceBounds.left + sliceBounds.width / 2 <
+ chartBounds.left + chartBounds.width / 2
+ ? "left"
+ : "right",
+ });
+ },
+ onBlur: () => setActiveTooltip(undefined),
+ };
+ };
+
+ return (
+ <>
+ {children({ activeIndex: activeTooltip?.index, getReferenceProps })}
+ {activeTooltip ? (
+ <FloatingPortal root={layerContainer}>
+ <div
+ ref={refs.setFloating}
+ role="tooltip"
+ className="border-border/50 bg-background pointer-events-none z-50 grid min-w-32 gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs shadow-xl"
+ style={floatingStyles}
+ >
+ <div className="flex items-center gap-2">
+ <svg
+ viewBox="0 0 10 10"
+ className="size-2.5 shrink-0"
+ aria-hidden="true"
+ >
+ <rect
+ width="10"
+ height="10"
+ rx="2"
+ fill={activeTooltip.color}
+ />
+ </svg>
+ <div className="flex min-w-0 flex-1 items-center justify-between gap-x-3 leading-tight">
+ <span
+ className="text-muted-foreground truncate"
+ title={activeTooltip.label}
+ >
+ {activeTooltip.label}
+ </span>
+ <span className="text-foreground shrink-0 font-mono font-bold whitespace-nowrap tabular-nums">
+ {activeTooltip.value}
+ </span>
+ </div>
+ </div>
+ {activeTooltip.details?.map((detail, index) => (
+ <div
+ key={`${detail.label}-${index}`}
+ className="flex min-w-0 items-center justify-between gap-x-3 pl-4 leading-tight"
+ >
+ <span
+ className="text-muted-foreground truncate"
+ title={detail.label}
+ >
+ {detail.label}
+ </span>
+ <span className="text-foreground shrink-0 font-mono whitespace-nowrap tabular-nums">
+ {detail.value}
+ </span>
+ </div>
+ ))}
+ </div>
+ </FloatingPortal>
+ ) : null}
+ </>
+ );
+}
diff --git a/web/src/components/design-system/charts/PieChart/PieChart.stories.tsx b/web/src/components/design-system/charts/PieChart/PieChart.stories.tsx
new file mode 100644
index 0000000000..2f7f76a084
--- /dev/null
+++ b/web/src/components/design-system/charts/PieChart/PieChart.stories.tsx
@@ -0,0 +1,129 @@
+import preview from "../../../../../.storybook/preview";
+import { expect, within } from "storybook/test";
+import { PieChart } from "./PieChart";
+
+const data = [
+ { label: "GPT-5", value: 46 },
+ { label: "Claude Sonnet", value: 31 },
+ { label: "Gemini Pro", value: 15 },
+ { label: "Other", value: 8 },
+];
+
+const meta = preview.meta({
+ component: PieChart,
+ parameters: {
+ layout: "fullscreen",
+ },
+ args: {
+ data,
+ valueFormatter: (value) => value.toLocaleString(),
+ },
+ decorators: [
+ (Story) => (
+ <div className="h-dvh w-full">
+ <Story />
+ </div>
+ ),
+ ],
+});
+
+export const Default = meta.story({});
+
+export const SubtleFill = meta.story({
+ args: {
+ variant: "subtle",
+ },
+});
+
+export const LongLabels = meta.story({
+ args: {
+ data: [
+ {
+ label: "A model name that is intentionally long enough to truncate",
+ value: 72_350,
+ },
+ { label: "Short model", value: 27_650 },
+ ],
+ },
+});
+
+export const KeyboardFocus = meta.story({
+ name: "(Test) Keyboard Focus",
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const slice = canvas.getByLabelText("Claude Sonnet: 31");
+
+ slice.focus();
+
+ const tooltip = await within(canvasElement.ownerDocument.body).findByRole(
+ "tooltip",
+ );
+ await expect(tooltip).toHaveTextContent("Claude Sonnet");
+ await expect(tooltip).toHaveTextContent("31");
+ },
+});
+
+export const NonPositiveValues = meta.story({
+ name: "(Test) Non-positive Values",
+ args: {
+ data: [
+ { label: "Zero", value: 0 },
+ { label: "Negative", value: -2 },
+ { label: "NaN", value: Number.NaN },
+ { label: "Infinity", value: Number.POSITIVE_INFINITY },
+ { label: "Positive", value: 2 },
+ ],
+ },
+ play: async ({ canvasElement }) => {
+ await expect(canvasElement.querySelectorAll("path")).toHaveLength(1);
+ },
+});
+
+export const CombinedSmallSlices = meta.story({
+ name: "(Test) Combined Small Slices",
+ args: {
+ data: [
+ { label: "Other", value: 96 },
+ { label: "Main", value: 2 },
+ { label: "Tiny A", value: 1 },
+ { label: "Tiny B", value: 1 },
+ ],
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const combinedSlice = canvas.getByLabelText("Other: 2");
+
+ await expect(canvasElement.querySelectorAll("path")).toHaveLength(3);
+ combinedSlice.focus();
+
+ const tooltip = await within(canvasElement.ownerDocument.body).findByRole(
+ "tooltip",
+ );
+ await expect(tooltip).toHaveTextContent("Tiny A");
+ await expect(tooltip).toHaveTextContent("Tiny B");
+ await expect(tooltip).toHaveTextContent("1 (1%)");
+ },
+});
+
+export const MinimumVisibleSlice = meta.story({
+ args: {
+ data: [
+ { label: "Main", value: 999 },
+ { label: "Tiny", value: 1 },
+ ],
+ },
+});
+
+export const Empty = meta.story({
+ name: "(Test) Empty",
+ args: {
+ data: [],
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+
+ await expect(canvasElement.querySelectorAll("circle")).toHaveLength(1);
+ await expect(canvas.getByText("0")).toBeInTheDocument();
+ await expect(canvas.getByText("Total")).toBeInTheDocument();
+ },
+});
diff --git a/web/src/components/design-system/charts/PieChart/PieChart.tsx b/web/src/components/design-system/charts/PieChart/PieChart.tsx
new file mode 100644
index 0000000000..086e076ad7
--- /dev/null
+++ b/web/src/components/design-system/charts/PieChart/PieChart.tsx
@@ -0,0 +1,244 @@
+"use client";
+
+import { useMemo } from "react";
+import { scaleOrdinal } from "d3-scale";
+import { arc, pie, type PieArcDatum } from "d3-shape";
+
+import { ChartContainer } from "@/src/components/design-system/charts/ChartContainer";
+import { ChartTooltip } from "@/src/components/design-system/charts/ChartTooltip";
+import { chartColors } from "@/src/components/design-system/charts/chartColors";
+import { cn } from "@/src/utils/tailwind";
+
+export type PieChartDatum = {
+ label: string;
+ value: number;
+};
+
+type PieChartSliceDatum = PieChartDatum & {
+ id: string;
+ details?: PieChartDatum[];
+};
+
+type PieChartProps = {
+ data: PieChartDatum[];
+ valueFormatter?: (value: number) => string;
+ centerLabel?: string;
+ variant?: "default" | "subtle";
+ ariaLabel?: string;
+};
+
+const VIEWBOX_SIZE = 280;
+const CENTER = VIEWBOX_SIZE / 2;
+const INNER_RADIUS = VIEWBOX_SIZE * (2 / 7);
+const OUTER_RADIUS = VIEWBOX_SIZE * (3 / 7);
+const ACTIVE_OUTER_RADIUS = VIEWBOX_SIZE * (13 / 28);
+const SMALL_SLICE_THRESHOLD = 0.02;
+const PAD_ANGLE = (2 * Math.PI) / 360;
+const MIN_VISIBLE_ANGLE = 2 * Math.PI * 0.01;
+const MIN_SLICE_ANGLE = PAD_ANGLE + MIN_VISIBLE_ANGLE;
+const percentageFormatter = new Intl.NumberFormat(undefined, {
+ style: "percent",
+ maximumFractionDigits: 1,
+});
+
+export function PieChart({ ...props }: PieChartProps) {
+ return (
+ <ChartContainer>
+ {({ width, height }) => (
+ <PieChartContent {...props} availableSize={Math.min(width, height)} />
+ )}
+ </ChartContainer>
+ );
+}
+
+function PieChartContent({
+ data,
+ valueFormatter = (value) => value.toLocaleString(),
+ centerLabel = "Total",
+ variant = "default",
+ ariaLabel = "Pie chart",
+ availableSize,
+}: PieChartProps & { availableSize: number }) {
+ const totalValue = useMemo(
+ () =>
+ data.reduce(
+ (total, datum) =>
+ Number.isFinite(datum.value) && datum.value > 0
+ ? total + datum.value
+ : total,
+ 0,
+ ),
+ [data],
+ );
+ const chartSlices = useMemo(() => {
+ const validData: PieChartSliceDatum[] = data.flatMap((datum, index) => {
+ if (!Number.isFinite(datum.value) || datum.value <= 0) return [];
+
+ return [{ ...datum, id: `datum-${index}`, details: undefined }];
+ });
+ const smallData = validData.filter(
+ (datum) => datum.value / totalValue < SMALL_SLICE_THRESHOLD,
+ );
+ const chartData = validData.filter(
+ (datum) => datum.value / totalValue >= SMALL_SLICE_THRESHOLD,
+ );
+
+ if (smallData.length > 0) {
+ chartData.push({
+ id: "combined-small-slices",
+ label: "Other",
+ value: smallData.reduce((total, datum) => total + datum.value, 0),
+ details: smallData,
+ });
+ }
+
+ const slicesNeedingMinimumAngle = chartData.filter(
+ (datum) => (datum.value / totalValue) * 2 * Math.PI < MIN_SLICE_ANGLE,
+ );
+ const flexibleValue = chartData.reduce(
+ (total, datum) =>
+ slicesNeedingMinimumAngle.includes(datum) ? total : total + datum.value,
+ 0,
+ );
+ const flexibleAngle =
+ 2 * Math.PI - slicesNeedingMinimumAngle.length * MIN_SLICE_ANGLE;
+ const colorScale = scaleOrdinal(
+ chartData.map((datum) => datum.id),
+ chartColors,
+ );
+
+ return pie<(typeof chartData)[number]>()
+ .value((datum) => {
+ if (slicesNeedingMinimumAngle.includes(datum)) return MIN_SLICE_ANGLE;
+ if (flexibleValue === 0) return (2 * Math.PI) / chartData.length;
+ return (datum.value / flexibleValue) * flexibleAngle;
+ })
+ .sort(null)
+ .padAngle(PAD_ANGLE)(chartData)
+ .flatMap((slice, index) => {
+ const path = arc<PieArcDatum<(typeof chartData)[number]>>()
+ .innerRadius(INNER_RADIUS)
+ .outerRadius(OUTER_RADIUS)
+ .cornerRadius(1)(slice);
+ const activePath = arc<PieArcDatum<(typeof chartData)[number]>>()
+ .innerRadius(INNER_RADIUS)
+ .outerRadius(ACTIVE_OUTER_RADIUS)
+ .cornerRadius(1)(slice);
+ if (!path || !activePath) return [];
+
+ return [
+ {
+ slice,
+ index,
+ path,
+ activePath,
+ color: colorScale(slice.data.id),
+ },
+ ];
+ });
+ }, [data, totalValue]);
+
+ const centerLabelSize = useMemo(() => {
+ if (availableSize >= 420) return "2xlarge";
+ if (availableSize >= 320) return "xlarge";
+ if (availableSize >= 240) return "large";
+ if (availableSize >= 160) return "medium";
+ return "small";
+ }, [availableSize]);
+
+ return (
+ <ChartTooltip>
+ {({ activeIndex, getReferenceProps }) => (
+ <>
+ <svg
+ viewBox={`0 0 ${VIEWBOX_SIZE} ${VIEWBOX_SIZE}`}
+ className="absolute inset-0 h-full min-h-0 w-full min-w-0 overflow-visible"
+ preserveAspectRatio="xMidYMid meet"
+ role="group"
+ aria-label={ariaLabel}
+ >
+ <g transform={`translate(${CENTER}, ${CENTER})`}>
+ {chartSlices.length === 0 ? (
+ <circle
+ r={(INNER_RADIUS + OUTER_RADIUS) / 2}
+ fill="none"
+ stroke="hsl(var(--muted))"
+ strokeWidth={OUTER_RADIUS - INNER_RADIUS}
+ aria-hidden="true"
+ />
+ ) : null}
+ {chartSlices.map(({ slice, index, path, activePath, color }) => {
+ const isActive = activeIndex === index;
+
+ let opacity = 0.82;
+ if (variant === "subtle") opacity = isActive ? 0.9 : 0.45;
+ if (isActive && variant === "default") opacity = 1;
+
+ return (
+ <path
+ key={slice.data.id}
+ d={isActive ? activePath : path}
+ fill={color}
+ opacity={opacity}
+ stroke="hsl(var(--background))"
+ strokeWidth={isActive ? 4 : 3}
+ className="outline-hidden transition-[opacity] duration-100 focus-visible:outline-2 focus-visible:outline-offset-2"
+ role="graphics-symbol"
+ tabIndex={0}
+ aria-label={`${slice.data.label}: ${valueFormatter(slice.data.value)}`}
+ {...getReferenceProps({
+ index,
+ label: slice.data.label,
+ value: `${valueFormatter(slice.data.value)} (${percentageFormatter.format(slice.data.value / totalValue)})`,
+ color,
+ details: slice.data.details?.map((datum) => ({
+ label: datum.label,
+ value: `${valueFormatter(datum.value)} (${percentageFormatter.format(datum.value / totalValue)})`,
+ })),
+ })}
+ />
+ );
+ })}
+ </g>
+ </svg>
+
+ <div
+ className={cn(
+ "pointer-events-none absolute inset-0 flex flex-col items-center justify-center",
+ centerLabelSize === "2xlarge" && "gap-2",
+ centerLabelSize === "xlarge" && "gap-1.5",
+ centerLabelSize === "large" && "gap-1",
+ centerLabelSize === "medium" && "gap-0.5",
+ )}
+ aria-hidden="true"
+ >
+ <span
+ className={cn(
+ "text-foreground leading-none font-bold",
+ centerLabelSize === "2xlarge" && "text-6xl",
+ centerLabelSize === "xlarge" && "text-5xl",
+ centerLabelSize === "large" && "text-3xl",
+ centerLabelSize === "medium" && "text-xl",
+ centerLabelSize === "small" && "text-sm",
+ )}
+ >
+ {valueFormatter(totalValue)}
+ </span>
+ <span
+ className={cn(
+ "text-muted-foreground leading-none",
+ centerLabelSize === "2xlarge" && "text-lg",
+ centerLabelSize === "xlarge" && "text-base",
+ centerLabelSize === "large" && "text-xs",
+ centerLabelSize === "medium" && "text-[10px]",
+ centerLabelSize === "small" && "text-[8px]",
+ )}
+ >
+ {centerLabel}
+ </span>
+ </div>
+ </>
+ )}
+ </ChartTooltip>
+ );
+}
diff --git a/web/src/components/design-system/charts/chartColors.ts b/web/src/components/design-system/charts/chartColors.ts
new file mode 100644
index 0000000000..b90a656b6b
--- /dev/null
+++ b/web/src/components/design-system/charts/chartColors.ts
@@ -0,0 +1,10 @@
+export const chartColors = [
+ "#3a3dee",
+ "#07b9d5",
+ "#71717a",
+ "#a855f7",
+ "#ebbd05",
+ "#ef4343",
+ "#82cb15",
+ "#ec4699",
+] as const;
diff --git a/web/src/features/widgets/chart-library/Chart.tsx b/web/src/features/widgets/chart-library/Chart.tsx
index aa5924a70d..c3cc831ace 100644
--- a/web/src/features/widgets/chart-library/Chart.tsx
+++ b/web/src/features/widgets/chart-library/Chart.tsx
@@ -250,7 +250,6 @@ const ChartComponent = ({
return (
<PieChart
data={renderedData.slice(0, rowLimit)}
- config={resolvedConfig}
metricFormatter={metricFormatter}
subtleFill={chartConfig?.subtle_fill}
/>
diff --git a/web/src/features/widgets/chart-library/PieChart.tsx b/web/src/features/widgets/chart-library/PieChart.tsx
index 09ed880766..f8a4fe543f 100644
--- a/web/src/features/widgets/chart-library/PieChart.tsx
+++ b/web/src/features/widgets/chart-library/PieChart.tsx
@@ -1,17 +1,5 @@
-/* eslint-disable no-nested-ternary */
import React, { useMemo } from "react";
-import {
- ChartContainer,
- ChartTooltip,
- ChartTooltipContent,
-} from "@/src/components/ui/chart";
-import {
- Label,
- Pie,
- PieChart as PieChartComponent,
- Sector,
- type PieSectorShapeProps,
-} from "recharts";
+import { PieChart as DesignSystemPieChart } from "@/src/components/design-system/charts/PieChart/PieChart";
import { type ChartProps } from "@/src/features/widgets/chart-library/chart-props";
import {
formatMetric,
@@ -21,120 +9,29 @@ import {
/**
* PieChart component
* @param data - Data to be displayed. Expects an array of objects with dimension and metric properties.
- * @param config - Configuration object for the chart. Can include theme settings for light and dark modes.
- * @param accessibilityLayer - Boolean to enable or disable the accessibility layer. Default is true.
*/
-export const PieChart: React.FC<ChartProps> = ({
+export const PieChart: React.FC<
+ Pick<ChartProps, "data" | "metricFormatter" | "subtleFill">
+> = ({
data,
- config = {
- metric: {
- theme: {
- light: "hsl(var(--chart-1))",
- dark: "hsl(var(--chart-1))",
- },
- },
- },
- accessibilityLayer = true,
metricFormatter = (value, options) => formatMetric(value, options),
subtleFill = false,
}) => {
const formatValue = (value: number) =>
toFullMetricString(metricFormatter(value, { style: "compact" }));
- // Calculate total metric value for center label
- const totalValue = useMemo(() => {
- return data.reduce((acc, curr) => acc + (curr.metric as number), 0);
- }, [data]);
-
- // Transform data for PieChart
const chartData = useMemo(() => {
- return data.map((item, index) => ({
- name: item.dimension || "Unknown",
- value: item.metric,
- fill: `hsl(var(--chart-${(index % 8) + 1}))`,
+ return data.map((item) => ({
+ label: item.dimension || "Unknown",
+ value: typeof item.metric === "number" ? item.metric : 0,
}));
}, [data]);
- const renderSector = (props: PieSectorShapeProps) => {
- const outerRadius =
- typeof props.outerRadius === "number" ? props.outerRadius : 0;
- const expandedOuterRadius = props.isActive ? outerRadius + 10 : outerRadius;
-
- return (
- <Sector
- {...props}
- outerRadius={expandedOuterRadius}
- opacity={
- subtleFill ? (props.isActive ? 0.9 : 0.45) : props.isActive ? 1 : 0.82
- }
- stroke="hsl(var(--background))"
- strokeWidth={props.isActive ? 4 : 3}
- />
- );
- };
-
return (
- <ChartContainer config={config}>
- <PieChartComponent accessibilityLayer={accessibilityLayer}>
- <ChartTooltip
- contentStyle={{ backgroundColor: "hsl(var(--background))" }}
- content={({ active, payload, label }) => (
- <ChartTooltipContent
- active={active}
- payload={payload}
- label={label}
- valueFormatter={(v) => formatValue(Number(v))}
- />
- )}
- />
- <Pie
- data={chartData}
- dataKey="value"
- nameKey="name"
- cx="50%"
- cy="50%"
- innerRadius={80}
- outerRadius={120}
- paddingAngle={2}
- strokeWidth={5}
- shape={renderSector}
- isAnimationActive={false}
- >
- {/* Label in the center of the donut */}
- {data.length > 0 && (
- <Label
- content={({ viewBox }) => {
- if (viewBox && "cx" in viewBox && "cy" in viewBox) {
- return (
- <text
- x={viewBox.cx}
- y={viewBox.cy}
- textAnchor="middle"
- dominantBaseline="middle"
- >
- <tspan
- x={viewBox.cx}
- y={viewBox.cy}
- className="fill-foreground text-3xl font-bold"
- >
- {formatValue(totalValue)}
- </tspan>
- <tspan
- x={viewBox.cx}
- y={(viewBox.cy || 0) + 24}
- className="fill-muted-foreground"
- >
- Total
- </tspan>
- </text>
- );
- }
- return null;
- }}
- />
- )}
- </Pie>
- </PieChartComponent>
- </ChartContainer>
+ <DesignSystemPieChart
+ data={chartData}
+ valueFormatter={formatValue}
+ variant={subtleFill ? "subtle" : "default"}
+ />
);
};