Skip to content

The Open Standard for Generative UI

feat(react-ui): add D3Charts alongside the Recharts charts (#1248)

Ankit Das301d66856835
diff --git a/.changeset/react-ui-d3-charts.md b/.changeset/react-ui-d3-charts.md
new file mode 100644
index 000000000..e7873ce5d
--- /dev/null
+++ b/.changeset/react-ui-d3-charts.md
@@ -0,0 +1,5 @@
+---
+"@openuidev/react-ui": patch
+---
+
+Add D3-based charts under `@openuidev/react-ui/D3Charts`: Area, Line, Bar (vertical and horizontal), Pie, Radial, Radar, Scatter, Heatmap, Funnel, SegmentedBar, CalendarHeatmap and the MiniArea / MiniBar / MiniLine sparklines, plus `StackedLegend` with `LegendStoreProvider`. They take the same `data` + `categoryKey` / `dataKey` shape and default to the same look as the existing charts (stacked-area totals, Pie/Radial stacked legend, SingleStackedBar compact legend, outline radar), and ship alongside them with `openui-d3-` prefixed classes; the existing Recharts charts are unchanged. Area, Line and Bar keep a fixed height: their x-axis labels never take more than half of it and truncate when they don't fit.
diff --git a/packages/react-ui/package.json b/packages/react-ui/package.json
index 33d208fd0..66433d4d5 100644
--- a/packages/react-ui/package.json
+++ b/packages/react-ui/package.json
@@ -135,6 +135,9 @@
"@radix-ui/react-tooltip": "^1.2.7",
"@tanstack/react-table": "^8.21.3",
"clsx": "^2.1.1",
+ "d3-scale": "^4.0.2",
+ "d3-selection": "^3.0.0",
+ "d3-shape": "^3.2.0",
"date-fns": "^4.1.0",
"lodash-es": "^4.17.21",
"lucide-react": "^0.562.0",
@@ -165,6 +168,9 @@
"@storybook/react-vite": "^8.5.3",
"@storybook/test": "^8.5.3",
"@storybook/theming": "^8.5.3",
+ "@types/d3-scale": "^4.0.9",
+ "@types/d3-selection": "^3.0.11",
+ "@types/d3-shape": "^3.1.8",
"@types/lodash-es": "^4.17.12",
"@types/node": "catalog:",
"@types/node-fetch": "2.6.13",
diff --git a/packages/react-ui/src/components/D3Charts/AreaChart/AreaChart.tsx b/packages/react-ui/src/components/D3Charts/AreaChart/AreaChart.tsx
new file mode 100644
index 000000000..3d28887d9
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/AreaChart/AreaChart.tsx
@@ -0,0 +1,233 @@
+import clsx from "clsx";
+import { useCallback, useMemo } from "react";
+
+import {
+ useCartesianChartOrchestrator,
+ useEffectiveAnimation,
+ useExportChartData,
+ useStackedData,
+ useXScale,
+ useYScale,
+} from "../hooks";
+import { CartesianXAxis } from "../shared/cartesian/axes/CartesianXAxis";
+import { CartesianChartLayout } from "../shared/cartesian/layouts/CartesianChartLayout";
+import { LineDotCrosshair } from "../shared/cartesian/LineDotCrosshair";
+import { findNearestDataIndex } from "../utils/mouseUtils";
+import { AreaSeries } from "./parts/AreaSeries";
+import { GradientDefs } from "./parts/GradientDefs";
+
+import { CHART_CLASS_PREFIX } from "../utils/constants";
+import type { AreaChartData, AreaChartProps } from "./types";
+
+/**
+ * Empty-data guard lives here, in a hook-free dispatcher: the chart impl below
+ * calls hooks unconditionally, so the "no data" branch must short-circuit
+ * *before* any hook runs (a count → 0 transition on a mounted chart would
+ * otherwise break the Rules of Hooks).
+ */
+export function AreaChart<T extends AreaChartData>(props: AreaChartProps<T>) {
+ if (!props.data || props.data.length === 0) {
+ return (
+ <div
+ className={clsx(
+ `${CHART_CLASS_PREFIX}-area-chart-container ${CHART_CLASS_PREFIX}-chart-empty`,
+ props.className,
+ )}
+ >
+ <span className={`${CHART_CLASS_PREFIX}-chart-empty-text`}>No data available</span>
+ </div>
+ );
+ }
+ return <AreaChartImpl {...props} />;
+}
+
+// Stacked areas keep one running total per row — a negative value lowers the
+// stack — matching Recharts' area charts (bars stack by sign instead).
+const AREA_STACK_OFFSET = "none";
+
+function AreaChartImpl<T extends AreaChartData>({
+ data,
+ categoryKey,
+ customPalette,
+ variant = "natural",
+ tickVariant: tickVariantProp,
+ stacked = true,
+ grid = true,
+ legend: showLegend = true,
+ icons,
+ isAnimationActive = false,
+ showYAxis = true,
+ xAxisLabel,
+ yAxisLabel,
+ className,
+ height,
+ width: fixedWidth,
+ fitLegendInHeight,
+ condensed = false,
+ density,
+ onClick,
+ crosshair = false,
+ highlight = false,
+ activeDots = true,
+ yTickCount,
+}: AreaChartProps<T>) {
+ const animate = useEffectiveAnimation(isAnimationActive);
+ const mode = condensed ? "fit" : "scroll";
+
+ const orch = useCartesianChartOrchestrator({
+ layout: mode,
+ data,
+ categoryKey,
+ themePaletteName: "areaChartPalette",
+ customPalette,
+ showLegend,
+ showYAxis,
+ height,
+ fixedWidth,
+ fitLegendInHeight,
+ tickVariantProp: tickVariantProp ?? (condensed ? "singleLine" : "multiLine"),
+ chartIdPrefix: "d3ac",
+ icons,
+ onClick,
+ density,
+ stacked,
+ stackOffset: AREA_STACK_OFFSET,
+ yTickCount,
+ });
+
+ const xScale = useXScale(
+ data,
+ orch.data.catKey,
+ orch.dimensions.chartAreaWidth,
+ orch.dimensions.widthOfGroup,
+ );
+ const stackedData = useStackedData(data, orch.data.dataKeys, stacked, AREA_STACK_OFFSET);
+
+ // Unstacked series whose values are entirely <= 0 hang below the zero line —
+ // flip their fill gradient so the strongest opacity stays at the data edge.
+ // Stacked series sit on the running total, so their gradient never flips.
+ const negativeKeys = useMemo(() => {
+ const keys = new Set<string>();
+ if (stacked) return keys;
+ for (const key of orch.data.dataKeys) {
+ let max = -Infinity;
+ for (const row of data) max = Math.max(max, Number(row[key]) || 0);
+ if (max <= 0) keys.add(key);
+ }
+ return keys;
+ }, [data, orch.data.dataKeys, stacked]);
+ const yScale = useYScale(
+ data,
+ orch.data.dataKeys,
+ orch.dimensions.chartInnerHeight,
+ stacked,
+ AREA_STACK_OFFSET,
+ );
+
+ const getYValue = useCallback(
+ (_row: Record<string, string | number>, key: string, seriesIndex: number) => {
+ if (stackedData && orch.hover.hoveredIndex !== null) {
+ const series = stackedData[seriesIndex];
+ const point = series?.[orch.hover.hoveredIndex];
+ // The running total after this series — the edge its line is drawn on.
+ return point ? point[1] : 0;
+ }
+ return Number(_row[key]) || 0;
+ },
+ [stackedData, orch.hover.hoveredIndex],
+ );
+
+ const findIndex = useCallback((mouseX: number) => findNearestDataIndex(xScale, mouseX), [xScale]);
+ const mouseHandlers = orch.hover.createMouseHandlers(findIndex);
+
+ // PPTX print-export JSON — mirrors react-ui's AreaChart call (type:'area',
+ // no extraOptions). Undefined off the print path.
+ const exportData = useExportChartData({
+ type: "area",
+ data,
+ categoryKey: orch.data.catKey,
+ dataKeys: orch.data.dataKeys,
+ colors: orch.data.colors,
+ legend: showLegend,
+ xAxisLabel,
+ yAxisLabel,
+ });
+
+ return (
+ <CartesianChartLayout
+ orch={orch}
+ yScale={yScale}
+ mouseHandlers={mouseHandlers}
+ classPrefix="area-chart"
+ chartType="area"
+ exportData={exportData}
+ ariaLabel="Area chart"
+ showYAxis={showYAxis}
+ grid={grid}
+ showLegend={showLegend}
+ xAxisLabel={xAxisLabel}
+ yAxisLabel={yAxisLabel}
+ yTickCount={yTickCount}
+ className={className}
+ defs={
+ <GradientDefs
+ negativeKeys={negativeKeys}
+ dataKeys={orch.data.dataKeys}
+ transformedKeys={orch.data.transformedKeys}
+ colors={orch.data.colorMap}
+ chartId={orch.identity.chartId}
+ chartWidth={orch.dimensions.chartAreaWidth}
+ chartHeight={orch.dimensions.chartInnerHeight}
+ />
+ }
+ series={
+ <>
+ <AreaSeries
+ data={data}
+ dataKeys={orch.data.dataKeys}
+ xScale={xScale}
+ yScale={yScale}
+ variant={variant}
+ stackedData={stackedData}
+ categoryKey={orch.data.catKey}
+ transformedKeys={orch.data.transformedKeys}
+ colors={orch.data.colorMap}
+ chartId={orch.identity.chartId}
+ isAnimationActive={animate}
+ />
+ <LineDotCrosshair
+ hoveredIndex={orch.hover.hoveredIndex}
+ xScale={xScale}
+ yScale={yScale}
+ data={data}
+ dataKeys={orch.data.dataKeys}
+ categoryKey={orch.data.catKey}
+ colors={orch.data.colorMap}
+ chartHeight={orch.dimensions.chartInnerHeight}
+ getYValue={getYValue}
+ classPrefix={`${CHART_CLASS_PREFIX}-area-chart`}
+ crosshair={crosshair}
+ highlight={highlight}
+ activeDots={activeDots}
+ />
+ </>
+ }
+ xAxis={
+ <CartesianXAxis
+ mode={mode}
+ scale={xScale}
+ classPrefix={`${CHART_CLASS_PREFIX}-area-chart`}
+ tickVariant={orch.dimensions.tickVariant}
+ widthOfGroup={orch.dimensions.widthOfGroup}
+ labelHeight={orch.xAxis.xAxisHeight}
+ labelWidth={orch.xAxis.labelWidth}
+ maxLines={orch.xAxis.maxLines}
+ labelInterval={orch.dimensions.labelInterval}
+ angle={orch.xAxis.angle}
+ chartWidth={orch.dimensions.chartAreaWidth}
+ yAxisWidth={orch.dimensions.effectiveYAxisWidth}
+ />
+ }
+ />
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/AreaChart/areaChart.scss b/packages/react-ui/src/components/D3Charts/AreaChart/areaChart.scss
new file mode 100644
index 000000000..2203eb1a1
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/AreaChart/areaChart.scss
@@ -0,0 +1,33 @@
+@use "../shared/cartesian/chartBase" as base;
+@use "../prefix" as brand;
+
+@include base.chart-base("area-chart");
+@include base.crosshair-styles("area-chart");
+
+// No `transition: d` here: data-change motion is the spring data morph in
+// AreaSeries (gated on isAnimationActive). A CSS transition restarted from
+// progress 0 on every attribute write, so per-frame streaming rewrites pinned
+// the rendered geometry (and would fight the morph's per-tick writes).
+.#{brand.$prefix}-area-chart-area-path {
+ transition: opacity 0.2s ease;
+}
+
+.#{brand.$prefix}-area-chart-area-line {
+ fill: none;
+ stroke-width: 2;
+}
+
+// Entrances are decorative: gate the whole rule (pre-state included) behind
+// reduced-motion so users who opt out get the natural static state immediately
+// — gating only the animation would strand elements at the opacity: 0 start.
+@media (prefers-reduced-motion: no-preference) {
+ .#{brand.$prefix}-area-chart-area-line--animated {
+ stroke-dasharray: var(--path-length);
+ stroke-dashoffset: var(--path-length);
+ animation: #{brand.$prefix}-draw-line 1s ease-out forwards;
+ }
+ .#{brand.$prefix}-area-chart-area-path--animated {
+ opacity: 0;
+ animation: #{brand.$prefix}-fade-appear 0.6s ease-out 0.4s forwards;
+ }
+}
diff --git a/packages/react-ui/src/components/D3Charts/AreaChart/index.ts b/packages/react-ui/src/components/D3Charts/AreaChart/index.ts
new file mode 100644
index 000000000..372c6d233
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/AreaChart/index.ts
@@ -0,0 +1,2 @@
+export { AreaChart } from "./AreaChart";
+export type { AreaChartData, AreaChartProps, AreaChartVariant } from "./types";
diff --git a/packages/react-ui/src/components/D3Charts/AreaChart/parts/AreaSeries.tsx b/packages/react-ui/src/components/D3Charts/AreaChart/parts/AreaSeries.tsx
new file mode 100644
index 000000000..0f382451b
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/AreaChart/parts/AreaSeries.tsx
@@ -0,0 +1,167 @@
+import type { ScaleLinear, ScalePoint } from "d3-scale";
+import { type CurveFactory, curveLinear, curveMonotoneX, curveStepAfter } from "d3-shape";
+import React, { useMemo, useRef } from "react";
+import type { StackedData } from "../../hooks";
+import { AnimatedPath } from "../../shared/cartesian/AnimatedPath";
+import { AREA_STRIDE, buildAreaD, buildAreaEdgeD } from "../../shared/cartesian/seriesGeometry";
+import { springPresets, useDataMorph, useIsomorphicLayoutEffect } from "../../shared/core/spring";
+import { CHART_CLASS_PREFIX } from "../../utils/constants";
+import { AreaChartVariant } from "../types";
+
+const curveMap = {
+ linear: curveLinear,
+ natural: curveMonotoneX,
+ step: curveStepAfter,
+};
+
+interface AreaSeriesProps {
+ data: Array<Record<string, string | number>>;
+ dataKeys: string[];
+ xScale: ScalePoint<string>;
+ yScale: ScaleLinear<number, number>;
+ variant: AreaChartVariant;
+ stackedData: StackedData | null;
+ categoryKey: string;
+ transformedKeys: Record<string, string>;
+ colors: Record<string, string>;
+ chartId: string;
+ isAnimationActive?: boolean;
+}
+
+export const AreaSeries: React.FC<AreaSeriesProps> = ({
+ data,
+ dataKeys,
+ xScale,
+ yScale,
+ variant,
+ stackedData,
+ categoryKey,
+ transformedKeys,
+ colors,
+ chartId,
+ isAnimationActive,
+}) => {
+ // Fall back to the default curve for any variant not in the map — during
+ // streaming the parser can hand us a placeholder (e.g. "") before the real
+ // enum value arrives, and `curveMap[""]` would otherwise be `undefined`,
+ // making d3-shape's `area().curve(undefined)` throw "curve is not a
+ // function" on that transient first render. `natural` mirrors the chart's
+ // own `variant = 'natural'` default.
+ const curve = curveMap[variant] ?? curveMap.natural;
+
+ // Target geometry per series: flat `[x, y0, y1, yEdge]` pixel scalars (see
+ // seriesGeometry.ts for the layout) + the two paths built from them. React
+ // commits these as the attributes; the morph only writes BETWEEN targets.
+ const seriesGeom = useMemo(() => {
+ if (stackedData) {
+ return stackedData.map((series) => {
+ const points = series as unknown as [number, number][];
+ const values = new Float64Array(points.length * AREA_STRIDE);
+ points.forEach((point, i) => {
+ values[i * AREA_STRIDE] = xScale(String(data[i]![categoryKey])) ?? 0;
+ values[i * AREA_STRIDE + 1] = yScale(point[0]);
+ values[i * AREA_STRIDE + 2] = yScale(point[1]);
+ // Stroke the running total after this series.
+ values[i * AREA_STRIDE + 3] = yScale(point[1]);
+ });
+ return {
+ key: series.key,
+ values,
+ areaPath: buildAreaD(values, curve),
+ linePath: buildAreaEdgeD(values, curve),
+ };
+ });
+ }
+ return dataKeys.map((key) => {
+ const values = new Float64Array(data.length * AREA_STRIDE);
+ data.forEach((row, i) => {
+ const y = yScale(Number(row[key]) || 0);
+ values[i * AREA_STRIDE] = xScale(String(row[categoryKey])) ?? 0;
+ values[i * AREA_STRIDE + 1] = yScale(0);
+ values[i * AREA_STRIDE + 2] = y;
+ values[i * AREA_STRIDE + 3] = y;
+ });
+ return {
+ key,
+ values,
+ areaPath: buildAreaD(values, curve),
+ linePath: buildAreaEdgeD(values, curve),
+ };
+ });
+ }, [data, dataKeys, xScale, yScale, stackedData, categoryKey, curve]);
+
+ return (
+ <g className={`${CHART_CLASS_PREFIX}-area-chart-areas`}>
+ {seriesGeom.map(({ key, values, areaPath, linePath }) => (
+ <AreaSeriesItem
+ key={key}
+ values={values}
+ areaPath={areaPath}
+ linePath={linePath}
+ curve={curve}
+ color={colors[key] ?? "#000"}
+ gradientId={`grad-${chartId}-${transformedKeys[key]}`}
+ isAnimationActive={isAnimationActive}
+ />
+ ))}
+ </g>
+ );
+};
+
+/**
+ * One series' fill + value-edge stroke under the spring data morph — same
+ * design as LineSeriesItem (see there for the streaming rationale). ONE morph
+ * drives both paths from the same scalars, so fill and stroke can never seam
+ * apart mid-animation.
+ */
+function AreaSeriesItem({
+ values,
+ areaPath,
+ linePath,
+ curve,
+ color,
+ gradientId,
+ isAnimationActive,
+}: {
+ values: Float64Array;
+ areaPath: string;
+ linePath: string;
+ curve: CurveFactory;
+ color: string;
+ gradientId: string;
+ isAnimationActive?: boolean;
+}) {
+ const areaRef = useRef<SVGPathElement | null>(null);
+ const lineRef = useRef<SVGPathElement | null>(null);
+ const curveRef = useRef(curve);
+ curveRef.current = curve;
+
+ const aim = useDataMorph(springPresets.dataMorph, (animated) => {
+ areaRef.current?.setAttribute("d", buildAreaD(animated, curveRef.current));
+ lineRef.current?.setAttribute("d", buildAreaEdgeD(animated, curveRef.current));
+ });
+
+ // Pre-paint so a mid-glide retarget restores the animated geometry before
+ // the freshly committed target attributes can flash.
+ useIsomorphicLayoutEffect(() => {
+ aim(values, !isAnimationActive);
+ }, [values, isAnimationActive, aim]);
+
+ return (
+ <g>
+ <path
+ ref={areaRef}
+ className={`${CHART_CLASS_PREFIX}-area-chart-area-path${isAnimationActive ? ` ${CHART_CLASS_PREFIX}-area-chart-area-path--animated` : ""}`}
+ d={areaPath}
+ fill={`url(#${gradientId})`}
+ />
+ <AnimatedPath
+ d={linePath}
+ color={color}
+ className={`${CHART_CLASS_PREFIX}-area-chart-area-line`}
+ isAnimationActive={isAnimationActive}
+ pathRef={lineRef}
+ />
+ </g>
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/AreaChart/parts/GradientDefs.tsx b/packages/react-ui/src/components/D3Charts/AreaChart/parts/GradientDefs.tsx
new file mode 100644
index 000000000..78d63cfd0
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/AreaChart/parts/GradientDefs.tsx
@@ -0,0 +1,52 @@
+import React from "react";
+import { ClipDefs } from "../../shared/cartesian/ClipDefs";
+
+const GRADIENT_TOP_OPACITY = 0.6;
+const GRADIENT_BOTTOM_OPACITY = 0;
+
+interface GradientDefsProps {
+ dataKeys: string[];
+ transformedKeys: Record<string, string>;
+ colors: Record<string, string>;
+ chartId: string;
+ chartWidth: number;
+ chartHeight: number;
+ /** Series rendered entirely below zero — their fade direction flips. */
+ negativeKeys?: Set<string>;
+}
+
+export const GradientDefs: React.FC<GradientDefsProps> = ({
+ dataKeys,
+ transformedKeys,
+ colors,
+ chartId,
+ chartWidth,
+ chartHeight,
+ negativeKeys,
+}) => {
+ return (
+ <defs>
+ <ClipDefs chartId={chartId} chartWidth={chartWidth} chartHeight={chartHeight} />
+ {dataKeys.map((key) => {
+ const transformedKey = transformedKeys[key];
+ const color = colors[key] ?? "#000";
+ // All-negative bands hang below zero: flip so the strong end sits at
+ // the data edge (bottom) and the fade reaches the zero line (top).
+ const flip = negativeKeys?.has(key) ?? false;
+ return (
+ <linearGradient
+ key={key}
+ id={`grad-${chartId}-${transformedKey}`}
+ x1="0"
+ y1={flip ? "1" : "0"}
+ x2="0"
+ y2={flip ? "0" : "1"}
+ >
+ <stop offset="5%" stopColor={color} stopOpacity={GRADIENT_TOP_OPACITY} />
+ <stop offset="95%" stopColor={color} stopOpacity={GRADIENT_BOTTOM_OPACITY} />
+ </linearGradient>
+ );
+ })}
+ </defs>
+ );
+};
diff --git a/packages/react-ui/src/components/D3Charts/AreaChart/stories/areaChart.stories.tsx b/packages/react-ui/src/components/D3Charts/AreaChart/stories/areaChart.stories.tsx
new file mode 100644
index 000000000..8040158fc
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/AreaChart/stories/areaChart.stories.tsx
@@ -0,0 +1,1367 @@
+// Copy of Charts/AreaChart/stories/areaChart.stories.tsx with only the chart import and the title changed:
+// the same args and renders, rendering the D3Charts chart via
+// ../../stories/rechartsStoryAdapters.
+import type { Meta, StoryObj } from "@storybook/react";
+import {
+ Calendar,
+ Globe,
+ Laptop,
+ Monitor,
+ Smartphone,
+ TabletSmartphone,
+ Tv,
+ Watch,
+} from "lucide-react";
+import { useState } from "react";
+import { Card } from "../../../Card";
+import { AreaChart, AreaChartProps } from "../../stories/rechartsStoryAdapters";
+
+// 🔥 COMPREHENSIVE DATA VARIATIONS - Designed to test label collision scenarios
+const dataVariations = {
+ default: [
+ { month: "January", desktop: 150, mobile: 90, tablet: 120 },
+ { month: "February", desktop: 280, mobile: 180, tablet: 140 },
+ { month: "March", desktop: 220, mobile: 140, tablet: 160 },
+ { month: "April", desktop: 180, mobile: 160, tablet: 180 },
+ { month: "May", desktop: 250, mobile: 120, tablet: 140 },
+ { month: "June", desktop: 300, mobile: 180, tablet: 160 },
+ { month: "July", desktop: 350, mobile: 220, tablet: 180 },
+ { month: "August", desktop: 400, mobile: 240, tablet: 200 },
+ { month: "September", desktop: 450, mobile: 260, tablet: 220 },
+ { month: "October", desktop: 500, mobile: 280, tablet: 240 },
+ { month: "November", desktop: 550, mobile: 300, tablet: 260 },
+ { month: "December", desktop: 600, mobile: 320, tablet: 280 },
+ ],
+ // 🏷️ BIG LABELS - Testing collision detection and truncation
+ bigLabels: [
+ {
+ category: "Very Long Category Name That Should Be Truncated",
+ sales: 150,
+ revenue: 90,
+ profit: 120,
+ },
+ {
+ category: "Another Extremely Long Label That Causes Collisions",
+ sales: 280,
+ revenue: 180,
+ profit: 140,
+ },
+ {
+ category: "Super Duper Long Category Name That Tests Truncation",
+ sales: 220,
+ revenue: 140,
+ profit: 160,
+ },
+ {
+ category: "Incredibly Long Text That Should Trigger Collision Detection",
+ sales: 180,
+ revenue: 160,
+ profit: 180,
+ },
+ {
+ category: "Maximum Length Category Name That Tests All Edge Cases",
+ sales: 250,
+ revenue: 120,
+ profit: 140,
+ },
+ {
+ category: "Extra Long Business Category Name With Many Words",
+ sales: 300,
+ revenue: 180,
+ profit: 160,
+ },
+ {
+ category: "Comprehensive Long Label For Testing Horizontal Offset",
+ sales: 350,
+ revenue: 220,
+ profit: 180,
+ },
+ {
+ category: "Extended Category Name That Pushes Truncation Limits",
+ sales: 400,
+ revenue: 240,
+ profit: 200,
+ },
+ ],
+ // 📅 DENSE TIMELINE - Many items with medium-length labels
+ denseTimeline: [
+ { period: "Q1 2022 Jan-Mar", visitors: 120, conversions: 15, revenue: 1200 },
+ { period: "Q1 2022 Apr-Jun", visitors: 150, conversions: 22, revenue: 1800 },
+ { period: "Q2 2022 Jul-Sep", visitors: 180, conversions: 28, revenue: 2100 },
+ { period: "Q2 2022 Oct-Dec", visitors: 200, conversions: 35, revenue: 2500 },
+ { period: "Q3 2023 Jan-Mar", visitors: 160, conversions: 18, revenue: 1600 },
+ { period: "Q3 2023 Apr-Jun", visitors: 190, conversions: 32, revenue: 2300 },
+ { period: "Q4 2023 Jul-Sep", visitors: 220, conversions: 40, revenue: 2800 },
+ { period: "Q4 2023 Oct-Dec", visitors: 240, conversions: 45, revenue: 3200 },
+ { period: "Q1 2024 Jan-Mar", visitors: 210, conversions: 38, revenue: 2700 },
+ { period: "Q1 2024 Apr-Jun", visitors: 230, conversions: 42, revenue: 3000 },
+ { period: "Q2 2024 Jul-Sep", visitors: 250, conversions: 48, revenue: 3400 },
+ { period: "Q2 2024 Oct-Dec", visitors: 270, conversions: 52, revenue: 3800 },
+ { period: "Q3 2024 Jan-Mar", visitors: 260, conversions: 50, revenue: 3600 },
+ { period: "Q3 2024 Apr-Jun", visitors: 280, conversions: 55, revenue: 4000 },
+ { period: "Q4 2024 Jul-Sep", visitors: 300, conversions: 60, revenue: 4300 },
+ { period: "Q4 2024 Oct-Dec", visitors: 290, conversions: 58, revenue: 4100 },
+ ],
+ // 🏢 COMPANY NAMES - Real-world long business names
+ companyNames: [
+ { company: "Apple Inc.", revenue: 394328000000, profit: 99803000000, marketCap: 3500000000000 },
+ {
+ company: "Microsoft Corporation",
+ revenue: 211915000000,
+ profit: 83383000000,
+ marketCap: 2800000000000,
+ },
+ {
+ company: "Alphabet Inc. (Google)",
+ revenue: 307394000000,
+ profit: 76033000000,
+ marketCap: 2100000000000,
+ },
+ {
+ company: "Amazon.com Inc.",
+ revenue: 574785000000,
+ profit: 33364000000,
+ marketCap: 1600000000000,
+ },
+ {
+ company: "Tesla Motors Inc.",
+ revenue: 96773000000,
+ profit: 15000000000,
+ marketCap: 800000000000,
+ },
+ {
+ company: "Meta Platforms Inc.",
+ revenue: 134902000000,
+ profit: 39370000000,
+ marketCap: 900000000000,
+ },
+ {
+ company: "NVIDIA Corporation",
+ revenue: 60922000000,
+ profit: 29760000000,
+ marketCap: 1800000000000,
+ },
+ {
+ company: "Berkshire Hathaway Inc.",
+ revenue: 364482000000,
+ profit: 96223000000,
+ marketCap: 780000000000,
+ },
+ ],
+ // 🌍 COUNTRY NAMES - Geographic labels with varying lengths
+ countryData: [
+ { country: "United States of America", population: 331900000, gdp: 26900000000000 },
+ { country: "People's Republic of China", population: 1412000000, gdp: 17700000000000 },
+ { country: "Federal Republic of Germany", population: 83200000, gdp: 4300000000000 },
+ { country: "United Kingdom of Great Britain", population: 67500000, gdp: 3100000000000 },
+ { country: "French Republic", population: 68000000, gdp: 2900000000000 },
+ { country: "Republic of India", population: 1380000000, gdp: 3700000000000 },
+ { country: "Federative Republic of Brazil", population: 215000000, gdp: 2100000000000 },
+ { country: "Russian Federation", population: 146000000, gdp: 1800000000000 },
+ ],
+ // 📈 FINANCIAL QUARTERS - Testing medium-density scenarios
+ financialQuarters: [
+ { quarter: "Q1 FY2022", revenue: 1200000, expenses: 800000, profit: 400000 },
+ { quarter: "Q2 FY2022", revenue: 1500000, expenses: 950000, profit: 550000 },
+ { quarter: "Q3 FY2022", revenue: 1800000, expenses: 1100000, profit: 700000 },
+ { quarter: "Q4 FY2022", revenue: 2000000, expenses: 1300000, profit: 700000 },
+ { quarter: "Q1 FY2023", revenue: 2200000, expenses: 1400000, profit: 800000 },
+ { quarter: "Q2 FY2023", revenue: 2500000, expenses: 1600000, profit: 900000 },
+ { quarter: "Q3 FY2023", revenue: 2800000, expenses: 1800000, profit: 1000000 },
+ { quarter: "Q4 FY2023", revenue: 3000000, expenses: 1900000, profit: 1100000 },
+ ],
+ // 🔤 MIXED LENGTHS - Testing various label length scenarios
+ mixedLengths: [
+ { item: "A", valueA: 100, valueB: 80 },
+ { item: "Short", valueA: 150, valueB: 120 },
+ { item: "Medium Length Item", valueA: 200, valueB: 160 },
+ { item: "Very Long Item Name That Tests Truncation", valueA: 250, valueB: 200 },
+ { item: "B", valueA: 180, valueB: 140 },
+ { item: "Another Really Long Category Name", valueA: 220, valueB: 180 },
+ { item: "XL", valueA: 190, valueB: 150 },
+ ],
+ // 🎯 EDGE CASES - Extreme scenarios
+ edgeCases: [
+ {
+ name: "SinglePointDataSetForTestingEdgeCasesInCollisionDetectionAndLabelTruncationFunctionality",
+ value: 500,
+ },
+ {
+ name: "SecondExtremelyLongDataPointNameThatShouldDefinitelyTriggerTruncationMechanisms",
+ value: 600,
+ },
+ ],
+ // 📱 MINIMAL - Small dataset for baseline testing
+ minimal: [
+ { category: "Mobile Devices", users: 150, sessions: 90 },
+ { category: "Desktop Computers", users: 280, sessions: 180 },
+ { category: "Tablet Devices", users: 220, sessions: 140 },
+ ],
+ // 🔄 EXPAND/COLLAPSE - Marketing channels dataset for legend overflow testing
+ expandCollapseMarketing: [
+ {
+ channel: "Website Traffic and Organic Search Results",
+ impressions: 120000,
+ clicks: 15000,
+ conversions: 1200,
+ cost: 8500,
+ revenue: 24000,
+ roi: 182,
+ ctr: 12.5,
+ cpc: 0.57,
+ cpa: 7.08,
+ reach: 95000,
+ engagement: 8200,
+ shares: 420,
+ saves: 180,
+ comments: 650,
+ videoViews: 0,
+ },
+ {
+ channel: "Social Media Engagement and Brand Awareness",
+ impressions: 85000,
+ clicks: 12000,
+ conversions: 950,
+ cost: 6200,
+ revenue: 19000,
+ roi: 206,
+ ctr: 14.1,
+ cpc: 0.52,
+ cpa: 6.53,
+ reach: 72000,
+ engagement: 15400,
+ shares: 890,
+ saves: 340,
+ comments: 1200,
+ videoViews: 28000,
+ },
+ {
+ channel: "Email Marketing Campaign Performance",
+ impressions: 45000,
+ clicks: 8500,
+ conversions: 800,
+ cost: 2100,
+ revenue: 16000,
+ roi: 562,
+ ctr: 18.9,
+ cpc: 0.25,
+ cpa: 2.63,
+ reach: 42000,
+ engagement: 6800,
+ shares: 120,
+ saves: 85,
+ comments: 240,
+ videoViews: 0,
+ },
+ {
+ channel: "Paid Advertising and PPC Campaign ROI",
+ impressions: 95000,
+ clicks: 18000,
+ conversions: 1500,
+ cost: 12500,
+ revenue: 30000,
+ roi: 140,
+ ctr: 18.9,
+ cpc: 0.69,
+ cpa: 8.33,
+ reach: 88000,
+ engagement: 12600,
+ shares: 320,
+ saves: 150,
+ comments: 480,
+ videoViews: 5200,
+ },
+ {
+ channel: "Content Marketing and Blog Performance",
+ impressions: 60000,
+ clicks: 9500,
+ conversions: 750,
+ cost: 4800,
+ revenue: 15000,
+ roi: 213,
+ ctr: 15.8,
+ cpc: 0.51,
+ cpa: 6.4,
+ reach: 55000,
+ engagement: 7800,
+ shares: 680,
+ saves: 420,
+ comments: 950,
+ videoViews: 12000,
+ },
+ {
+ channel: "Mobile Application Downloads and Usage",
+ impressions: 70000,
+ clicks: 11000,
+ conversions: 1100,
+ cost: 5500,
+ revenue: 22000,
+ roi: 300,
+ ctr: 15.7,
+ cpc: 0.5,
+ cpa: 5.0,
+ reach: 65000,
+ engagement: 9200,
+ shares: 180,
+ saves: 95,
+ comments: 320,
+ videoViews: 8500,
+ },
+ {
+ channel: "Customer Support Response Time and Quality",
+ impressions: 35000,
+ clicks: 5500,
+ conversions: 450,
+ cost: 2800,
+ revenue: 9000,
+ roi: 221,
+ ctr: 15.7,
+ cpc: 0.51,
+ cpa: 6.22,
+ reach: 32000,
+ engagement: 4200,
+ shares: 45,
+ saves: 25,
+ comments: 180,
+ videoViews: 0,
+ },
+ {
+ channel: "Sales Funnel Conversion and Lead Generation",
+ impressions: 110000,
+ clicks: 22000,
+ conversions: 1800,
+ cost: 15000,
+ revenue: 36000,
+ roi: 140,
+ ctr: 20.0,
+ cpc: 0.68,
+ cpa: 8.33,
+ reach: 98000,
+ engagement: 18500,
+ shares: 420,
+ saves: 280,
+ comments: 750,
+ videoViews: 3200,
+ },
+ {
+ channel: "User Retention and Churn Rate Analysis",
+ impressions: 80000,
+ clicks: 14000,
+ conversions: 1200,
+ cost: 7200,
+ revenue: 24000,
+ roi: 233,
+ ctr: 17.5,
+ cpc: 0.51,
+ cpa: 6.0,
+ reach: 75000,
+ engagement: 11200,
+ shares: 280,
+ saves: 150,
+ comments: 420,
+ videoViews: 6800,
+ },
+ {
+ channel: "Product Feature Usage and Performance Metrics",
+ impressions: 65000,
+ clicks: 10500,
+ conversions: 900,
+ cost: 5200,
+ revenue: 18000,
+ roi: 246,
+ ctr: 16.2,
+ cpc: 0.5,
+ cpa: 5.78,
+ reach: 58000,
+ engagement: 8500,
+ shares: 320,
+ saves: 180,
+ comments: 650,
+ videoViews: 4200,
+ },
+ {
+ channel: "Market Research and Competitive Analysis",
+ impressions: 40000,
+ clicks: 6500,
+ conversions: 500,
+ cost: 3200,
+ revenue: 10000,
+ roi: 213,
+ ctr: 16.3,
+ cpc: 0.49,
+ cpa: 6.4,
+ reach: 36000,
+ engagement: 5200,
+ shares: 95,
+ saves: 65,
+ comments: 220,
+ videoViews: 1800,
+ },
+ {
+ channel: "Brand Sentiment and Public Relations Impact",
+ impressions: 55000,
+ clicks: 8000,
+ conversions: 650,
+ cost: 4100,
+ revenue: 13000,
+ roi: 217,
+ ctr: 14.5,
+ cpc: 0.51,
+ cpa: 6.31,
+ reach: 48000,
+ engagement: 6800,
+ shares: 520,
+ saves: 280,
+ comments: 950,
+ videoViews: 15000,
+ },
+ ],
+};
+
+// Category key mappings for different datasets
+const categoryKeys = {
+ default: "month",
+ bigLabels: "category",
+ denseTimeline: "period",
+ companyNames: "company",
+ countryData: "country",
+ financialQuarters: "quarter",
+ mixedLengths: "item",
+ edgeCases: "name",
+ minimal: "category",
+ expandCollapseMarketing: "channel",
+};
+
+// 🔥 ACTIVE DATA - For backward compatibility
+const areaChartData = dataVariations.default;
+
+const icons = {
+ desktop: Monitor,
+ mobile: TabletSmartphone,
+ tablet: Calendar,
+ sales: Globe,
+ revenue: Smartphone,
+ profit: Laptop,
+ visitors: Tv,
+ conversions: Watch,
+ users: Monitor,
+ sessions: TabletSmartphone,
+} as const;
+
+/**
+ * # ScrollableAreaChart Component Documentation
+ *
+ * The AreaChart is excellent for visualizing quantitative data and showing the volume of a metric over a progression.
+ * It's ideal for:
+ *
+ * - **Time-Series Analysis**: Showing how a value or volume changes over time.
+ * - **Showing Volume**: Emphasizing the magnitude of a value.
+ * - **Comparing Trends**: Stacking areas to show how different series contribute to a total.
+ *
+ * ## Key Features
+ *
+ * ### Advanced Label Handling
+ * - **Collision Detection**: Prevents X-axis labels from overlapping.
+ * - **Intelligent Truncation**: Automatically shortens long labels with an ellipsis (...).
+ * - **Horizontal Offset**: Ensures labels are correctly positioned for maximum readability.
+ *
+ * ### Interactive & Responsive
+ * - **Interactive Legend**: Toggle data series visibility. It gracefully handles overflow with a "Show More" feature.
+ * - **Hover Tooltips**: Choose between a standard tooltip or a floating one that follows the cursor.
+ * - **Responsive Design**: Adapts fluidly to its container's size.
+ *
+ * ### Customization
+ * - **Theming**: Comes with six pre-built color palettes.
+ * - **Area Styles**: Supports `linear`, `natural` (smooth), and `step` interpolation.
+ * - **Styling Options**: Control grid visibility, axes, and more.
+ */
+const meta: Meta<AreaChartProps<typeof areaChartData>> = {
+ title: "Components/D3Charts/ScrollableAreaChart",
+ component: AreaChart,
+ parameters: {
+ layout: "centered",
+ docs: {
+ description: {
+ component: `
+## Installation and Basic Usage
+
+\`\`\`tsx
+import { ScrollableAreaChart } from '@openuidev/react-ui';
+
+const trafficData = [
+ { date: "2023-01-01", visits: 2200 },
+ { date: "2023-01-02", visits: 2500 },
+ { date: "2023-01-03", visits: 2300 },
+];
+
+// Basic implementation
+<ScrollableAreaChart
+ data={trafficData}
+ categoryKey="date"
+ theme="ocean"
+/>
+\`\`\`
+
+## Data Structure Requirements
+
+Your data should be an array of objects. Each object must contain:
+- A **category field** (string or number): This will be used for the X-axis labels (e.g., dates, names, etc.).
+- One or more **data series fields** (number): These are the values that will be plotted on the Y-axis. The key of the field will be used as the series name in the legend and tooltip.
+
+\`\`\`tsx
+const salesData = [
+ { month: "January", desktop: 150, mobile: 90 },
+ { month: "February", desktop: 280, mobile: 180 },
+ { month: "March", desktop: 220, mobile: 140 },
+];
+\`\`\`
+
+## Performance Considerations
+- **Data Density**: For very large datasets, consider disabling animations to maintain smooth performance.
+- **Responsiveness**: The chart is fully responsive, but test label visibility on very small screens.
+- **Animation**: Controlled via \`isAnimationActive={false}\`.
+`,
+ },
+ },
+ },
+ tags: ["!dev", "autodocs"],
+ argTypes: {
+ data: {
+ description: `
+**Required.** An array of data objects for the area chart. Each object should contain:
+- A category identifier (string/number) for the X-axis.
+- One or more numeric values for the Y-axis.
+`,
+ control: false,
+ table: {
+ type: { summary: "Array<Record<string, string | number>>" },
+ category: "📊 Data Configuration",
+ },
+ },
+ categoryKey: {
+ description:
+ "**Required.** The key in your data object that represents the category for the X-axis.",
+ control: false,
+ table: {
+ type: { summary: "string" },
+ category: "📊 Data Configuration",
+ },
+ },
+ theme: {
+ description:
+ "Specifies the color palette for the chart's areas, tooltips, and legend. Ignored when customPalette is provided.",
+ control: "select",
+ options: ["ocean", "orchid", "emerald", "sunset", "spectrum", "vivid"],
+ table: {
+ defaultValue: { summary: "ocean" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ customPalette: {
+ description:
+ "Custom array of colors to use instead of the theme palette. Overrides the theme prop when provided.",
+ control: "object",
+ table: {
+ type: { summary: "string[]" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ variant: {
+ description: "Determines the area interpolation method, affecting the shape of the curves.",
+ control: "radio",
+ options: ["linear", "natural", "step"],
+ table: {
+ defaultValue: { summary: "natural" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ icons: {
+ description:
+ "An object mapping data series keys to React components to be used as icons in the legend.",
+ control: false,
+ table: {
+ type: { summary: "Record<string, React.ReactNode>" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ grid: {
+ description: "Toggles the visibility of the background grid lines.",
+ control: "boolean",
+ table: {
+ defaultValue: { summary: "true" },
+ category: "📱 Display Options",
+ },
+ },
+ legend: {
+ description: "Toggles the visibility of the chart legend.",
+ control: "boolean",
+ table: {
+ defaultValue: { summary: "true" },
+ category: "📱 Display Options",
+ },
+ },
+ showYAxis: {
+ description: "Toggles the visibility of the Y-axis line and labels.",
+ control: "boolean",
+ table: {
+ defaultValue: { summary: "true" },
+ category: "📱 Display Options",
+ },
+ },
+ xAxisLabel: {
+ description: "A label to display below the X-axis.",
+ control: "text",
+ table: {
+ type: { summary: "React.ReactNode" },
+ category: "📱 Display Options",
+ },
+ },
+ yAxisLabel: {
+ description: "A label to display beside the Y-axis.",
+ control: "text",
+ table: {
+ type: { summary: "React.ReactNode" },
+ category: "📱 Display Options",
+ },
+ },
+ isAnimationActive: {
+ description: "Enables or disables the initial loading animation for the areas.",
+ control: "boolean",
+ table: {
+ defaultValue: { summary: "true" },
+ category: "🎬 Animation & Interaction",
+ },
+ },
+ height: {
+ description: "Sets a fixed height for the chart container in pixels.",
+ control: "number",
+ table: {
+ type: { summary: "number" },
+ category: "Layout & Sizing",
+ },
+ },
+ width: {
+ description: "Sets a fixed width for the chart container in pixels.",
+ control: "number",
+ table: {
+ type: { summary: "number" },
+ category: "Layout & Sizing",
+ },
+ },
+ className: {
+ description: "Custom CSS class to apply to the chart's container.",
+ control: "text",
+ table: {
+ type: { summary: "string" },
+ category: "Layout & Sizing",
+ },
+ },
+ },
+} satisfies Meta<typeof AreaChart>;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+/**
+ * ## Comprehensive Data Explorer
+ *
+ * This story serves as a comprehensive test suite for the AreaChart component.
+ * Use the buttons to switch between various datasets designed to test edge cases in:
+ *
+ * - **Label Collision**: Datasets with long, dense, or overlapping labels.
+ * - **Data Density**: Scenarios with few or many data points.
+ * - **Legend Overflow**: A dataset with many series to test legend expand/collapse functionality.
+ *
+ * It's an excellent tool for developers to see how the chart behaves under different conditions.
+ */
+export const DataExplorer: Story = {
+ name: "🎛️ Comprehensive Data Explorer",
+ args: {
+ data: areaChartData,
+ categoryKey: "month",
+ theme: "ocean",
+ variant: "natural",
+ grid: true,
+ legend: true,
+ isAnimationActive: true,
+ showYAxis: true,
+ xAxisLabel: "Time Period",
+ yAxisLabel: "Values",
+ // height: 300,
+ },
+ render: (args: any) => {
+ const [selectedDataType, setSelectedDataType] =
+ useState<keyof typeof dataVariations>("default");
+
+ const currentData = dataVariations[selectedDataType];
+ const currentCategoryKey = categoryKeys[selectedDataType];
+
+ const buttonStyle = {
+ margin: "2px",
+ padding: "6px 12px",
+ fontSize: "12px",
+ border: "1px solid #ddd",
+ borderRadius: "4px",
+ cursor: "pointer",
+ background: "#fff",
+ fontFamily: "monospace",
+ };
+
+ const activeButtonStyle = {
+ ...buttonStyle,
+ background: "#007acc",
+ color: "white",
+ border: "1px solid #007acc",
+ };
+
+ return (
+ <div>
+ <div
+ style={{
+ marginBottom: "16px",
+ padding: "12px",
+ background: "#f8f9fa",
+ borderRadius: "8px",
+ border: "1px solid #e9ecef",
+ width: "600px",
+ }}
+ >
+ <strong>🏷️ Label Collision Test Suite:</strong>
+ <div style={{ marginTop: "8px", display: "flex", flexWrap: "wrap", gap: "4px" }}>
+ <button
+ onClick={() => setSelectedDataType("default")}
+ style={selectedDataType === "default" ? activeButtonStyle : buttonStyle}
+ >
+ 📅 Default (12 months)
+ </button>
+ <button
+ onClick={() => setSelectedDataType("bigLabels")}
+ style={selectedDataType === "bigLabels" ? activeButtonStyle : buttonStyle}
+ >
+ 🏷️ Big Labels (Collision Test)
+ </button>
+ <button
+ onClick={() => setSelectedDataType("denseTimeline")}
+ style={selectedDataType === "denseTimeline" ? activeButtonStyle : buttonStyle}
+ >
+ 📅 Dense Timeline (16 periods)
+ </button>
+ <button
+ onClick={() => setSelectedDataType("companyNames")}
+ style={selectedDataType === "companyNames" ? activeButtonStyle : buttonStyle}
+ >
+ 🏢 Company Names
+ </button>
+ <button
+ onClick={() => setSelectedDataType("countryData")}
+ style={selectedDataType === "countryData" ? activeButtonStyle : buttonStyle}
+ >
+ 🌍 Country Names
+ </button>
+ <button
+ onClick={() => setSelectedDataType("financialQuarters")}
+ style={selectedDataType === "financialQuarters" ? activeButtonStyle : buttonStyle}
+ >
+ 📈 Financial Quarters
+ </button>
+ <button
+ onClick={() => setSelectedDataType("mixedLengths")}
+ style={selectedDataType === "mixedLengths" ? activeButtonStyle : buttonStyle}
+ >
+ 🔤 Mixed Lengths
+ </button>
+ <button
+ onClick={() => setSelectedDataType("edgeCases")}
+ style={selectedDataType === "edgeCases" ? activeButtonStyle : buttonStyle}
+ >
+ 🎯 Edge Cases
+ </button>
+ <button
+ onClick={() => setSelectedDataType("minimal")}
+ style={selectedDataType === "minimal" ? activeButtonStyle : buttonStyle}
+ >
+ 📱 Minimal (3 items)
+ </button>
+ <button
+ onClick={() => setSelectedDataType("expandCollapseMarketing")}
+ style={
+ selectedDataType === "expandCollapseMarketing" ? activeButtonStyle : buttonStyle
+ }
+ >
+ 🔄 Marketing Channels (12 items)
+ </button>
+ </div>
+ <div
+ style={{ marginTop: "12px", fontSize: "12px", color: "#666", fontFamily: "monospace" }}
+ >
+ <div>
+ <strong>Current Dataset:</strong> {selectedDataType}
+ </div>
+ <div>
+ <strong>Items:</strong> {currentData.length} | <strong>Category Key:</strong>{" "}
+ {currentCategoryKey}
+ </div>
+ <div>
+ <strong>Features:</strong> Auto-truncation, Collision Detection, Horizontal Offset
+ </div>
+ </div>
+ </div>
+ <Card style={{ width: "600px" }}>
+ <AreaChart {...args} data={currentData} categoryKey={currentCategoryKey} />
+ </Card>
+ </div>
+ );
+ },
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "**🏷️ Big Labels Focus:** This story specifically tests label collision detection and truncation scenarios. Use the buttons to switch between different data variations that stress-test the chart's ability to handle long category names.\n\n**Key Features:**\n- ✂️ **Auto-truncation** with ellipsis for long labels\n- 🔍 **Collision detection** prevents overlapping text\n- ↔️ **Horizontal offset** for better visual distribution\n- 🚫 **No angle rotation** - labels stay horizontal for readability\n\n**Test Cases:**\n- **Big Labels**: Extremely long category names that trigger truncation\n- **Dense Timeline**: Many items with medium-length labels\n- **Company Names**: Real-world business names with varying lengths\n- **Mixed Lengths**: Combination of short and long labels\n- **Edge Cases**: Extreme scenarios for boundary testing",
+ },
+ },
+ },
+};
+
+/**
+ * ## Big Labels
+ *
+ * This story demonstrates the chart's ability to handle very long category labels.
+ * The chart's intelligent truncation and collision detection should be visible here.
+ * X-axis labels that are too long to fit will be gracefully truncated with an ellipsis.
+ */
+export const BigLabelsStory: Story = {
+ name: "🏷️ Big Labels (Collision Detection)",
+ args: {
+ data: dataVariations.bigLabels as any,
+ categoryKey: "category" as any,
+ theme: "emerald",
+ variant: "natural",
+ grid: true,
+ legend: true,
+ isAnimationActive: true,
+ showYAxis: true,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "700px" }}>
+ <AreaChart {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests the chart's collision detection system with extremely long category names. Labels should be automatically truncated with ellipsis (...) to prevent overlapping.",
+ },
+ },
+ },
+};
+
+/**
+ * ## Dense Timeline
+ *
+ * Tests how the chart handles many data points with medium-length period labels.
+ * The chart should enable horizontal scrolling and apply intelligent label truncation.
+ * This scenario is common in financial or analytical dashboards where many time periods are displayed.
+ */
+export const DenseTimelineStory: Story = {
+ name: "📅 Dense Timeline (Many Periods)",
+ args: {
+ data: dataVariations.denseTimeline as any,
+ categoryKey: "period" as any,
+ theme: "sunset",
+ variant: "natural",
+ grid: true,
+ legend: true,
+ isAnimationActive: true,
+ showYAxis: true,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "500px" }}>
+ <AreaChart {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests how the chart handles many data points with medium-length period labels. The chart should enable horizontal scrolling and apply intelligent label truncation.",
+ },
+ },
+ },
+};
+
+/**
+ * ## Company Names
+ *
+ * This story tests the chart with real-world company names that have varying lengths.
+ * It demonstrates how the chart handles business data with naturally occurring long labels.
+ */
+export const CompanyNamesStory: Story = {
+ name: "🏢 Company Names (Real-world Labels)",
+ args: {
+ data: dataVariations.companyNames as any,
+ categoryKey: "company" as any,
+ theme: "vivid",
+ variant: "natural",
+ grid: true,
+ legend: true,
+ isAnimationActive: true,
+ showYAxis: true,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "700px" }}>
+ <AreaChart {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests with real-world company names that have varying lengths. Demonstrates how the chart handles business data with naturally occurring long labels.",
+ },
+ },
+ },
+};
+
+/**
+ * ## Country Names
+ *
+ * This story tests the chart with official country names, which are often long.
+ * It shows how geographic data is handled by the label collision detection system.
+ */
+export const CountryDataStory: Story = {
+ name: "🌍 Country Names (Geographic Labels)",
+ args: {
+ data: dataVariations.countryData as any,
+ categoryKey: "country" as any,
+ theme: "orchid",
+ variant: "natural",
+ grid: true,
+ legend: true,
+ isAnimationActive: true,
+ showYAxis: true,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "600px" }}>
+ <AreaChart {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests with official country names that include full formal names. Shows how geographic data with naturally long names is handled by the collision detection system.",
+ },
+ },
+ },
+};
+
+/**
+ * ## Mixed Lengths
+ *
+ * This story tests the chart's ability to handle a mix of very short and very long labels
+ * within the same dataset, demonstrating its adaptive truncation behavior.
+ */
+export const MixedLengthsStory: Story = {
+ name: "🔤 Mixed Lengths (Varied Label Sizes)",
+ args: {
+ data: dataVariations.mixedLengths as any,
+ categoryKey: "item" as any,
+ theme: "spectrum",
+ variant: "linear",
+ grid: true,
+ legend: true,
+ isAnimationActive: true,
+ showYAxis: true,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "500px" }}>
+ <AreaChart {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests the chart's ability to handle a mix of very short and very long labels within the same dataset. Demonstrates adaptive truncation behavior.",
+ },
+ },
+ },
+};
+
+/**
+ * ## Edge Cases
+ *
+ * This story pushes the collision detection and truncation system to its limits
+ * with exceptionally long labels and minimal data points.
+ */
+export const EdgeCasesStory: Story = {
+ name: "🎯 Edge Cases (Extreme Scenarios)",
+ args: {
+ data: dataVariations.edgeCases as any,
+ categoryKey: "name" as any,
+ theme: "ocean",
+ variant: "step",
+ grid: true,
+ legend: true,
+ isAnimationActive: true,
+ showYAxis: true,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "400px" }}>
+ <AreaChart {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests extreme edge cases with exceptionally long labels and minimal data points. Pushes the collision detection and truncation system to its limits.",
+ },
+ },
+ },
+};
+
+/**
+ * ## Minimal Data
+ *
+ * A baseline test with a small dataset and standard-length labels. This serves as a control
+ * case to compare against the more complex label scenarios.
+ */
+export const MinimalDataStory: Story = {
+ name: "📱 Minimal Data (Baseline)",
+ args: {
+ data: dataVariations.minimal as any,
+ categoryKey: "category" as any,
+ theme: "emerald",
+ variant: "natural",
+ grid: true,
+ legend: true,
+ isAnimationActive: true,
+ showYAxis: true,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "400px" }}>
+ <AreaChart {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Baseline test with minimal data and standard-length labels. Provides a control case to compare against the big label scenarios.",
+ },
+ },
+ },
+};
+
+/**
+ * ## Legend Expand/Collapse
+ *
+ * Tests the legend's expand/collapse functionality with a large number of data series.
+ * The legend should automatically show a "Show More" button when items overflow,
+ * allowing users to toggle between a collapsed and expanded view.
+ */
+export const ExpandCollapseMarketingStory: Story = {
+ name: "🔄 Legend Expand/Collapse",
+ args: {
+ data: dataVariations.expandCollapseMarketing as any,
+ categoryKey: "channel" as any,
+ theme: "vivid",
+ variant: "natural",
+ grid: true,
+ legend: true,
+ isAnimationActive: true,
+ showYAxis: true,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "600px" }}>
+ <AreaChart {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests the legend expand/collapse functionality with 12 marketing channels that have long descriptive names. The legend should automatically show a 'Show More' button when items overflow the container width, allowing users to toggle between collapsed and expanded states.",
+ },
+ },
+ },
+};
+
+/**
+ * ## Custom Palette
+ *
+ * This story demonstrates how to use the customPalette prop to provide your own color scheme
+ * for the chart. This is useful when you need to match your brand colors or create
+ * specific visual themes.
+ */
+
+export const CustomPaletteStory: Story = {
+ name: "🎨 Custom Palette",
+ args: {
+ data: dataVariations.default as any,
+ categoryKey: "month" as any,
+ theme: "ocean", // This will be overridden by customPalette
+ variant: "natural",
+ grid: true,
+ legend: true,
+ isAnimationActive: true,
+ showYAxis: true,
+ xAxisLabel: "Month",
+ yAxisLabel: "Traffic",
+ },
+ render: (args: any) => (
+ <div>
+ <div
+ style={{
+ marginBottom: "16px",
+ padding: "12px",
+ background: "#f8f9fa",
+ borderRadius: "8px",
+ border: "1px solid #e9ecef",
+ }}
+ >
+ <h4 style={{ margin: "0 0 8px 0", color: "#333" }}>🎨 Custom Color Palette</h4>
+ <p style={{ margin: "0 0 12px 0", fontSize: "14px", color: "#666" }}>
+ This chart uses a custom color palette instead of the default theme colors.
+ </p>
+ <div style={{ display: "flex", gap: "8px", flexWrap: "wrap" }}>
+ {args.customPalette?.map((color: string, index: number) => (
+ <div
+ key={index}
+ style={{
+ display: "flex",
+ alignItems: "center",
+ gap: "4px",
+ padding: "4px 8px",
+ background: "white",
+ borderRadius: "4px",
+ border: "1px solid #ddd",
+ fontSize: "12px",
+ }}
+ >
+ <div
+ style={{
+ width: "12px",
+ height: "12px",
+ borderRadius: "2px",
+ backgroundColor: color,
+ border: "1px solid #ccc",
+ }}
+ />
+ <span style={{ fontFamily: "monospace" }}>{color}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ <Card style={{ width: "600px" }}>
+ <AreaChart {...args} />
+ </Card>
+ </div>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'Demonstrates how to use the `customPalette` prop to provide your own color scheme for the chart. When `customPalette` is provided, it overrides the `theme` prop and uses your specified colors instead of the predefined theme palettes.\n\n**Key Features:**\n- 🎨 **Custom Colors**: Override default theme colors with your own palette\n- 🔄 **Theme Override**: The `theme` prop is ignored when `customPalette` is provided\n- 📊 **Consistent Distribution**: Colors are distributed evenly across data series\n- 🎯 **Brand Matching**: Perfect for matching your application\'s brand colors\n\n**Usage:**\n```tsx\n<AreaChart\n data={data}\n categoryKey="month"\n customPalette={["#FF6B6B", "#4ECDC4", "#45B7D1"]}\n // theme prop is ignored when customPalette is provided\n/>\n```',
+ },
+ },
+ },
+};
+
+/**
+ * ## Responsive Behavior Demo
+ *
+ * This story demonstrates the responsive capabilities of the AreaChart. Drag the handles
+ * on the container to resize it and observe how the chart adapts.
+ *
+ * **Responsive Features:**
+ * - **Label Truncation**: More aggressive truncation on smaller container widths.
+ * - **Layout Adaptation**: Chart elements adjust to fit the available space.
+ * - **Legend Behavior**: The legend may wrap or show expand/collapse buttons as needed.
+ */
+export const ResponsiveBehaviorDemo: Story = {
+ name: "📱 Responsive Behavior Demo",
+ args: {
+ data: dataVariations.bigLabels as any,
+ categoryKey: "category" as any,
+ theme: "sunset",
+ variant: "natural",
+ grid: true,
+ legend: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ },
+ render: (args: any) => {
+ const [dimensions, setDimensions] = useState<{ width: number; height: number | string }>({
+ width: 700,
+ height: "auto",
+ });
+
+ const handleMouseDown = (e: React.MouseEvent<HTMLDivElement>, handle: string) => {
+ e.preventDefault();
+ e.stopPropagation();
+ const startX = e.clientX;
+ const startY = e.clientY;
+ const startWidth = dimensions.width;
+ const startHeight = (e.currentTarget.parentElement as HTMLElement).offsetHeight;
+
+ const doDrag = (e: MouseEvent) => {
+ const dx = e.clientX - startX;
+ const dy = e.clientY - startY;
+ let newWidth = startWidth;
+ let newHeight = startHeight;
+
+ if (handle.includes("e")) newWidth = startWidth + dx;
+ if (handle.includes("w")) newWidth = startWidth - dx;
+ if (handle.includes("s")) newHeight = startHeight + dy;
+ if (handle.includes("n")) newHeight = startHeight - dy;
+
+ setDimensions({
+ width: Math.max(300, newWidth),
+ height: "auto",
+ });
+ };
+
+ const stopDrag = () => {
+ document.removeEventListener("mousemove", doDrag);
+ document.removeEventListener("mouseup", stopDrag);
+ };
+
+ document.addEventListener("mousemove", doDrag);
+ document.addEventListener("mouseup", stopDrag);
+ };
+
+ const handleStyle: React.CSSProperties = {
+ position: "absolute",
+ background: "#3b82f6",
+ opacity: 0.6,
+ zIndex: 10,
+ transition: "opacity 0.2s ease",
+ };
+
+ return (
+ <div style={{ padding: "20px" }}>
+ <div style={{ marginBottom: "20px" }}>
+ <h3 style={{ margin: "0 0 8px 0", fontSize: "18px", fontWeight: "600" }}>
+ Responsive Behavior Demonstration
+ </h3>
+ <p style={{ margin: "0 0 12px 0", color: "#666", fontSize: "14px" }}>
+ Drag the edges or corners of the container below to see how the chart adapts
+ </p>
+ <div
+ style={{
+ padding: "12px",
+ backgroundColor: "#e3f2fd",
+ borderRadius: "6px",
+ fontSize: "12px",
+ color: "#1565c0",
+ }}
+ >
+ <strong>🎯 Try This:</strong> Resize the container to see automatic label truncation and
+ layout adjustments.
+ </div>
+ </div>
+
+ <Card
+ style={{
+ position: "relative",
+ width: `${dimensions.width}px`,
+ height:
+ typeof dimensions.height === "number" ? `${dimensions.height}px` : dimensions.height,
+ border: "2px dashed #9ca3af",
+ padding: "20px",
+ boxSizing: "border-box",
+ overflow: "hidden",
+ cursor: "default",
+ }}
+ >
+ <AreaChart {...args} />
+
+ {/* Resize Handles */}
+ <div
+ style={{ ...handleStyle, top: -2, left: 0, right: 0, height: 12, cursor: "ns-resize" }}
+ onMouseDown={(e) => handleMouseDown(e, "n")}
+ />
+ <div
+ style={{
+ ...handleStyle,
+ bottom: -2,
+ left: 0,
+ right: 0,
+ height: 12,
+ cursor: "ns-resize",
+ }}
+ onMouseDown={(e) => handleMouseDown(e, "s")}
+ />
+ <div
+ style={{ ...handleStyle, top: 0, bottom: 0, left: -2, width: 12, cursor: "ew-resize" }}
+ onMouseDown={(e) => handleMouseDown(e, "w")}
+ />
+ <div
+ style={{ ...handleStyle, top: 0, bottom: 0, right: -2, width: 12, cursor: "ew-resize" }}
+ onMouseDown={(e) => handleMouseDown(e, "e")}
+ />
+
+ {/* Corner Handles */}
+ <div
+ style={{
+ ...handleStyle,
+ top: -2,
+ left: -2,
+ width: 20,
+ height: 20,
+ cursor: "nwse-resize",
+ borderRadius: "2px",
+ }}
+ onMouseDown={(e) => handleMouseDown(e, "nw")}
+ />
+ <div
+ style={{
+ ...handleStyle,
+ top: -2,
+ right: -2,
+ width: 20,
+ height: 20,
+ cursor: "nesw-resize",
+ borderRadius: "2px",
+ }}
+ onMouseDown={(e) => handleMouseDown(e, "ne")}
+ />
+ <div
+ style={{
+ ...handleStyle,
+ bottom: -2,
+ right: -2,
+ width: 20,
+ height: 20,
+ cursor: "nwse-resize",
+ borderRadius: "2px",
+ }}
+ onMouseDown={(e) => handleMouseDown(e, "se")}
+ />
+
+ {/* Dimension Display */}
+ <div
+ style={{
+ position: "absolute",
+ bottom: 8,
+ right: 8,
+ background: "rgba(0,0,0,0.8)",
+ color: "white",
+ padding: "4px 8px",
+ borderRadius: "4px",
+ fontSize: "11px",
+ fontFamily: "monospace",
+ fontWeight: "500",
+ }}
+ >
+ {dimensions.width}px ×{" "}
+ {typeof dimensions.height === "number" ? `${dimensions.height}px` : "auto"}
+ </div>
+ </Card>
+ </div>
+ );
+ },
+};
diff --git a/packages/react-ui/src/components/D3Charts/AreaChart/stories/areaChartCondensed.stories.tsx b/packages/react-ui/src/components/D3Charts/AreaChart/stories/areaChartCondensed.stories.tsx
new file mode 100644
index 000000000..3a064e0c6
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/AreaChart/stories/areaChartCondensed.stories.tsx
@@ -0,0 +1,1422 @@
+// Copy of Charts/AreaChartCondensed/stories/areaChartCondensed.stories.tsx with only the chart import and the title changed:
+// the same args and renders, rendering the D3Charts chart via
+// ../../stories/rechartsStoryAdapters.
+import type { Meta, StoryObj } from "@storybook/react";
+import {
+ Calendar,
+ Globe,
+ Laptop,
+ Monitor,
+ Smartphone,
+ TabletSmartphone,
+ Tv,
+ Watch,
+} from "lucide-react";
+import { useState } from "react";
+import { Card } from "../../../Card";
+import { AreaChartCondensed, AreaChartCondensedProps } from "../../stories/rechartsStoryAdapters";
+
+// 🔥 COMPREHENSIVE DATA VARIATIONS - Designed to test various scenarios
+const dataVariations = {
+ default: [
+ { month: "January", desktop: 150, mobile: 90, tablet: 120 },
+ { month: "February", desktop: 280, mobile: 180, tablet: 140 },
+ { month: "March", desktop: 220, mobile: 140, tablet: 160 },
+ { month: "April", desktop: 180, mobile: 160, tablet: 180 },
+ { month: "May", desktop: 250, mobile: 120, tablet: 140 },
+ { month: "June", desktop: 300, mobile: 180, tablet: 160 },
+ { month: "July", desktop: 350, mobile: 220, tablet: 180 },
+ { month: "August", desktop: 400, mobile: 240, tablet: 200 },
+ { month: "September", desktop: 450, mobile: 260, tablet: 220 },
+ { month: "October", desktop: 500, mobile: 280, tablet: 240 },
+ { month: "November", desktop: 550, mobile: 300, tablet: 260 },
+ { month: "December", desktop: 600, mobile: 320, tablet: 280 },
+ ],
+ // 🏷️ BIG LABELS - Testing angled tick labels
+ bigLabels: [
+ {
+ category: "Very Long Category Name That Should Be Truncated",
+ sales: 150,
+ revenue: 90,
+ profit: 120,
+ },
+ {
+ category: "Another Extremely Long Label That Causes Collisions",
+ sales: 280,
+ revenue: 180,
+ profit: 140,
+ },
+ {
+ category: "Super Duper Long Category Name That Tests Truncation",
+ sales: 220,
+ revenue: 140,
+ profit: 160,
+ },
+ {
+ category: "Incredibly Long Text That Should Trigger Collision Detection",
+ sales: 180,
+ revenue: 160,
+ profit: 180,
+ },
+ {
+ category: "Maximum Length Category Name That Tests All Edge Cases",
+ sales: 250,
+ revenue: 120,
+ profit: 140,
+ },
+ {
+ category: "Extra Long Business Category Name With Many Words",
+ sales: 300,
+ revenue: 180,
+ profit: 160,
+ },
+ {
+ category: "Comprehensive Long Label For Testing Horizontal Offset",
+ sales: 350,
+ revenue: 220,
+ profit: 180,
+ },
+ {
+ category: "Extended Category Name That Pushes Truncation Limits",
+ sales: 400,
+ revenue: 240,
+ profit: 200,
+ },
+ ],
+ // 📅 DENSE TIMELINE - Many items with medium-length labels
+ denseTimeline: [
+ { period: "Q1 2022 Jan-Mar", visitors: 120, conversions: 15, revenue: 1200 },
+ { period: "Q1 2022 Apr-Jun", visitors: 150, conversions: 22, revenue: 1800 },
+ { period: "Q2 2022 Jul-Sep", visitors: 180, conversions: 28, revenue: 2100 },
+ { period: "Q2 2022 Oct-Dec", visitors: 200, conversions: 35, revenue: 2500 },
+ { period: "Q3 2023 Jan-Mar", visitors: 160, conversions: 18, revenue: 1600 },
+ { period: "Q3 2023 Apr-Jun", visitors: 190, conversions: 32, revenue: 2300 },
+ { period: "Q4 2023 Jul-Sep", visitors: 220, conversions: 40, revenue: 2800 },
+ { period: "Q4 2023 Oct-Dec", visitors: 240, conversions: 45, revenue: 3200 },
+ { period: "Q1 2024 Jan-Mar", visitors: 210, conversions: 38, revenue: 2700 },
+ { period: "Q1 2024 Apr-Jun", visitors: 230, conversions: 42, revenue: 3000 },
+ { period: "Q2 2024 Jul-Sep", visitors: 250, conversions: 48, revenue: 3400 },
+ { period: "Q2 2024 Oct-Dec", visitors: 270, conversions: 52, revenue: 3800 },
+ { period: "Q3 2024 Jan-Mar", visitors: 260, conversions: 50, revenue: 3600 },
+ { period: "Q3 2024 Apr-Jun", visitors: 280, conversions: 55, revenue: 4000 },
+ { period: "Q4 2024 Jul-Sep", visitors: 300, conversions: 60, revenue: 4300 },
+ { period: "Q4 2024 Oct-Dec", visitors: 290, conversions: 58, revenue: 4100 },
+ ],
+ // 🏢 COMPANY NAMES - Real-world long business names
+ companyNames: [
+ { company: "Apple Inc.", revenue: 394328000000, profit: 99803000000, marketCap: 3500000000000 },
+ {
+ company: "Microsoft Corporation",
+ revenue: 211915000000,
+ profit: 83383000000,
+ marketCap: 2800000000000,
+ },
+ {
+ company: "Alphabet Inc. (Google)",
+ revenue: 307394000000,
+ profit: 76033000000,
+ marketCap: 2100000000000,
+ },
+ {
+ company: "Amazon.com Inc.",
+ revenue: 574785000000,
+ profit: 33364000000,
+ marketCap: 1600000000000,
+ },
+ {
+ company: "Tesla Motors Inc.",
+ revenue: 96773000000,
+ profit: 15000000000,
+ marketCap: 800000000000,
+ },
+ {
+ company: "Meta Platforms Inc.",
+ revenue: 134902000000,
+ profit: 39370000000,
+ marketCap: 900000000000,
+ },
+ {
+ company: "NVIDIA Corporation",
+ revenue: 60922000000,
+ profit: 29760000000,
+ marketCap: 1800000000000,
+ },
+ {
+ company: "Berkshire Hathaway Inc.",
+ revenue: 364482000000,
+ profit: 96223000000,
+ marketCap: 780000000000,
+ },
+ ],
+ // 🌍 COUNTRY NAMES - Geographic labels with varying lengths
+ countryData: [
+ { country: "United States of America", population: 331900000, gdp: 26900000000000 },
+ { country: "People's Republic of China", population: 1412000000, gdp: 17700000000000 },
+ { country: "Federal Republic of Germany", population: 83200000, gdp: 4300000000000 },
+ { country: "United Kingdom of Great Britain", population: 67500000, gdp: 3100000000000 },
+ { country: "French Republic", population: 68000000, gdp: 2900000000000 },
+ { country: "Republic of India", population: 1380000000, gdp: 3700000000000 },
+ { country: "Federative Republic of Brazil", population: 215000000, gdp: 2100000000000 },
+ { country: "Russian Federation", population: 146000000, gdp: 1800000000000 },
+ ],
+ // 📈 FINANCIAL QUARTERS - Testing medium-density scenarios
+ financialQuarters: [
+ { quarter: "Q1 FY2022", revenue: 1200000, expenses: 800000, profit: 400000 },
+ { quarter: "Q2 FY2022", revenue: 1500000, expenses: 950000, profit: 550000 },
+ { quarter: "Q3 FY2022", revenue: 1800000, expenses: 1100000, profit: 700000 },
+ { quarter: "Q4 FY2022", revenue: 2000000, expenses: 1300000, profit: 700000 },
+ { quarter: "Q1 FY2023", revenue: 2200000, expenses: 1400000, profit: 800000 },
+ { quarter: "Q2 FY2023", revenue: 2500000, expenses: 1600000, profit: 900000 },
+ { quarter: "Q3 FY2023", revenue: 2800000, expenses: 1800000, profit: 1000000 },
+ { quarter: "Q4 FY2023", revenue: 3000000, expenses: 1900000, profit: 1100000 },
+ ],
+ // 🔤 MIXED LENGTHS - Testing various label length scenarios
+ mixedLengths: [
+ { item: "A", valueA: 100, valueB: 80 },
+ { item: "Short", valueA: 150, valueB: 120 },
+ { item: "Medium Length Item", valueA: 200, valueB: 160 },
+ { item: "Very Long Item Name That Tests Truncation", valueA: 250, valueB: 200 },
+ { item: "B", valueA: 180, valueB: 140 },
+ { item: "Another Really Long Category Name", valueA: 220, valueB: 180 },
+ { item: "XL", valueA: 190, valueB: 150 },
+ ],
+ // 🎯 EDGE CASES - Extreme scenarios
+ edgeCases: [
+ {
+ name: "SinglePointDataSetForTestingEdgeCasesInCollisionDetectionAndLabelTruncationFunctionality",
+ value: 500,
+ },
+ {
+ name: "SecondExtremelyLongDataPointNameThatShouldDefinitelyTriggerTruncationMechanisms",
+ value: 600,
+ },
+ ],
+ // 📱 MINIMAL - Small dataset for baseline testing
+ minimal: [
+ { category: "Mobile Devices", users: 150, sessions: 90 },
+ { category: "Desktop Computers", users: 280, sessions: 180 },
+ { category: "Tablet Devices", users: 220, sessions: 140 },
+ ],
+};
+
+// Category key mappings for different datasets
+const categoryKeys = {
+ default: "month",
+ bigLabels: "category",
+ denseTimeline: "period",
+ companyNames: "company",
+ countryData: "country",
+ financialQuarters: "quarter",
+ mixedLengths: "item",
+ edgeCases: "name",
+ minimal: "category",
+};
+
+// 🔥 ACTIVE DATA - For backward compatibility
+const areaChartCondensedData = dataVariations.default;
+
+const icons = {
+ desktop: Monitor,
+ mobile: TabletSmartphone,
+ tablet: Calendar,
+ sales: Globe,
+ revenue: Smartphone,
+ profit: Laptop,
+ visitors: Tv,
+ conversions: Watch,
+ users: Monitor,
+ sessions: TabletSmartphone,
+ expenses: Calendar,
+ marketCap: Globe,
+ population: Monitor,
+ gdp: Smartphone,
+ valueA: Monitor,
+ valueB: TabletSmartphone,
+ value: Calendar,
+} as const;
+
+/**
+ * # AreaChart Component Documentation
+ *
+ * The AreaChart is a compact chart designed for space-constrained layouts
+ * like dashboards and sidebars. It's ideal for:
+ *
+ * - **Compact Dashboards**: Showing multiple metrics in limited space
+ * - **Sidebar Analytics**: Quick trend visualization without taking up too much room
+ * - **Dense Data Display**: Efficiently showing many data points in a small area
+ *
+ * ## Key Features
+ *
+ * ### Space-Efficient Design
+ * - **Compact Height**: Default 200px height for tight layouts
+ * - **Minimal Legend**: Legend is compact and doesn't take up vertical space
+ * - **Adjustable Tick Variants**: Choose between horizontal or angled labels for better space usage
+ *
+ * ### Flexible Label Handling
+ * - **Single Line Ticks**: Horizontal labels with automatic collision detection
+ * - **Angled Ticks**: -45° rotation for longer labels that need more space
+ * - **Smart Angle Calculation**: Automatically calculates optimal rotation based on label width
+ *
+ * ### Interactive & Responsive
+ * - **Hover Tooltips**: Standard tooltip showing all data series
+ * - **Responsive Design**: Adapts fluidly to its container's size
+ *
+ * ### Customization
+ * - **Theming**: Comes with six pre-built color palettes
+ * - **Area Styles**: Supports `linear`, `natural` (smooth), and `step` interpolation
+ * - **Styling Options**: Control grid visibility, axes, and more
+ */
+const meta: Meta<AreaChartCondensedProps<typeof areaChartCondensedData>> = {
+ title: "Components/D3Charts/AreaChart",
+ component: AreaChartCondensed,
+ parameters: {
+ layout: "centered",
+ docs: {
+ description: {
+ component: `
+## Installation and Basic Usage
+
+\`\`\`tsx
+import { AreaChart } from '@openuidev/react-ui';
+
+const trafficData = [
+ { date: "2023-01-01", visits: 2200 },
+ { date: "2023-01-02", visits: 2500 },
+ { date: "2023-01-03", visits: 2300 },
+];
+
+// Basic implementation
+<AreaChart
+ data={trafficData}
+ categoryKey="date"
+ theme="ocean"
+ height={200}
+/>
+\`\`\`
+
+## Data Structure Requirements
+
+Your data should be an array of objects. Each object must contain:
+- A **category field** (string or number): This will be used for the X-axis labels (e.g., dates, names, etc.).
+- One or more **data series fields** (number): These are the values that will be plotted on the Y-axis.
+
+\`\`\`tsx
+const salesData = [
+ { month: "January", desktop: 150, mobile: 90 },
+ { month: "February", desktop: 280, mobile: 180 },
+ { month: "March", desktop: 220, mobile: 140 },
+];
+\`\`\`
+
+## Key Differences from AreaChart
+
+- **Compact**: Designed for smaller spaces with a default height of 200px
+- **No Interactive Legend**: Legend is simplified and non-interactive
+- **Tick Variants**: Supports both horizontal (singleLine) and angled labels
+- **Performance**: Optimized for quick rendering in dashboards
+
+## Performance Considerations
+- **Data Density**: For very large datasets, consider disabling animations
+- **Responsiveness**: The chart is fully responsive, but test label visibility on small screens
+- **Animation**: Controlled via \`isAnimationActive={false}\`
+`,
+ },
+ },
+ },
+ tags: ["!dev", "autodocs"],
+ argTypes: {
+ data: {
+ description: `
+**Required.** An array of data objects for the area chart. Each object should contain:
+- A category identifier (string/number) for the X-axis.
+- One or more numeric values for the Y-axis.
+`,
+ control: false,
+ table: {
+ type: { summary: "Array<Record<string, string | number>>" },
+ category: "📊 Data Configuration",
+ },
+ },
+ categoryKey: {
+ description:
+ "**Required.** The key in your data object that represents the category for the X-axis.",
+ control: false,
+ table: {
+ type: { summary: "string" },
+ category: "📊 Data Configuration",
+ },
+ },
+ theme: {
+ description:
+ "Specifies the color palette for the chart's areas and tooltips. Ignored when customPalette is provided.",
+ control: "select",
+ options: ["ocean", "orchid", "emerald", "sunset", "spectrum", "vivid"],
+ table: {
+ defaultValue: { summary: "ocean" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ customPalette: {
+ description:
+ "Custom array of colors to use instead of the theme palette. Overrides the theme prop when provided.",
+ control: "object",
+ table: {
+ type: { summary: "string[]" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ variant: {
+ description: "Determines the area interpolation method, affecting the shape of the curves.",
+ control: "radio",
+ options: ["linear", "natural", "step"],
+ table: {
+ defaultValue: { summary: "natural" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ tickVariant: {
+ description:
+ "X-axis tick label style. Choose between 'singleLine' (horizontal) or 'angled' (rotated at optimal angle).",
+ control: "radio",
+ options: ["singleLine", "angled"],
+ table: {
+ defaultValue: { summary: "singleLine" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ icons: {
+ description:
+ "An object mapping data series keys to React components to be used as icons in the legend.",
+ control: false,
+ table: {
+ type: { summary: "Record<string, React.ReactNode>" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ grid: {
+ description: "Toggles the visibility of the background grid lines.",
+ control: "boolean",
+ table: {
+ defaultValue: { summary: "true" },
+ category: "📱 Display Options",
+ },
+ },
+ showYAxis: {
+ description: "Toggles the visibility of the Y-axis line and labels.",
+ control: "boolean",
+ table: {
+ defaultValue: { summary: "true" },
+ category: "📱 Display Options",
+ },
+ },
+ xAxisLabel: {
+ description: "A label to display below the X-axis.",
+ control: "text",
+ table: {
+ type: { summary: "React.ReactNode" },
+ category: "📱 Display Options",
+ },
+ },
+ yAxisLabel: {
+ description: "A label to display beside the Y-axis.",
+ control: "text",
+ table: {
+ type: { summary: "React.ReactNode" },
+ category: "📱 Display Options",
+ },
+ },
+ isAnimationActive: {
+ description: "Enables or disables the initial loading animation for the areas.",
+ control: "boolean",
+ table: {
+ defaultValue: { summary: "false" },
+ category: "🎬 Animation & Interaction",
+ },
+ },
+ height: {
+ description: "Sets a fixed height for the chart container in pixels.",
+ control: "number",
+ table: {
+ defaultValue: { summary: "200" },
+ type: { summary: "number" },
+ category: "Layout & Sizing",
+ },
+ },
+ width: {
+ description: "Sets a fixed width for the chart container in pixels.",
+ control: "number",
+ table: {
+ type: { summary: "number" },
+ category: "Layout & Sizing",
+ },
+ },
+ className: {
+ description: "Custom CSS class to apply to the chart's container.",
+ control: "text",
+ table: {
+ type: { summary: "string" },
+ category: "Layout & Sizing",
+ },
+ },
+ },
+} satisfies Meta<typeof AreaChartCondensed>;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+/**
+ * ## Comprehensive Data Explorer
+ *
+ * This story serves as a comprehensive test suite for the AreaChartCondensed component.
+ * Use the buttons to switch between various datasets designed to test edge cases in:
+ *
+ * - **Label Handling**: Datasets with long, dense, or overlapping labels.
+ * - **Data Density**: Scenarios with few or many data points.
+ * - **Tick Variants**: Toggle between horizontal and angled label orientations.
+ *
+ * It's an excellent tool for developers to see how the chart behaves under different conditions.
+ */
+export const DataExplorer: Story = {
+ name: "🎛️ Comprehensive Data Explorer",
+ args: {
+ data: areaChartCondensedData,
+ categoryKey: "month",
+ theme: "ocean",
+ variant: "natural",
+ tickVariant: "singleLine",
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ xAxisLabel: "Time Period",
+ yAxisLabel: "Values",
+ height: 200,
+ },
+ render: (args: any) => {
+ const [selectedDataType, setSelectedDataType] =
+ useState<keyof typeof dataVariations>("default");
+ const [tickVariant, setTickVariant] = useState<"singleLine" | "angled">("singleLine");
+
+ const currentData = dataVariations[selectedDataType];
+ const currentCategoryKey = categoryKeys[selectedDataType];
+
+ const buttonStyle = {
+ margin: "2px",
+ padding: "6px 12px",
+ fontSize: "12px",
+ border: "1px solid #ddd",
+ borderRadius: "4px",
+ cursor: "pointer",
+ background: "#fff",
+ fontFamily: "monospace",
+ };
+
+ const activeButtonStyle = {
+ ...buttonStyle,
+ background: "#007acc",
+ color: "white",
+ border: "1px solid #007acc",
+ };
+
+ return (
+ <div>
+ <div
+ style={{
+ marginBottom: "16px",
+ padding: "12px",
+ background: "#f8f9fa",
+ borderRadius: "8px",
+ border: "1px solid #e9ecef",
+ width: "600px",
+ }}
+ >
+ <strong>🏷️ Dataset Selection:</strong>
+ <div style={{ marginTop: "8px", display: "flex", flexWrap: "wrap", gap: "4px" }}>
+ <button
+ onClick={() => setSelectedDataType("default")}
+ style={selectedDataType === "default" ? activeButtonStyle : buttonStyle}
+ >
+ 📅 Default (12 months)
+ </button>
+ <button
+ onClick={() => setSelectedDataType("bigLabels")}
+ style={selectedDataType === "bigLabels" ? activeButtonStyle : buttonStyle}
+ >
+ 🏷️ Big Labels
+ </button>
+ <button
+ onClick={() => setSelectedDataType("denseTimeline")}
+ style={selectedDataType === "denseTimeline" ? activeButtonStyle : buttonStyle}
+ >
+ 📅 Dense Timeline (16)
+ </button>
+ <button
+ onClick={() => setSelectedDataType("companyNames")}
+ style={selectedDataType === "companyNames" ? activeButtonStyle : buttonStyle}
+ >
+ 🏢 Company Names
+ </button>
+ <button
+ onClick={() => setSelectedDataType("countryData")}
+ style={selectedDataType === "countryData" ? activeButtonStyle : buttonStyle}
+ >
+ 🌍 Country Names
+ </button>
+ <button
+ onClick={() => setSelectedDataType("financialQuarters")}
+ style={selectedDataType === "financialQuarters" ? activeButtonStyle : buttonStyle}
+ >
+ 📈 Financial Quarters
+ </button>
+ <button
+ onClick={() => setSelectedDataType("mixedLengths")}
+ style={selectedDataType === "mixedLengths" ? activeButtonStyle : buttonStyle}
+ >
+ 🔤 Mixed Lengths
+ </button>
+ <button
+ onClick={() => setSelectedDataType("edgeCases")}
+ style={selectedDataType === "edgeCases" ? activeButtonStyle : buttonStyle}
+ >
+ 🎯 Edge Cases
+ </button>
+ <button
+ onClick={() => setSelectedDataType("minimal")}
+ style={selectedDataType === "minimal" ? activeButtonStyle : buttonStyle}
+ >
+ 📱 Minimal (3 items)
+ </button>
+ </div>
+ <div style={{ marginTop: "12px" }}>
+ <strong>📐 Tick Variant:</strong>
+ <div style={{ marginTop: "8px", display: "flex", gap: "4px" }}>
+ <button
+ onClick={() => setTickVariant("singleLine")}
+ style={tickVariant === "singleLine" ? activeButtonStyle : buttonStyle}
+ >
+ Horizontal Labels
+ </button>
+ <button
+ onClick={() => setTickVariant("angled")}
+ style={tickVariant === "angled" ? activeButtonStyle : buttonStyle}
+ >
+ Angled Labels
+ </button>
+ </div>
+ </div>
+ <div
+ style={{ marginTop: "12px", fontSize: "12px", color: "#666", fontFamily: "monospace" }}
+ >
+ <div>
+ <strong>Current Dataset:</strong> {selectedDataType}
+ </div>
+ <div>
+ <strong>Items:</strong> {currentData.length} | <strong>Category Key:</strong>{" "}
+ {currentCategoryKey} | <strong>Tick:</strong> {tickVariant}
+ </div>
+ </div>
+ </div>
+ <Card style={{ width: "600px" }}>
+ <AreaChartCondensed
+ {...args}
+ data={currentData}
+ categoryKey={currentCategoryKey}
+ tickVariant={tickVariant}
+ />
+ </Card>
+ </div>
+ );
+ },
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "**🎛️ Interactive Explorer:** This story allows you to explore different datasets and tick variants interactively. Use the buttons to switch between:\n\n**Datasets:**\n- **Default**: Standard 12-month data\n- **Big Labels**: Extremely long category names\n- **Dense Timeline**: Many items with medium-length labels\n- **Company Names**: Real-world business names\n- **Country Names**: Geographic labels\n- **Financial Quarters**: Quarterly financial data\n- **Mixed Lengths**: Combination of short and long labels\n- **Edge Cases**: Extreme scenarios\n- **Minimal**: Baseline with 3 items\n\n**Tick Variants:**\n- **Horizontal Labels**: Standard single-line labels with collision detection\n- **Angled Labels**: Rotated labels for better space utilization",
+ },
+ },
+ },
+};
+
+/**
+ * ## Large Dataset with Sidebar Tooltip
+ *
+ * This story demonstrates the sidebar tooltip feature that appears when you have
+ * more than 10 data series. Click on any point in the chart to see the sidebar
+ * tooltip in action. This provides a better UX for viewing many data series at once.
+ */
+export const LargeDatasetWithSidebarTooltip: Story = {
+ name: "🎯 Large Dataset (>10 Series) - Sidebar Tooltip",
+ args: {
+ data: [
+ {
+ month: "Jan",
+ series1: 120,
+ series2: 150,
+ series3: 180,
+ series4: 200,
+ series5: 160,
+ series6: 190,
+ series7: 220,
+ series8: 240,
+ series9: 210,
+ series10: 230,
+ series11: 250,
+ series12: 270,
+ series13: 260,
+ series14: 280,
+ series15: 300,
+ },
+ {
+ month: "Feb",
+ series1: 140,
+ series2: 170,
+ series3: 200,
+ series4: 220,
+ series5: 180,
+ series6: 210,
+ series7: 240,
+ series8: 260,
+ series9: 230,
+ series10: 250,
+ series11: 270,
+ series12: 290,
+ series13: 280,
+ series14: 300,
+ series15: 320,
+ },
+ {
+ month: "Mar",
+ series1: 160,
+ series2: 190,
+ series3: 220,
+ series4: 240,
+ series5: 200,
+ series6: 230,
+ series7: 260,
+ series8: 280,
+ series9: 250,
+ series10: 270,
+ series11: 290,
+ series12: 310,
+ series13: 300,
+ series14: 320,
+ series15: 340,
+ },
+ {
+ month: "Apr",
+ series1: 180,
+ series2: 210,
+ series3: 240,
+ series4: 260,
+ series5: 220,
+ series6: 250,
+ series7: 280,
+ series8: 300,
+ series9: 270,
+ series10: 290,
+ series11: 310,
+ series12: 330,
+ series13: 320,
+ series14: 340,
+ series15: 360,
+ },
+ {
+ month: "May",
+ series1: 200,
+ series2: 230,
+ series3: 260,
+ series4: 280,
+ series5: 240,
+ series6: 270,
+ series7: 300,
+ series8: 320,
+ series9: 290,
+ series10: 310,
+ series11: 330,
+ series12: 350,
+ series13: 340,
+ series14: 360,
+ series15: 380,
+ },
+ {
+ month: "Jun",
+ series1: 220,
+ series2: 250,
+ series3: 280,
+ series4: 300,
+ series5: 260,
+ series6: 290,
+ series7: 320,
+ series8: 340,
+ series9: 310,
+ series10: 330,
+ series11: 350,
+ series12: 370,
+ series13: 360,
+ series14: 380,
+ series15: 400,
+ },
+ {
+ month: "Jul",
+ series1: 240,
+ series2: 270,
+ series3: 300,
+ series4: 320,
+ series5: 280,
+ series6: 310,
+ series7: 340,
+ series8: 360,
+ series9: 330,
+ series10: 350,
+ series11: 370,
+ series12: 390,
+ series13: 380,
+ series14: 400,
+ series15: 420,
+ },
+ {
+ month: "Aug",
+ series1: 260,
+ series2: 290,
+ series3: 320,
+ series4: 340,
+ series5: 300,
+ series6: 330,
+ series7: 360,
+ series8: 380,
+ series9: 350,
+ series10: 370,
+ series11: 390,
+ series12: 410,
+ series13: 400,
+ series14: 420,
+ series15: 440,
+ },
+ {
+ month: "Sep",
+ series1: 280,
+ series2: 310,
+ series3: 340,
+ series4: 360,
+ series5: 320,
+ series6: 350,
+ series7: 380,
+ series8: 400,
+ series9: 370,
+ series10: 390,
+ series11: 410,
+ series12: 430,
+ series13: 420,
+ series14: 440,
+ series15: 460,
+ },
+ {
+ month: "Oct",
+ series1: 300,
+ series2: 330,
+ series3: 360,
+ series4: 380,
+ series5: 340,
+ series6: 370,
+ series7: 400,
+ series8: 420,
+ series9: 390,
+ series10: 410,
+ series11: 430,
+ series12: 450,
+ series13: 440,
+ series14: 460,
+ series15: 480,
+ },
+ {
+ month: "Nov",
+ series1: 320,
+ series2: 350,
+ series3: 380,
+ series4: 400,
+ series5: 360,
+ series6: 390,
+ series7: 420,
+ series8: 440,
+ series9: 410,
+ series10: 430,
+ series11: 450,
+ series12: 470,
+ series13: 460,
+ series14: 480,
+ series15: 500,
+ },
+ {
+ month: "Dec",
+ series1: 340,
+ series2: 370,
+ series3: 400,
+ series4: 420,
+ series5: 380,
+ series6: 410,
+ series7: 440,
+ series8: 460,
+ series9: 430,
+ series10: 450,
+ series11: 470,
+ series12: 490,
+ series13: 480,
+ series14: 500,
+ series15: 520,
+ },
+ ] as any,
+ categoryKey: "month" as any,
+ theme: "ocean",
+ variant: "natural",
+ tickVariant: "singleLine",
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ xAxisLabel: "Months",
+ yAxisLabel: "Performance Metrics",
+ height: 300,
+ },
+ render: (args: any) => (
+ <div>
+ <div
+ style={{
+ marginBottom: "16px",
+ padding: "16px",
+ background: "#e3f2fd",
+ borderRadius: "8px",
+ border: "2px solid #2196f3",
+ maxWidth: "700px",
+ }}
+ >
+ <div style={{ fontSize: "14px", marginBottom: "8px" }}>
+ <strong>🎯 Sidebar Tooltip Demo</strong>
+ </div>
+ <div style={{ fontSize: "13px", color: "#1565c0", lineHeight: "1.6" }}>
+ This chart has <strong>15 data series</strong> (more than 10). <br />
+ <strong>✨ Click on any point</strong> in the chart to open the sidebar tooltip on the
+ right side.
+ <br />
+ The sidebar provides a scrollable list of all series values at that point, making it easy
+ to view large datasets.
+ <br />
+ <em>
+ 💡 Try hovering first (shows inline tooltip), then click to see the sidebar version!
+ </em>
+ </div>
+ </div>
+ <Card style={{ width: "700px" }}>
+ <AreaChartCondensed {...args} />
+ </Card>
+ </div>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "**🎯 Large Dataset Handling:** When your chart has more than 10 data series, the inline tooltip becomes too crowded. This story demonstrates the sidebar tooltip feature:\n\n**Features:**\n- **15 data series** to showcase the sidebar tooltip\n- **Click interaction:** Click any point to open the sidebar\n- **Scrollable view:** All series values in an organized, scrollable list\n- **Better UX:** Cleaner way to view many data points simultaneously\n- **Color-coded:** Each series maintains its color for easy identification\n\n**Usage:**\n1. Hover over the chart to see the inline tooltip (works for smaller datasets)\n2. Click on any data point to open the sidebar tooltip\n3. Scroll through all 15 series values\n4. Click outside or on the X button to close the sidebar",
+ },
+ },
+ },
+};
+
+/**
+ * ## Big Labels
+ *
+ * This story demonstrates the chart's ability to handle very long category labels.
+ * The angled tick variant is particularly useful here for preventing label overlap.
+ */
+export const BigLabelsStory: Story = {
+ name: "🏷️ Big Labels (Angled Ticks)",
+ args: {
+ data: dataVariations.bigLabels as any,
+ categoryKey: "category" as any,
+ theme: "emerald",
+ variant: "natural",
+ tickVariant: "angled",
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 250,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "700px" }}>
+ <AreaChartCondensed {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests the chart with extremely long category names. The angled tick variant automatically rotates labels at an optimal angle to prevent overlapping and maximize readability.",
+ },
+ },
+ },
+};
+
+/**
+ * ## Dense Timeline
+ *
+ * Tests how the chart handles many data points with medium-length period labels.
+ * The angled tick variant helps display more labels without collision.
+ */
+export const DenseTimelineStory: Story = {
+ name: "📅 Dense Timeline (Many Periods)",
+ args: {
+ data: dataVariations.denseTimeline as any,
+ categoryKey: "period" as any,
+ theme: "sunset",
+ variant: "natural",
+ tickVariant: "angled",
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 250,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "700px" }}>
+ <AreaChartCondensed {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests how the chart handles many data points (16 periods) with medium-length labels. The angled tick variant provides better label visibility compared to horizontal labels.",
+ },
+ },
+ },
+};
+
+/**
+ * ## Company Names
+ *
+ * This story tests the chart with real-world company names that have varying lengths.
+ * It demonstrates how the chart handles business data with naturally occurring long labels.
+ */
+export const CompanyNamesStory: Story = {
+ name: "🏢 Company Names (Real-world Labels)",
+ args: {
+ data: dataVariations.companyNames as any,
+ categoryKey: "company" as any,
+ theme: "vivid",
+ variant: "natural",
+ tickVariant: "angled",
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 250,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "700px" }}>
+ <AreaChartCondensed {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests with real-world company names that have varying lengths. Demonstrates how the chart handles business data with naturally occurring long labels.",
+ },
+ },
+ },
+};
+
+/**
+ * ## Country Names
+ *
+ * This story tests the chart with official country names, which are often long.
+ * It shows how geographic data is handled by the angled tick system.
+ */
+export const CountryDataStory: Story = {
+ name: "🌍 Country Names (Geographic Labels)",
+ args: {
+ data: dataVariations.countryData as any,
+ categoryKey: "country" as any,
+ theme: "orchid",
+ variant: "natural",
+ tickVariant: "angled",
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 250,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "700px" }}>
+ <AreaChartCondensed {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests with official country names that include full formal names. Shows how geographic data with naturally long names is handled.",
+ },
+ },
+ },
+};
+
+/**
+ * ## Mixed Lengths
+ *
+ * This story tests the chart's ability to handle a mix of very short and very long labels
+ * within the same dataset, demonstrating its adaptive behavior.
+ */
+export const MixedLengthsStory: Story = {
+ name: "🔤 Mixed Lengths (Varied Label Sizes)",
+ args: {
+ data: dataVariations.mixedLengths as any,
+ categoryKey: "item" as any,
+ theme: "spectrum",
+ variant: "linear",
+ tickVariant: "singleLine",
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 200,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "500px" }}>
+ <AreaChartCondensed {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests the chart's ability to handle a mix of very short and very long labels within the same dataset.",
+ },
+ },
+ },
+};
+
+/**
+ * ## Edge Cases
+ *
+ * This story tests extreme edge cases with exceptionally long labels and minimal data points.
+ */
+export const EdgeCasesStory: Story = {
+ name: "🎯 Edge Cases (Extreme Scenarios)",
+ args: {
+ data: dataVariations.edgeCases as any,
+ categoryKey: "name" as any,
+ theme: "ocean",
+ variant: "step",
+ tickVariant: "angled",
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 250,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "500px" }}>
+ <AreaChartCondensed {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests extreme edge cases with exceptionally long labels and minimal data points. Pushes the label handling system to its limits.",
+ },
+ },
+ },
+};
+
+/**
+ * ## Minimal Data
+ *
+ * A baseline test with a small dataset and standard-length labels. This serves as a control
+ * case to compare against the more complex label scenarios.
+ */
+export const MinimalDataStory: Story = {
+ name: "📱 Minimal Data (Baseline)",
+ args: {
+ data: dataVariations.minimal as any,
+ categoryKey: "category" as any,
+ theme: "emerald",
+ variant: "natural",
+ tickVariant: "singleLine",
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 200,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "400px" }}>
+ <AreaChartCondensed {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Baseline test with minimal data and standard-length labels. Provides a control case to compare against complex scenarios.",
+ },
+ },
+ },
+};
+
+/**
+ * ## Custom Palette
+ *
+ * This story demonstrates how to use the customPalette prop to provide your own color scheme
+ * for the chart. This is useful when you need to match your brand colors.
+ */
+export const CustomPaletteStory: Story = {
+ name: "🎨 Custom Palette",
+ args: {
+ data: dataVariations.default as any,
+ categoryKey: "month" as any,
+ theme: "ocean", // This will be overridden by customPalette
+ variant: "natural",
+ tickVariant: "singleLine",
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ xAxisLabel: "Month",
+ yAxisLabel: "Traffic",
+ customPalette: ["#FF6B6B", "#4ECDC4", "#45B7D1"],
+ height: 200,
+ },
+ render: (args: any) => (
+ <div>
+ <div
+ style={{
+ marginBottom: "16px",
+ padding: "12px",
+ background: "#f8f9fa",
+ borderRadius: "8px",
+ border: "1px solid #e9ecef",
+ width: "600px",
+ }}
+ >
+ <h4 style={{ margin: "0 0 8px 0", color: "#333" }}>🎨 Custom Color Palette</h4>
+ <p style={{ margin: "0 0 12px 0", fontSize: "14px", color: "#666" }}>
+ This chart uses a custom color palette instead of the default theme colors.
+ </p>
+ <div style={{ display: "flex", gap: "8px", flexWrap: "wrap" }}>
+ {args.customPalette?.map((color: string, index: number) => (
+ <div
+ key={index}
+ style={{
+ display: "flex",
+ alignItems: "center",
+ gap: "4px",
+ padding: "4px 8px",
+ background: "white",
+ borderRadius: "4px",
+ border: "1px solid #ddd",
+ fontSize: "12px",
+ }}
+ >
+ <div
+ style={{
+ width: "12px",
+ height: "12px",
+ borderRadius: "2px",
+ backgroundColor: color,
+ border: "1px solid #ccc",
+ }}
+ />
+ <span style={{ fontFamily: "monospace" }}>{color}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ <Card style={{ width: "600px" }}>
+ <AreaChartCondensed {...args} />
+ </Card>
+ </div>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'Demonstrates how to use the `customPalette` prop to provide your own color scheme. When `customPalette` is provided, it overrides the `theme` prop.\n\n**Usage:**\n```tsx\n<AreaChartCondensed\n data={data}\n categoryKey="month"\n customPalette={["#FF6B6B", "#4ECDC4", "#45B7D1"]}\n/>\n```',
+ },
+ },
+ },
+};
+
+/**
+ * ## Tick Variant Comparison
+ *
+ * Side-by-side comparison of single-line (horizontal) and angled tick variants.
+ * This helps you choose the right variant for your data.
+ */
+export const TickVariantComparison: Story = {
+ name: "📐 Tick Variant Comparison",
+ render: () => (
+ <div style={{ display: "flex", flexDirection: "column", gap: "24px" }}>
+ <Card style={{ width: "700px", padding: "16px" }}>
+ <div style={{ marginBottom: "12px" }}>
+ <div style={{ fontSize: "16px", fontWeight: "600", marginBottom: "4px" }}>
+ Single Line Variant (Horizontal)
+ </div>
+ <div style={{ fontSize: "13px", color: "#666" }}>
+ Standard horizontal labels. Recharts automatically hides overlapping labels.
+ </div>
+ </div>
+ <AreaChartCondensed
+ data={dataVariations.bigLabels as any}
+ categoryKey="category"
+ tickVariant="singleLine"
+ theme="ocean"
+ height={200}
+ />
+ </Card>
+ <Card style={{ width: "700px", padding: "16px" }}>
+ <div style={{ marginBottom: "12px" }}>
+ <div style={{ fontSize: "16px", fontWeight: "600", marginBottom: "4px" }}>
+ Angled Variant (Rotated)
+ </div>
+ <div style={{ fontSize: "13px", color: "#666" }}>
+ Automatically rotates labels at an optimal angle. Shows more labels without collision.
+ </div>
+ </div>
+ <AreaChartCondensed
+ data={dataVariations.bigLabels as any}
+ categoryKey="category"
+ tickVariant="angled"
+ theme="emerald"
+ height={260}
+ />
+ </Card>
+ </div>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "**Side-by-side comparison** of tick variants:\n\n- **Single Line**: Standard horizontal labels with automatic collision detection. Recharts hides overlapping labels.\n- **Angled**: Rotates labels at an optimal angle calculated based on label width and available space. Shows more labels without collision.\n\n**When to use each:**\n- Use **singleLine** for short labels or when you have few data points\n- Use **angled** for long labels or many data points where horizontal labels would overlap",
+ },
+ },
+ },
+};
+
+/**
+ * ## Responsive Behavior Demo
+ *
+ * This story demonstrates the responsive capabilities of the AreaChartCondensed.
+ * Drag the handles on the container to resize it and observe how the chart adapts.
+ */
+export const ResponsiveBehaviorDemo: Story = {
+ name: "📱 Responsive Behavior Demo",
+ args: {
+ data: dataVariations.bigLabels as any,
+ categoryKey: "category" as any,
+ theme: "sunset",
+ variant: "natural",
+ tickVariant: "angled",
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 250,
+ },
+ render: (args: any) => {
+ const [dimensions, setDimensions] = useState<{ width: number }>({
+ width: 700,
+ });
+
+ const handleMouseDown = (e: React.MouseEvent<HTMLDivElement>, handle: string) => {
+ e.preventDefault();
+ e.stopPropagation();
+ const startX = e.clientX;
+ const startWidth = dimensions.width;
+
+ const doDrag = (e: MouseEvent) => {
+ const dx = e.clientX - startX;
+ let newWidth = startWidth;
+
+ if (handle.includes("e")) newWidth = startWidth + dx;
+ if (handle.includes("w")) newWidth = startWidth - dx;
+
+ setDimensions({
+ width: Math.max(300, newWidth),
+ });
+ };
+
+ const stopDrag = () => {
+ document.removeEventListener("mousemove", doDrag);
+ document.removeEventListener("mouseup", stopDrag);
+ };
+
+ document.addEventListener("mousemove", doDrag);
+ document.addEventListener("mouseup", stopDrag);
+ };
+
+ const handleStyle: React.CSSProperties = {
+ position: "absolute",
+ background: "#3b82f6",
+ opacity: 0.6,
+ zIndex: 10,
+ transition: "opacity 0.2s ease",
+ };
+
+ return (
+ <div style={{ padding: "20px" }}>
+ <div style={{ marginBottom: "20px" }}>
+ <h3 style={{ margin: "0 0 8px 0", fontSize: "18px", fontWeight: "600" }}>
+ Responsive Behavior Demonstration
+ </h3>
+ <p style={{ margin: "0 0 12px 0", color: "#666", fontSize: "14px" }}>
+ Drag the left or right edges of the container to see how the chart adapts
+ </p>
+ <div
+ style={{
+ padding: "12px",
+ backgroundColor: "#e3f2fd",
+ borderRadius: "6px",
+ fontSize: "12px",
+ color: "#1565c0",
+ }}
+ >
+ <strong>🎯 Try This:</strong> Resize the container to see how angled labels adapt to
+ available space.
+ </div>
+ </div>
+
+ <Card
+ style={{
+ position: "relative",
+ width: `${dimensions.width}px`,
+ border: "2px dashed #9ca3af",
+ padding: "20px",
+ boxSizing: "border-box",
+ overflow: "hidden",
+ cursor: "default",
+ }}
+ >
+ <AreaChartCondensed {...args} />
+
+ {/* Resize Handles */}
+ <div
+ style={{ ...handleStyle, top: 0, bottom: 0, left: -2, width: 12, cursor: "ew-resize" }}
+ onMouseDown={(e) => handleMouseDown(e, "w")}
+ />
+ <div
+ style={{ ...handleStyle, top: 0, bottom: 0, right: -2, width: 12, cursor: "ew-resize" }}
+ onMouseDown={(e) => handleMouseDown(e, "e")}
+ />
+
+ {/* Dimension Display */}
+ <div
+ style={{
+ position: "absolute",
+ bottom: 8,
+ right: 8,
+ background: "rgba(0,0,0,0.8)",
+ color: "white",
+ padding: "4px 8px",
+ borderRadius: "4px",
+ fontSize: "11px",
+ fontFamily: "monospace",
+ fontWeight: "500",
+ }}
+ >
+ {dimensions.width}px
+ </div>
+ </Card>
+ </div>
+ );
+ },
+};
diff --git a/packages/react-ui/src/components/D3Charts/AreaChart/types.ts b/packages/react-ui/src/components/D3Charts/AreaChart/types.ts
new file mode 100644
index 000000000..294f52d62
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/AreaChart/types.ts
@@ -0,0 +1,12 @@
+import type { BaseChartProps, ChartData, HoverOverlayProps } from "../types";
+
+export type AreaChartData = ChartData;
+
+export type AreaChartVariant = "linear" | "natural" | "step";
+
+export interface AreaChartProps<T extends AreaChartData>
+ extends BaseChartProps<T>, HoverOverlayProps {
+ variant?: AreaChartVariant;
+ stacked?: boolean;
+ onClick?: (row: T[number], index: number) => void;
+}
diff --git a/packages/react-ui/src/components/D3Charts/BarChart/BarChart.tsx b/packages/react-ui/src/components/D3Charts/BarChart/BarChart.tsx
new file mode 100644
index 000000000..f355a9494
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/BarChart/BarChart.tsx
@@ -0,0 +1,189 @@
+import clsx from "clsx";
+import { useCallback } from "react";
+
+import {
+ useCartesianChartOrchestrator,
+ useEffectiveAnimation,
+ useExportChartData,
+ useStackedData,
+ useXBandScale,
+ useYScale,
+} from "../hooks";
+import { ClipDefs } from "../shared/cartesian/ClipDefs";
+import { CartesianXAxis } from "../shared/cartesian/axes/CartesianXAxis";
+import { CartesianChartLayout } from "../shared/cartesian/layouts/CartesianChartLayout";
+import { findBandIndex } from "../utils/mouseUtils";
+import { BarSeries } from "./parts/BarSeries";
+import { Crosshair } from "./parts/Crosshair";
+import { HorizontalBarChartImpl } from "./parts/HorizontalBarChartImpl";
+
+import { CHART_CLASS_PREFIX } from "../utils/constants";
+import type { BarChartData, BarChartProps } from "./types";
+
+/**
+ * Empty-data guard lives here, in a hook-free dispatcher: the chart impl below
+ * calls hooks unconditionally, so the "no data" branch must short-circuit
+ * *before* any hook runs (a count → 0 transition on a mounted chart would
+ * otherwise break the Rules of Hooks).
+ */
+export function BarChart<T extends BarChartData>(props: BarChartProps<T>) {
+ if (!props.data || props.data.length === 0) {
+ return (
+ <div
+ className={clsx(
+ `${CHART_CLASS_PREFIX}-bar-chart-container ${CHART_CLASS_PREFIX}-chart-empty`,
+ props.className,
+ )}
+ >
+ <span className={`${CHART_CLASS_PREFIX}-chart-empty-text`}>No data available</span>
+ </div>
+ );
+ }
+ if (props.orientation === "horizontal") {
+ return <HorizontalBarChartImpl {...props} />;
+ }
+ return <BarChartImpl {...props} />;
+}
+
+function BarChartImpl<T extends BarChartData>({
+ data,
+ categoryKey,
+ customPalette,
+ variant = "grouped",
+ tickVariant: tickVariantProp,
+ barRadius = 4,
+ maxBarWidth,
+ internalLine = true,
+ internalLineColor,
+ internalLineWidth,
+ grid = true,
+ legend: showLegend = true,
+ icons,
+ isAnimationActive = false,
+ showYAxis = true,
+ xAxisLabel,
+ yAxisLabel,
+ className,
+ height,
+ width: fixedWidth,
+ fitLegendInHeight,
+ condensed = false,
+ density,
+ onClick,
+ yTickCount,
+}: BarChartProps<T>) {
+ const animate = useEffectiveAnimation(isAnimationActive);
+ const mode = condensed ? "fit" : "scroll";
+
+ const orch = useCartesianChartOrchestrator({
+ layout: mode,
+ data,
+ categoryKey,
+ themePaletteName: "barChartPalette",
+ customPalette,
+ showLegend,
+ showYAxis,
+ height,
+ fixedWidth,
+ fitLegendInHeight,
+ tickVariantProp: tickVariantProp ?? (condensed ? "singleLine" : "multiLine"),
+ chartIdPrefix: "d3bc",
+ icons,
+ onClick,
+ density,
+ stacked: variant === "stacked",
+ yTickCount,
+ });
+
+ const isStacked = variant === "stacked";
+ const xScale = useXBandScale(data, orch.data.catKey, orch.dimensions.chartAreaWidth);
+ const stackedData = useStackedData(data, orch.data.dataKeys, isStacked);
+ const yScale = useYScale(data, orch.data.dataKeys, orch.dimensions.chartInnerHeight, isStacked);
+
+ const findIndex = useCallback((mouseX: number) => findBandIndex(xScale, mouseX), [xScale]);
+ const mouseHandlers = orch.hover.createMouseHandlers(findIndex);
+
+ // PPTX print-export JSON — mirrors react-ui's vertical BarChart call
+ // (type:'bar', no extraOptions → barDir defaults to "col"). Undefined off
+ // the print path.
+ const exportData = useExportChartData({
+ type: "bar",
+ data,
+ categoryKey: orch.data.catKey,
+ dataKeys: orch.data.dataKeys,
+ colors: orch.data.colors,
+ legend: showLegend,
+ xAxisLabel,
+ yAxisLabel,
+ });
+
+ return (
+ <CartesianChartLayout
+ orch={orch}
+ yScale={yScale}
+ mouseHandlers={mouseHandlers}
+ classPrefix="bar-chart"
+ chartType="bar"
+ exportData={exportData}
+ ariaLabel="Bar chart"
+ showYAxis={showYAxis}
+ grid={grid}
+ showLegend={showLegend}
+ xAxisLabel={xAxisLabel}
+ yAxisLabel={yAxisLabel}
+ yTickCount={yTickCount}
+ className={className}
+ defs={
+ <defs>
+ <ClipDefs
+ chartId={orch.identity.chartId}
+ chartWidth={orch.dimensions.chartAreaWidth}
+ chartHeight={orch.dimensions.chartInnerHeight}
+ />
+ </defs>
+ }
+ series={
+ <>
+ <Crosshair
+ hoveredIndex={orch.hover.hoveredIndex}
+ xScale={xScale}
+ data={data}
+ categoryKey={orch.data.catKey}
+ chartHeight={orch.dimensions.chartInnerHeight}
+ />
+ <BarSeries
+ data={data}
+ dataKeys={orch.data.dataKeys}
+ xScale={xScale}
+ yScale={yScale}
+ variant={variant}
+ stackedData={stackedData}
+ categoryKey={orch.data.catKey}
+ colors={orch.data.colorMap}
+ barRadius={barRadius}
+ maxBarWidth={maxBarWidth}
+ internalLine={internalLine}
+ internalLineColor={internalLineColor}
+ internalLineWidth={internalLineWidth}
+ isAnimationActive={animate}
+ />
+ </>
+ }
+ xAxis={
+ <CartesianXAxis
+ mode={mode}
+ scale={xScale}
+ classPrefix={`${CHART_CLASS_PREFIX}-bar-chart`}
+ tickVariant={orch.dimensions.tickVariant}
+ labelHeight={orch.xAxis.xAxisHeight}
+ labelWidth={orch.xAxis.labelWidth}
+ maxLines={orch.xAxis.maxLines}
+ labelInterval={orch.dimensions.labelInterval}
+ angle={orch.xAxis.angle}
+ chartWidth={orch.dimensions.chartAreaWidth}
+ yAxisWidth={orch.dimensions.effectiveYAxisWidth}
+ />
+ }
+ />
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/BarChart/barChart.scss b/packages/react-ui/src/components/D3Charts/BarChart/barChart.scss
new file mode 100644
index 000000000..caf9b8a43
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/BarChart/barChart.scss
@@ -0,0 +1,44 @@
+@use "../../../cssUtils" as cssUtils;
+@use "../shared/cartesian/chartBase" as base;
+@use "../prefix" as brand;
+
+@include base.chart-base("bar-chart");
+
+// (No data-change transition on the bar-chart-bar class: the old
+// `height/y 0.3s` rule was inert — bars render as <path d=roundedBarPath(…)>,
+// and height/y are rect geometry properties — so bars have always snapped.
+// Removed rather than ported to the spring morph: no behavior to preserve.)
+
+.#{brand.$prefix}-bar-chart-hover-highlight {
+ fill: cssUtils.$text-neutral-primary;
+ opacity: 0.04;
+ pointer-events: none;
+}
+
+.#{brand.$prefix}-bar-chart-internal-line {
+ pointer-events: none;
+}
+
+// Entrances are decorative: gate the whole rule (pre-state included) behind
+// reduced-motion so users who opt out get the natural static state immediately
+// — gating only the animation would strand elements at the opacity: 0 start.
+@media (prefers-reduced-motion: no-preference) {
+ .#{brand.$prefix}-bar-chart-bar--animated {
+ transform-box: fill-box;
+ transform-origin: center bottom;
+ animation: #{brand.$prefix}-bar-grow 0.6s ease-out both;
+ }
+ // A negative bar's zero-line edge is its TOP — grow downward from there.
+ .#{brand.$prefix}-bar-chart-bar--animated.#{brand.$prefix}-bar-chart-bar--negative {
+ transform-origin: center top;
+ }
+}
+
+@keyframes #{brand.$prefix}-bar-grow {
+ from {
+ transform: scaleY(0);
+ }
+ to {
+ transform: scaleY(1);
+ }
+}
diff --git a/packages/react-ui/src/components/D3Charts/BarChart/horizontalBarChart.scss b/packages/react-ui/src/components/D3Charts/BarChart/horizontalBarChart.scss
new file mode 100644
index 000000000..8806c1314
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/BarChart/horizontalBarChart.scss
@@ -0,0 +1,142 @@
+// The HORIZONTAL BarChart's layout + look — a faithful port of react-ui's
+// `horizontalBarChart.scss`, re-prefixed `#{brand.$prefix}-horizontal-bar-chart*` and
+// pulling the same design tokens from `@openuidev/react-ui/scssUtils`.
+//
+// Owns the scrolling-body / fixed-bottom-axis flex layout (openui's
+// container / inner-wrapper / inner / main-container / x-axis-container), the
+// full-width category label (ellipsis-truncated in CSS via the renderer's
+// `<foreignObject>`), the value-tick + gridline styling, and the bars'
+// grow-from-the-zero-line entrance. `@forward`ed from `src/styles.scss` — never
+// imported from a `.tsx` (eslint-banned).
+
+@use "../../../cssUtils" as cssUtils;
+@use "../shared/cartesian/chartBase" as base;
+@use "../prefix" as brand;
+
+.#{brand.$prefix}-horizontal-bar-chart {
+ &-container {
+ position: relative;
+ width: 100%;
+ height: auto;
+ display: flex;
+ flex-direction: column;
+ }
+
+ // The flex ROW that holds the inner body beside the scroll-buttons column.
+ // Clips overflow so the scrolling body scrolls internally (never the page).
+ &-container-inner-wrapper {
+ width: 100%;
+ display: flex;
+ flex-direction: row;
+ overflow: hidden;
+ }
+
+ // The inner body (flex:1) — the MEASURED node (see the impl's SCROLL-GUTTER
+ // CONTRACT). `min-width:0` lets it shrink so the category label's ellipsis has
+ // a real width to truncate against.
+ &-container-inner {
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ width: 100%;
+ flex: 1;
+ min-width: 0;
+ }
+
+ // The vertically-scrolling rows body. `height:100%` + the default flex-shrink
+ // lets it fill the space above the flex-shrink:0 bottom axis. Scrollbar hidden
+ // across engines (the ScrollButtonsVertical column drives scrolling instead).
+ &-main-container {
+ height: 100%;
+ overflow-y: auto;
+
+ // Chrome / Safari / Opera
+ &::-webkit-scrollbar {
+ display: none;
+ }
+ // Firefox
+ scrollbar-width: none;
+ // IE / Edge
+ -ms-overflow-style: none;
+ }
+
+ // The fixed bottom value-axis band, pinned below the scrolling body.
+ &-x-axis-container {
+ flex-shrink: 0;
+ width: 100%;
+ box-sizing: border-box;
+ border-top: 1px solid cssUtils.$border-default;
+ padding-top: cssUtils.$space-2xs;
+ }
+
+ // The per-row category label (rendered once, above its bar group, inside a
+ // full-width `<foreignObject>` so this div can ellipsis-truncate in CSS).
+ &-category-label {
+ display: flex;
+ align-items: center;
+ color: cssUtils.$text-neutral-secondary;
+ @include cssUtils.typography(label, extra-small);
+ overflow: hidden;
+ white-space: nowrap;
+ text-overflow: ellipsis;
+ width: 100%;
+ padding-left: cssUtils.$space-m;
+ box-sizing: border-box;
+ }
+}
+
+// Bottom value-axis tick labels — the shared native-SVG tick typography + fill.
+.#{brand.$prefix}-horizontal-bar-chart-x-tick {
+ @include base.svg-tick-label;
+}
+
+// Vertical gridlines at the value ticks (dashed), matching the other cartesian
+// grids. `VerticalGrid` emits bare `<line>`s, so the stroke lives here.
+.#{brand.$prefix}-horizontal-bar-chart-grid-vertical line {
+ stroke: cssUtils.$border-default;
+ stroke-dasharray: 3 3;
+}
+
+// The internal decorative line never eats the row's hover (the svg-level handler
+// hit-tests the pointer's y against the row offsets).
+.#{brand.$prefix}-horizontal-bar-chart-internal-line {
+ pointer-events: none;
+}
+
+// The hovered-ROW highlight band (full row width, one group tall), springing on
+// Y behind the bars. Mirrors the vertical BarChart's `-hover-highlight` fill/
+// opacity (openui's cursor is `var(--openui-highlight)`); never eats the hover.
+.#{brand.$prefix}-horizontal-bar-chart-crosshair {
+ fill: cssUtils.$text-neutral-primary;
+ opacity: 0.04;
+ pointer-events: none;
+}
+
+// Entrance: each bar (and its internal line — the renderer tags both with the
+// same `--animated` class) grows rightward from the value-zero line
+// (`transform-origin: left center` + `scaleX`). Gate the WHOLE rule behind
+// reduced-motion so opt-out users get the settled bar immediately — gating only
+// the animation would strand bars at `scaleX(0)`. The painter sets the per-row
+// `animationDelay` for the stagger.
+@media (prefers-reduced-motion: no-preference) {
+ .#{brand.$prefix}-horizontal-bar-chart-bar--animated {
+ transform-box: fill-box;
+ transform-origin: left center;
+ animation: #{brand.$prefix}-horizontal-bar-grow 0.6s ease-out both;
+ }
+ // A negative bar's zero-line edge is its RIGHT (its left edge is the outer
+ // end) — grow leftward from there so it expands outward from zero like a
+ // positive bar, not inward toward it.
+ .#{brand.$prefix}-horizontal-bar-chart-bar--animated.#{brand.$prefix}-horizontal-bar-chart-bar--negative {
+ transform-origin: right center;
+ }
+}
+
+@keyframes #{brand.$prefix}-horizontal-bar-grow {
+ from {
+ transform: scaleX(0);
+ }
+ to {
+ transform: scaleX(1);
+ }
+}
diff --git a/packages/react-ui/src/components/D3Charts/BarChart/index.ts b/packages/react-ui/src/components/D3Charts/BarChart/index.ts
new file mode 100644
index 000000000..7a169665b
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/BarChart/index.ts
@@ -0,0 +1,2 @@
+export { BarChart } from "./BarChart";
+export type { BarChartData, BarChartProps, BarChartVariant } from "./types";
diff --git a/packages/react-ui/src/components/D3Charts/BarChart/parts/BarSeries.tsx b/packages/react-ui/src/components/D3Charts/BarChart/parts/BarSeries.tsx
new file mode 100644
index 000000000..5b65e1ef2
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/BarChart/parts/BarSeries.tsx
@@ -0,0 +1,227 @@
+import type { ScaleBand, ScaleLinear } from "d3-scale";
+import { scaleBand } from "d3-scale";
+import React, { useMemo } from "react";
+import type { StackedData } from "../../hooks";
+import { roundedBarPath } from "../../shared/cartesian/roundedBarPath";
+import { CHART_CLASS_PREFIX } from "../../utils/constants";
+import { entranceProps } from "../../utils/entranceUtils";
+import type { BarChartVariant } from "../types";
+import { verticalBarRadii } from "./verticalBarRadii";
+
+const DEFAULT_MAX_BAR_WIDTH = 16;
+const MIN_BAR_HEIGHT_FOR_LINE = 8;
+const LINE_PADDING = 6;
+
+interface BarSeriesProps {
+ data: Array<Record<string, string | number>>;
+ dataKeys: string[];
+ xScale: ScaleBand<string>;
+ yScale: ScaleLinear<number, number>;
+ variant: BarChartVariant;
+ stackedData: StackedData | null;
+ categoryKey: string;
+ colors: Record<string, string>;
+ barRadius: number;
+ maxBarWidth?: number;
+ internalLine?: boolean;
+ internalLineColor?: string;
+ internalLineWidth?: number;
+ isAnimationActive?: boolean;
+}
+
+/**
+ * Computes capped bar width and centering offset within a band.
+ * When bandwidth exceeds maxBarWidth, the bar is capped and centered.
+ */
+function getBarLayout(bandwidth: number, maxBarWidth: number) {
+ const cappedWidth = Math.min(bandwidth, maxBarWidth);
+ const offset = (bandwidth - cappedWidth) / 2;
+ return { barWidth: cappedWidth, offset };
+}
+
+export const BarSeries: React.FC<BarSeriesProps> = ({
+ data,
+ dataKeys,
+ xScale,
+ yScale,
+ variant,
+ stackedData,
+ categoryKey,
+ colors,
+ barRadius,
+ maxBarWidth = DEFAULT_MAX_BAR_WIDTH,
+ internalLine = false,
+ internalLineColor = "rgba(255, 255, 255, 0.3)",
+ internalLineWidth = 1,
+ isAnimationActive,
+}) => {
+ const bandwidth = xScale.bandwidth();
+
+ const innerScale = useMemo(() => {
+ if (variant !== "grouped") return null;
+ return scaleBand<string>().domain(dataKeys).range([0, xScale.bandwidth()]).padding(0.05);
+ }, [variant, dataKeys, xScale]);
+
+ // For grouped: cap individual bar within its inner band
+ // For stacked: cap the single bar within the full band
+ const groupedBarLayout = useMemo(() => {
+ if (variant !== "grouped" || !innerScale) return null;
+ return getBarLayout(innerScale.bandwidth(), maxBarWidth);
+ }, [variant, innerScale, maxBarWidth]);
+
+ const stackedBarLayout = useMemo(() => {
+ if (variant !== "stacked") return null;
+ return getBarLayout(bandwidth, maxBarWidth);
+ }, [variant, bandwidth, maxBarWidth]);
+
+ if (variant === "stacked" && stackedData && stackedBarLayout) {
+ const { barWidth, offset } = stackedBarLayout;
+
+ // Per category, the series index of the OUTERMOST rendered segment in each
+ // sign direction — the topmost positive (rounds its top corners) and the
+ // bottommost negative (rounds its bottom corners). Only these round; inner
+ // segments stay square, matching react-ui. d3 normalises every point to
+ // `[y0, y1]` with y0 <= y1, so a segment's sign comes from `point[0] < 0`
+ // (never the height) and a zero-height segment (point[0] === point[1]) is
+ // skipped so it never claims the rounding.
+ const lastPositiveSeries: number[] = new Array(data.length).fill(-1);
+ const lastNegativeSeries: number[] = new Array(data.length).fill(-1);
+ stackedData.forEach((series, seriesIndex) => {
+ (series as unknown as [number, number][]).forEach((point, i) => {
+ if (point[0] === point[1]) return; // zero-height segment: not rendered
+ if (point[0] < 0) lastNegativeSeries[i] = seriesIndex;
+ else lastPositiveSeries[i] = seriesIndex;
+ });
+ });
+
+ return (
+ <g className={`${CHART_CLASS_PREFIX}-bar-chart-bars`}>
+ {stackedData.map((series, seriesIndex) => {
+ const color = colors[series.key] ?? "#000";
+ return (
+ <g key={series.key}>
+ {(series as unknown as [number, number][]).map((point, i) => {
+ const category = String(data[i]![categoryKey]);
+ const bandX = xScale(category) ?? 0;
+ const barX = bandX + offset;
+ // Diverging stacks put negative segments below zero with
+ // point[0] as the more-negative end — anchor at whichever
+ // scaled end is higher on screen.
+ const y0 = yScale(point[0]);
+ const y1 = yScale(point[1]);
+ const barY = Math.min(y0, y1);
+ const barHeight = Math.abs(y0 - y1);
+ const isNegative = point[0] < 0;
+ // Only the outermost segment of this segment's sign group
+ // rounds its outer corners.
+ const rounded = isNegative
+ ? seriesIndex === lastNegativeSeries[i]
+ : seriesIndex === lastPositiveSeries[i];
+ const { className: animatedClass, animationDelay } = entranceProps(
+ isAnimationActive,
+ `${CHART_CLASS_PREFIX}-bar-chart-bar--animated`,
+ i * 30,
+ );
+ const animatedSuffix = animatedClass ? ` ${animatedClass}` : "";
+
+ return (
+ <g key={i}>
+ <path
+ className={`${CHART_CLASS_PREFIX}-bar-chart-bar${isNegative ? ` ${CHART_CLASS_PREFIX}-bar-chart-bar--negative` : ""}${animatedSuffix}`}
+ d={roundedBarPath(
+ barX,
+ barY,
+ barWidth,
+ barHeight,
+ verticalBarRadii(barRadius, isNegative, rounded),
+ )}
+ fill={color}
+ style={animationDelay ? { animationDelay } : undefined}
+ />
+ {internalLine && barHeight >= MIN_BAR_HEIGHT_FOR_LINE && barWidth >= 3 && (
+ <line
+ className={`${CHART_CLASS_PREFIX}-bar-chart-internal-line${isNegative ? ` ${CHART_CLASS_PREFIX}-bar-chart-bar--negative` : ""}${animatedSuffix}`}
+ x1={barX + barWidth / 2}
+ y1={barY + LINE_PADDING}
+ x2={barX + barWidth / 2}
+ y2={barY + barHeight - LINE_PADDING}
+ stroke={internalLineColor}
+ strokeWidth={internalLineWidth}
+ strokeLinecap="round"
+ style={animationDelay ? { animationDelay } : undefined}
+ />
+ )}
+ </g>
+ );
+ })}
+ </g>
+ );
+ })}
+ </g>
+ );
+ }
+
+ // Grouped variant
+ return (
+ <g className={`${CHART_CLASS_PREFIX}-bar-chart-bars`}>
+ {data.map((row, i) => {
+ const category = String(row[categoryKey]);
+ const groupX = xScale(category) ?? 0;
+ const { className: animatedClass, animationDelay } = entranceProps(
+ isAnimationActive,
+ `${CHART_CLASS_PREFIX}-bar-chart-bar--animated`,
+ i * 30,
+ );
+ const animatedSuffix = animatedClass ? ` ${animatedClass}` : "";
+ return (
+ <g key={category}>
+ {dataKeys.map((key) => {
+ const value = Number(row[key]) || 0;
+ const innerBandX = innerScale?.(key) ?? 0;
+ const barX = groupX + innerBandX + (groupedBarLayout?.offset ?? 0);
+ // Bars grow from the zero line (== the chart bottom only while
+ // the domain has no negatives), downward for negative values.
+ const zeroY = yScale(0);
+ const valueY = yScale(value);
+ const barY = Math.min(valueY, zeroY);
+ const barHeight = Math.abs(valueY - zeroY);
+ const isNegative = value < 0;
+ const barWidth = groupedBarLayout?.barWidth ?? innerScale?.bandwidth() ?? bandwidth;
+ const color = colors[key] ?? "#000";
+
+ return (
+ <g key={key}>
+ <path
+ className={`${CHART_CLASS_PREFIX}-bar-chart-bar${isNegative ? ` ${CHART_CLASS_PREFIX}-bar-chart-bar--negative` : ""}${animatedSuffix}`}
+ d={roundedBarPath(
+ barX,
+ barY,
+ barWidth,
+ barHeight,
+ verticalBarRadii(barRadius, isNegative, true),
+ )}
+ fill={color}
+ style={animationDelay ? { animationDelay } : undefined}
+ />
+ {internalLine && barHeight >= MIN_BAR_HEIGHT_FOR_LINE && barWidth >= 3 && (
+ <line
+ className={`${CHART_CLASS_PREFIX}-bar-chart-internal-line${isNegative ? ` ${CHART_CLASS_PREFIX}-bar-chart-bar--negative` : ""}${animatedSuffix}`}
+ x1={barX + barWidth / 2}
+ y1={barY + LINE_PADDING}
+ x2={barX + barWidth / 2}
+ y2={barY + barHeight - LINE_PADDING}
+ stroke={internalLineColor}
+ strokeWidth={internalLineWidth}
+ strokeLinecap="round"
+ style={animationDelay ? { animationDelay } : undefined}
+ />
+ )}
+ </g>
+ );
+ })}
+ </g>
+ );
+ })}
+ </g>
+ );
+};
diff --git a/packages/react-ui/src/components/D3Charts/BarChart/parts/Crosshair.tsx b/packages/react-ui/src/components/D3Charts/BarChart/parts/Crosshair.tsx
new file mode 100644
index 000000000..95200d1d5
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/BarChart/parts/Crosshair.tsx
@@ -0,0 +1,45 @@
+import type { ScaleBand } from "d3-scale";
+import React from "react";
+import { FadeFollower } from "../../shared/core/spring";
+import { CHART_CLASS_PREFIX } from "../../utils/constants";
+
+interface CrosshairProps {
+ hoveredIndex: number | null;
+ xScale: ScaleBand<string>;
+ data: Array<Record<string, string | number>>;
+ categoryKey: string;
+ chartHeight: number;
+}
+
+/**
+ * The hovered-column highlight. Kept mounted (the parent always renders it with a
+ * possibly-null `hoveredIndex`), so the spring persists and the band GLIDES between
+ * columns instead of snapping. The band is bar-width (`xScale.bandwidth()`), so
+ * only its x springs; it jumps in on first show and fades out when nothing's
+ * hovered.
+ */
+export const Crosshair: React.FC<CrosshairProps> = ({
+ hoveredIndex,
+ xScale,
+ data,
+ categoryKey,
+ chartHeight,
+}) => {
+ const visible = hoveredIndex !== null && hoveredIndex >= 0 && hoveredIndex < data.length;
+ const row = visible ? data[hoveredIndex]! : undefined;
+ const x = row ? (xScale(String(row[categoryKey])) ?? 0) : 0;
+ const width = xScale.bandwidth();
+
+ return (
+ <FadeFollower x={x} visible={visible}>
+ <rect
+ className={`${CHART_CLASS_PREFIX}-bar-chart-hover-highlight`}
+ x={0}
+ y={0}
+ width={width}
+ height={chartHeight}
+ rx={4}
+ />
+ </FadeFollower>
+ );
+};
diff --git a/packages/react-ui/src/components/D3Charts/BarChart/parts/HorizontalBarChartImpl.tsx b/packages/react-ui/src/components/D3Charts/BarChart/parts/HorizontalBarChartImpl.tsx
new file mode 100644
index 000000000..4e60b10c9
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/BarChart/parts/HorizontalBarChartImpl.tsx
@@ -0,0 +1,229 @@
+import type { CSSProperties } from "react";
+import { useRef } from "react";
+
+import { useHorizontalBarChartOrchestrator } from "../../hooks/cartesian/useHorizontalBarChartOrchestrator";
+import { useExportChartData } from "../../hooks/core/useExportChartData";
+import { NumericXAxis } from "../../shared/cartesian/axes/NumericXAxis";
+import { ScrollButtonsVertical } from "../../shared/cartesian/ScrollButtonsVertical/ScrollButtonsVertical";
+import { VerticalGrid } from "../../shared/cartesian/VerticalGrid";
+import { ChartShell } from "../../shared/core/ChartShell";
+import { DefaultLegend } from "../../shared/core/DefaultLegend/DefaultLegend";
+import { ChartTooltip } from "../../shared/core/PortalTooltip/ChartTooltip";
+import { CHART_CLASS_PREFIX } from "../../utils/constants";
+import type { BarChartData, BarChartProps } from "../types";
+import { X_AXIS_HEIGHT } from "./horizontalBarGeometry";
+import { HorizontalBarSeries } from "./HorizontalBarSeries";
+import { HorizontalCrosshair } from "./HorizontalCrosshair";
+
+const CLASS_PREFIX = `${CHART_CLASS_PREFIX}-horizontal-bar-chart`;
+
+/**
+ * The HORIZONTAL BarChart shell — the integration layer that assembles the
+ * private orchestrator, the row renderer, the shared value axis/grid, the
+ * vertical snap-scroll, the tooltip, and the legend into a working chart.
+ * Renders through `ChartShell` (container + `LabelTooltipProvider`) WITHOUT
+ * `CartesianChartLayout`, mirroring the `ScatterChart`/`FunnelChart` precedent,
+ * so it touches none of the shared vertical Line/Area machinery.
+ *
+ * DOM (a faithful port of openui's `horizontalBarChart.scss` structure,
+ * re-prefixed `${CHART_CLASS_PREFIX}-horizontal-bar-chart*`):
+ *
+ * ChartShell -container (flex column, its own persistent ref)
+ * -container-inner-wrapper (flex row, overflow hidden, height = chartHeight)
+ * -container-inner (flex column, flex:1, min-width:0) ← containerRef
+ * -main-container (overflow-y:auto, scrollbar hidden) ← scrollBodyRef
+ * <svg> VerticalGrid + HorizontalBarSeries </svg> (height = svgHeight)
+ * -x-axis-container (fixed, border-top)
+ * <svg> NumericXAxis </svg> (same valueScale)
+ * ScrollButtonsVertical (25px column, gated on overflow)
+ * DefaultLegend (below)
+ * ChartTooltip (on hover)
+ *
+ * SCROLL-GUTTER CONTRACT: the orchestrator's `chartWidth = measured containerRef
+ * width` with NO subtraction for the 25px scroll-buttons column. So the measured
+ * `containerRef` is attached to `-container-inner` (flex:1) — which sits to the
+ * LEFT of `ScrollButtonsVertical` and whose measured width therefore already
+ * excludes the gutter. Attaching it to the OUTER container would let the bars
+ * overshoot ~25px under the buttons on overflow. `ChartShell` gets its OWN
+ * persistent ref (`shellContainerRef`) instead, so the measured node is the
+ * nested inner body.
+ *
+ * EMPTY: the hook-free dispatcher (`BarChart`, Task 7) short-circuits empty data
+ * BEFORE this impl mounts (as the vertical `BarChart` already does), so `inner`
+ * always mounts WITH data present and the `ResizeObserver` on it never observes
+ * an unmounted node. The `isEmpty` guard passed to `ChartShell` is the
+ * defensive belt-and-suspenders for a direct empty render.
+ */
+export function HorizontalBarChartImpl<T extends BarChartData>(props: BarChartProps<T>) {
+ const {
+ data,
+ categoryKey,
+ grid = true,
+ legend: showLegend = true,
+ isAnimationActive = false,
+ className,
+ xAxisLabel,
+ yAxisLabel,
+ } = props;
+
+ // Measured (width feeds `chartWidth`); attached to `-container-inner`.
+ const containerRef = useRef<HTMLDivElement>(null);
+ // The `overflow-y:auto` scroll body; read for the snap-scroll boundaries.
+ const scrollBodyRef = useRef<HTMLDivElement>(null);
+ // ChartShell's persistent `-container` div — a separate ref so the measured
+ // node stays the nested inner body (see SCROLL-GUTTER CONTRACT above).
+ const shellContainerRef = useRef<HTMLDivElement>(null);
+
+ const orch = useHorizontalBarChartOrchestrator(props, containerRef, scrollBodyRef);
+
+ const {
+ isEmpty,
+ isPrinting,
+ legendRef,
+ containerStyle,
+ legendItems,
+ labelHeight,
+ valueScale,
+ chartWidth,
+ chartHeight,
+ svgHeight,
+ rows,
+ rowOffsets,
+ groupHeight,
+ hover,
+ tooltip,
+ legend: legendControls,
+ scroll,
+ dataKeys,
+ colors,
+ } = orch;
+
+ // PPTX print-export JSON — mirrors react-ui's HorizontalBarChart call
+ // (type:'bar' + extraOptions.barDir:'bar' for the horizontal orientation).
+ // `colors` runs parallel to the visible `dataKeys`. Undefined off the print
+ // path; passed to ChartShell's root `data-openui-chart`.
+ const exportData = useExportChartData({
+ type: "bar",
+ data,
+ categoryKey: String(categoryKey),
+ dataKeys,
+ colors,
+ legend: showLegend,
+ xAxisLabel,
+ yAxisLabel,
+ extraOptions: {
+ barDir: "bar",
+ },
+ });
+
+ return (
+ <ChartShell
+ containerRef={shellContainerRef}
+ classPrefix={CLASS_PREFIX}
+ className={className}
+ style={containerStyle as CSSProperties}
+ isEmpty={isEmpty}
+ exportData={exportData}
+ >
+ {() => (
+ <>
+ <div
+ className={`${CLASS_PREFIX}-container-inner-wrapper`}
+ style={{ height: chartHeight }}
+ >
+ <div ref={containerRef} className={`${CLASS_PREFIX}-container-inner`}>
+ <div
+ ref={scrollBodyRef}
+ className={`${CLASS_PREFIX}-main-container`}
+ onScroll={scroll.onScroll}
+ >
+ <svg
+ width="100%"
+ height={svgHeight}
+ role="img"
+ aria-label="Horizontal bar chart"
+ onMouseMove={hover.onMouseMove}
+ onMouseLeave={hover.onMouseLeave}
+ >
+ {grid && (
+ <VerticalGrid
+ xScale={valueScale}
+ chartWidth={chartWidth}
+ chartHeight={svgHeight}
+ className={`${CLASS_PREFIX}-grid-vertical`}
+ />
+ )}
+
+ {/* Hovered-row highlight band — mounted BEHIND the rows so
+ the bars/labels paint over it. Springs on Y between rows
+ (the transpose of the vertical BarChart's column
+ crosshair). */}
+ <HorizontalCrosshair
+ hoveredIndex={hover.hoveredIndex}
+ rowOffsets={rowOffsets}
+ groupHeight={groupHeight}
+ chartWidth={chartWidth}
+ />
+
+ <HorizontalBarSeries
+ rows={rows}
+ labelHeight={labelHeight}
+ chartWidth={chartWidth}
+ hoveredCategory={hover.hoveredCategory}
+ isAnimationActive={isAnimationActive}
+ isPrinting={isPrinting}
+ classPrefix={CLASS_PREFIX}
+ />
+ </svg>
+ </div>
+
+ <div className={`${CLASS_PREFIX}-x-axis-container`}>
+ <svg width="100%" height={X_AXIS_HEIGHT}>
+ <NumericXAxis
+ scale={valueScale}
+ chartWidth={chartWidth}
+ height={X_AXIS_HEIGHT}
+ className={`${CLASS_PREFIX}-x-axis`}
+ tickClassName={`${CLASS_PREFIX}-x-tick`}
+ edgeAlign
+ />
+ </svg>
+ </div>
+ </div>
+
+ {scroll.needsScroll && (
+ <ScrollButtonsVertical
+ canScrollUp={scroll.canUp}
+ canScrollDown={scroll.canDown}
+ onScrollUp={scroll.onScrollUp}
+ onScrollDown={scroll.onScrollDown}
+ />
+ )}
+ </div>
+
+ {showLegend && (
+ <DefaultLegend
+ ref={legendRef}
+ items={legendItems}
+ containerWidth={chartWidth}
+ isExpanded={legendControls.isLegendExpanded}
+ setIsExpanded={legendControls.setIsLegendExpanded}
+ onItemClick={legendControls.toggleSeries}
+ hiddenSeries={legendControls.hiddenSeries}
+ xAxisLabel={xAxisLabel}
+ yAxisLabel={yAxisLabel}
+ />
+ )}
+
+ {tooltip.payload && tooltip.position && (
+ <ChartTooltip
+ label={tooltip.payload.label}
+ items={tooltip.payload.items}
+ viewportPosition={tooltip.position}
+ />
+ )}
+ </>
+ )}
+ </ChartShell>
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/BarChart/parts/HorizontalBarSeries.tsx b/packages/react-ui/src/components/D3Charts/BarChart/parts/HorizontalBarSeries.tsx
new file mode 100644
index 000000000..c60500b61
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/BarChart/parts/HorizontalBarSeries.tsx
@@ -0,0 +1,150 @@
+import clsx from "clsx";
+import React from "react";
+import { useTheme } from "../../../ThemeProvider";
+
+import type { HorizontalBarRow } from "../../hooks/cartesian/useHorizontalBarChartOrchestrator";
+import { roundedBarPath } from "../../shared/cartesian/roundedBarPath";
+import { entranceProps } from "../../utils/entranceUtils";
+import { LINE_PADDING } from "./horizontalBarGeometry";
+
+/** Per-row entrance stagger (ms), matching the vertical `BarSeries`. */
+const ROW_STAGGER_MS = 30;
+
+/** Internal decorative-line color by theme mode — openui's horizontal look:
+ * a faint light line on light surfaces, a faint dark line on dark ones. */
+const INTERNAL_LINE_LIGHT = "rgba(255, 255, 255, 0.3)";
+const INTERNAL_LINE_DARK = "rgba(0, 0, 0, 0.3)";
+
+interface HorizontalBarSeriesProps {
+ /** Render-ready rows from `useHorizontalBarChartOrchestrator` — one per
+ * category, each carrying its `rowTop`, `groupHeight`, and laid-out `bars`
+ * (x/y/width/height/color/radii/showLine already computed). This painter
+ * recomputes NO geometry. */
+ rows: HorizontalBarRow[];
+ /** Measured category-label band height (px) — the label sits at `row.rowTop`
+ * with this height; `bar.y` already includes it. From the orchestrator
+ * (`labelHeight`); NOT carried on the row. */
+ labelHeight: number;
+ /** Row-SVG width (px) — the `<foreignObject>` label spans it so the CSS
+ * ellipsis has the full row to truncate against. From the orchestrator
+ * (`chartWidth`). */
+ chartWidth: number;
+ /** The hovered category, or `null` when nothing is hovered. Non-hovered rows
+ * dim to 0.4. */
+ hoveredCategory: string | null;
+ /** Gate the entrance/width tween. Combined with `!isPrinting` below. */
+ isAnimationActive: boolean;
+ /** Printing snaps to the settled frame (no entrance animation). */
+ isPrinting: boolean;
+ /** Owning chart's class prefix (`${CHART_CLASS_PREFIX}-horizontal-bar-chart`) — drives the
+ * label / bar / internal-line / animated class names, so Task 6's scss owns
+ * the look (incl. the `--animated` grow keyframe). */
+ classPrefix: string;
+}
+
+/**
+ * Pure SVG painter for the HORIZONTAL BarChart's category rows. Consumes the
+ * orchestrator's `rows` and paints, per row: a `<foreignObject>` category label
+ * once above the bar group, then each bar as a rounded `<path>` with an optional
+ * centered 1px internal `<line>`. Owns NO geometry (the orchestrator +
+ * `horizontalBarGeometry` do) and NO layout state — it only maps rows → SVG,
+ * applies the hover dim, and emits the entrance-animation hooks (class +
+ * `animationDelay`) that the scss animates. Mirrors the vertical `BarSeries`.
+ *
+ * Hooks are unconditional (`useTheme` at the top); wrapped in `React.memo` so it
+ * repaints only when its props change (e.g. hover, scroll size), not on every
+ * parent render.
+ */
+export const HorizontalBarSeries: React.FC<HorizontalBarSeriesProps> = React.memo(
+ function HorizontalBarSeries({
+ rows,
+ labelHeight,
+ chartWidth,
+ hoveredCategory,
+ isAnimationActive,
+ isPrinting,
+ classPrefix,
+ }) {
+ // Theme-mode-aware internal-line color — light surfaces get the faint white
+ // line, dark surfaces the faint black one (openui's horizontal look). Read
+ // the same way the heatmap orchestrator reads it.
+ const { mode } = useTheme();
+ const internalLineColor = mode === "dark" ? INTERNAL_LINE_DARK : INTERNAL_LINE_LIGHT;
+
+ // Printing always snaps to the settled frame; streaming defaults off.
+ const animate = isAnimationActive && !isPrinting;
+
+ return (
+ <g className={`${classPrefix}-bars`}>
+ {rows.map((row, rowIndex) => {
+ // Hover dim: the hovered category (or all rows when nothing is
+ // hovered) stay opaque; everything else drops to 0.4.
+ const opacity = hoveredCategory === null || row.category === hoveredCategory ? 1 : 0.4;
+
+ // Per-row entrance stagger — the whole row's bars grow together.
+ const { className: animatedClass, animationDelay } = entranceProps(
+ animate,
+ `${classPrefix}-bar--animated`,
+ rowIndex * ROW_STAGGER_MS,
+ );
+ const animatedStyle = animationDelay ? { animationDelay } : undefined;
+
+ return (
+ <g key={row.key} className={`${classPrefix}-row`}>
+ {/* Category label, once per row, above the bar group. A
+ foreignObject spans the full row width so the `-category-label`
+ div can ellipsis-truncate in CSS (openui does the same). It is
+ non-interactive so it never eats the row's hover. */}
+ <foreignObject
+ x={0}
+ y={row.rowTop}
+ width={Math.max(0, chartWidth)}
+ height={labelHeight}
+ style={{ pointerEvents: "none" }}
+ xmlns="http://www.w3.org/1999/xhtml"
+ >
+ <div className={`${classPrefix}-category-label`}>{row.category}</div>
+ </foreignObject>
+
+ {row.bars.map((bar) => (
+ <g key={bar.key}>
+ <path
+ className={clsx(
+ `${classPrefix}-bar`,
+ animatedClass,
+ bar.isNegative && `${classPrefix}-bar--negative`,
+ )}
+ d={roundedBarPath(bar.x, bar.y, bar.width, bar.height, bar.radii)}
+ fill={bar.color}
+ opacity={opacity}
+ style={animatedStyle}
+ />
+ {bar.showLine && (
+ <line
+ className={clsx(
+ `${classPrefix}-internal-line`,
+ animatedClass,
+ bar.isNegative && `${classPrefix}-bar--negative`,
+ )}
+ x1={bar.x + LINE_PADDING}
+ x2={bar.x + bar.width - LINE_PADDING}
+ y1={bar.y + bar.height / 2}
+ y2={bar.y + bar.height / 2}
+ stroke={internalLineColor}
+ strokeWidth={1}
+ strokeLinecap="round"
+ opacity={opacity}
+ style={animatedStyle}
+ />
+ )}
+ </g>
+ ))}
+ </g>
+ );
+ })}
+ </g>
+ );
+ },
+);
+
+HorizontalBarSeries.displayName = "HorizontalBarSeries";
diff --git a/packages/react-ui/src/components/D3Charts/BarChart/parts/HorizontalCrosshair.tsx b/packages/react-ui/src/components/D3Charts/BarChart/parts/HorizontalCrosshair.tsx
new file mode 100644
index 000000000..772edb8b8
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/BarChart/parts/HorizontalCrosshair.tsx
@@ -0,0 +1,54 @@
+import React from "react";
+
+import { FadeFollower } from "../../shared/core/spring";
+import { CHART_CLASS_PREFIX } from "../../utils/constants";
+
+interface HorizontalCrosshairProps {
+ /** Hovered category row index, or `null` when nothing is hovered. */
+ hoveredIndex: number | null;
+ /** Cumulative top (y, px) of each category row in the scrolling SVG's
+ * coordinate space — from the orchestrator (`rowOffsets`). */
+ rowOffsets: number[];
+ /** Height (px) of one whole category group (label band + bars). Uniform
+ * across rows — from the orchestrator (`groupHeight`). */
+ groupHeight: number;
+ /** Row-SVG width (px) — the band spans it. From the orchestrator
+ * (`chartWidth`). */
+ chartWidth: number;
+}
+
+/**
+ * The hovered-ROW highlight for the HORIZONTAL BarChart — the transpose of the
+ * vertical `Crosshair`. Kept mounted (the parent always renders it with a
+ * possibly-null `hoveredIndex`), so the spring persists and the band GLIDES
+ * between rows instead of snapping. The band is full row width
+ * (`chartWidth`) and one group tall (`groupHeight`), so only its Y springs; it
+ * jumps in on first show and fades out when nothing's hovered.
+ *
+ * Ported from openui's HorizontalBarChart cursor (`fill: var(--openui-highlight)`,
+ * `stroke: var(--openui-stroke-default)`) — here the fill/stroke live in
+ * `horizontalBarChart.scss` (`-crosshair`), mirroring the vertical crosshair's
+ * `-hover-highlight`.
+ */
+export const HorizontalCrosshair: React.FC<HorizontalCrosshairProps> = ({
+ hoveredIndex,
+ rowOffsets,
+ groupHeight,
+ chartWidth,
+}) => {
+ const visible = hoveredIndex !== null && hoveredIndex >= 0 && hoveredIndex < rowOffsets.length;
+ const y = visible ? (rowOffsets[hoveredIndex] ?? 0) : 0;
+
+ return (
+ <FadeFollower x={0} y={y} visible={visible}>
+ <rect
+ className={`${CHART_CLASS_PREFIX}-horizontal-bar-chart-crosshair`}
+ x={0}
+ y={0}
+ width={Math.max(0, chartWidth)}
+ height={groupHeight}
+ rx={4}
+ />
+ </FadeFollower>
+ );
+};
diff --git a/packages/react-ui/src/components/D3Charts/BarChart/parts/horizontalBarGeometry.test.ts b/packages/react-ui/src/components/D3Charts/BarChart/parts/horizontalBarGeometry.test.ts
new file mode 100644
index 000000000..cfdac0b2c
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/BarChart/parts/horizontalBarGeometry.test.ts
@@ -0,0 +1,323 @@
+import { describe, expect, it } from "vitest";
+import {
+ BAR_GAP,
+ BAR_HEIGHT,
+ BAR_RADIUS,
+ GROUP_PADDING,
+ LINE_PADDING,
+ MIN_LINE_DIMENSION,
+ SINGLE_ROW_MIN,
+ barValue,
+ contentHeight,
+ groupHeight,
+ nearestSnap,
+ radiusArray,
+ rowOffsets,
+ showInternalLine,
+ snapPositions,
+ stackSegments,
+ valueDomain,
+ verticalPadding,
+} from "./horizontalBarGeometry";
+
+describe("constants", () => {
+ it("match the openui reference values", () => {
+ expect(BAR_HEIGHT).toBe(16);
+ expect(BAR_GAP).toBe(10);
+ expect(GROUP_PADDING).toBe(16);
+ expect(SINGLE_ROW_MIN).toBe(80);
+ expect(BAR_RADIUS).toBe(4);
+ expect(MIN_LINE_DIMENSION).toBe(8);
+ expect(LINE_PADDING).toBe(6);
+ });
+});
+
+describe("groupHeight", () => {
+ it("grouped: n*(BAR_HEIGHT+BAR_GAP) - BAR_GAP + labelHeight + GROUP_PADDING (worked example → 108)", () => {
+ expect(groupHeight(3, "grouped", 24)).toBe(108);
+ });
+ it("stacked: BAR_HEIGHT + labelHeight + GROUP_PADDING, ignoring seriesCount (worked example → 56)", () => {
+ expect(groupHeight(3, "stacked", 24)).toBe(56);
+ });
+ it("grouped single series collapses the inter-bar gap", () => {
+ // 1*(16+10) - 10 + 24 + 16 = 56
+ expect(groupHeight(1, "grouped", 24)).toBe(56);
+ });
+ it("grouped two series", () => {
+ // 2*26 - 10 + 24 + 16 = 82
+ expect(groupHeight(2, "grouped", 24)).toBe(82);
+ });
+ it("grouped four series with a taller label", () => {
+ // 4*26 - 10 + 20 + 16 = 130
+ expect(groupHeight(4, "grouped", 20)).toBe(130);
+ });
+ it("stacked is independent of seriesCount", () => {
+ expect(groupHeight(1, "stacked", 24)).toBe(56);
+ expect(groupHeight(5, "stacked", 24)).toBe(56);
+ });
+ it("stacked honours a taller label", () => {
+ // 16 + 30 + 16 = 62
+ expect(groupHeight(5, "stacked", 30)).toBe(62);
+ });
+});
+
+describe("contentHeight", () => {
+ it("multi-row: rowCount * groupHeight", () => {
+ expect(contentHeight(4, 108)).toBe(432);
+ });
+ it("single-row applies the 80px floor when the group is shorter", () => {
+ expect(contentHeight(1, 56)).toBe(80);
+ });
+ it("single-row keeps the group height when it exceeds the floor", () => {
+ expect(contentHeight(1, 108)).toBe(108);
+ });
+ it("empty → 0 regardless of groupHeight", () => {
+ expect(contentHeight(0, 108)).toBe(0);
+ });
+});
+
+describe("verticalPadding", () => {
+ it("content fits → padding halved to center it", () => {
+ expect(verticalPadding(200, 336)).toEqual({ top: 68, bottom: 68 });
+ });
+ it("content overflows → fixed {10, 10}", () => {
+ expect(verticalPadding(500, 336)).toEqual({ top: 10, bottom: 10 });
+ });
+ it("exact fit → {0, 0}", () => {
+ expect(verticalPadding(336, 336)).toEqual({ top: 0, bottom: 0 });
+ });
+});
+
+describe("rowOffsets", () => {
+ it("cumulative y per category, shifted by topPad", () => {
+ expect(rowOffsets(3, 108, 68)).toEqual([68, 176, 284]);
+ });
+ it("topPad of 0 starts at the origin", () => {
+ expect(rowOffsets(2, 56, 0)).toEqual([0, 56]);
+ });
+ it("empty → []", () => {
+ expect(rowOffsets(0, 108, 68)).toEqual([]);
+ });
+});
+
+describe("snapPositions", () => {
+ it("one position per category: [0, g, 2g, …]", () => {
+ expect(snapPositions(3, 108)).toEqual([0, 108, 216]);
+ });
+ it("single category → [0]", () => {
+ expect(snapPositions(1, 108)).toEqual([0]);
+ });
+ it("empty → [0]", () => {
+ expect(snapPositions(0, 108)).toEqual([0]);
+ });
+});
+
+describe("nearestSnap", () => {
+ const positions = [0, 108, 216, 324];
+
+ it("current at 0, up clamps at the first index", () => {
+ expect(nearestSnap(positions, 0, "up")).toBe(0);
+ });
+ it("current at 0, down steps to the next index", () => {
+ expect(nearestSnap(positions, 0, "down")).toBe(1);
+ });
+ it("current exactly on a snap, up steps back one", () => {
+ expect(nearestSnap(positions, 216, "up")).toBe(1);
+ });
+ it("current exactly on a snap, down steps forward one", () => {
+ expect(nearestSnap(positions, 216, "down")).toBe(3);
+ });
+ it("current between snaps, up goes to the enclosing index", () => {
+ // 108 <= 150 < 216 → idx 1; up → 0
+ expect(nearestSnap(positions, 150, "up")).toBe(0);
+ });
+ it("current between snaps, down goes past the enclosing index", () => {
+ // idx 1; down → 2
+ expect(nearestSnap(positions, 150, "down")).toBe(2);
+ });
+ it("current past the last snap, up steps back from the end", () => {
+ expect(nearestSnap(positions, 500, "up")).toBe(2);
+ });
+ it("current past the last snap, down clamps at the last index", () => {
+ expect(nearestSnap(positions, 500, "down")).toBe(3);
+ });
+ it("down clamps at the last index when already there", () => {
+ expect(nearestSnap(positions, 324, "down")).toBe(3);
+ });
+});
+
+describe("barValue", () => {
+ it("passes a plain number through", () => {
+ expect(barValue(42)).toBe(42);
+ });
+ it("coerces a numeric string", () => {
+ expect(barValue("42")).toBe(42);
+ expect(barValue("3.5")).toBeCloseTo(3.5);
+ });
+ it("keeps the sign of a negative value (unlike SegmentedBar)", () => {
+ expect(barValue(-17)).toBe(-17);
+ expect(barValue("-3.5")).toBeCloseTo(-3.5);
+ });
+ it("collapses NaN / non-numeric / undefined / null to 0", () => {
+ expect(barValue(NaN)).toBe(0);
+ expect(barValue("oops")).toBe(0);
+ expect(barValue(undefined)).toBe(0);
+ expect(barValue(null)).toBe(0);
+ });
+ it("collapses non-finite values to 0", () => {
+ expect(barValue(Infinity)).toBe(0);
+ expect(barValue(-Infinity)).toBe(0);
+ });
+ it("keeps zero as zero", () => {
+ expect(barValue(0)).toBe(0);
+ });
+});
+
+describe("valueDomain", () => {
+ it("grouped all-positive: [0, max] with 0 always included", () => {
+ const data = [
+ { m: "Jan", a: 10, b: 40 },
+ { m: "Feb", a: 30, b: 20 },
+ ];
+ expect(valueDomain(data, ["a", "b"], "grouped")).toEqual([0, 40]);
+ });
+ it("grouped mixed sign: global [min, max] across all series values", () => {
+ const data = [
+ { m: "Jan", a: -25, b: 60 },
+ { m: "Feb", a: 10, b: -5 },
+ ];
+ expect(valueDomain(data, ["a", "b"], "grouped")).toEqual([-25, 60]);
+ });
+ it("grouped all-negative still includes 0 at the top", () => {
+ const data = [
+ { m: "Jan", a: -10 },
+ { m: "Feb", a: -40 },
+ ];
+ expect(valueDomain(data, ["a"], "grouped")).toEqual([-40, 0]);
+ });
+ it("grouped all-zero → [0, 0]", () => {
+ const data = [{ m: "Jan", a: 0, b: 0 }];
+ expect(valueDomain(data, ["a", "b"], "grouped")).toEqual([0, 0]);
+ });
+ it("stacked sums positives rightward and negatives leftward per row", () => {
+ const data = [
+ { m: "Jan", a: 10, b: 40, c: 20 }, // posSum 70
+ { m: "Feb", a: -15, b: -25, c: 5 }, // negSum -40, posSum 5
+ ];
+ expect(valueDomain(data, ["a", "b", "c"], "stacked")).toEqual([-40, 70]);
+ });
+ it("stacked domain differs from grouped for the same data (signed sums)", () => {
+ const data = [{ m: "Jan", a: 30, b: 20 }];
+ // grouped max is the largest single value (30); stacked max is the sum (50)
+ expect(valueDomain(data, ["a", "b"], "grouped")).toEqual([0, 30]);
+ expect(valueDomain(data, ["a", "b"], "stacked")).toEqual([0, 50]);
+ });
+ it("ignores non-numeric cells (coerced to 0 via barValue)", () => {
+ const data = [{ m: "Jan", a: "oops", b: 25 }];
+ expect(valueDomain(data, ["a", "b"], "grouped")).toEqual([0, 25]);
+ });
+ it("empty data → [0, 0]", () => {
+ expect(valueDomain([], ["a", "b"], "grouped")).toEqual([0, 0]);
+ expect(valueDomain([], ["a", "b"], "stacked")).toEqual([0, 0]);
+ });
+});
+
+describe("stackSegments", () => {
+ it("orders positives left→right from zero and flags the outermost", () => {
+ const { positives, negatives } = stackSegments({ a: 10, b: 40, c: 20 }, ["a", "b", "c"]);
+ expect(negatives).toEqual([]);
+ expect(positives.map((s) => s.key)).toEqual(["a", "b", "c"]);
+ expect(positives[0]).toMatchObject({
+ key: "a",
+ isFirst: true,
+ isLast: false,
+ });
+ expect(positives[2]).toMatchObject({
+ key: "c",
+ isFirst: false,
+ isLast: true,
+ });
+ expect(positives[1]).toMatchObject({ isFirst: false, isLast: false });
+ });
+ it("orders negatives from zero outward (leftward) and flags the outermost", () => {
+ const { positives, negatives } = stackSegments({ a: -10, b: -40 }, ["a", "b"]);
+ expect(positives).toEqual([]);
+ expect(negatives.map((s) => s.key)).toEqual(["a", "b"]);
+ expect(negatives[0]).toMatchObject({
+ key: "a",
+ isFirst: true,
+ isLast: false,
+ });
+ expect(negatives[1]).toMatchObject({
+ key: "b",
+ isFirst: false,
+ isLast: true,
+ });
+ });
+ it("splits a mixed row: positives and negatives keyed and flagged independently", () => {
+ const { positives, negatives } = stackSegments({ a: 10, b: -15, c: 20, d: -25 }, [
+ "a",
+ "b",
+ "c",
+ "d",
+ ]);
+ expect(positives.map((s) => s.key)).toEqual(["a", "c"]);
+ expect(negatives.map((s) => s.key)).toEqual(["b", "d"]);
+ // outermost of each sign group
+ expect(positives.find((s) => s.isLast)?.key).toBe("c");
+ expect(negatives.find((s) => s.isLast)?.key).toBe("d");
+ expect(positives[0]).toMatchObject({ key: "a", isFirst: true });
+ expect(negatives[0]).toMatchObject({ key: "b", isFirst: true });
+ });
+ it("a lone segment is both first and last in its group", () => {
+ const { positives } = stackSegments({ a: 10 }, ["a"]);
+ expect(positives[0]).toMatchObject({ isFirst: true, isLast: true });
+ });
+ it("zero-valued keys join the positive group (openui >= 0)", () => {
+ const { positives, negatives } = stackSegments({ a: 0, b: -5 }, ["a", "b"]);
+ expect(positives.map((s) => s.key)).toEqual(["a"]);
+ expect(negatives.map((s) => s.key)).toEqual(["b"]);
+ });
+});
+
+describe("radiusArray", () => {
+ const r = BAR_RADIUS;
+
+ it("grouped positive rounds the right end [0, r, r, 0]", () => {
+ expect(radiusArray("grouped", r, false, false, false)).toEqual([0, r, r, 0]);
+ });
+ it("grouped negative rounds the left end [r, 0, 0, r]", () => {
+ expect(radiusArray("grouped", r, false, false, true)).toEqual([r, 0, 0, r]);
+ });
+ it("stacked single segment (first && last) rounds like grouped positive", () => {
+ expect(radiusArray("stacked", r, true, true, false)).toEqual([0, r, r, 0]);
+ });
+ it("stacked single segment negative rounds the left end", () => {
+ expect(radiusArray("stacked", r, true, true, true)).toEqual([r, 0, 0, r]);
+ });
+ it("stacked outermost (last, not first) positive rounds its far right end", () => {
+ expect(radiusArray("stacked", r, false, true, false)).toEqual([0, r, r, 0]);
+ });
+ it("stacked outermost negative rounds its far left end", () => {
+ expect(radiusArray("stacked", r, false, true, true)).toEqual([r, 0, 0, r]);
+ });
+ it("stacked inner/first-but-not-last segment stays square", () => {
+ expect(radiusArray("stacked", r, true, false, false)).toEqual([0, 0, 0, 0]);
+ expect(radiusArray("stacked", r, false, false, true)).toEqual([0, 0, 0, 0]);
+ });
+});
+
+describe("showInternalLine", () => {
+ it("is false just below the threshold (7 < 8)", () => {
+ expect(showInternalLine(7)).toBe(false);
+ });
+ it("is true exactly at the threshold (8)", () => {
+ expect(showInternalLine(MIN_LINE_DIMENSION)).toBe(true);
+ });
+ it("is true above the threshold", () => {
+ expect(showInternalLine(120)).toBe(true);
+ });
+ it("is false for a zero-width bar", () => {
+ expect(showInternalLine(0)).toBe(false);
+ });
+});
diff --git a/packages/react-ui/src/components/D3Charts/BarChart/parts/horizontalBarGeometry.ts b/packages/react-ui/src/components/D3Charts/BarChart/parts/horizontalBarGeometry.ts
new file mode 100644
index 000000000..5add6b886
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/BarChart/parts/horizontalBarGeometry.ts
@@ -0,0 +1,267 @@
+// Pure layout geometry for the horizontal BarChart: the load-bearing math that
+// turns a category/series count into per-row heights, the scrolling content
+// height, its vertical centering pad, the cumulative row offsets, the
+// snap-scroll positions, and the value/bar math — value coercion, the
+// zero-anchored value domain, the sign-diverging stack split, per-corner bar
+// radii, and the internal-line threshold. Kept out of the React layer so every
+// value is unit-testable in isolation (node env, no DOM). The orientation-
+// neutral rounded-rect SVG path lives in `../../shared/cartesian/roundedBarPath`.
+//
+// Ported from openui's HorizontalBarChart constants + getRadiusArray corner
+// logic (the `orientation:"horizontal"` branches).
+
+import type { ChartData } from "../../types";
+
+/** One bar's cross-axis thickness (px). */
+export const BAR_HEIGHT = 16;
+/** Gap between grouped bars within a single category (px). */
+export const BAR_GAP = 10;
+/** Padding added below each category group, between the label and the next
+ * row (px). openui's BAR_CATEGORY_GAP. */
+export const GROUP_PADDING = 16;
+/** Floor for a lone category's content height so a single row still fills a
+ * sensible amount of the body (px). */
+export const SINGLE_ROW_MIN = 80;
+
+/** Fixed height (px) of the bottom value-axis band. The scroll body's height is
+ * `chartHeight - X_AXIS_HEIGHT`, and the fixed axis svg is drawn at exactly
+ * this height, so keeping ONE constant keeps the two in lock-step (drift would
+ * desync the axis svg vs the body sizing). openui's X_AXIS_HEIGHT. */
+export const X_AXIS_HEIGHT = 40;
+
+/** Corner radius for a bar's rounded (outer) end (px). openui BAR_RADIUS. */
+export const BAR_RADIUS = 4;
+/** A bar's extent (width) must reach this before its internal decorative line
+ * is drawn (px). Below it the line is hidden. openui MIN_LINE_DIMENSION. */
+export const MIN_LINE_DIMENSION = 8;
+/** Inset from each end of the bar to the internal line's endpoints (px).
+ * Consumed by the React layer when it lays out the internal line. openui
+ * LINE_PADDING. */
+export const LINE_PADDING = 6;
+
+type BarChartVariant = "grouped" | "stacked";
+
+/**
+ * Height of one category group: its label plus the bar stack plus the trailing
+ * group padding.
+ * - grouped: every series gets its own `BAR_HEIGHT` bar separated by `BAR_GAP`
+ * (n bars → n-1 gaps), so `n*(BAR_HEIGHT+BAR_GAP) - BAR_GAP`.
+ * - stacked: all series share a single `BAR_HEIGHT` bar, so `seriesCount` is
+ * irrelevant.
+ * `labelHeight` is the measured category-label height (caller measures it).
+ */
+export function groupHeight(
+ seriesCount: number,
+ variant: BarChartVariant,
+ labelHeight: number,
+): number {
+ const barsHeight =
+ variant === "stacked" ? BAR_HEIGHT : seriesCount * (BAR_HEIGHT + BAR_GAP) - BAR_GAP;
+ return barsHeight + labelHeight + GROUP_PADDING;
+}
+
+/**
+ * Total scrollable content height for `rowCount` categories. Empty → 0. A lone
+ * category is floored at `SINGLE_ROW_MIN` so a single row doesn't collapse to a
+ * sliver.
+ */
+export function contentHeight(rowCount: number, groupHeight: number): number {
+ if (rowCount === 0) return 0;
+ const total = rowCount * groupHeight;
+ if (rowCount === 1) return Math.max(total, SINGLE_ROW_MIN);
+ return total;
+}
+
+/**
+ * Vertical pad that centers the content within the scroll body. When the
+ * content overflows the body (`paddingValue < 0`) fall back to a fixed
+ * `{top:10, bottom:10}` inset so the first/last rows aren't flush to the edges;
+ * otherwise split the slack evenly top and bottom.
+ */
+export function verticalPadding(
+ contentHeight: number,
+ bodyHeight: number,
+): { top: number; bottom: number } {
+ const paddingValue = bodyHeight - contentHeight;
+ if (paddingValue < 0) return { top: 10, bottom: 10 };
+ return { top: paddingValue / 2, bottom: paddingValue / 2 };
+}
+
+/**
+ * Cumulative y (top) of each category row: `topPad + i*groupHeight`. Empty → [].
+ */
+export function rowOffsets(rowCount: number, groupHeight: number, topPad: number): number[] {
+ return Array.from({ length: rowCount }, (_, i) => topPad + i * groupHeight);
+}
+
+/**
+ * Snap-scroll targets, one per category: `[0, g, 2g, …]`. Empty → `[0]` so the
+ * caller always has a valid target to scroll to.
+ */
+export function snapPositions(rowCount: number, groupHeight: number): number[] {
+ if (rowCount === 0) return [0];
+ return Array.from({ length: rowCount }, (_, i) => i * groupHeight);
+}
+
+/**
+ * Index of the snap to scroll to. Finds the highest snap at or before `current`
+ * (the enclosing row), then steps one row in `dir`, clamped to the ends. The
+ * caller scrolls to `positions[idx] ?? 0`.
+ */
+export function nearestSnap(positions: number[], current: number, dir: "up" | "down"): number {
+ let idx = 0;
+ for (let i = 0; i < positions.length; i++) {
+ if (positions[i]! <= current) idx = i;
+ }
+ return dir === "up" ? Math.max(0, idx - 1) : Math.min(positions.length - 1, idx + 1);
+}
+
+/**
+ * A single row value as a finite number. Anything non-numeric (`undefined`,
+ * `null`, a non-numeric string, `NaN`, `±Infinity`) collapses to 0; the SIGN is
+ * kept — unlike the SegmentedBar, negatives are meaningful here (they draw left
+ * of the value-zero line), so we clamp only to finiteness, never to `>= 0`.
+ */
+export function barValue(raw: unknown): number {
+ const value = Number(raw);
+ return Number.isFinite(value) ? value : 0;
+}
+
+/**
+ * The value-axis domain, always anchored through zero (the bar origin), so 0 is
+ * ALWAYS inside the returned range.
+ * - grouped: the global `[min(0, minValue), max(0, maxValue)]` over every
+ * series value (each bar is independent).
+ * - stacked: per-row signed sums — positives sum rightward, negatives sum
+ * leftward (d3 `stackOffsetDiverging`) — so the extent is
+ * `[min(0, lowest negative sum), max(0, highest positive sum)]`.
+ *
+ * Empty data → `[0, 0]` (matching `computeYDomain`). The caller applies
+ * `.nice()`; this stays exact.
+ */
+export function valueDomain(
+ data: ChartData,
+ dataKeys: string[],
+ variant: BarChartVariant,
+): [number, number] {
+ let min = 0;
+ let max = 0;
+
+ for (const row of data) {
+ if (variant === "stacked") {
+ let positiveSum = 0;
+ let negativeSum = 0;
+ for (const key of dataKeys) {
+ const value = barValue(row[key]);
+ if (value >= 0) positiveSum += value;
+ else negativeSum += value;
+ }
+ if (positiveSum > max) max = positiveSum;
+ if (negativeSum < min) min = negativeSum;
+ } else {
+ for (const key of dataKeys) {
+ const value = barValue(row[key]);
+ if (value > max) max = value;
+ if (value < min) min = value;
+ }
+ }
+ }
+
+ return [min, max];
+}
+
+/** One classified segment of a stacked row. */
+export interface StackSegment {
+ /** The series key this segment renders. */
+ key: string;
+ /** The (finite, signed) value. */
+ value: number;
+ /** Negatives draw left of the zero line, positives right. */
+ isNegative: boolean;
+ /** Innermost segment of its sign group (adjacent to the zero line). */
+ isFirst: boolean;
+ /** Outermost segment of its sign group (its far end rounds). */
+ isLast: boolean;
+}
+
+/**
+ * Split a stacked row's values into its ordered positive and negative segments.
+ * Series keep their `dataKeys` order within each sign group, so positives read
+ * left→right from the zero line (index 0 innermost, growing rightward) and
+ * negatives read right→left from it (index 0 innermost, growing leftward) — the
+ * order d3's diverging stack lays them out. Zero-valued keys join the positive
+ * group (openui `>= 0`), matching `getBarStackInfo`; they render zero-width so
+ * their placement is immaterial. The first/last flags per group drive corner
+ * rounding: only the OUTERMOST (`isLast`) segment rounds its far end.
+ */
+export function stackSegments(
+ rowValues: ChartData[number],
+ dataKeys: string[],
+): { positives: StackSegment[]; negatives: StackSegment[] } {
+ const positives: StackSegment[] = [];
+ const negatives: StackSegment[] = [];
+
+ for (const key of dataKeys) {
+ const value = barValue(rowValues[key]);
+ const isNegative = value < 0;
+ const segment: StackSegment = {
+ key,
+ value,
+ isNegative,
+ isFirst: false,
+ isLast: false,
+ };
+ if (isNegative) negatives.push(segment);
+ else positives.push(segment);
+ }
+
+ for (const group of [positives, negatives]) {
+ if (group.length > 0) {
+ group[0]!.isFirst = true;
+ group[group.length - 1]!.isLast = true;
+ }
+ }
+
+ return { positives, negatives };
+}
+
+/**
+ * Per-corner radii `[tl, tr, br, bl]` for one horizontal bar segment. The
+ * horizontal slice of openui's `getRadiusArray`:
+ * - grouped: positive rounds its right end `[0, r, r, 0]`, negative its left
+ * end `[r, 0, 0, r]` (each bar is independent).
+ * - stacked: only the OUTERMOST segment of a sign group (`isLast`) rounds its
+ * far end; a single-segment stack (`isFirst && isLast`) rounds like a grouped
+ * bar; inner segments stay square `[0, 0, 0, 0]`.
+ */
+export function radiusArray(
+ variant: BarChartVariant,
+ radius: number,
+ isFirst: boolean,
+ isLast: boolean,
+ isNegative: boolean,
+): [number, number, number, number] {
+ if (variant === "grouped") {
+ return isNegative ? [radius, 0, 0, radius] : [0, radius, radius, 0];
+ }
+
+ // stacked
+ // A lone segment rounds its outer end exactly like a grouped bar.
+ if (isFirst && isLast) {
+ return isNegative ? [radius, 0, 0, radius] : [0, radius, radius, 0];
+ }
+ // In a multi-segment stack only the outermost segment rounds its far end.
+ if (isLast) {
+ return isNegative ? [radius, 0, 0, radius] : [0, radius, radius, 0];
+ }
+ return [0, 0, 0, 0];
+}
+
+/**
+ * Whether a bar is wide enough to carry its internal decorative line: openui
+ * hides the line once the bar's extent drops below `MIN_LINE_DIMENSION` so it
+ * doesn't crowd a sliver of a bar.
+ */
+export function showInternalLine(barWidth: number): boolean {
+ return barWidth >= MIN_LINE_DIMENSION;
+}
diff --git a/packages/react-ui/src/components/D3Charts/BarChart/parts/verticalBarRadii.test.ts b/packages/react-ui/src/components/D3Charts/BarChart/parts/verticalBarRadii.test.ts
new file mode 100644
index 000000000..0c0af0da9
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/BarChart/parts/verticalBarRadii.test.ts
@@ -0,0 +1,15 @@
+import { describe, expect, it } from "vitest";
+import { verticalBarRadii } from "./verticalBarRadii";
+
+describe("verticalBarRadii", () => {
+ it("positive rounded → rounds the TOP two corners [r, r, 0, 0]", () => {
+ expect(verticalBarRadii(4, false, true)).toEqual([4, 4, 0, 0]);
+ });
+ it("negative rounded → rounds the BOTTOM two corners [0, 0, r, r]", () => {
+ expect(verticalBarRadii(4, true, true)).toEqual([0, 0, 4, 4]);
+ });
+ it("not rounded → all zero regardless of sign", () => {
+ expect(verticalBarRadii(4, false, false)).toEqual([0, 0, 0, 0]);
+ expect(verticalBarRadii(4, true, false)).toEqual([0, 0, 0, 0]);
+ });
+});
diff --git a/packages/react-ui/src/components/D3Charts/BarChart/parts/verticalBarRadii.ts b/packages/react-ui/src/components/D3Charts/BarChart/parts/verticalBarRadii.ts
new file mode 100644
index 000000000..548e2b54d
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/BarChart/parts/verticalBarRadii.ts
@@ -0,0 +1,20 @@
+/**
+ * Per-corner radii `[tl, tr, br, bl]` for one VERTICAL bar, matching react-ui:
+ * only the OUTER corners round, so a bar stays flat against its baseline.
+ * - `rounded === false` → no rounding, `[0, 0, 0, 0]` (inner stacked segments).
+ * - positive bar (grows up from the baseline) rounds its TOP two corners,
+ * `[radius, radius, 0, 0]`.
+ * - negative bar (grows down from the baseline) rounds its BOTTOM two corners,
+ * `[0, 0, radius, radius]`.
+ *
+ * The vertical counterpart of the horizontal `radiusArray`; fed to
+ * `roundedBarPath` alongside the bar box.
+ */
+export function verticalBarRadii(
+ radius: number,
+ isNegative: boolean,
+ rounded: boolean,
+): [number, number, number, number] {
+ if (!rounded) return [0, 0, 0, 0];
+ return isNegative ? [0, 0, radius, radius] : [radius, radius, 0, 0];
+}
diff --git a/packages/react-ui/src/components/D3Charts/BarChart/stories/HorizontalBarChart.stories.tsx b/packages/react-ui/src/components/D3Charts/BarChart/stories/HorizontalBarChart.stories.tsx
new file mode 100644
index 000000000..caea56f4f
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/BarChart/stories/HorizontalBarChart.stories.tsx
@@ -0,0 +1,913 @@
+// Copy of Charts/HorizontalBarChart/stories/HorizontalBarChart.stories.tsx with only the chart import and the title changed:
+// the same args and renders, rendering the D3Charts chart via
+// ../../stories/rechartsStoryAdapters.
+import type { Meta, StoryObj } from "@storybook/react";
+import { Monitor, TabletSmartphone } from "lucide-react";
+import { useState } from "react";
+import { Card } from "../../../Card";
+import { HorizontalBarChart, HorizontalBarChartProps } from "../../stories/rechartsStoryAdapters";
+
+// 📊 ALL DATA VARIATIONS - For easy switching in stories
+const dataVariations = {
+ default: [
+ {
+ category: "A",
+ desktop: 150,
+ mobile: 90,
+ tablet: 120,
+ laptop: 180,
+ },
+ {
+ category: "B",
+ desktop: 280,
+ mobile: 180,
+ tablet: 140,
+ laptop: 160,
+ },
+ {
+ category: "C",
+ desktop: 220,
+ mobile: 140,
+ tablet: 160,
+ laptop: 180,
+ },
+ {
+ category: "D",
+ desktop: 180,
+ mobile: 160,
+ tablet: 180,
+ laptop: 200,
+ },
+ {
+ category: "E",
+ desktop: 250,
+ mobile: 120,
+ tablet: 140,
+ laptop: 160,
+ },
+ ],
+ small: [
+ { category: "Q1", desktop: 150, mobile: 90 },
+ { category: "Q2", desktop: 280, mobile: 180 },
+ { category: "Q3", desktop: 220, mobile: 140 },
+ ],
+ large: [
+ {
+ category: "North America",
+ revenue: 150000,
+ expenses: 90000,
+ profit: 60000,
+ marketing: 30000,
+ operations: 40000,
+ },
+ {
+ category: "Europe",
+ revenue: 280000,
+ expenses: 180000,
+ profit: 100000,
+ marketing: 50000,
+ operations: 70000,
+ },
+ {
+ category: "Asia Pacific",
+ revenue: 220000,
+ expenses: 140000,
+ profit: 80000,
+ marketing: 40000,
+ operations: 60000,
+ },
+ {
+ category: "Latin America",
+ revenue: 180000,
+ expenses: 160000,
+ profit: 20000,
+ marketing: 35000,
+ operations: 55000,
+ },
+ {
+ category: "Middle East",
+ revenue: 250000,
+ expenses: 120000,
+ profit: 130000,
+ marketing: 45000,
+ operations: 65000,
+ },
+ {
+ category: "Africa",
+ revenue: 120000,
+ expenses: 80000,
+ profit: 40000,
+ marketing: 25000,
+ operations: 35000,
+ },
+ {
+ category: "Oceania",
+ revenue: 95000,
+ expenses: 65000,
+ profit: 30000,
+ marketing: 20000,
+ operations: 25000,
+ },
+ {
+ category: "Southeast Asia",
+ revenue: 180000,
+ expenses: 110000,
+ profit: 70000,
+ marketing: 35000,
+ operations: 50000,
+ },
+ {
+ category: "Eastern Europe",
+ revenue: 140000,
+ expenses: 95000,
+ profit: 45000,
+ marketing: 28000,
+ operations: 42000,
+ },
+ {
+ category: "Scandinavia",
+ revenue: 160000,
+ expenses: 100000,
+ profit: 60000,
+ marketing: 32000,
+ operations: 48000,
+ },
+ ],
+ simple: [
+ { department: "Sales", performance: 1200 },
+ { department: "Marketing", performance: 950 },
+ { department: "Engineering", performance: 1100 },
+ { department: "Support", performance: 800 },
+ ],
+ edge: [{ period: "Current Quarter", sales: 500, target: 600 }],
+ bigNumbers: [
+ { company: "Apple Inc.", revenue: 394328000000, profit: 99803000000 },
+ { company: "Microsoft Corp.", revenue: 211915000000, profit: 83383000000 },
+ { company: "Alphabet Inc.", revenue: 307394000000, profit: 76033000000 },
+ { company: "Amazon.com Inc.", revenue: 574785000000, profit: 33364000000 },
+ ],
+ expandCollapseChannels: [
+ {
+ channel: "Website Traffic and Organic Search Results",
+ impressions: 120000,
+ clicks: 15000,
+ conversions: 1200,
+ cost: 8500,
+ revenue: 24000,
+ roi: 182,
+ ctr: 12.5,
+ cpc: 0.57,
+ cpa: 7.08,
+ reach: 95000,
+ engagement: 8200,
+ shares: 420,
+ saves: 180,
+ comments: 650,
+ videoViews: 0,
+ },
+ {
+ channel: "Social Media Engagement and Brand Awareness",
+ impressions: 85000,
+ clicks: 12000,
+ conversions: 950,
+ cost: 6200,
+ revenue: 19000,
+ roi: 206,
+ ctr: 14.1,
+ cpc: 0.52,
+ cpa: 6.53,
+ reach: 72000,
+ engagement: 15400,
+ shares: 890,
+ saves: 340,
+ comments: 1200,
+ videoViews: 28000,
+ },
+ {
+ channel: "Email Marketing Campaign Performance",
+ impressions: 45000,
+ clicks: 8500,
+ conversions: 800,
+ cost: 2100,
+ revenue: 16000,
+ roi: 562,
+ ctr: 18.9,
+ cpc: 0.25,
+ cpa: 2.63,
+ reach: 42000,
+ engagement: 6800,
+ shares: 120,
+ saves: 85,
+ comments: 240,
+ videoViews: 0,
+ },
+ {
+ channel: "Paid Advertising and PPC Campaign ROI",
+ impressions: 95000,
+ clicks: 18000,
+ conversions: 1500,
+ cost: 12500,
+ revenue: 30000,
+ roi: 140,
+ ctr: 18.9,
+ cpc: 0.69,
+ cpa: 8.33,
+ reach: 88000,
+ engagement: 12600,
+ shares: 320,
+ saves: 150,
+ comments: 480,
+ videoViews: 5200,
+ },
+ {
+ channel: "Content Marketing and Blog Performance",
+ impressions: 60000,
+ clicks: 9500,
+ conversions: 750,
+ cost: 4800,
+ revenue: 15000,
+ roi: 213,
+ ctr: 15.8,
+ cpc: 0.51,
+ cpa: 6.4,
+ reach: 55000,
+ engagement: 7800,
+ shares: 680,
+ saves: 420,
+ comments: 950,
+ videoViews: 12000,
+ },
+ {
+ channel: "Mobile Application Downloads and Usage",
+ impressions: 70000,
+ clicks: 11000,
+ conversions: 1100,
+ cost: 5500,
+ revenue: 22000,
+ roi: 300,
+ ctr: 15.7,
+ cpc: 0.5,
+ cpa: 5.0,
+ reach: 65000,
+ engagement: 9200,
+ shares: 180,
+ saves: 95,
+ comments: 320,
+ videoViews: 8500,
+ },
+ {
+ channel: "Customer Support Response Time and Quality",
+ impressions: 35000,
+ clicks: 5500,
+ conversions: 450,
+ cost: 2800,
+ revenue: 9000,
+ roi: 221,
+ ctr: 15.7,
+ cpc: 0.51,
+ cpa: 6.22,
+ reach: 32000,
+ engagement: 4200,
+ shares: 45,
+ saves: 25,
+ comments: 180,
+ videoViews: 0,
+ },
+ {
+ channel: "Sales Funnel Conversion and Lead Generation",
+ impressions: 110000,
+ clicks: 22000,
+ conversions: 1800,
+ cost: 15000,
+ revenue: 36000,
+ roi: 140,
+ ctr: 20.0,
+ cpc: 0.68,
+ cpa: 8.33,
+ reach: 98000,
+ engagement: 18500,
+ shares: 420,
+ saves: 280,
+ comments: 750,
+ videoViews: 3200,
+ },
+ {
+ channel: "User Retention and Churn Rate Analysis",
+ impressions: 80000,
+ clicks: 14000,
+ conversions: 1200,
+ cost: 7200,
+ revenue: 24000,
+ roi: 233,
+ ctr: 17.5,
+ cpc: 0.51,
+ cpa: 6.0,
+ reach: 75000,
+ engagement: 11200,
+ shares: 280,
+ saves: 150,
+ comments: 420,
+ videoViews: 6800,
+ },
+ {
+ channel: "Product Feature Usage and Performance Metrics",
+ impressions: 65000,
+ clicks: 10500,
+ conversions: 900,
+ cost: 5200,
+ revenue: 18000,
+ roi: 246,
+ ctr: 16.2,
+ cpc: 0.5,
+ cpa: 5.78,
+ reach: 58000,
+ engagement: 8500,
+ shares: 320,
+ saves: 180,
+ comments: 650,
+ videoViews: 4200,
+ },
+ {
+ channel: "Market Research and Competitive Analysis",
+ impressions: 40000,
+ clicks: 6500,
+ conversions: 500,
+ cost: 3200,
+ revenue: 10000,
+ roi: 213,
+ ctr: 16.3,
+ cpc: 0.49,
+ cpa: 6.4,
+ reach: 36000,
+ engagement: 5200,
+ shares: 95,
+ saves: 65,
+ comments: 220,
+ videoViews: 1800,
+ },
+ {
+ channel: "Brand Sentiment and Public Relations Impact",
+ impressions: 55000,
+ clicks: 8000,
+ conversions: 650,
+ cost: 4100,
+ revenue: 13000,
+ roi: 217,
+ ctr: 14.5,
+ cpc: 0.51,
+ cpa: 6.31,
+ reach: 48000,
+ engagement: 6800,
+ shares: 520,
+ saves: 280,
+ comments: 950,
+ videoViews: 15000,
+ },
+ ],
+ mixedPositiveNegative: [
+ { category: "Product A", profit: 100, loss: -50, net: 50 },
+ { category: "Product B", profit: 150, loss: -200, net: -50 },
+ { category: "Product C", profit: 200, loss: -100, net: 100 },
+ { category: "Product D", profit: -80, loss: -120, net: -200 },
+ { category: "Product E", profit: 300, loss: -150, net: 150 },
+ ],
+ singleGroup: [
+ { region: "North America (USA, Canada, Mexico)", sales: 150000 },
+ { region: "Europe (UK, Germany, France, Italy)", sales: 280000 },
+ { region: "Asia Pacific (Japan, Australia, South Korea)", sales: 220000 },
+ { region: "Latin America (Brazil, Argentina, Chile)", sales: 180000 },
+ { region: "Middle East (UAE, Saudi Arabia, Israel)", sales: 250000 },
+ ],
+};
+
+// Category key mappings for different datasets
+const categoryKeys = {
+ default: "category",
+ small: "category",
+ large: "category",
+ simple: "department",
+ edge: "period",
+ bigNumbers: "company",
+ expandCollapseChannels: "channel",
+ mixedPositiveNegative: "category",
+ singleGroup: "region",
+};
+
+// 🔥 ACTIVE DATA - For backward compatibility
+const horizontalBarChartData = dataVariations.default;
+
+const icons = {
+ desktop: Monitor,
+ mobile: TabletSmartphone,
+} as const;
+
+/**
+ * # HorizontalBarChart Component Documentation
+ *
+ * The HorizontalBarChart is a versatile component for comparing values across different categories in a horizontal layout.
+ * It's highly effective for:
+ *
+ * - **Category Comparison**: Easily compare metrics like sales, performance, or revenue across different groups.
+ * - **Ranking**: Show the highest and lowest performing items with a clear visual hierarchy.
+ * - **Data with Long Labels**: Perfect for datasets with lengthy category names that don't fit well in vertical layouts.
+ *
+ * ## Key Features
+ *
+ * ### Layout Variants
+ * - **Grouped**: Compare sub-categories side-by-side within a primary category.
+ * - **Stacked**: Show how sub-categories contribute to a total value for each primary category.
+ *
+ * ### Interactive & Responsive
+ * - **Vertical Scrolling**: Automatically enables scrolling when the number of bars exceeds the container height.
+ * - **Interactive Legend**: Toggle data series on and off. Handles overflow with a "Show More" button.
+ * - **Hover Tooltips**: Provides detailed data on hover for better user engagement.
+ * - **Responsive Design**: Adjusts gracefully to the size of its container.
+ *
+ * ### Customization
+ * - **Theming**: Six built-in color palettes, or use custom colors with `customPalette`.
+ * - **Bar Styling**: Customize the corner radius of the bars.
+ * - **Axis and Grid Control**: Toggle visibility of axes and grid lines.
+ */
+const meta: Meta<HorizontalBarChartProps<typeof horizontalBarChartData>> = {
+ title: "Components/D3Charts/HorizontalBarChart",
+ component: HorizontalBarChart,
+ parameters: {
+ layout: "centered",
+ docs: {
+ description: {
+ component: `
+## Installation and Basic Usage
+
+\`\`\`tsx
+import { HorizontalBarChart } from '@openuidev/react-ui/Charts/HorizontalBarChart';
+
+const salesData = [
+ { region: "North America", sales: 150000, profit: 45000 },
+ { region: "Europe", sales: 280000, profit: 68000 },
+ { region: "Asia Pacific", sales: 220000, profit: 52000 },
+];
+
+// Basic implementation
+<HorizontalBarChart
+ data={salesData}
+ categoryKey="region"
+ theme="ocean"
+/>
+
+// With custom colors
+<HorizontalBarChart
+ data={salesData}
+ categoryKey="region"
+ customPalette={["#FF6B6B", "#4ECDC4", "#45B7D1"]}
+/>
+\`\`\`
+
+## Data Structure Requirements
+
+Your data should be an array of objects. Each object must contain:
+- A **category field** (string or number): Used for the Y-axis labels (e.g., regions, departments).
+- One or more **data series fields** (number): These are the values that will be plotted as bars. The key of the field is used as the series name in the legend and tooltip.
+
+\`\`\`tsx
+const performanceData = [
+ { department: "Sales", performance: 5400, target: 6000 },
+ { department: "Marketing", performance: 8200, target: 7500 },
+ { department: "Engineering", performance: 7100, target: 7000 },
+];
+\`\`\`
+
+## Performance Considerations
+- **Data Volume**: The chart uses virtualization for vertical scrolling, but performance can still be impacted by an extremely large number of data points (e.g., 1000+).
+- **Responsiveness**: The chart adapts to its container, but ensure that bar heights and gaps are readable on very small screens.
+- **Animation**: Can be disabled via \`isAnimationActive={false}\` for better performance with large datasets.
+`,
+ },
+ },
+ },
+ tags: ["!dev", "autodocs"],
+ argTypes: {
+ data: {
+ description: `
+**Required.** An array of data objects representing your dataset. Each object should contain:
+- A category identifier (string/number) for the Y-axis.
+- One or more numeric values for the X-axis bars.
+`,
+ control: false,
+ table: {
+ type: { summary: "Array<Record<string, string | number>>" },
+ category: "📊 Data Configuration",
+ },
+ },
+ categoryKey: {
+ description:
+ "**Required.** The key in your data object that represents the category for the Y-axis (e.g., 'region', 'department').",
+ control: false,
+ table: {
+ type: { summary: "string" },
+ category: "📊 Data Configuration",
+ },
+ },
+ theme: {
+ description:
+ "Specifies the color palette for the chart's bars, tooltips, and legend. Ignored when customPalette is provided.",
+ control: "select",
+ options: ["ocean", "orchid", "emerald", "sunset", "spectrum", "vivid"],
+ table: {
+ defaultValue: { summary: "ocean" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ customPalette: {
+ description:
+ "Custom array of colors to use instead of the theme palette. Overrides the theme prop when provided.",
+ control: "object",
+ table: {
+ type: { summary: "string[]" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ variant: {
+ description:
+ "Defines how multiple data series are displayed: `grouped` (side-by-side) or `stacked` (on top of each other).",
+ control: "radio",
+ options: ["grouped", "stacked"],
+ table: {
+ defaultValue: { summary: "grouped" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ radius: {
+ description: "Sets the corner radius for the bars, creating a rounded look.",
+ control: { type: "number", min: 0, max: 20 },
+ table: {
+ type: { summary: "number" },
+ defaultValue: { summary: "4" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ icons: {
+ description:
+ "An object mapping data series keys to React components to be used as icons in the legend.",
+ control: false,
+ table: {
+ type: { summary: "Record<string, React.ReactNode>" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ grid: {
+ description: "Toggles the visibility of the background grid lines.",
+ control: "boolean",
+ table: {
+ defaultValue: { summary: "true" },
+ category: "📱 Display Options",
+ },
+ },
+ legend: {
+ description: "Toggles the visibility of the chart legend.",
+ control: "boolean",
+ table: {
+ defaultValue: { summary: "true" },
+ category: "📱 Display Options",
+ },
+ },
+ showXAxis: {
+ description: "Toggles the visibility of the X-axis line and labels.",
+ control: "boolean",
+ table: {
+ defaultValue: { summary: "true" },
+ category: "📱 Display Options",
+ },
+ },
+ xAxisLabel: {
+ description: "A label to display below the X-axis.",
+ control: "text",
+ table: {
+ type: { summary: "React.ReactNode" },
+ category: "📱 Display Options",
+ },
+ },
+ yAxisLabel: {
+ description: "A label to display beside the Y-axis.",
+ control: "text",
+ table: {
+ type: { summary: "React.ReactNode" },
+ category: "📱 Display Options",
+ },
+ },
+ isAnimationActive: {
+ description: "Enables or disables the initial loading animation for the bars.",
+ control: "boolean",
+ table: {
+ defaultValue: { summary: "false" },
+ category: "🎬 Animation & Interaction",
+ },
+ },
+ height: {
+ description: "Sets a fixed height for the chart container in pixels.",
+ control: "number",
+ table: {
+ type: { summary: "number" },
+ category: "Layout & Sizing",
+ },
+ },
+ width: {
+ description: "Sets a fixed width for the chart container in pixels.",
+ control: "number",
+ table: {
+ type: { summary: "number" },
+ category: "Layout & Sizing",
+ },
+ },
+ },
+} satisfies Meta<typeof HorizontalBarChart>;
+
+export default meta;
+
+type Story = StoryObj<typeof meta>;
+
+/**
+ * ## Comprehensive Data Explorer
+ *
+ * This story serves as a comprehensive test suite for the HorizontalBarChart component.
+ * Use the buttons to switch between various datasets designed to test edge cases in:
+ *
+ * - **Data Volume**: Scenarios with few, many, or a single data point.
+ * - **Data Formatting**: Handling of large numbers and different value ranges.
+ * - **Legend Overflow**: A dataset with many series to test legend expand/collapse functionality.
+ *
+ * It's an excellent tool for developers to see how the chart behaves under different conditions.
+ */
+export const DataExplorer: Story = {
+ name: "🎛️ Comprehensive Data Explorer",
+ args: {
+ data: horizontalBarChartData,
+ categoryKey: "category",
+ theme: "ocean",
+ variant: "grouped",
+ radius: 4,
+ grid: true,
+ isAnimationActive: false,
+ showXAxis: true,
+ legend: true,
+ height: 400,
+ width: 600,
+ },
+ render: (args: any) => {
+ const [selectedDataType, setSelectedDataType] =
+ useState<keyof typeof dataVariations>("default");
+
+ const currentData = dataVariations[selectedDataType];
+ const currentCategoryKey = categoryKeys[selectedDataType];
+
+ const buttonStyle = {
+ margin: "2px",
+ padding: "6px 12px",
+ fontSize: "12px",
+ border: "1px solid #ddd",
+ borderRadius: "4px",
+ cursor: "pointer",
+ background: "#fff",
+ };
+
+ const activeButtonStyle = {
+ ...buttonStyle,
+ background: "#007acc",
+ color: "white",
+ border: "1px solid #007acc",
+ };
+
+ return (
+ <div>
+ <div
+ style={{
+ marginBottom: "16px",
+ padding: "12px",
+ background: "#f8f9fa",
+ borderRadius: "8px",
+ border: "1px solid #e9ecef",
+ width: "700px",
+ }}
+ >
+ <strong>💡 Quick Data Switch:</strong>
+ <div style={{ marginTop: "8px", display: "flex", flexWrap: "wrap", gap: "4px" }}>
+ <button
+ onClick={() => setSelectedDataType("default")}
+ style={selectedDataType === "default" ? activeButtonStyle : buttonStyle}
+ >
+ 📊 Default (5 categories)
+ </button>
+ <button
+ onClick={() => setSelectedDataType("small")}
+ style={selectedDataType === "small" ? activeButtonStyle : buttonStyle}
+ >
+ 📱 Small (3 items)
+ </button>
+ <button
+ onClick={() => setSelectedDataType("large")}
+ style={selectedDataType === "large" ? activeButtonStyle : buttonStyle}
+ >
+ 🌐 Large (10 regions)
+ </button>
+ <button
+ onClick={() => setSelectedDataType("simple")}
+ style={selectedDataType === "simple" ? activeButtonStyle : buttonStyle}
+ >
+ 🏢 Simple (4 departments)
+ </button>
+ <button
+ onClick={() => setSelectedDataType("bigNumbers")}
+ style={selectedDataType === "bigNumbers" ? activeButtonStyle : buttonStyle}
+ >
+ 💰 Big Numbers
+ </button>
+ <button
+ onClick={() => setSelectedDataType("edge")}
+ style={selectedDataType === "edge" ? activeButtonStyle : buttonStyle}
+ >
+ 🎯 Single Item
+ </button>
+ <button
+ onClick={() => setSelectedDataType("singleGroup")}
+ style={selectedDataType === "singleGroup" ? activeButtonStyle : buttonStyle}
+ >
+ 🌍 Single Group
+ </button>
+ <button
+ onClick={() => setSelectedDataType("mixedPositiveNegative")}
+ style={selectedDataType === "mixedPositiveNegative" ? activeButtonStyle : buttonStyle}
+ >
+ 📈 Mixed +/-
+ </button>
+ <button
+ onClick={() => setSelectedDataType("expandCollapseChannels")}
+ style={
+ selectedDataType === "expandCollapseChannels" ? activeButtonStyle : buttonStyle
+ }
+ >
+ 🔄 Marketing Channels
+ </button>
+ </div>
+ <div style={{ marginTop: "8px", fontSize: "12px", color: "#666" }}>
+ <strong>Current:</strong> {selectedDataType} | <strong>Items:</strong>{" "}
+ {currentData.length} | <strong>Category:</strong> {currentCategoryKey}
+ </div>
+ </div>
+ <Card style={{ width: "700px" }}>
+ <HorizontalBarChart {...args} data={currentData} categoryKey={currentCategoryKey} />
+ </Card>
+ </div>
+ );
+ },
+};
+
+// Basic stories using the new data structure
+export const Default: Story = {
+ args: {
+ data: dataVariations.default,
+ categoryKey: "category",
+ theme: "ocean",
+ variant: "grouped",
+ height: 400,
+ width: 600,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "600px" }}>
+ <HorizontalBarChart {...args} />
+ </Card>
+ ),
+};
+
+export const Stacked: Story = {
+ args: {
+ data: dataVariations.default,
+ categoryKey: "category",
+ theme: "ocean",
+ variant: "stacked",
+ height: 400,
+ width: 600,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "600px" }}>
+ <HorizontalBarChart {...args} />
+ </Card>
+ ),
+};
+
+export const WithAnimations: Story = {
+ args: {
+ data: dataVariations.default,
+ categoryKey: "category",
+ theme: "ocean",
+ variant: "grouped",
+ isAnimationActive: true,
+ height: 400,
+ width: 600,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "600px" }}>
+ <HorizontalBarChart {...args} />
+ </Card>
+ ),
+};
+
+export const CustomPalette: Story = {
+ args: {
+ data: dataVariations.default,
+ categoryKey: "category",
+ customPalette: ["#FF6B6B", "#4ECDC4", "#45B7D1", "#96CEB4", "#FECA57"],
+ variant: "grouped",
+ height: 400,
+ width: 600,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "600px" }}>
+ <HorizontalBarChart {...args} />
+ </Card>
+ ),
+};
+
+export const CustomPaletteVibrant: Story = {
+ name: "🎨 Custom Palette - Vibrant",
+ args: {
+ data: dataVariations.default,
+ categoryKey: "category",
+ customPalette: ["#FF1744", "#00E676", "#2979FF", "#FF9100", "#9C27B0"],
+ variant: "grouped",
+ height: 400,
+ width: 600,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "600px" }}>
+ <HorizontalBarChart {...args} />
+ </Card>
+ ),
+};
+
+export const BigNumbers: Story = {
+ args: {
+ data: dataVariations.bigNumbers,
+ categoryKey: "company",
+ theme: "vivid",
+ variant: "grouped",
+ height: 400,
+ width: 600,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "600px" }}>
+ <HorizontalBarChart {...args} />
+ </Card>
+ ),
+};
+
+export const LargeDataset: Story = {
+ args: {
+ data: dataVariations.large,
+ categoryKey: "category",
+ theme: "emerald",
+ variant: "grouped",
+ height: 400,
+ width: 600,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "600px" }}>
+ <HorizontalBarChart {...args} />
+ </Card>
+ ),
+};
+
+export const MixedPositiveNegative: Story = {
+ name: "📈 Mixed Positive and Negative",
+ args: {
+ data: dataVariations.mixedPositiveNegative,
+ categoryKey: "category",
+ theme: "spectrum",
+ variant: "grouped",
+ height: 400,
+ width: 600,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "600px" }}>
+ <HorizontalBarChart {...args} />
+ </Card>
+ ),
+};
+
+export const WithIcons: Story = {
+ args: {
+ data: dataVariations.default,
+ categoryKey: "category",
+ theme: "ocean",
+ variant: "grouped",
+ height: 400,
+ width: 600,
+ icons: {
+ desktop: Monitor,
+ mobile: TabletSmartphone,
+ },
+ },
+ render: (args: any) => (
+ <Card style={{ width: "600px" }}>
+ <HorizontalBarChart {...args} />
+ </Card>
+ ),
+};
diff --git a/packages/react-ui/src/components/D3Charts/BarChart/stories/barChart.stories.tsx b/packages/react-ui/src/components/D3Charts/BarChart/stories/barChart.stories.tsx
new file mode 100644
index 000000000..1d5ed5e44
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/BarChart/stories/barChart.stories.tsx
@@ -0,0 +1,1435 @@
+// Copy of Charts/BarChart/stories/barChart.stories.tsx with only the chart import and the title changed:
+// the same args and renders, rendering the D3Charts chart via
+// ../../stories/rechartsStoryAdapters.
+import type { Meta, StoryObj } from "@storybook/react";
+import { Monitor, TabletSmartphone } from "lucide-react";
+import { useState } from "react";
+import { Card } from "../../../Card";
+import { BarChart, BarChartProps } from "../../stories/rechartsStoryAdapters";
+
+// 📊 ALL DATA VARIATIONS - For easy switching in stories
+const dataVariations = {
+ default: [
+ {
+ month: "January 2024 - First Month of the Year",
+ desktop: 150,
+ mobile: 90,
+ tablet: 120,
+ laptop: 180,
+ },
+ {
+ month: "February 2024 - Second Month of the Year",
+ desktop: 280,
+ mobile: 180,
+ tablet: 140,
+ laptop: 160,
+ },
+ {
+ month: "March 2024 - Third Month of the Year",
+ desktop: 220,
+ mobile: 140,
+ tablet: 160,
+ laptop: 180,
+ },
+ {
+ month: "April 2024 - Fourth Month of the Year",
+ desktop: 180,
+ mobile: 160,
+ tablet: 180,
+ laptop: 200,
+ },
+ {
+ month: "May 2024 - Fifth Month of the Year",
+ desktop: 250,
+ mobile: 120,
+ tablet: 140,
+ laptop: 160,
+ },
+ {
+ month: "June 2024 - Sixth Month of the Year",
+ desktop: 300,
+ mobile: 180,
+ tablet: 160,
+ laptop: 180,
+ },
+ {
+ month: "July 2024 - Seventh Month of the Year",
+ desktop: 350,
+ mobile: 220,
+ tablet: 180,
+ laptop: 200,
+ },
+ {
+ month: "August 2024 - Eighth Month of the Year",
+ desktop: 400,
+ mobile: 240,
+ tablet: 200,
+ laptop: 220,
+ },
+ {
+ month: "September 2024 - Ninth Month of the Year",
+ desktop: 450,
+ mobile: 260,
+ tablet: 220,
+ laptop: 240,
+ },
+ {
+ month: "October 2024 - Tenth Month of the Year",
+ desktop: 500,
+ mobile: 280,
+ tablet: 240,
+ laptop: 260,
+ },
+ {
+ month: "November 2024 - Eleventh Month of the Year",
+ desktop: 550,
+ mobile: 300,
+ tablet: 260,
+ laptop: 280,
+ },
+ {
+ month: "December 2024 - Twelfth Month of the Year",
+ desktop: 600,
+ mobile: 320,
+ tablet: 280,
+ laptop: 300,
+ },
+ ],
+ small: [
+ { month: "Jan", desktop: 150, mobile: 90 },
+ { month: "Feb", desktop: 280, mobile: 180 },
+ { month: "Mar", desktop: 220, mobile: 140 },
+ ],
+ large: [
+ {
+ month: "Jan 2022",
+ desktop: 150,
+ mobile: 90,
+ tablet: 120,
+ laptop: 180,
+ tv: 50,
+ watch: 30,
+ smartwatch: 20,
+ },
+ {
+ month: "Feb 2022",
+ desktop: 280,
+ mobile: 180,
+ tablet: 140,
+ laptop: 160,
+ tv: 70,
+ watch: 40,
+ smartwatch: 30,
+ },
+ {
+ month: "Mar 2022",
+ desktop: 220,
+ mobile: 140,
+ tablet: 160,
+ laptop: 180,
+ tv: 60,
+ watch: 35,
+ smartwatch: 25,
+ },
+ {
+ month: "Apr 2022",
+ desktop: 180,
+ mobile: 160,
+ tablet: 180,
+ laptop: 200,
+ tv: 80,
+ watch: 45,
+ smartwatch: 35,
+ },
+ {
+ month: "May 2022",
+ desktop: 250,
+ mobile: 120,
+ tablet: 140,
+ laptop: 160,
+ tv: 55,
+ watch: 25,
+ smartwatch: 20,
+ },
+ {
+ month: "Jun 2022",
+ desktop: 300,
+ mobile: 180,
+ tablet: 160,
+ laptop: 180,
+ tv: 75,
+ watch: 50,
+ smartwatch: 30,
+ },
+ {
+ month: "Jul 2022",
+ desktop: 350,
+ mobile: 220,
+ tablet: 180,
+ laptop: 200,
+ tv: 85,
+ watch: 55,
+ smartwatch: 35,
+ },
+ {
+ month: "Aug 2022",
+ desktop: 400,
+ mobile: 240,
+ tablet: 200,
+ laptop: 220,
+ tv: 90,
+ watch: 60,
+ smartwatch: 40,
+ },
+ {
+ month: "Sep 2022",
+ desktop: 450,
+ mobile: 260,
+ tablet: 220,
+ laptop: 240,
+ tv: 95,
+ watch: 65,
+ smartwatch: 45,
+ },
+ {
+ month: "Oct 2022",
+ desktop: 500,
+ mobile: 280,
+ tablet: 240,
+ laptop: 260,
+ tv: 100,
+ watch: 70,
+ smartwatch: 50,
+ },
+ {
+ month: "Nov 2022",
+ desktop: 550,
+ mobile: 300,
+ tablet: 260,
+ laptop: 280,
+ tv: 105,
+ watch: 75,
+ smartwatch: 55,
+ },
+ {
+ month: "Dec 2022",
+ desktop: 600,
+ mobile: 320,
+ tablet: 280,
+ laptop: 300,
+ tv: 110,
+ watch: 80,
+ smartwatch: 60,
+ },
+ {
+ month: "Jan 2023",
+ desktop: 650,
+ mobile: 340,
+ tablet: 300,
+ laptop: 320,
+ tv: 115,
+ watch: 85,
+ smartwatch: 65,
+ },
+ {
+ month: "Feb 2023",
+ desktop: 700,
+ mobile: 360,
+ tablet: 320,
+ laptop: 340,
+ tv: 120,
+ watch: 90,
+ smartwatch: 70,
+ },
+ {
+ month: "Mar 2023",
+ desktop: 750,
+ mobile: 380,
+ tablet: 340,
+ laptop: 360,
+ tv: 125,
+ watch: 95,
+ smartwatch: 75,
+ },
+ {
+ month: "Apr 2023",
+ desktop: 800,
+ mobile: 400,
+ tablet: 360,
+ laptop: 380,
+ tv: 130,
+ watch: 100,
+ smartwatch: 80,
+ },
+ {
+ month: "May 2023",
+ desktop: 850,
+ mobile: 420,
+ tablet: 380,
+ laptop: 400,
+ tv: 135,
+ watch: 105,
+ smartwatch: 85,
+ },
+ {
+ month: "Jun 2023",
+ desktop: 900,
+ mobile: 440,
+ tablet: 400,
+ laptop: 420,
+ tv: 140,
+ watch: 110,
+ smartwatch: 90,
+ },
+ ],
+ simple: [
+ { quarter: "Q1", revenue: 1200, profit: 800 },
+ { quarter: "Q2", revenue: 1500, profit: 950 },
+ { quarter: "Q3", revenue: 1800, profit: 1100 },
+ { quarter: "Q4", revenue: 2000, profit: 1300 },
+ ],
+ edge: [{ period: "Current", sales: 500, target: 600 }],
+ numbers: [
+ { category: "Small", valueA: 5, valueB: 12, valueC: 8 },
+ { category: "Medium", valueA: 150, valueB: 180, valueC: 120 },
+ { category: "Large", valueA: 2500, valueB: 3200, valueC: 2800 },
+ { category: "XLarge", valueA: 45000, valueB: 52000, valueC: 48000 },
+ ],
+ weekly: [
+ { week: "W1", visits: 120, conversions: 15, sales: 1200 },
+ { week: "W2", visits: 150, conversions: 22, sales: 1800 },
+ { week: "W3", visits: 180, conversions: 28, sales: 2100 },
+ { week: "W4", visits: 200, conversions: 35, sales: 2500 },
+ { week: "W5", visits: 160, conversions: 18, sales: 1600 },
+ { week: "W6", visits: 190, conversions: 32, sales: 2300 },
+ { week: "W7", visits: 220, conversions: 40, sales: 2800 },
+ { week: "W8", visits: 240, conversions: 45, sales: 3200 },
+ { week: "W9", visits: 210, conversions: 38, sales: 2700 },
+ { week: "W10", visits: 230, conversions: 42, sales: 3000 },
+ { week: "W11", visits: 250, conversions: 48, sales: 3400 },
+ { week: "W12", visits: 270, conversions: 52, sales: 3800 },
+ { week: "W13", visits: 260, conversions: 50, sales: 3600 },
+ { week: "W14", visits: 280, conversions: 55, sales: 4000 },
+ { week: "W15", visits: 300, conversions: 60, sales: 4300 },
+ { week: "W16", visits: 290, conversions: 58, sales: 4100 },
+ ],
+ bigNumbers: [
+ { company: "Apple", revenue: 394328000000, profit: 99803000000, marketCap: 3500000000000 }, // 394B, 99B, 3.5T
+ { company: "Microsoft", revenue: 211915000000, profit: 83383000000, marketCap: 2800000000000 }, // 211B, 83B, 2.8T
+ { company: "Alphabet", revenue: 307394000000, profit: 76033000000, marketCap: 2100000000000 }, // 307B, 76B, 2.1T
+ { company: "Amazon", revenue: 574785000000, profit: 33364000000, marketCap: 1600000000000 }, // 574B, 33B, 1.6T
+ { company: "Tesla", revenue: 96773000000, profit: 15000000000, marketCap: 800000000000 }, // 96B, 15B, 800B
+ { company: "Meta", revenue: 134902000000, profit: 39370000000, marketCap: 900000000000 }, // 134B, 39B, 900B
+ ],
+ // 🔄 EXPAND/COLLAPSE - Marketing channels dataset for legend overflow testing
+ expandCollapseMarketing: [
+ {
+ channel: "Website Traffic and Organic Search Results",
+ impressions: 120000,
+ clicks: 15000,
+ conversions: 1200,
+ cost: 8500,
+ revenue: 24000,
+ roi: 182,
+ ctr: 12.5,
+ cpc: 0.57,
+ cpa: 7.08,
+ reach: 95000,
+ engagement: 8200,
+ shares: 420,
+ saves: 180,
+ comments: 650,
+ videoViews: 0,
+ },
+ {
+ channel: "Social Media Engagement and Brand Awareness",
+ impressions: 85000,
+ clicks: 12000,
+ conversions: 950,
+ cost: 6200,
+ revenue: 19000,
+ roi: 206,
+ ctr: 14.1,
+ cpc: 0.52,
+ cpa: 6.53,
+ reach: 72000,
+ engagement: 15400,
+ shares: 890,
+ saves: 340,
+ comments: 1200,
+ videoViews: 28000,
+ },
+ {
+ channel: "Email Marketing Campaign Performance",
+ impressions: 45000,
+ clicks: 8500,
+ conversions: 800,
+ cost: 2100,
+ revenue: 16000,
+ roi: 562,
+ ctr: 18.9,
+ cpc: 0.25,
+ cpa: 2.63,
+ reach: 42000,
+ engagement: 6800,
+ shares: 120,
+ saves: 85,
+ comments: 240,
+ videoViews: 0,
+ },
+ {
+ channel: "Paid Advertising and PPC Campaign ROI",
+ impressions: 95000,
+ clicks: 18000,
+ conversions: 1500,
+ cost: 12500,
+ revenue: 30000,
+ roi: 140,
+ ctr: 18.9,
+ cpc: 0.69,
+ cpa: 8.33,
+ reach: 88000,
+ engagement: 12600,
+ shares: 320,
+ saves: 150,
+ comments: 480,
+ videoViews: 5200,
+ },
+ {
+ channel: "Content Marketing and Blog Performance",
+ impressions: 60000,
+ clicks: 9500,
+ conversions: 750,
+ cost: 4800,
+ revenue: 15000,
+ roi: 213,
+ ctr: 15.8,
+ cpc: 0.51,
+ cpa: 6.4,
+ reach: 55000,
+ engagement: 7800,
+ shares: 680,
+ saves: 420,
+ comments: 950,
+ videoViews: 12000,
+ },
+ {
+ channel: "Mobile Application Downloads and Usage",
+ impressions: 70000,
+ clicks: 11000,
+ conversions: 1100,
+ cost: 5500,
+ revenue: 22000,
+ roi: 300,
+ ctr: 15.7,
+ cpc: 0.5,
+ cpa: 5.0,
+ reach: 65000,
+ engagement: 9200,
+ shares: 180,
+ saves: 95,
+ comments: 320,
+ videoViews: 8500,
+ },
+ {
+ channel: "Customer Support Response Time and Quality",
+ impressions: 35000,
+ clicks: 5500,
+ conversions: 450,
+ cost: 2800,
+ revenue: 9000,
+ roi: 221,
+ ctr: 15.7,
+ cpc: 0.51,
+ cpa: 6.22,
+ reach: 32000,
+ engagement: 4200,
+ shares: 45,
+ saves: 25,
+ comments: 180,
+ videoViews: 0,
+ },
+ {
+ channel: "Sales Funnel Conversion and Lead Generation",
+ impressions: 110000,
+ clicks: 22000,
+ conversions: 1800,
+ cost: 15000,
+ revenue: 36000,
+ roi: 140,
+ ctr: 20.0,
+ cpc: 0.68,
+ cpa: 8.33,
+ reach: 98000,
+ engagement: 18500,
+ shares: 420,
+ saves: 280,
+ comments: 750,
+ videoViews: 3200,
+ },
+ {
+ channel: "User Retention and Churn Rate Analysis",
+ impressions: 80000,
+ clicks: 14000,
+ conversions: 1200,
+ cost: 7200,
+ revenue: 24000,
+ roi: 233,
+ ctr: 17.5,
+ cpc: 0.51,
+ cpa: 6.0,
+ reach: 75000,
+ engagement: 11200,
+ shares: 280,
+ saves: 150,
+ comments: 420,
+ videoViews: 6800,
+ },
+ {
+ channel: "Product Feature Usage and Performance Metrics",
+ impressions: 65000,
+ clicks: 10500,
+ conversions: 900,
+ cost: 5200,
+ revenue: 18000,
+ roi: 246,
+ ctr: 16.2,
+ cpc: 0.5,
+ cpa: 5.78,
+ reach: 58000,
+ engagement: 8500,
+ shares: 320,
+ saves: 180,
+ comments: 650,
+ videoViews: 4200,
+ },
+ {
+ channel: "Market Research and Competitive Analysis",
+ impressions: 40000,
+ clicks: 6500,
+ conversions: 500,
+ cost: 3200,
+ revenue: 10000,
+ roi: 213,
+ ctr: 16.3,
+ cpc: 0.49,
+ cpa: 6.4,
+ reach: 36000,
+ engagement: 5200,
+ shares: 95,
+ saves: 65,
+ comments: 220,
+ videoViews: 1800,
+ },
+ {
+ channel: "Brand Sentiment and Public Relations Impact",
+ impressions: 55000,
+ clicks: 8000,
+ conversions: 650,
+ cost: 4100,
+ revenue: 13000,
+ roi: 217,
+ ctr: 14.5,
+ cpc: 0.51,
+ cpa: 6.31,
+ reach: 48000,
+ engagement: 6800,
+ shares: 520,
+ saves: 280,
+ comments: 950,
+ videoViews: 15000,
+ },
+ ],
+ singleGroup: [
+ { month: "January 1st - January 31st, 2024 (Winter Quarter)", sales: 150 },
+ { month: "February 1st - February 28th, 2024 (Winter Quarter)", sales: 280 },
+ { month: "March 1st - March 31st, 2024 (Spring Quarter)", sales: 220 },
+ { month: "April 1st - April 30th, 2024 (Spring Quarter)", sales: 180 },
+ { month: "May 1st - May 31st, 2024 (Spring Quarter)", sales: 250 },
+ { month: "June 1st - June 30th, 2024 (Summer Quarter)", sales: 300 },
+ { month: "July 1st - July 31st, 2024 (Summer Quarter)", sales: 350 },
+ { month: "August 1st - August 31st, 2024 (Summer Quarter)", sales: 400 },
+ ],
+ positiveNegative: [
+ { month: "January", profit: -4000000, loss: -2000000, netWorth: 2000000 },
+ { month: "February", profit: 3000000, loss: -4000000, netWorth: -1000000 },
+ { month: "March", profit: -1000000, loss: -1500000, netWorth: -2500000 },
+ { month: "April", profit: 5000000, loss: -2500000, netWorth: 2500000 },
+ { month: "May", profit: -2000000, loss: -3000000, netWorth: -5000000 },
+ { month: "June", profit: 1000000, loss: -500000, netWorth: 500000 },
+ ],
+};
+
+// Category key mappings for different datasets
+const categoryKeys = {
+ default: "month",
+ small: "month",
+ large: "month",
+ simple: "quarter",
+ edge: "period",
+ numbers: "category",
+ weekly: "week",
+ bigNumbers: "company",
+ expandCollapseMarketing: "channel",
+ singleGroup: "month",
+ positiveNegative: "month",
+};
+
+// 🔥 ACTIVE DATA - For backward compatibility
+const barChartData = dataVariations.default;
+
+const icons = {
+ desktop: Monitor,
+ mobile: TabletSmartphone,
+} as const;
+
+/**
+ * # ScrollableBarChart Component Documentation
+ *
+ * The BarChart is a versatile component for comparing values across different categories.
+ * It's highly effective for:
+ *
+ * - **Category Comparison**: Easily compare metrics like sales, users, or revenue across different groups.
+ * - **Ranking**: Show the highest and lowest performing items in a dataset.
+ * - **Data Over Time**: Visualize changes across discrete time intervals (e.g., monthly sales).
+ *
+ * ## Key Features
+ *
+ * ### Layout Variants
+ * - **Grouped**: Compare sub-categories side-by-side within a primary category.
+ * - **Stacked**: Show how sub-categories contribute to a total value for each primary category.
+ *
+ * ### Interactive & Responsive
+ * - **Horizontal Scrolling**: Automatically enables scrolling when the number of bars exceeds the container width.
+ * - **Interactive Legend**: Toggle data series on and off. Handles overflow with a "Show More" button.
+ * - **Hover Tooltips**: Provides detailed data on hover for better user engagement.
+ * - **Responsive Design**: Adjusts gracefully to the size of its container.
+ *
+ * ### Customization
+ * - **Theming**: Six built-in color palettes, or use custom colors with `customPalette`.
+ * - **Bar Styling**: Customize the corner radius of the bars.
+ * - **Axis and Grid Control**: Toggle visibility of axes and grid lines.
+ */
+const meta: Meta<BarChartProps<typeof barChartData>> = {
+ title: "Components/D3Charts/ScrollableBarChart",
+ component: BarChart,
+ parameters: {
+ layout: "centered",
+ docs: {
+ description: {
+ component: `
+## Installation and Basic Usage
+
+\`\`\`tsx
+import { ScrollableBarChart } from '@openuidev/react-ui';
+
+const monthlyData = [
+ { month: "January", desktop: 150, mobile: 90 },
+ { month: "February", desktop: 280, mobile: 180 },
+ { month: "March", desktop: 220, mobile: 140 },
+];
+
+// Basic implementation
+<ScrollableBarChart
+ data={monthlyData}
+ categoryKey="month"
+ theme="ocean"
+/>
+
+// With custom colors
+<ScrollableBarChart
+ data={monthlyData}
+ categoryKey="month"
+ customPalette={["#FF6B6B", "#4ECDC4", "#45B7D1"]}
+/>
+\`\`\`
+
+## Data Structure Requirements
+
+Your data should be an array of objects. Each object must contain:
+- A **category field** (string or number): Used for the X-axis labels (e.g., months, quarters).
+- One or more **data series fields** (number): These are the values that will be plotted as bars. The key of the field is used as the series name in the legend and tooltip.
+
+\`\`\`tsx
+const salesData = [
+ { region: "North", sales: 5400, marketing: 1200 },
+ { region: "South", sales: 8200, marketing: 1500 },
+ { region: "East", sales: 7100, marketing: 1300 },
+];
+\`\`\`
+
+## Performance Considerations
+- **Data Volume**: The chart uses virtualization for the X-axis, but performance can still be impacted by an extremely large number of data points (e.g., 1000+).
+- **Responsiveness**: The chart adapts to its container, but ensure that bar widths and gaps are readable on very small screens.
+- **Animation**: Can be disabled via \`isAnimationActive={false}\` for better performance with large datasets.
+`,
+ },
+ },
+ },
+ tags: ["!dev", "autodocs"],
+ argTypes: {
+ data: {
+ description: `
+**Required.** An array of data objects representing your dataset. Each object should contain:
+- A category identifier (string/number) for the X-axis.
+- One or more numeric values for the Y-axis bars.
+`,
+ control: false,
+ table: {
+ type: { summary: "Array<Record<string, string | number>>" },
+ category: "📊 Data Configuration",
+ },
+ },
+ categoryKey: {
+ description:
+ "**Required.** The key in your data object that represents the category for the X-axis (e.g., 'month', 'department').",
+ control: false,
+ table: {
+ type: { summary: "string" },
+ category: "📊 Data Configuration",
+ },
+ },
+ theme: {
+ description:
+ "Specifies the color palette for the chart's bars, tooltips, and legend. Ignored when customPalette is provided.",
+ control: "select",
+ options: ["ocean", "orchid", "emerald", "sunset", "spectrum", "vivid"],
+ table: {
+ defaultValue: { summary: "ocean" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ customPalette: {
+ description:
+ "Custom array of colors to use instead of the theme palette. Overrides the theme prop when provided.",
+ control: "object",
+ table: {
+ type: { summary: "string[]" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ variant: {
+ description:
+ "Defines how multiple data series are displayed: `grouped` (side-by-side) or `stacked` (on top of each other).",
+ control: "radio",
+ options: ["grouped", "stacked"],
+ table: {
+ defaultValue: { summary: "grouped" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ radius: {
+ description: "Sets the corner radius for the top of each bar, creating a rounded look.",
+ control: { type: "number", min: 0, max: 20 },
+ table: {
+ type: { summary: "number" },
+ defaultValue: { summary: "4" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ icons: {
+ description:
+ "An object mapping data series keys to React components to be used as icons in the legend.",
+ control: false,
+ table: {
+ type: { summary: "Record<string, React.ReactNode>" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ grid: {
+ description: "Toggles the visibility of the background grid lines.",
+ control: "boolean",
+ table: {
+ defaultValue: { summary: "true" },
+ category: "📱 Display Options",
+ },
+ },
+ legend: {
+ description: "Toggles the visibility of the chart legend.",
+ control: "boolean",
+ table: {
+ defaultValue: { summary: "true" },
+ category: "📱 Display Options",
+ },
+ },
+ showYAxis: {
+ description: "Toggles the visibility of the Y-axis line and labels.",
+ control: "boolean",
+ table: {
+ defaultValue: { summary: "true" },
+ category: "📱 Display Options",
+ },
+ },
+ xAxisLabel: {
+ description: "A label to display below the X-axis.",
+ control: "text",
+ table: {
+ type: { summary: "React.ReactNode" },
+ category: "📱 Display Options",
+ },
+ },
+ yAxisLabel: {
+ description: "A label to display beside the Y-axis.",
+ control: "text",
+ table: {
+ type: { summary: "React.ReactNode" },
+ category: "📱 Display Options",
+ },
+ },
+ isAnimationActive: {
+ description: "Enables or disables the initial loading animation for the bars.",
+ control: "boolean",
+ table: {
+ defaultValue: { summary: "true" },
+ category: "🎬 Animation & Interaction",
+ },
+ },
+ height: {
+ description: "Sets a fixed height for the chart container in pixels.",
+ control: "number",
+ table: {
+ type: { summary: "number" },
+ category: "Layout & Sizing",
+ },
+ },
+ width: {
+ description: "Sets a fixed width for the chart container in pixels.",
+ control: "number",
+ table: {
+ type: { summary: "number" },
+ category: "Layout & Sizing",
+ },
+ },
+ },
+} satisfies Meta<typeof BarChart>;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+/**
+ * ## Comprehensive Data Explorer
+ *
+ * This story serves as a comprehensive test suite for the BarChart component.
+ * Use the buttons to switch between various datasets designed to test edge cases in:
+ *
+ * - **Data Volume**: Scenarios with few, many, or a single data point.
+ * - **Data Formatting**: Handling of large numbers and different value ranges.
+ * - **Legend Overflow**: A dataset with many series to test legend expand/collapse functionality.
+ *
+ * It's an excellent tool for developers to see how the chart behaves under different conditions.
+ */
+export const DataExplorer: Story = {
+ name: "🎛️ Comprehensive Data Explorer",
+ args: {
+ data: barChartData,
+ categoryKey: "month",
+ theme: "ocean",
+ variant: "grouped",
+ radius: 4,
+ grid: true,
+ isAnimationActive: true,
+ showYAxis: true,
+ // height: 500,
+ },
+ render: (args: any) => {
+ const [selectedDataType, setSelectedDataType] =
+ useState<keyof typeof dataVariations>("default");
+
+ const currentData = dataVariations[selectedDataType];
+ const currentCategoryKey = categoryKeys[selectedDataType];
+
+ const buttonStyle = {
+ margin: "2px",
+ padding: "6px 12px",
+ fontSize: "12px",
+ border: "1px solid #ddd",
+ borderRadius: "4px",
+ cursor: "pointer",
+ background: "#fff",
+ };
+
+ const activeButtonStyle = {
+ ...buttonStyle,
+ background: "#007acc",
+ color: "white",
+ border: "1px solid #007acc",
+ };
+
+ return (
+ <div>
+ <div
+ style={{
+ marginBottom: "16px",
+ padding: "12px",
+ background: "#f8f9fa",
+ borderRadius: "8px",
+ border: "1px solid #e9ecef",
+ width: "700px",
+ }}
+ >
+ <strong>💡 Quick Data Switch:</strong>
+ <div style={{ marginTop: "8px", display: "flex", flexWrap: "wrap", gap: "4px" }}>
+ <button
+ onClick={() => setSelectedDataType("default")}
+ style={selectedDataType === "default" ? activeButtonStyle : buttonStyle}
+ >
+ 📅 Default (12 months)
+ </button>
+ <button
+ onClick={() => setSelectedDataType("small")}
+ style={selectedDataType === "small" ? activeButtonStyle : buttonStyle}
+ >
+ 📱 Small (3 items)
+ </button>
+ <button
+ onClick={() => setSelectedDataType("large")}
+ style={selectedDataType === "large" ? activeButtonStyle : buttonStyle}
+ >
+ 🌐 Large (18 months)
+ </button>
+ <button
+ onClick={() => setSelectedDataType("weekly")}
+ style={selectedDataType === "weekly" ? activeButtonStyle : buttonStyle}
+ >
+ 📈 Weekly (16 weeks)
+ </button>
+ <button
+ onClick={() => setSelectedDataType("bigNumbers")}
+ style={selectedDataType === "bigNumbers" ? activeButtonStyle : buttonStyle}
+ >
+ 💰 Big Numbers
+ </button>
+ <button
+ onClick={() => setSelectedDataType("edge")}
+ style={selectedDataType === "edge" ? activeButtonStyle : buttonStyle}
+ >
+ 🎯 Single Item
+ </button>
+ <button
+ onClick={() => setSelectedDataType("numbers")}
+ style={selectedDataType === "numbers" ? activeButtonStyle : buttonStyle}
+ >
+ 🔢 Number Ranges
+ </button>
+ <button
+ onClick={() => setSelectedDataType("singleGroup")}
+ style={selectedDataType === "singleGroup" ? activeButtonStyle : buttonStyle}
+ >
+ 🏢 Single Group
+ </button>
+ <button
+ onClick={() => setSelectedDataType("expandCollapseMarketing")}
+ style={
+ selectedDataType === "expandCollapseMarketing" ? activeButtonStyle : buttonStyle
+ }
+ >
+ 🔄 Marketing Channels
+ </button>
+ <button
+ onClick={() => setSelectedDataType("positiveNegative")}
+ style={selectedDataType === "positiveNegative" ? activeButtonStyle : buttonStyle}
+ >
+ 📈 Positive & Negative
+ </button>
+ </div>
+ <div style={{ marginTop: "8px", fontSize: "12px", color: "#666" }}>
+ <strong>Current:</strong> {selectedDataType} | <strong>Items:</strong>{" "}
+ {currentData.length} | <strong>Category:</strong> {currentCategoryKey}
+ </div>
+ </div>
+ <Card style={{ width: "700px" }}>
+ <BarChart {...args} data={currentData} categoryKey={currentCategoryKey} />
+ </Card>
+ </div>
+ );
+ },
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Use the buttons above the chart to quickly switch between different data variations and test the scrolling functionality. Active button is highlighted in blue.",
+ },
+ },
+ },
+};
+
+/**
+ * ## Small Dataset (No Scroll)
+ *
+ * This story demonstrates the BarChart's appearance with a small dataset.
+ * When the number of bars fits within the container width, horizontal scrolling is disabled.
+ */
+export const SmallDataStory: Story = {
+ name: "📱 Small Data (No Scroll)",
+ args: {
+ data: dataVariations.small as any,
+ categoryKey: "month" as any,
+ theme: "ocean",
+ variant: "grouped",
+ radius: 2,
+ grid: true,
+ isAnimationActive: true,
+ showYAxis: true,
+ legend: true,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "400px" }}>
+ <BarChart {...args} />
+ </Card>
+ ),
+};
+
+/**
+ * ## Large Dataset (With Scrolling)
+ *
+ * This story showcases the chart's horizontal scrolling capability.
+ * When the total width of the bars exceeds the container's width, users can scroll to view all data points.
+ */
+export const LargeDataStory: Story = {
+ name: "🌐 Large Data (Scrolling)",
+ args: {
+ data: dataVariations.large as any,
+ categoryKey: "month" as any,
+ theme: "emerald",
+ variant: "grouped",
+ radius: 2,
+ grid: true,
+ isAnimationActive: true,
+ showYAxis: true,
+ legend: true,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "400px" }}>
+ <BarChart {...args} />
+ </Card>
+ ),
+};
+
+/**
+ * ## Weekly Data (Many Categories)
+ *
+ * Similar to the large dataset, this story tests the chart with a high number of categories,
+ * which should trigger horizontal scrolling.
+ */
+export const WeeklyDataStory: Story = {
+ name: "📈 Weekly Data (Many Categories)",
+ args: {
+ data: dataVariations.weekly as any,
+ categoryKey: "week" as any,
+ theme: "sunset",
+ variant: "grouped",
+ radius: 2,
+ grid: true,
+ isAnimationActive: true,
+ showYAxis: true,
+ legend: true,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "400px" }}>
+ <BarChart {...args} />
+ </Card>
+ ),
+};
+
+/**
+ * ## Big Numbers
+ *
+ * This story tests the chart's ability to handle and format very large numbers,
+ * such as billions and trillions, on the Y-axis. The axis labels should be formatted
+ * with appropriate suffixes (e.g., "B" for billion, "T" for trillion).
+ */
+export const BigNumbersStory: Story = {
+ name: "💰 Big Numbers (Billions/Trillions)",
+ args: {
+ data: dataVariations.bigNumbers as any,
+ categoryKey: "company" as any,
+ theme: "vivid",
+ variant: "grouped",
+ radius: 2,
+ grid: true,
+ isAnimationActive: true,
+ showYAxis: true,
+ legend: true,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "500px" }}>
+ <BarChart {...args} />
+ </Card>
+ ),
+};
+
+/**
+ * ## Edge Case (Single Data Point)
+ *
+ * This story demonstrates how the chart renders with only a single data point.
+ * It's a useful test to ensure that the layout and axes behave correctly in minimal-data scenarios.
+ */
+export const EdgeCaseStory: Story = {
+ name: "🎯 Edge Case (Single Data Point)",
+ args: {
+ data: dataVariations.edge as any,
+ categoryKey: "period" as any,
+ theme: "orchid",
+ variant: "grouped",
+ radius: 2,
+ grid: true,
+ isAnimationActive: true,
+ showYAxis: true,
+ legend: true,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "400px" }}>
+ <BarChart {...args} />
+ </Card>
+ ),
+};
+
+/**
+ * ## Number Ranges (Scale Testing)
+ *
+ * This story tests the Y-axis scaling with data points of vastly different magnitudes.
+ * The chart should automatically adjust its scale to accommodate all values appropriately.
+ */
+export const NumberRangesStory: Story = {
+ name: "🔢 Number Ranges (Scale Testing)",
+ args: {
+ data: dataVariations.numbers as any,
+ categoryKey: "category" as any,
+ theme: "spectrum",
+ variant: "grouped",
+ radius: 2,
+ grid: true,
+ isAnimationActive: true,
+ showYAxis: true,
+ legend: true,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "400px" }}>
+ <BarChart {...args} />
+ </Card>
+ ),
+};
+
+/**
+ * ## Legend Expand/Collapse
+ *
+ * Tests the legend's expand/collapse functionality with a large number of data series.
+ * The legend should automatically show a "Show More" button when items overflow,
+ * allowing users to toggle between a collapsed and expanded view.
+ */
+export const ExpandCollapseMarketingStory: Story = {
+ name: "🔄 Legend Expand/Collapse",
+ args: {
+ data: dataVariations.expandCollapseMarketing as any,
+ categoryKey: "channel" as any,
+ theme: "emerald",
+ variant: "grouped",
+ radius: 4,
+ grid: true,
+ isAnimationActive: true,
+ showYAxis: true,
+ legend: true,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "600px" }}>
+ <BarChart {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests the legend expand/collapse functionality with 12 marketing channels that have long descriptive names. The legend should automatically show a 'Show More' button when items overflow the container width, allowing users to toggle between collapsed and expanded states.",
+ },
+ },
+ },
+};
+
+/**
+ * ## Custom Palette
+ *
+ * This story demonstrates how to use the customPalette prop to provide your own color scheme
+ * for the chart. This is useful when you need to match your brand colors or create
+ * specific visual themes.
+ */
+export const CustomPaletteStory: Story = {
+ name: "🎨 Custom Palette",
+ args: {
+ data: dataVariations.default as any,
+ categoryKey: "month" as any,
+ customPalette: [
+ "#0A0E60",
+ "#14197B",
+ "#272DA6",
+ "#383FC9",
+ "#444CE7",
+ "#5F67F4",
+ "#7884FF",
+ "#97A9FF",
+ "#B4C6FF",
+ "#CBD7FF",
+ ],
+ theme: "ocean", // This will be overridden by customPalette
+ variant: "grouped",
+ radius: 4,
+ grid: true,
+ legend: true,
+ isAnimationActive: true,
+ showYAxis: true,
+ xAxisLabel: "Month",
+ yAxisLabel: "Traffic",
+ },
+ render: (args: any) => (
+ <div>
+ <div
+ style={{
+ marginBottom: "16px",
+ padding: "12px",
+ background: "#f8f9fa",
+ borderRadius: "8px",
+ border: "1px solid #e9ecef",
+ }}
+ >
+ <h4 style={{ margin: "0 0 8px 0", color: "#333" }}>🎨 Custom Color Palette</h4>
+ <p style={{ margin: "0 0 12px 0", fontSize: "14px", color: "#666" }}>
+ This chart uses a custom color palette instead of the default theme colors.
+ </p>
+ <div style={{ display: "flex", gap: "8px", flexWrap: "wrap" }}>
+ {args.customPalette?.map((color: string, index: number) => (
+ <div
+ key={index}
+ style={{
+ display: "flex",
+ alignItems: "center",
+ gap: "4px",
+ padding: "4px 8px",
+ background: "white",
+ borderRadius: "4px",
+ border: "1px solid #ddd",
+ fontSize: "12px",
+ }}
+ >
+ <div
+ style={{
+ width: "12px",
+ height: "12px",
+ borderRadius: "2px",
+ backgroundColor: color,
+ border: "1px solid #ccc",
+ }}
+ />
+ <span style={{ fontFamily: "monospace" }}>{color}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ <Card style={{ width: "600px" }}>
+ <BarChart {...args} />
+ </Card>
+ </div>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'Demonstrates how to use the `customPalette` prop to provide your own color scheme for the chart. When `customPalette` is provided, it overrides the `theme` prop and uses your specified colors instead of the predefined theme palettes.\n\n**Key Features:**\n- 🎨 **Custom Colors**: Override default theme colors with your own palette\n- 🔄 **Theme Override**: The `theme` prop is ignored when `customPalette` is provided\n- 📊 **Consistent Distribution**: Colors are distributed evenly across data series\n- 🎯 **Brand Matching**: Perfect for matching your application\'s brand colors\n\n**Usage:**\n```tsx\n<BarChart\n data={data}\n categoryKey="month"\n customPalette={["#FF6B6B", "#4ECDC4", "#45B7D1"]}\n // theme prop is ignored when customPalette is provided\n/>\n```',
+ },
+ },
+ },
+};
+
+/**
+ * ## Responsive Behavior Demo
+ *
+ * This story demonstrates the responsive capabilities of the BarChart. Drag the handles
+ * on the container to resize it and observe how the chart adapts.
+ *
+ * **Responsive Features:**
+ * - **Bar Sizing**: Bar widths and gaps adjust to the container size.
+ * - **Layout Adaptation**: Chart elements are repositioned to fit the available space.
+ * - **Legend Behavior**: The legend may wrap or show expand/collapse buttons as needed.
+ */
+export const ResponsiveBehaviorDemo: Story = {
+ name: "📱 Responsive Behavior Demo",
+ args: {
+ data: dataVariations.default as any,
+ categoryKey: "month" as any,
+ theme: "sunset",
+ variant: "grouped",
+ grid: true,
+ legend: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ },
+ render: (args: any) => {
+ const [dimensions, setDimensions] = useState<{ width: number; height: number | string }>({
+ width: 700,
+ height: "auto",
+ });
+
+ const handleMouseDown = (e: React.MouseEvent<HTMLDivElement>, handle: string) => {
+ e.preventDefault();
+ e.stopPropagation();
+ const startX = e.clientX;
+ const startY = e.clientY;
+ const startWidth = dimensions.width;
+ const startHeight = (e.currentTarget.parentElement as HTMLElement).offsetHeight;
+
+ const doDrag = (e: MouseEvent) => {
+ const dx = e.clientX - startX;
+ const dy = e.clientY - startY;
+ let newWidth = startWidth;
+ let newHeight = startHeight;
+
+ if (handle.includes("e")) newWidth = startWidth + dx;
+ if (handle.includes("w")) newWidth = startWidth - dx;
+ if (handle.includes("s")) newHeight = startHeight + dy;
+ if (handle.includes("n")) newHeight = startHeight - dy;
+
+ setDimensions({
+ width: Math.max(300, newWidth),
+ height: "auto",
+ });
+ };
+
+ const stopDrag = () => {
+ document.removeEventListener("mousemove", doDrag);
+ document.removeEventListener("mouseup", stopDrag);
+ };
+
+ document.addEventListener("mousemove", doDrag);
+ document.addEventListener("mouseup", stopDrag);
+ };
+
+ const handleStyle: React.CSSProperties = {
+ position: "absolute",
+ background: "#3b82f6",
+ opacity: 0.6,
+ zIndex: 10,
+ transition: "opacity 0.2s ease",
+ };
+
+ return (
+ <div style={{ padding: "20px" }}>
+ <div style={{ marginBottom: "20px" }}>
+ <h3 style={{ margin: "0 0 8px 0", fontSize: "18px", fontWeight: "600" }}>
+ Responsive Behavior Demonstration
+ </h3>
+ <p style={{ margin: "0 0 12px 0", color: "#666", fontSize: "14px" }}>
+ Drag the edges or corners of the container below to see how the chart adapts
+ </p>
+ <div
+ style={{
+ padding: "12px",
+ backgroundColor: "#e3f2fd",
+ borderRadius: "6px",
+ fontSize: "12px",
+ color: "#1565c0",
+ }}
+ >
+ <strong>🎯 Try This:</strong> Resize the container to see how the bar widths and layout
+ adjustments.
+ </div>
+ </div>
+
+ <Card
+ style={{
+ position: "relative",
+ width: `${dimensions.width}px`,
+ height:
+ typeof dimensions.height === "number" ? `${dimensions.height}px` : dimensions.height,
+ border: "2px dashed #9ca3af",
+ padding: "20px",
+ boxSizing: "border-box",
+ overflow: "hidden",
+ cursor: "default",
+ }}
+ >
+ <BarChart {...args} />
+
+ {/* Resize Handles */}
+ <div
+ style={{ ...handleStyle, top: -2, left: 0, right: 0, height: 12, cursor: "ns-resize" }}
+ onMouseDown={(e) => handleMouseDown(e, "n")}
+ />
+ <div
+ style={{
+ ...handleStyle,
+ bottom: -2,
+ left: 0,
+ right: 0,
+ height: 12,
+ cursor: "ns-resize",
+ }}
+ onMouseDown={(e) => handleMouseDown(e, "s")}
+ />
+ <div
+ style={{ ...handleStyle, top: 0, bottom: 0, left: -2, width: 12, cursor: "ew-resize" }}
+ onMouseDown={(e) => handleMouseDown(e, "w")}
+ />
+ <div
+ style={{ ...handleStyle, top: 0, bottom: 0, right: -2, width: 12, cursor: "ew-resize" }}
+ onMouseDown={(e) => handleMouseDown(e, "e")}
+ />
+
+ {/* Corner Handles */}
+ <div
+ style={{
+ ...handleStyle,
+ top: -2,
+ left: -2,
+ width: 20,
+ height: 20,
+ cursor: "nwse-resize",
+ borderRadius: "2px",
+ }}
+ onMouseDown={(e) => handleMouseDown(e, "nw")}
+ />
+ <div
+ style={{
+ ...handleStyle,
+ top: -2,
+ right: -2,
+ width: 20,
+ height: 20,
+ cursor: "nesw-resize",
+ borderRadius: "2px",
+ }}
+ onMouseDown={(e) => handleMouseDown(e, "ne")}
+ />
+ <div
+ style={{
+ ...handleStyle,
+ bottom: -2,
+ right: -2,
+ width: 20,
+ height: 20,
+ cursor: "nwse-resize",
+ borderRadius: "2px",
+ }}
+ onMouseDown={(e) => handleMouseDown(e, "se")}
+ />
+
+ {/* Dimension Display */}
+ <div
+ style={{
+ position: "absolute",
+ bottom: 8,
+ right: 8,
+ background: "rgba(0,0,0,0.8)",
+ color: "white",
+ padding: "4px 8px",
+ borderRadius: "4px",
+ fontSize: "11px",
+ fontFamily: "monospace",
+ fontWeight: "500",
+ }}
+ >
+ {dimensions.width}px ×{" "}
+ {typeof dimensions.height === "number" ? `${dimensions.height}px` : "auto"}
+ </div>
+ </Card>
+ </div>
+ );
+ },
+};
diff --git a/packages/react-ui/src/components/D3Charts/BarChart/stories/barChartCondensed.stories.tsx b/packages/react-ui/src/components/D3Charts/BarChart/stories/barChartCondensed.stories.tsx
new file mode 100644
index 000000000..741f4a8c2
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/BarChart/stories/barChartCondensed.stories.tsx
@@ -0,0 +1,1777 @@
+// Copy of Charts/BarChartCondensed/stories/barChartCondensed.stories.tsx with only the chart import and the title changed:
+// the same args and renders, rendering the D3Charts chart via
+// ../../stories/rechartsStoryAdapters.
+import type { Meta, StoryObj } from "@storybook/react";
+import {
+ Calendar,
+ Globe,
+ Laptop,
+ Monitor,
+ Smartphone,
+ TabletSmartphone,
+ Tv,
+ Watch,
+} from "lucide-react";
+import { useState } from "react";
+import { Card } from "../../../Card";
+import { BarChartCondensed, BarChartCondensedProps } from "../../stories/rechartsStoryAdapters";
+
+// 🔥 COMPREHENSIVE DATA VARIATIONS - Designed to test various scenarios
+const dataVariations = {
+ default: [
+ { month: "January", desktop: 150, mobile: 90, tablet: 120 },
+ { month: "February", desktop: 280, mobile: 180, tablet: 140 },
+ { month: "March", desktop: 220, mobile: 140, tablet: 160 },
+ { month: "April", desktop: 180, mobile: 160, tablet: 180 },
+ { month: "May", desktop: 250, mobile: 120, tablet: 140 },
+ { month: "June", desktop: 300, mobile: 180, tablet: 160 },
+ { month: "July", desktop: 350, mobile: 220, tablet: 180 },
+ { month: "August", desktop: 400, mobile: 240, tablet: 200 },
+ { month: "September", desktop: 450, mobile: 260, tablet: 220 },
+ { month: "October", desktop: 500, mobile: 280, tablet: 240 },
+ { month: "November", desktop: 550, mobile: 300, tablet: 260 },
+ { month: "December", desktop: 600, mobile: 320, tablet: 280 },
+ ],
+ // 🏷️ BIG LABELS - Testing angled tick labels
+ bigLabels: [
+ {
+ category: "Very Long Category Name That Should Be Truncated",
+ sales: 150,
+ revenue: 90,
+ profit: 120,
+ },
+ {
+ category: "Another Extremely Long Label That Causes Collisions",
+ sales: 280,
+ revenue: 180,
+ profit: 140,
+ },
+ {
+ category: "Super Duper Long Category Name That Tests Truncation",
+ sales: 220,
+ revenue: 140,
+ profit: 160,
+ },
+ {
+ category: "Incredibly Long Text That Should Trigger Collision Detection",
+ sales: 180,
+ revenue: 160,
+ profit: 180,
+ },
+ {
+ category: "Maximum Length Category Name That Tests All Edge Cases",
+ sales: 250,
+ revenue: 120,
+ profit: 140,
+ },
+ {
+ category: "Extra Long Business Category Name With Many Words",
+ sales: 300,
+ revenue: 180,
+ profit: 160,
+ },
+ {
+ category: "Comprehensive Long Label For Testing Horizontal Offset",
+ sales: 350,
+ revenue: 220,
+ profit: 180,
+ },
+ {
+ category: "Extended Category Name That Pushes Truncation Limits",
+ sales: 400,
+ revenue: 240,
+ profit: 200,
+ },
+ ],
+ // 🏢 COMPANY NAMES - Real-world long business names
+ companyNames: [
+ { company: "Apple Inc.", revenue: 394328000000, profit: 99803000000, marketCap: 3500000000000 },
+ {
+ company: "Microsoft Corporation",
+ revenue: 211915000000,
+ profit: 83383000000,
+ marketCap: 2800000000000,
+ },
+ {
+ company: "Alphabet Inc. (Google)",
+ revenue: 307394000000,
+ profit: 76033000000,
+ marketCap: 2100000000000,
+ },
+ {
+ company: "Amazon.com Inc.",
+ revenue: 574785000000,
+ profit: 33364000000,
+ marketCap: 1600000000000,
+ },
+ {
+ company: "Tesla Motors Inc.",
+ revenue: 96773000000,
+ profit: 15000000000,
+ marketCap: 800000000000,
+ },
+ {
+ company: "Meta Platforms Inc.",
+ revenue: 134902000000,
+ profit: 39370000000,
+ marketCap: 900000000000,
+ },
+ ],
+ // 📈 FINANCIAL QUARTERS - Testing medium-density scenarios
+ financialQuarters: [
+ { quarter: "Q1 FY2022", revenue: 1200000, expenses: 800000, profit: 400000 },
+ { quarter: "Q2 FY2022", revenue: 1500000, expenses: 950000, profit: 550000 },
+ { quarter: "Q3 FY2022", revenue: 1800000, expenses: 1100000, profit: 700000 },
+ { quarter: "Q4 FY2022", revenue: 2000000, expenses: 1300000, profit: 700000 },
+ { quarter: "Q1 FY2023", revenue: 2200000, expenses: 1400000, profit: 800000 },
+ { quarter: "Q2 FY2023", revenue: 2500000, expenses: 1600000, profit: 900000 },
+ { quarter: "Q3 FY2023", revenue: 2800000, expenses: 1800000, profit: 1000000 },
+ { quarter: "Q4 FY2023", revenue: 3000000, expenses: 1900000, profit: 1100000 },
+ ],
+ // 📱 MINIMAL - Small dataset for baseline testing
+ minimal: [
+ { category: "Mobile Devices", users: 150, sessions: 90 },
+ { category: "Desktop Computers", users: 280, sessions: 180 },
+ { category: "Tablet Devices", users: 220, sessions: 140 },
+ ],
+ // 📊 WEEKLY TRAFFIC
+ weeklyTraffic: [
+ { day: "Monday", visits: 2200, conversions: 180, bounces: 800 },
+ { day: "Tuesday", visits: 2500, conversions: 220, bounces: 900 },
+ { day: "Wednesday", visits: 2300, conversions: 190, bounces: 850 },
+ { day: "Thursday", visits: 2800, conversions: 250, bounces: 1000 },
+ { day: "Friday", visits: 3200, conversions: 280, bounces: 1100 },
+ { day: "Saturday", visits: 1800, conversions: 120, bounces: 600 },
+ { day: "Sunday", visits: 1500, conversions: 100, bounces: 500 },
+ ],
+};
+
+// Category key mappings for different datasets
+const categoryKeys = {
+ default: "month",
+ bigLabels: "category",
+ companyNames: "company",
+ financialQuarters: "quarter",
+ minimal: "category",
+ weeklyTraffic: "day",
+};
+
+// 🔥 ACTIVE DATA - For backward compatibility
+const barChartCondensedData = dataVariations.default;
+
+const icons = {
+ desktop: Monitor,
+ mobile: TabletSmartphone,
+ tablet: Calendar,
+ sales: Globe,
+ revenue: Smartphone,
+ profit: Laptop,
+ visitors: Tv,
+ conversions: Watch,
+ users: Monitor,
+ sessions: TabletSmartphone,
+ expenses: Calendar,
+ marketCap: Globe,
+ visits: Monitor,
+ bounces: Calendar,
+} as const;
+
+/**
+ * # BarChart Component Documentation
+ *
+ * The BarChart is a compact chart designed for space-constrained layouts
+ * like dashboards and sidebars. It's ideal for:
+ *
+ * - **Compact Dashboards**: Showing multiple metrics in limited space
+ * - **Sidebar Analytics**: Quick comparison visualization without taking up too much room
+ * - **Dense Data Display**: Efficiently showing many data points in a small area
+ *
+ * ## Key Features
+ *
+ * ### Space-Efficient Design
+ * - **Compact Height**: Default 200px height for tight layouts
+ * - **Minimal Legend**: Legend is compact and doesn't take up vertical space
+ * - **Adjustable Tick Variants**: Choose between horizontal or angled labels for better space usage
+ *
+ * ### Layout Variants
+ * - **Grouped**: Compare sub-categories side-by-side within a primary category
+ * - **Stacked**: Show how sub-categories contribute to a total value
+ *
+ * ### Flexible Label Handling
+ * - **Single Line Ticks**: Horizontal labels with automatic collision detection
+ * - **Angled Ticks**: Optimal rotation angle for longer labels that need more space
+ * - **Smart Angle Calculation**: Automatically calculates optimal rotation based on label width
+ *
+ * ### Interactive & Responsive
+ * - **Hover Tooltips**: Standard tooltip showing all data series
+ * - **Responsive Design**: Adapts fluidly to its container's size
+ *
+ * ### Customization
+ * - **Theming**: Comes with six pre-built color palettes
+ * - **Bar Styling**: Customize corner radius with the radius prop
+ * - **Styling Options**: Control grid visibility, axes, and more
+ */
+const meta: Meta<BarChartCondensedProps<typeof barChartCondensedData>> = {
+ title: "Components/D3Charts/BarChart",
+ component: BarChartCondensed,
+ parameters: {
+ layout: "centered",
+ docs: {
+ description: {
+ component: `
+## Installation and Basic Usage
+
+\`\`\`tsx
+import { BarChart } from '@openuidev/react-ui';
+
+const salesData = [
+ { month: "January", desktop: 150, mobile: 90 },
+ { month: "February", desktop: 280, mobile: 180 },
+ { month: "March", desktop: 220, mobile: 140 },
+];
+
+// Basic implementation
+<BarChart
+ data={salesData}
+ categoryKey="month"
+ theme="ocean"
+ height={200}
+/>
+\`\`\`
+
+## Data Structure Requirements
+
+Your data should be an array of objects. Each object must contain:
+- A **category field** (string or number): This will be used for the X-axis labels (e.g., months, categories, etc.).
+- One or more **data series fields** (number): These are the values that will be plotted as bars.
+
+\`\`\`tsx
+const salesData = [
+ { region: "North", sales: 150, marketing: 90 },
+ { region: "South", sales: 280, marketing: 180 },
+ { region: "East", sales: 220, marketing: 140 },
+];
+\`\`\`
+
+## Key Differences from BarChart
+
+- **Compact**: Designed for smaller spaces with a default height of 200px
+- **No Interactive Legend**: Legend is simplified and non-interactive
+- **Tick Variants**: Supports both horizontal (singleLine) and angled labels
+- **Performance**: Optimized for quick rendering in dashboards
+
+## Performance Considerations
+- **Data Density**: For very large datasets, consider disabling animations
+- **Responsiveness**: The chart is fully responsive, but test label visibility on small screens
+- **Animation**: Controlled via \`isAnimationActive={false}\`
+`,
+ },
+ },
+ },
+ tags: ["dev", "autodocs"],
+ argTypes: {
+ data: {
+ description: `
+**Required.** An array of data objects for the bar chart. Each object should contain:
+- A category identifier (string/number) for the X-axis.
+- One or more numeric values for the Y-axis bars.
+`,
+ control: false,
+ table: {
+ type: { summary: "Array<Record<string, string | number>>" },
+ category: "📊 Data Configuration",
+ },
+ },
+ categoryKey: {
+ description:
+ "**Required.** The key in your data object that represents the category for the X-axis.",
+ control: false,
+ table: {
+ type: { summary: "string" },
+ category: "📊 Data Configuration",
+ },
+ },
+ theme: {
+ description:
+ "Specifies the color palette for the chart's bars and tooltips. Ignored when customPalette is provided.",
+ control: "select",
+ options: ["ocean", "orchid", "emerald", "sunset", "spectrum", "vivid"],
+ table: {
+ defaultValue: { summary: "ocean" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ customPalette: {
+ description:
+ "Custom array of colors to use instead of the theme palette. Overrides the theme prop when provided.",
+ control: "object",
+ table: {
+ type: { summary: "string[]" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ variant: {
+ description:
+ "Defines how multiple data series are displayed: `grouped` (side-by-side) or `stacked` (on top of each other).",
+ control: "radio",
+ options: ["grouped", "stacked"],
+ table: {
+ defaultValue: { summary: "grouped" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ tickVariant: {
+ description:
+ "X-axis tick label style. Choose between 'singleLine' (horizontal) or 'angled' (rotated at optimal angle).",
+ control: "radio",
+ options: ["singleLine", "angled"],
+ table: {
+ defaultValue: { summary: "singleLine" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ radius: {
+ description: "Sets the corner radius for the top of each bar, creating a rounded look.",
+ control: { type: "number", min: 0, max: 12, step: 1 },
+ table: {
+ defaultValue: { summary: "4" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ icons: {
+ description:
+ "An object mapping data series keys to React components to be used as icons in the legend.",
+ control: false,
+ table: {
+ type: { summary: "Record<string, React.ReactNode>" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ grid: {
+ description: "Toggles the visibility of the background grid lines.",
+ control: "boolean",
+ table: {
+ defaultValue: { summary: "true" },
+ category: "📱 Display Options",
+ },
+ },
+ showYAxis: {
+ description: "Toggles the visibility of the Y-axis line and labels.",
+ control: "boolean",
+ table: {
+ defaultValue: { summary: "true" },
+ category: "📱 Display Options",
+ },
+ },
+ xAxisLabel: {
+ description: "A label to display below the X-axis.",
+ control: "text",
+ table: {
+ type: { summary: "React.ReactNode" },
+ category: "📱 Display Options",
+ },
+ },
+ yAxisLabel: {
+ description: "A label to display beside the Y-axis.",
+ control: "text",
+ table: {
+ type: { summary: "React.ReactNode" },
+ category: "📱 Display Options",
+ },
+ },
+ isAnimationActive: {
+ description: "Enables or disables the initial loading animation for the bars.",
+ control: "boolean",
+ table: {
+ defaultValue: { summary: "false" },
+ category: "🎬 Animation & Interaction",
+ },
+ },
+ height: {
+ description: "Sets a fixed height for the chart container in pixels.",
+ control: "number",
+ table: {
+ defaultValue: { summary: "200" },
+ type: { summary: "number" },
+ category: "Layout & Sizing",
+ },
+ },
+ width: {
+ description: "Sets a fixed width for the chart container in pixels.",
+ control: "number",
+ table: {
+ type: { summary: "number" },
+ category: "Layout & Sizing",
+ },
+ },
+ className: {
+ description: "Custom CSS class to apply to the chart's container.",
+ control: "text",
+ table: {
+ type: { summary: "string" },
+ category: "Layout & Sizing",
+ },
+ },
+ },
+} satisfies Meta<typeof BarChartCondensed>;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+/**
+ * ## Comprehensive Data Explorer
+ *
+ * This story serves as a comprehensive test suite for the BarChartCondensed component.
+ * Use the buttons to switch between various datasets designed to test edge cases in:
+ *
+ * - **Label Handling**: Datasets with long, dense, or overlapping labels.
+ * - **Data Density**: Scenarios with few or many data points.
+ * - **Chart Variants**: Toggle between grouped and stacked layouts.
+ * - **Tick Variants**: Toggle between horizontal and angled label orientations.
+ *
+ * It's an excellent tool for developers to see how the chart behaves under different conditions.
+ */
+export const DataExplorer: Story = {
+ name: "🎛️ Comprehensive Data Explorer",
+ args: {
+ data: barChartCondensedData,
+ categoryKey: "month",
+ theme: "ocean",
+ variant: "grouped",
+ tickVariant: "singleLine",
+ radius: 4,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ xAxisLabel: "Time Period",
+ yAxisLabel: "Values",
+ height: 200,
+ },
+ render: (args: any) => {
+ const [selectedDataType, setSelectedDataType] =
+ useState<keyof typeof dataVariations>("default");
+ const [variant, setVariant] = useState<"grouped" | "stacked">("grouped");
+ const [tickVariant, setTickVariant] = useState<"singleLine" | "angled">("singleLine");
+
+ const currentData = dataVariations[selectedDataType];
+ const currentCategoryKey = categoryKeys[selectedDataType];
+
+ const buttonStyle = {
+ margin: "2px",
+ padding: "6px 12px",
+ fontSize: "12px",
+ border: "1px solid #ddd",
+ borderRadius: "4px",
+ cursor: "pointer",
+ background: "#fff",
+ fontFamily: "monospace",
+ };
+
+ const activeButtonStyle = {
+ ...buttonStyle,
+ background: "#007acc",
+ color: "white",
+ border: "1px solid #007acc",
+ };
+
+ return (
+ <div>
+ <div
+ style={{
+ marginBottom: "16px",
+ padding: "12px",
+ background: "#f8f9fa",
+ borderRadius: "8px",
+ border: "1px solid #e9ecef",
+ width: "600px",
+ }}
+ >
+ <strong>🏷️ Dataset Selection:</strong>
+ <div style={{ marginTop: "8px", display: "flex", flexWrap: "wrap", gap: "4px" }}>
+ <button
+ onClick={() => setSelectedDataType("default")}
+ style={selectedDataType === "default" ? activeButtonStyle : buttonStyle}
+ >
+ 📅 Default (12 months)
+ </button>
+ <button
+ onClick={() => setSelectedDataType("bigLabels")}
+ style={selectedDataType === "bigLabels" ? activeButtonStyle : buttonStyle}
+ >
+ 🏷️ Big Labels
+ </button>
+ <button
+ onClick={() => setSelectedDataType("companyNames")}
+ style={selectedDataType === "companyNames" ? activeButtonStyle : buttonStyle}
+ >
+ 🏢 Company Names
+ </button>
+ <button
+ onClick={() => setSelectedDataType("financialQuarters")}
+ style={selectedDataType === "financialQuarters" ? activeButtonStyle : buttonStyle}
+ >
+ 📈 Financial Quarters
+ </button>
+ <button
+ onClick={() => setSelectedDataType("minimal")}
+ style={selectedDataType === "minimal" ? activeButtonStyle : buttonStyle}
+ >
+ 📱 Minimal (3 items)
+ </button>
+ <button
+ onClick={() => setSelectedDataType("weeklyTraffic")}
+ style={selectedDataType === "weeklyTraffic" ? activeButtonStyle : buttonStyle}
+ >
+ 📊 Weekly Traffic
+ </button>
+ </div>
+ <div style={{ marginTop: "12px" }}>
+ <strong>📊 Chart Variant:</strong>
+ <div style={{ marginTop: "8px", display: "flex", gap: "4px" }}>
+ <button
+ onClick={() => setVariant("grouped")}
+ style={variant === "grouped" ? activeButtonStyle : buttonStyle}
+ >
+ Grouped (Side-by-side)
+ </button>
+ <button
+ onClick={() => setVariant("stacked")}
+ style={variant === "stacked" ? activeButtonStyle : buttonStyle}
+ >
+ Stacked (On top)
+ </button>
+ </div>
+ </div>
+ <div style={{ marginTop: "12px" }}>
+ <strong>📐 Tick Variant:</strong>
+ <div style={{ marginTop: "8px", display: "flex", gap: "4px" }}>
+ <button
+ onClick={() => setTickVariant("singleLine")}
+ style={tickVariant === "singleLine" ? activeButtonStyle : buttonStyle}
+ >
+ Horizontal Labels
+ </button>
+ <button
+ onClick={() => setTickVariant("angled")}
+ style={tickVariant === "angled" ? activeButtonStyle : buttonStyle}
+ >
+ Angled Labels
+ </button>
+ </div>
+ </div>
+ <div
+ style={{ marginTop: "12px", fontSize: "12px", color: "#666", fontFamily: "monospace" }}
+ >
+ <div>
+ <strong>Current Dataset:</strong> {selectedDataType}
+ </div>
+ <div>
+ <strong>Items:</strong> {currentData.length} | <strong>Category Key:</strong>{" "}
+ {currentCategoryKey} | <strong>Variant:</strong> {variant} | <strong>Tick:</strong>{" "}
+ {tickVariant}
+ </div>
+ </div>
+ </div>
+ <Card style={{ width: "600px" }}>
+ <BarChartCondensed
+ {...args}
+ data={currentData}
+ categoryKey={currentCategoryKey}
+ variant={variant}
+ tickVariant={tickVariant}
+ />
+ </Card>
+ </div>
+ );
+ },
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "**🎛️ Interactive Explorer:** This story allows you to explore different datasets, chart variants, and tick variants interactively. Use the buttons to switch between:\n\n**Datasets:**\n- **Default**: Standard 12-month data\n- **Big Labels**: Extremely long category names\n- **Company Names**: Real-world business names\n- **Financial Quarters**: Quarterly financial data\n- **Minimal**: Baseline with 3 items\n- **Weekly Traffic**: 7-day traffic data\n\n**Chart Variants:**\n- **Grouped**: Bars side-by-side for comparison\n- **Stacked**: Bars stacked to show totals\n\n**Tick Variants:**\n- **Horizontal Labels**: Standard single-line labels with collision detection\n- **Angled Labels**: Rotated labels for better space utilization",
+ },
+ },
+ },
+};
+
+/**
+ * ## Large Dataset with Sidebar Tooltip
+ *
+ * This story demonstrates the sidebar tooltip feature that appears when you have
+ * more than 10 data series. Click on any bar in the chart to see the sidebar
+ * tooltip in action. This provides a better UX for viewing many data series at once.
+ */
+export const LargeDatasetWithSidebarTooltip: Story = {
+ name: "🎯 Large Dataset (>10 Series) - Sidebar Tooltip",
+ args: {
+ data: [
+ {
+ quarter: "Q1",
+ metric1: 120,
+ metric2: 150,
+ metric3: 180,
+ metric4: 200,
+ metric5: 160,
+ metric6: 190,
+ metric7: 220,
+ metric8: 240,
+ metric9: 210,
+ metric10: 230,
+ metric11: 250,
+ metric12: 270,
+ metric13: 260,
+ metric14: 280,
+ metric15: 300,
+ },
+ {
+ quarter: "Q2",
+ metric1: 140,
+ metric2: 170,
+ metric3: 200,
+ metric4: 220,
+ metric5: 180,
+ metric6: 210,
+ metric7: 240,
+ metric8: 260,
+ metric9: 230,
+ metric10: 250,
+ metric11: 270,
+ metric12: 290,
+ metric13: 280,
+ metric14: 300,
+ metric15: 320,
+ },
+ {
+ quarter: "Q3",
+ metric1: 160,
+ metric2: 190,
+ metric3: 220,
+ metric4: 240,
+ metric5: 200,
+ metric6: 230,
+ metric7: 260,
+ metric8: 280,
+ metric9: 250,
+ metric10: 270,
+ metric11: 290,
+ metric12: 310,
+ metric13: 300,
+ metric14: 320,
+ metric15: 340,
+ },
+ {
+ quarter: "Q4",
+ metric1: 180,
+ metric2: 210,
+ metric3: 240,
+ metric4: 260,
+ metric5: 220,
+ metric6: 250,
+ metric7: 280,
+ metric8: 300,
+ metric9: 270,
+ metric10: 290,
+ metric11: 310,
+ metric12: 330,
+ metric13: 320,
+ metric14: 340,
+ metric15: 360,
+ },
+ ] as any,
+ categoryKey: "quarter" as any,
+ theme: "ocean",
+ variant: "grouped",
+ tickVariant: "singleLine",
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ xAxisLabel: "Quarters",
+ yAxisLabel: "Performance Metrics",
+ height: 300,
+ },
+ render: (args: any) => (
+ <div>
+ <div
+ style={{
+ marginBottom: "16px",
+ padding: "16px",
+ background: "#e3f2fd",
+ borderRadius: "8px",
+ border: "2px solid #2196f3",
+ maxWidth: "700px",
+ }}
+ >
+ <div style={{ fontSize: "14px", marginBottom: "8px" }}>
+ <strong>🎯 Sidebar Tooltip Demo</strong>
+ </div>
+ <div style={{ fontSize: "13px", color: "#1565c0", lineHeight: "1.6" }}>
+ This chart has <strong>15 data series</strong> (more than 10). <br />
+ <strong>✨ Click on any bar</strong> in the chart to open the sidebar tooltip on the right
+ side.
+ <br />
+ The sidebar provides a scrollable list of all series values at that quarter, making it
+ easy to view large datasets.
+ <br />
+ <em>
+ 💡 Try hovering first (shows inline tooltip), then click to see the sidebar version!
+ </em>
+ </div>
+ </div>
+ <Card style={{ width: "700px" }}>
+ <BarChartCondensed {...args} />
+ </Card>
+ </div>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "**🎯 Large Dataset Handling:** When your chart has more than 10 data series, the inline tooltip becomes too crowded. This story demonstrates the sidebar tooltip feature:\n\n**Features:**\n- **15 data series** to showcase the sidebar tooltip\n- **Click interaction:** Click any bar to open the sidebar\n- **Scrollable view:** All series values in an organized, scrollable list\n- **Better UX:** Cleaner way to view many data points simultaneously\n- **Color-coded:** Each series maintains its color for easy identification\n- **Works with both variants:** Try switching between grouped and stacked variants\n\n**Usage:**\n1. Hover over the chart to see the inline tooltip (works for smaller datasets)\n2. Click on any bar to open the sidebar tooltip\n3. Scroll through all 15 series values\n4. Click outside or on the X button to close the sidebar",
+ },
+ },
+ },
+};
+
+/**
+ * ## Grouped vs Stacked Comparison
+ *
+ * Side-by-side comparison of grouped and stacked bar chart variants.
+ * This helps you choose the right variant for your data visualization needs.
+ */
+export const VariantComparison: Story = {
+ name: "📊 Grouped vs Stacked Comparison",
+ render: () => (
+ <div style={{ display: "flex", flexDirection: "column", gap: "24px" }}>
+ <Card style={{ width: "700px", padding: "16px" }}>
+ <div style={{ marginBottom: "12px" }}>
+ <div style={{ fontSize: "16px", fontWeight: "600", marginBottom: "4px" }}>
+ Grouped Variant (Side-by-side)
+ </div>
+ <div style={{ fontSize: "13px", color: "#666" }}>
+ Best for comparing individual values across categories
+ </div>
+ </div>
+ <BarChartCondensed
+ data={dataVariations.default as any}
+ categoryKey="month"
+ variant="grouped"
+ theme="ocean"
+ height={200}
+ />
+ </Card>
+ <Card style={{ width: "700px", padding: "16px" }}>
+ <div style={{ marginBottom: "12px" }}>
+ <div style={{ fontSize: "16px", fontWeight: "600", marginBottom: "4px" }}>
+ Stacked Variant (On top of each other)
+ </div>
+ <div style={{ fontSize: "13px", color: "#666" }}>
+ Best for showing how parts contribute to a total
+ </div>
+ </div>
+ <BarChartCondensed
+ data={dataVariations.default as any}
+ categoryKey="month"
+ variant="stacked"
+ theme="emerald"
+ height={200}
+ />
+ </Card>
+ </div>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "**Side-by-side comparison** of chart variants:\n\n- **Grouped**: Bars are placed side-by-side within each category. Perfect for comparing individual values across different categories.\n- **Stacked**: Bars are stacked on top of each other to show how parts contribute to a total. Great for showing composition and totals simultaneously.\n\n**When to use each:**\n- Use **grouped** when you want to compare individual series values\n- Use **stacked** when you want to emphasize totals and part-to-whole relationships",
+ },
+ },
+ },
+};
+
+/**
+ * ## Big Labels with Angled Ticks
+ *
+ * This story demonstrates the chart's ability to handle very long category labels.
+ * The angled tick variant is particularly useful here for preventing label overlap.
+ */
+export const BigLabelsStory: Story = {
+ name: "🏷️ Big Labels (Angled Ticks)",
+ args: {
+ data: dataVariations.bigLabels as any,
+ categoryKey: "category" as any,
+ theme: "emerald",
+ variant: "grouped",
+ tickVariant: "angled",
+ radius: 4,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 250,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "700px" }}>
+ <BarChartCondensed {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests the chart with extremely long category names. The angled tick variant automatically rotates labels at an optimal angle to prevent overlapping and maximize readability.",
+ },
+ },
+ },
+};
+
+/**
+ * ## Company Names with Big Numbers
+ *
+ * This story tests the chart with real-world company names and very large numbers (billions/trillions).
+ * It demonstrates both label handling and number formatting capabilities.
+ */
+export const CompanyNamesStory: Story = {
+ name: "🏢 Company Names (Big Numbers)",
+ args: {
+ data: dataVariations.companyNames as any,
+ categoryKey: "company" as any,
+ theme: "vivid",
+ variant: "grouped",
+ tickVariant: "angled",
+ radius: 4,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 250,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "700px" }}>
+ <BarChartCondensed {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests with real-world company names and very large numbers (billions and trillions). The Y-axis should format numbers with appropriate suffixes (B, T).",
+ },
+ },
+ },
+};
+
+/**
+ * ## Financial Quarters (Grouped)
+ *
+ * Standard financial reporting scenario with quarterly data in grouped layout.
+ */
+export const FinancialQuartersGrouped: Story = {
+ name: "📈 Financial Quarters (Grouped)",
+ args: {
+ data: dataVariations.financialQuarters as any,
+ categoryKey: "quarter" as any,
+ theme: "sunset",
+ variant: "grouped",
+ tickVariant: "singleLine",
+ radius: 4,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 220,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "600px" }}>
+ <BarChartCondensed {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Financial reporting scenario with quarterly data. Grouped layout allows comparison of revenue, expenses, and profit across quarters.",
+ },
+ },
+ },
+};
+
+/**
+ * ## Financial Quarters (Stacked)
+ *
+ * Same financial data in stacked layout to show totals and composition.
+ */
+export const FinancialQuartersStacked: Story = {
+ name: "📈 Financial Quarters (Stacked)",
+ args: {
+ data: dataVariations.financialQuarters as any,
+ categoryKey: "quarter" as any,
+ theme: "orchid",
+ variant: "stacked",
+ tickVariant: "singleLine",
+ radius: 4,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 220,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "600px" }}>
+ <BarChartCondensed {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Same financial data in stacked layout. This view emphasizes the total values and how components contribute to them.",
+ },
+ },
+ },
+};
+
+/**
+ * ## Weekly Traffic Analytics
+ *
+ * Typical analytics dashboard data showing weekly traffic metrics.
+ */
+export const WeeklyTrafficStory: Story = {
+ name: "📊 Weekly Traffic Analytics",
+ args: {
+ data: dataVariations.weeklyTraffic as any,
+ categoryKey: "day" as any,
+ theme: "spectrum",
+ variant: "grouped",
+ tickVariant: "singleLine",
+ radius: 4,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 220,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "650px" }}>
+ <BarChartCondensed {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story: "Weekly traffic analytics showing visits, conversions, and bounces across the week.",
+ },
+ },
+ },
+};
+
+/**
+ * ## Minimal Data
+ *
+ * A baseline test with a small dataset and standard-length labels.
+ */
+export const MinimalDataStory: Story = {
+ name: "📱 Minimal Data (Baseline)",
+ args: {
+ data: dataVariations.minimal as any,
+ categoryKey: "category" as any,
+ theme: "emerald",
+ variant: "grouped",
+ tickVariant: "singleLine",
+ radius: 4,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 200,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "400px" }}>
+ <BarChartCondensed {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story: "Baseline test with minimal data (3 items) and standard-length labels.",
+ },
+ },
+ },
+};
+
+/**
+ * ## Custom Palette
+ *
+ * This story demonstrates how to use the customPalette prop to provide your own color scheme.
+ */
+export const CustomPaletteStory: Story = {
+ name: "🎨 Custom Palette",
+ args: {
+ data: dataVariations.default as any,
+ categoryKey: "month" as any,
+ theme: "ocean", // This will be overridden by customPalette
+ variant: "grouped",
+ tickVariant: "singleLine",
+ radius: 4,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ xAxisLabel: "Month",
+ yAxisLabel: "Traffic",
+ customPalette: ["#FF6B6B", "#4ECDC4", "#45B7D1"],
+ height: 200,
+ },
+ render: (args: any) => (
+ <div>
+ <div
+ style={{
+ marginBottom: "16px",
+ padding: "12px",
+ background: "#f8f9fa",
+ borderRadius: "8px",
+ border: "1px solid #e9ecef",
+ width: "600px",
+ }}
+ >
+ <h4 style={{ margin: "0 0 8px 0", color: "#333" }}>🎨 Custom Color Palette</h4>
+ <p style={{ margin: "0 0 12px 0", fontSize: "14px", color: "#666" }}>
+ This chart uses a custom color palette instead of the default theme colors.
+ </p>
+ <div style={{ display: "flex", gap: "8px", flexWrap: "wrap" }}>
+ {args.customPalette?.map((color: string, index: number) => (
+ <div
+ key={index}
+ style={{
+ display: "flex",
+ alignItems: "center",
+ gap: "4px",
+ padding: "4px 8px",
+ background: "white",
+ borderRadius: "4px",
+ border: "1px solid #ddd",
+ fontSize: "12px",
+ }}
+ >
+ <div
+ style={{
+ width: "12px",
+ height: "12px",
+ borderRadius: "2px",
+ backgroundColor: color,
+ border: "1px solid #ccc",
+ }}
+ />
+ <span style={{ fontFamily: "monospace" }}>{color}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ <Card style={{ width: "600px" }}>
+ <BarChartCondensed {...args} />
+ </Card>
+ </div>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'Demonstrates how to use the `customPalette` prop to provide your own color scheme. When `customPalette` is provided, it overrides the `theme` prop.\n\n**Usage:**\n```tsx\n<BarChartCondensed\n data={data}\n categoryKey="month"\n customPalette={["#FF6B6B", "#4ECDC4", "#45B7D1"]}\n/>\n```',
+ },
+ },
+ },
+};
+
+/**
+ * ## Radius Comparison
+ *
+ * Compare different corner radius values for the bars.
+ */
+export const RadiusComparison: Story = {
+ name: "🔘 Radius Comparison",
+ render: () => (
+ <div style={{ display: "flex", flexDirection: "column", gap: "24px" }}>
+ <Card style={{ width: "700px", padding: "16px" }}>
+ <div style={{ marginBottom: "12px" }}>
+ <div style={{ fontSize: "16px", fontWeight: "600", marginBottom: "4px" }}>
+ Sharp Corners (0px)
+ </div>
+ <div style={{ fontSize: "13px", color: "#666" }}>No rounding, clean angular look</div>
+ </div>
+ <BarChartCondensed
+ data={dataVariations.default as any}
+ categoryKey="month"
+ variant="grouped"
+ theme="ocean"
+ radius={0}
+ height={180}
+ />
+ </Card>
+ <Card style={{ width: "700px", padding: "16px" }}>
+ <div style={{ marginBottom: "12px" }}>
+ <div style={{ fontSize: "16px", fontWeight: "600", marginBottom: "4px" }}>
+ Default Radius (4px)
+ </div>
+ <div style={{ fontSize: "13px", color: "#666" }}>Subtle rounding, balanced look</div>
+ </div>
+ <BarChartCondensed
+ data={dataVariations.default as any}
+ categoryKey="month"
+ variant="grouped"
+ theme="emerald"
+ radius={4}
+ height={180}
+ />
+ </Card>
+ <Card style={{ width: "700px", padding: "16px" }}>
+ <div style={{ marginBottom: "12px" }}>
+ <div style={{ fontSize: "16px", fontWeight: "600", marginBottom: "4px" }}>
+ Rounded Corners (8px)
+ </div>
+ <div style={{ fontSize: "13px", color: "#666" }}>More pronounced rounding</div>
+ </div>
+ <BarChartCondensed
+ data={dataVariations.default as any}
+ categoryKey="month"
+ variant="grouped"
+ theme="sunset"
+ radius={8}
+ height={180}
+ />
+ </Card>
+ </div>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "**Radius comparison** showing different corner radius values:\n\n- **0px**: Sharp, angular corners for a clean, modern look\n- **4px**: Default subtle rounding, balanced appearance\n- **8px**: More pronounced rounding for a softer appearance\n\n**When to use each:**\n- Use **0px** for a clean, technical, or minimalist aesthetic\n- Use **4px** (default) for general purpose use\n- Use **8px** for a friendlier, more approachable design",
+ },
+ },
+ },
+};
+
+/**
+ * ## Tick Variant Comparison
+ *
+ * Side-by-side comparison of single-line (horizontal) and angled tick variants.
+ */
+export const TickVariantComparison: Story = {
+ name: "📐 Tick Variant Comparison",
+ render: () => (
+ <div style={{ display: "flex", flexDirection: "column", gap: "24px" }}>
+ <Card style={{ width: "700px", padding: "16px" }}>
+ <div style={{ marginBottom: "12px" }}>
+ <div style={{ fontSize: "16px", fontWeight: "600", marginBottom: "4px" }}>
+ Single Line Variant (Horizontal)
+ </div>
+ <div style={{ fontSize: "13px", color: "#666" }}>
+ Standard horizontal labels. Recharts automatically hides overlapping labels.
+ </div>
+ </div>
+ <BarChartCondensed
+ data={dataVariations.bigLabels as any}
+ categoryKey="category"
+ variant="grouped"
+ tickVariant="singleLine"
+ theme="ocean"
+ height={200}
+ />
+ </Card>
+ <Card style={{ width: "700px", padding: "16px" }}>
+ <div style={{ marginBottom: "12px" }}>
+ <div style={{ fontSize: "16px", fontWeight: "600", marginBottom: "4px" }}>
+ Angled Variant (Rotated)
+ </div>
+ <div style={{ fontSize: "13px", color: "#666" }}>
+ Automatically rotates labels at an optimal angle. Shows more labels without collision.
+ </div>
+ </div>
+ <BarChartCondensed
+ data={dataVariations.bigLabels as any}
+ categoryKey="category"
+ variant="grouped"
+ tickVariant="angled"
+ theme="emerald"
+ height={260}
+ />
+ </Card>
+ </div>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "**Side-by-side comparison** of tick variants:\n\n- **Single Line**: Standard horizontal labels with automatic collision detection. Recharts hides overlapping labels.\n- **Angled**: Rotates labels at an optimal angle calculated based on label width and available space. Shows more labels without collision.\n\n**When to use each:**\n- Use **singleLine** for short labels or when you have few data points\n- Use **angled** for long labels or many data points where horizontal labels would overlap",
+ },
+ },
+ },
+};
+
+/**
+ * ## Super Condensed Bar Chart
+ *
+ * This story demonstrates the chart with many data points in a very narrow container,
+ * creating extremely thin bars. This tests the minimum bar width logic and the
+ * automatic removal of rounded corners for bars thinner than 7px.
+ */
+export const SuperCondensedStory: Story = {
+ name: "🔬 Super Condensed (Many Bars)",
+ args: {
+ data: [
+ { month: "Jan '23", desktop: 150, mobile: 90, tablet: 60 },
+ { month: "Feb '23", desktop: 280, mobile: 180, tablet: 100 },
+ { month: "Mar '23", desktop: 220, mobile: 140, tablet: 80 },
+ { month: "Apr '23", desktop: 180, mobile: 160, tablet: 90 },
+ { month: "May '23", desktop: 250, mobile: 120, tablet: 70 },
+ { month: "Jun '23", desktop: 300, mobile: 180, tablet: 110 },
+ { month: "Jul '23", desktop: 350, mobile: 220, tablet: 130 },
+ { month: "Aug '23", desktop: 400, mobile: 240, tablet: 150 },
+ { month: "Sep '23", desktop: 450, mobile: 260, tablet: 170 },
+ { month: "Oct '23", desktop: 500, mobile: 280, tablet: 190 },
+ { month: "Nov '23", desktop: 550, mobile: 300, tablet: 210 },
+ { month: "Dec '23", desktop: 600, mobile: 320, tablet: 230 },
+ { month: "Jan '24", desktop: 620, mobile: 340, tablet: 250 },
+ { month: "Feb '24", desktop: 640, mobile: 360, tablet: 270 },
+ { month: "Mar '24", desktop: 680, mobile: 380, tablet: 290 },
+ { month: "Apr '24", desktop: 700, mobile: 400, tablet: 310 },
+ { month: "May '24", desktop: 720, mobile: 420, tablet: 330 },
+ { month: "Jun '24", desktop: 750, mobile: 440, tablet: 350 },
+ { month: "Jul '24", desktop: 780, mobile: 460, tablet: 370 },
+ { month: "Aug '24", desktop: 800, mobile: 480, tablet: 390 },
+ { month: "Sep '24", desktop: 820, mobile: 500, tablet: 410 },
+ { month: "Oct '24", desktop: 850, mobile: 520, tablet: 430 },
+ { month: "Nov '24", desktop: 880, mobile: 540, tablet: 450 },
+ { month: "Dec '24", desktop: 900, mobile: 560, tablet: 470 },
+ ] as any,
+ categoryKey: "month" as any,
+ theme: "ocean",
+ variant: "grouped",
+ tickVariant: "angled",
+ radius: 4,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 180,
+ },
+ render: (args: any) => (
+ <div>
+ <div
+ style={{
+ marginBottom: "16px",
+ padding: "12px",
+ background: "#f8f9fa",
+ borderRadius: "8px",
+ border: "1px solid #e9ecef",
+ width: "320px",
+ }}
+ >
+ <h4 style={{ margin: "0 0 8px 0", color: "#333" }}>🔬 Ultra Condensed View</h4>
+ <p style={{ margin: "0 0 12px 0", fontSize: "14px", color: "#666" }}>
+ 24 months × 3 series = 72 bars in 320px width. Each bar is ~4px wide or less!
+ </p>
+ <ul style={{ margin: "0", paddingLeft: "20px", fontSize: "12px", color: "#666" }}>
+ <li>Bars {"<"} 7px wide = no rounded corners</li>
+ <li>Minimum bar width: 2px enforced</li>
+ <li>Angled labels prevent overlap</li>
+ <li>Internal lines hidden on thin bars</li>
+ </ul>
+ </div>
+ <Card style={{ width: "320px" }}>
+ <BarChartCondensed {...args} />
+ </Card>
+ </div>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "**Extreme density test** with 24 data points × 3 series (72 total bars) in a 320px container, making each bar approximately 4px wide or less. This demonstrates:\n\n- **Automatic corner removal**: Bars thinner than 7px automatically become square (no rounded corners)\n- **Minimum width enforcement**: Bars maintain a minimum width of 2px for visibility\n- **Grouped bar handling**: Multiple series create even thinner individual bars\n- **Label handling**: Angled labels prevent overlap in ultra-dense scenarios\n- **Internal line hiding**: The internal line is hidden when bars are too thin to display it properly\n\nThis represents an extreme edge case useful for:\n- Compact dashboard widgets\n- Sidebar sparkline-style analytics\n- Mobile-optimized views\n- High-density data visualization in limited space",
+ },
+ },
+ },
+};
+
+/**
+ * ## Responsive Behavior Demo
+ *
+ * This story demonstrates the responsive capabilities of the BarChartCondensed.
+ * Drag the handles on the container to resize it and observe how the chart adapts.
+ */
+export const ResponsiveBehaviorDemo: Story = {
+ name: "📱 Responsive Behavior Demo",
+ args: {
+ data: dataVariations.bigLabels as any,
+ categoryKey: "category" as any,
+ theme: "sunset",
+ variant: "grouped",
+ tickVariant: "angled",
+ radius: 4,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 250,
+ },
+ render: (args: any) => {
+ const [dimensions, setDimensions] = useState<{ width: number }>({
+ width: 700,
+ });
+
+ const handleMouseDown = (e: React.MouseEvent<HTMLDivElement>, handle: string) => {
+ e.preventDefault();
+ e.stopPropagation();
+ const startX = e.clientX;
+ const startWidth = dimensions.width;
+
+ const doDrag = (e: MouseEvent) => {
+ const dx = e.clientX - startX;
+ let newWidth = startWidth;
+
+ if (handle.includes("e")) newWidth = startWidth + dx;
+ if (handle.includes("w")) newWidth = startWidth - dx;
+
+ setDimensions({
+ width: Math.max(300, newWidth),
+ });
+ };
+
+ const stopDrag = () => {
+ document.removeEventListener("mousemove", doDrag);
+ document.removeEventListener("mouseup", stopDrag);
+ };
+
+ document.addEventListener("mousemove", doDrag);
+ document.addEventListener("mouseup", stopDrag);
+ };
+
+ const handleStyle: React.CSSProperties = {
+ position: "absolute",
+ background: "#3b82f6",
+ opacity: 0.6,
+ zIndex: 10,
+ transition: "opacity 0.2s ease",
+ };
+
+ return (
+ <div style={{ padding: "20px" }}>
+ <div style={{ marginBottom: "20px" }}>
+ <h3 style={{ margin: "0 0 8px 0", fontSize: "18px", fontWeight: "600" }}>
+ Responsive Behavior Demonstration
+ </h3>
+ <p style={{ margin: "0 0 12px 0", color: "#666", fontSize: "14px" }}>
+ Drag the left or right edges of the container to see how the chart adapts
+ </p>
+ <div
+ style={{
+ padding: "12px",
+ backgroundColor: "#e3f2fd",
+ borderRadius: "6px",
+ fontSize: "12px",
+ color: "#1565c0",
+ }}
+ >
+ <strong>🎯 Try This:</strong> Resize the container to see how bar widths and labels
+ adapt to available space.
+ </div>
+ </div>
+
+ <Card
+ style={{
+ position: "relative",
+ width: `${dimensions.width}px`,
+ border: "2px dashed #9ca3af",
+ padding: "20px",
+ boxSizing: "border-box",
+ overflow: "hidden",
+ cursor: "default",
+ }}
+ >
+ <BarChartCondensed {...args} />
+
+ {/* Resize Handles */}
+ <div
+ style={{ ...handleStyle, top: 0, bottom: 0, left: -2, width: 12, cursor: "ew-resize" }}
+ onMouseDown={(e) => handleMouseDown(e, "w")}
+ />
+ <div
+ style={{ ...handleStyle, top: 0, bottom: 0, right: -2, width: 12, cursor: "ew-resize" }}
+ onMouseDown={(e) => handleMouseDown(e, "e")}
+ />
+
+ {/* Dimension Display */}
+ <div
+ style={{
+ position: "absolute",
+ bottom: 8,
+ right: 8,
+ background: "rgba(0,0,0,0.8)",
+ color: "white",
+ padding: "4px 8px",
+ borderRadius: "4px",
+ fontSize: "11px",
+ fontFamily: "monospace",
+ fontWeight: "500",
+ }}
+ >
+ {dimensions.width}px
+ </div>
+ </Card>
+ </div>
+ );
+ },
+};
+
+/**
+ * 🎯 Bar Width Testing Playground
+ * Interactive story to test bar width calculations with various configurations:
+ * - Different data set sizes (few bars vs many bars)
+ * - Grouped vs Stacked variants
+ * - Max bar width constraint (prevents bars from being too wide)
+ * - Container width variations
+ */
+export const BarWidthPlayground: StoryObj<typeof BarChartCondensed> = {
+ render: () => {
+ const [variant, setVariant] = useState<"grouped" | "stacked">("grouped");
+ const [dataSize, setDataSize] = useState<"small" | "medium" | "large" | "xlarge">("medium");
+ const [maxBarWidth, setMaxBarWidth] = useState(60);
+ const [containerWidth, setContainerWidth] = useState<number | undefined>(undefined);
+
+ // Generate data based on size selection
+ const generateData = () => {
+ const sizes = {
+ small: 4,
+ medium: 12,
+ large: 24,
+ xlarge: 50,
+ };
+
+ const count = sizes[dataSize];
+ return Array.from({ length: count }, (_, i) => ({
+ quarter: `Q${(i % 4) + 1} FY${2022 + Math.floor(i / 4)}`,
+ revenue: Math.floor(Math.random() * 2000000) + 500000,
+ expenses: Math.floor(Math.random() * 1500000) + 300000,
+ profit: Math.floor(Math.random() * 800000) + 100000,
+ }));
+ };
+
+ const data = generateData();
+
+ return (
+ <div style={{ padding: "20px" }}>
+ {/* Control Panel */}
+ <Card style={{ marginBottom: "24px", padding: "20px" }}>
+ <h3 style={{ marginTop: 0, marginBottom: "20px", fontSize: "18px", fontWeight: 600 }}>
+ 🎛️ Bar Width Controls
+ </h3>
+
+ <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "20px" }}>
+ {/* Variant Control */}
+ <div>
+ <label style={{ display: "block", marginBottom: "8px", fontWeight: 500 }}>
+ Chart Variant
+ </label>
+ <div style={{ display: "flex", gap: "8px" }}>
+ <button
+ onClick={() => setVariant("grouped")}
+ style={{
+ padding: "8px 16px",
+ borderRadius: "6px",
+ border: "1px solid",
+ borderColor: variant === "grouped" ? "#6366f1" : "#e5e7eb",
+ backgroundColor: variant === "grouped" ? "#6366f1" : "white",
+ color: variant === "grouped" ? "white" : "#374151",
+ cursor: "pointer",
+ fontWeight: 500,
+ }}
+ >
+ Grouped
+ </button>
+ <button
+ onClick={() => setVariant("stacked")}
+ style={{
+ padding: "8px 16px",
+ borderRadius: "6px",
+ border: "1px solid",
+ borderColor: variant === "stacked" ? "#6366f1" : "#e5e7eb",
+ backgroundColor: variant === "stacked" ? "#6366f1" : "white",
+ color: variant === "stacked" ? "white" : "#374151",
+ cursor: "pointer",
+ fontWeight: 500,
+ }}
+ >
+ Stacked
+ </button>
+ </div>
+ </div>
+
+ {/* Data Size Control */}
+ <div>
+ <label style={{ display: "block", marginBottom: "8px", fontWeight: 500 }}>
+ Number of Data Points
+ </label>
+ <select
+ value={dataSize}
+ onChange={(e) => setDataSize(e.target.value as any)}
+ style={{
+ width: "100%",
+ padding: "8px 12px",
+ borderRadius: "6px",
+ border: "1px solid #e5e7eb",
+ fontSize: "14px",
+ }}
+ >
+ <option value="small">Small (4 points)</option>
+ <option value="medium">Medium (12 points)</option>
+ <option value="large">Large (24 points)</option>
+ <option value="xlarge">X-Large (50 points)</option>
+ </select>
+ </div>
+
+ {/* Max Bar Width Control */}
+ <div style={{ gridColumn: "1 / -1" }}>
+ <label style={{ display: "block", marginBottom: "8px", fontWeight: 500 }}>
+ Max Bar Width: {maxBarWidth}px
+ <span style={{ fontWeight: 400, color: "#6b7280", marginLeft: "8px" }}>
+ (Prevents bars from becoming too wide)
+ </span>
+ </label>
+ <input
+ type="range"
+ min="10"
+ max="120"
+ value={maxBarWidth}
+ onChange={(e) => setMaxBarWidth(Number(e.target.value))}
+ style={{ width: "100%" }}
+ />
+ <div
+ style={{
+ display: "flex",
+ justifyContent: "space-between",
+ fontSize: "11px",
+ color: "#6b7280",
+ marginTop: "4px",
+ }}
+ >
+ <span>10px</span>
+ <span>120px</span>
+ </div>
+ </div>
+
+ {/* Container Width Control */}
+ <div style={{ gridColumn: "1 / -1" }}>
+ <label style={{ display: "block", marginBottom: "8px", fontWeight: 500 }}>
+ Container Width: {containerWidth ? `${containerWidth}px` : "Auto (100%)"}
+ </label>
+ <div style={{ display: "flex", gap: "8px", alignItems: "center" }}>
+ <input
+ type="range"
+ min="400"
+ max="1400"
+ step="50"
+ value={containerWidth || 1400}
+ onChange={(e) => setContainerWidth(Number(e.target.value))}
+ style={{ flex: 1 }}
+ disabled={!containerWidth}
+ />
+ <button
+ onClick={() => setContainerWidth(containerWidth ? undefined : 800)}
+ style={{
+ padding: "6px 12px",
+ borderRadius: "6px",
+ border: "1px solid #e5e7eb",
+ backgroundColor: containerWidth ? "#ef4444" : "#10b981",
+ color: "white",
+ cursor: "pointer",
+ fontSize: "12px",
+ fontWeight: 500,
+ }}
+ >
+ {containerWidth ? "Auto" : "Fixed"}
+ </button>
+ </div>
+ <div
+ style={{
+ display: "flex",
+ justifyContent: "space-between",
+ fontSize: "11px",
+ color: "#6b7280",
+ marginTop: "4px",
+ }}
+ >
+ <span>400px</span>
+ <span>1400px</span>
+ </div>
+ </div>
+ </div>
+
+ {/* Info Display */}
+ <div
+ style={{
+ marginTop: "20px",
+ padding: "12px",
+ backgroundColor: "#f3f4f6",
+ borderRadius: "6px",
+ fontSize: "13px",
+ }}
+ >
+ <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: "12px" }}>
+ <div>
+ <strong>Data Points:</strong> {data.length}
+ </div>
+ <div>
+ <strong>Bars per Category:</strong> {variant === "stacked" ? 1 : 3}
+ </div>
+ <div>
+ <strong>Total Bars:</strong> {data.length * (variant === "stacked" ? 1 : 3)}
+ </div>
+ </div>
+ </div>
+ </Card>
+
+ {/* Chart Display */}
+ <Card>
+ <h3 style={{ marginTop: 0, marginBottom: "16px" }}>
+ {variant === "grouped" ? "📊 Grouped" : "📚 Stacked"} Bar Chart - Bar Width Test
+ </h3>
+ <div style={{ width: containerWidth ? `${containerWidth}px` : "100%" }}>
+ <BarChartCondensed
+ data={data}
+ categoryKey="quarter"
+ variant={variant}
+ maxBarWidth={maxBarWidth}
+ width={containerWidth}
+ height={400}
+ legend
+ grid
+ showYAxis
+ xAxisLabel="Fiscal Quarter"
+ yAxisLabel="Amount ($)"
+ />
+ </div>
+ </Card>
+
+ {/* Quick Test Presets */}
+ <Card style={{ marginTop: "24px", padding: "20px" }}>
+ <h3 style={{ marginTop: 0, marginBottom: "16px", fontSize: "16px", fontWeight: 600 }}>
+ 🚀 Quick Test Presets
+ </h3>
+ <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: "12px" }}>
+ <button
+ onClick={() => {
+ setDataSize("small");
+ setVariant("grouped");
+ setMaxBarWidth(60);
+ setContainerWidth(undefined);
+ }}
+ style={{
+ padding: "12px",
+ borderRadius: "6px",
+ border: "1px solid #e5e7eb",
+ backgroundColor: "white",
+ cursor: "pointer",
+ textAlign: "left",
+ }}
+ >
+ <div style={{ fontWeight: 600, marginBottom: "4px" }}>🎯 Few Bars (Wide)</div>
+ <div style={{ fontSize: "12px", color: "#6b7280" }}>4 points, max 60px cap</div>
+ </button>
+
+ <button
+ onClick={() => {
+ setDataSize("xlarge");
+ setVariant("grouped");
+ setMaxBarWidth(60);
+ setContainerWidth(undefined);
+ }}
+ style={{
+ padding: "12px",
+ borderRadius: "6px",
+ border: "1px solid #e5e7eb",
+ backgroundColor: "white",
+ cursor: "pointer",
+ textAlign: "left",
+ }}
+ >
+ <div style={{ fontWeight: 600, marginBottom: "4px" }}>📉 Many Bars (Thin)</div>
+ <div style={{ fontSize: "12px", color: "#6b7280" }}>
+ 50 points, auto-sized thin bars
+ </div>
+ </button>
+
+ <button
+ onClick={() => {
+ setDataSize("large");
+ setVariant("stacked");
+ setMaxBarWidth(40);
+ setContainerWidth(800);
+ }}
+ style={{
+ padding: "12px",
+ borderRadius: "6px",
+ border: "1px solid #e5e7eb",
+ backgroundColor: "white",
+ cursor: "pointer",
+ textAlign: "left",
+ }}
+ >
+ <div style={{ fontWeight: 600, marginBottom: "4px" }}>🔄 Fixed Container</div>
+ <div style={{ fontSize: "12px", color: "#6b7280" }}>24 points, stacked, 800px</div>
+ </button>
+
+ <button
+ onClick={() => {
+ setDataSize("medium");
+ setVariant("grouped");
+ setMaxBarWidth(100);
+ setContainerWidth(undefined);
+ }}
+ style={{
+ padding: "12px",
+ borderRadius: "6px",
+ border: "1px solid #e5e7eb",
+ backgroundColor: "white",
+ cursor: "pointer",
+ textAlign: "left",
+ }}
+ >
+ <div style={{ fontWeight: 600, marginBottom: "4px" }}>🎨 Large Max Width</div>
+ <div style={{ fontSize: "12px", color: "#6b7280" }}>Medium data, max 100px</div>
+ </button>
+
+ <button
+ onClick={() => {
+ setDataSize("small");
+ setVariant("stacked");
+ setMaxBarWidth(30);
+ setContainerWidth(400);
+ }}
+ style={{
+ padding: "12px",
+ borderRadius: "6px",
+ border: "1px solid #e5e7eb",
+ backgroundColor: "white",
+ cursor: "pointer",
+ textAlign: "left",
+ }}
+ >
+ <div style={{ fontWeight: 600, marginBottom: "4px" }}>📱 Narrow Container</div>
+ <div style={{ fontSize: "12px", color: "#6b7280" }}>Small data, 400px width</div>
+ </button>
+
+ <button
+ onClick={() => {
+ setDataSize("xlarge");
+ setVariant("stacked");
+ setMaxBarWidth(20);
+ setContainerWidth(undefined);
+ }}
+ style={{
+ padding: "12px",
+ borderRadius: "6px",
+ border: "1px solid #e5e7eb",
+ backgroundColor: "white",
+ cursor: "pointer",
+ textAlign: "left",
+ }}
+ >
+ <div style={{ fontWeight: 600, marginBottom: "4px" }}>🔬 Ultra Condensed</div>
+ <div style={{ fontSize: "12px", color: "#6b7280" }}>50 points, stacked, max 20px</div>
+ </button>
+ </div>
+ </Card>
+ </div>
+ );
+ },
+};
diff --git a/packages/react-ui/src/components/D3Charts/BarChart/types.ts b/packages/react-ui/src/components/D3Charts/BarChart/types.ts
new file mode 100644
index 000000000..c7b63699d
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/BarChart/types.ts
@@ -0,0 +1,27 @@
+import type { BaseChartProps, ChartData } from "../types";
+
+export type BarChartData = ChartData;
+
+export type BarChartVariant = "grouped" | "stacked";
+
+export type BarChartOrientation = "vertical" | "horizontal";
+
+export interface BarChartProps<T extends BarChartData> extends BaseChartProps<T> {
+ variant?: BarChartVariant;
+ /**
+ * Bar orientation. `'vertical'` (default) renders upward bars per category;
+ * `'horizontal'` renders labeled scrolling rows with bars growing rightward
+ * from the value-zero line. Default `'vertical'`.
+ */
+ orientation?: BarChartOrientation;
+ barRadius?: number;
+ /** Maximum width in px for a single bar. Bars will center within their band when capped. */
+ maxBarWidth?: number;
+ /** Show a decorative internal line inside each bar from base toward the tip. Default true. */
+ internalLine?: boolean;
+ /** Color of the internal line. Defaults to semi-transparent white. */
+ internalLineColor?: string;
+ /** Stroke width of the internal line. Defaults to 1. */
+ internalLineWidth?: number;
+ onClick?: (row: T[number], index: number) => void;
+}
diff --git a/packages/react-ui/src/components/D3Charts/CalendarHeatmap/CalendarHeatmap.tsx b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/CalendarHeatmap.tsx
new file mode 100644
index 000000000..2c7ea077d
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/CalendarHeatmap.tsx
@@ -0,0 +1,259 @@
+import { useId, useMemo } from "react";
+import { useEffectiveAnimation } from "../hooks";
+import { useCalendarHeatmapOrchestrator } from "../hooks/cartesian/useCalendarHeatmapOrchestrator";
+import { ChartShell } from "../shared/core/ChartShell";
+import { ChartTooltip } from "../shared/core/PortalTooltip/ChartTooltip";
+import { CHART_CLASS_PREFIX } from "../utils/constants";
+import { CalendarCells } from "./parts/CalendarCells";
+import { CalendarLegend } from "./parts/CalendarLegend";
+import { CalendarPatternDefs, calendarPatternId } from "./parts/CalendarPatternDefs";
+import { CalendarSeparatorLabels, CalendarSeparators } from "./parts/CalendarSeparators";
+import { MonthAxis } from "./parts/MonthAxis";
+import { useDelayedHover } from "./parts/useDelayedHover";
+import { WeekdayAxis } from "./parts/WeekdayAxis";
+import type { CalendarHeatmapProps } from "./types";
+
+const CLASS_PREFIX = `${CHART_CLASS_PREFIX}-calendar-heatmap`;
+
+/** `` (q, year) => `Q1 2026` `` — the default quarter-label formatter. */
+const defaultQuarterLabel = (quarter: number, year: number) => `Q${quarter} ${year}`;
+
+export function CalendarHeatmap(props: CalendarHeatmapProps) {
+ const {
+ data,
+ range,
+ thresholds,
+ levelColors,
+ levelStyles,
+ layout = "fluid",
+ binSize,
+ gap = 3,
+ weekStartDay = 0,
+ hideGhostCells = true,
+ weekdayTickFilter = "odd",
+ weekdayLabelFormat = "full",
+ showMonthLabels = true,
+ columnSeparators,
+ legendVariant = "swatches",
+ legendLabels,
+ formatTooltipLabel,
+ tooltipDelay,
+ rowOpacity,
+ isAnimationActive = false,
+ animationDuration = 1600,
+ width,
+ height,
+ customPalette,
+ onClick,
+ className,
+ } = props;
+
+ const showLegend = legendVariant !== "none";
+
+ const orch = useCalendarHeatmapOrchestrator({
+ data: data ?? [],
+ // No calendarHeatmapPalette token on react-ui's ChartColorPalette yet (same
+ // gap as heatmap/funnel/scatter) — the catch-all default palette is the token.
+ themePaletteName: "defaultChartPalette",
+ customPalette,
+ levelColors,
+ levelStyles,
+ thresholds,
+ range,
+ layout,
+ binSize,
+ gap,
+ weekStartDay,
+ hideGhostCells,
+ weekdayTickFilter,
+ weekdayLabelFormat,
+ showMonthLabels,
+ columnSeparators,
+ showLegend,
+ formatTooltipLabel,
+ width,
+ height,
+ });
+
+ const animate = useEffectiveAnimation(isAnimationActive);
+
+ // Namespace the pattern ids so several calendars on one page never collide.
+ const patternBaseId = useId().replace(/:/g, "");
+
+ const {
+ separators,
+ dimensions: {
+ svgWidth,
+ svgHeight,
+ gutterLeft,
+ gutterTop,
+ pitchX,
+ pitchY,
+ cellW,
+ cellH,
+ plotHeight,
+ monthLabelY,
+ weekdayLabelX,
+ },
+ } = orch;
+
+ // Per-level fill: the level CSS var, or a pattern ref when that level sets one.
+ const levelFills = useMemo(
+ () =>
+ orch.levelStyles.map((style, level) =>
+ style?.pattern
+ ? `url(#${calendarPatternId(patternBaseId, level)})`
+ : `var(--${CLASS_PREFIX}-level-${level})`,
+ ),
+ [orch.levelStyles, patternBaseId],
+ );
+
+ // Hovering a legend level highlights it and clears any cell hover/tooltip.
+ const handleLevelEnter = (level: number) => {
+ orch.hover.setHoveredLevel(level);
+ orch.hover.handleMouseLeave();
+ };
+ const handleLevelLeave = () => orch.hover.setHoveredLevel(null);
+
+ // Delay the tooltip's show/hide edges (grace period smooths cell-to-cell hops).
+ const activeTooltip = useMemo(
+ () =>
+ orch.tooltip.tooltipPayload && orch.hover.mousePos
+ ? {
+ ...orch.tooltip.tooltipPayload,
+ viewportPosition: orch.hover.mousePos,
+ }
+ : null,
+ [orch.tooltip.tooltipPayload, orch.hover.mousePos],
+ );
+ const shownTooltip = useDelayedHover(activeTooltip, tooltipDelay);
+
+ const labelFormat = columnSeparators?.labelFormat ?? defaultQuarterLabel;
+
+ return (
+ <ChartShell
+ containerRef={orch.refs.containerRef}
+ classPrefix={CLASS_PREFIX}
+ className={className}
+ style={orch.style.containerStyle}
+ isEmpty={orch.isEmpty}
+ >
+ {() => (
+ <>
+ <div className={`${CLASS_PREFIX}-plot`} style={{ position: "relative", width: svgWidth }}>
+ <svg
+ width={svgWidth}
+ height={svgHeight}
+ style={{ overflow: "visible" }}
+ role="img"
+ aria-label="Calendar heatmap chart"
+ >
+ <CalendarPatternDefs
+ baseId={patternBaseId}
+ levelStyles={orch.levelStyles}
+ levelColors={orch.levelColors}
+ />
+
+ {showMonthLabels && (
+ <g transform={`translate(${gutterLeft}, 0)`}>
+ <MonthAxis
+ labels={orch.monthLabels}
+ pitchX={pitchX}
+ xOffsets={separators.offsets}
+ y={monthLabelY}
+ classPrefix={CLASS_PREFIX}
+ />
+ </g>
+ )}
+
+ <g transform={`translate(0, ${gutterTop})`}>
+ <WeekdayAxis
+ ticks={orch.weekdayTicks}
+ pitchY={pitchY}
+ x={weekdayLabelX}
+ classPrefix={CLASS_PREFIX}
+ />
+ </g>
+
+ <g
+ transform={`translate(${gutterLeft}, ${gutterTop})`}
+ onMouseLeave={orch.hover.handleMouseLeave}
+ // Grid dim is LEGEND-hover scoped (bklit parity): hovering a
+ // cell only lights up its legend swatch, never re-shades the
+ // grid — so this reads `hoveredLevel`, not `highlightedLevel`.
+ {...{
+ [`data-${CHART_CLASS_PREFIX}-highlight-level`]:
+ orch.hover.hoveredLevel ?? undefined,
+ }}
+ >
+ <CalendarCells
+ cells={orch.cells}
+ classPrefix={CLASS_PREFIX}
+ pitchX={pitchX}
+ pitchY={pitchY}
+ cellW={cellW}
+ cellH={cellH}
+ gap={gap}
+ levelFills={levelFills}
+ xOffsets={separators.offsets}
+ rowOpacity={rowOpacity}
+ animate={animate}
+ animationDuration={animationDuration}
+ onCellMouseMove={orch.hover.handleCellMouseMove}
+ onCellMouseLeave={orch.hover.handleMouseLeave}
+ onClick={onClick}
+ />
+ <CalendarSeparators
+ columns={separators.columns}
+ offsets={separators.offsets}
+ pitchX={pitchX}
+ spacing={separators.spacing}
+ gap={gap}
+ plotHeight={plotHeight}
+ stroke={columnSeparators?.stroke}
+ dashed={columnSeparators?.dashed}
+ classPrefix={CLASS_PREFIX}
+ />
+ </g>
+ </svg>
+
+ <CalendarSeparatorLabels
+ labels={separators.labels}
+ offsets={separators.offsets}
+ pitchX={pitchX}
+ gutterLeft={gutterLeft}
+ format={labelFormat}
+ classPrefix={CLASS_PREFIX}
+ />
+ </div>
+
+ {showLegend && (
+ <CalendarLegend
+ ref={orch.refs.legendRef}
+ variant={legendVariant === "gradient" ? "gradient" : "swatches"}
+ levelColors={orch.levelColors}
+ levelStyles={orch.levelStyles}
+ patternBaseId={patternBaseId}
+ labels={{
+ less: legendLabels?.less ?? "Less",
+ more: legendLabels?.more ?? "More",
+ }}
+ highlightedLevel={orch.hover.highlightedLevel}
+ onLevelEnter={handleLevelEnter}
+ onLevelLeave={handleLevelLeave}
+ classPrefix={CLASS_PREFIX}
+ />
+ )}
+
+ {shownTooltip && (
+ <ChartTooltip
+ label={shownTooltip.label}
+ items={shownTooltip.items}
+ viewportPosition={shownTooltip.viewportPosition}
+ />
+ )}
+ </>
+ )}
+ </ChartShell>
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/CalendarHeatmap/calendarHeatmap.scss b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/calendarHeatmap.scss
new file mode 100644
index 000000000..8f0ebdd3b
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/calendarHeatmap.scss
@@ -0,0 +1,137 @@
+@use "../../../cssUtils" as cssUtils;
+@use "../shared/cartesian/chartBase" as base;
+@use "../prefix" as brand;
+
+@include base.centered-container("calendar-heatmap");
+
+.#{brand.$prefix}-calendar-heatmap-month-label,
+.#{brand.$prefix}-calendar-heatmap-weekday-label {
+ @include base.svg-tick-label;
+}
+
+// Cell fill is set inline per cell from a level CSS var (declared on the
+// container), so a later task's per-level styles can override a level without
+// touching the painter.
+.#{brand.$prefix}-calendar-heatmap-cell:hover {
+ stroke: cssUtils.$foreground;
+ stroke-width: 1.5;
+}
+
+// Ghost cells are decorative padding (only rendered when hideGhostCells is
+// false) — dim them via fill-opacity, NOT opacity, so the entrance keyframe's
+// forwards `opacity: 1` can't defeat the dim.
+.#{brand.$prefix}-calendar-heatmap-cell--ghost {
+ fill-opacity: 0.4;
+}
+
+// Entrances are decorative: gate the whole rule (pre-state included) behind
+// reduced-motion so users who opt out get the natural static state immediately
+// — gating only the animation would strand cells at opacity: 0.
+@media (prefers-reduced-motion: no-preference) {
+ .#{brand.$prefix}-calendar-heatmap-cell--animated {
+ opacity: 0;
+ animation: #{brand.$prefix}-calendar-cell-in 0.4s ease-out forwards;
+ }
+}
+
+@keyframes #{brand.$prefix}-calendar-cell-in {
+ from {
+ opacity: 0;
+ }
+ to {
+ opacity: 1;
+ }
+}
+
+// Level-hover dimming: while a LEGEND level is hovered (and only then — cell
+// hover highlights its legend swatch but never re-shades the grid; bklit
+// parity), the plot group carries `data-<prefix>-highlight-level=N` and every
+// cell not on level N dims. Driven by ONE attribute swap on the group — cells
+// keep their static `--level-N` class, so there's no per-cell JS churn. Dim via
+// fill-opacity (like ghost/rowOpacity) so it never fights the entrance keyframe.
+@for $level from 0 through 4 {
+ [data-#{brand.$prefix}-highlight-level="#{$level}"]
+ .#{brand.$prefix}-calendar-heatmap-cell:not(
+ .#{brand.$prefix}-calendar-heatmap-cell--level-#{$level}
+ ) {
+ fill-opacity: 0.3;
+ }
+}
+
+// The dim + legend-swatch fade are hover feedback, not entrances — but still
+// motion, so gate the transitions behind reduced-motion (the end states above
+// apply regardless).
+@media (prefers-reduced-motion: no-preference) {
+ .#{brand.$prefix}-calendar-heatmap-cell,
+ .#{brand.$prefix}-calendar-heatmap-legend-swatch-slot {
+ transition:
+ fill-opacity 0.2s ease,
+ opacity 0.2s ease;
+ }
+}
+
+// ── Column separators ─────────────────────────────────────────────────────────
+
+// Base stroke token so an unstyled rule still reads in both themes; the `stroke`
+// prop overrides it inline when set.
+.#{brand.$prefix}-calendar-heatmap-separator {
+ stroke: cssUtils.$border-default;
+ stroke-width: 1;
+}
+
+.#{brand.$prefix}-calendar-heatmap-quarter-label {
+ @include cssUtils.typography(label, extra-small);
+ color: cssUtils.$text-neutral-secondary;
+ white-space: nowrap;
+ pointer-events: none;
+}
+
+// ── Less → More scale legend ──────────────────────────────────────────────────
+
+.#{brand.$prefix}-calendar-heatmap-legend {
+ display: flex;
+ align-items: center;
+ justify-content: flex-end;
+ gap: cssUtils.$space-s;
+ width: 100%;
+ padding-top: cssUtils.$space-m;
+
+ &-label {
+ @include cssUtils.typography(label, extra-small);
+ color: cssUtils.$text-neutral-secondary;
+ }
+
+ &-swatches {
+ display: flex;
+ align-items: center;
+ gap: cssUtils.$space-3xs;
+ }
+
+ &-swatch-slot {
+ display: inline-flex;
+ cursor: pointer;
+ }
+
+ &-swatch {
+ display: block;
+ width: 12px;
+ height: 12px;
+ flex-shrink: 0;
+ border-radius: cssUtils.$radius-2xs;
+ }
+
+ &-gradient {
+ position: relative;
+ width: 60px;
+ height: 12px;
+ flex-shrink: 0;
+ border-radius: cssUtils.$radius-2xs;
+ }
+
+ &-gradient-hit {
+ position: absolute;
+ top: 0;
+ height: 100%;
+ cursor: pointer;
+ }
+}
diff --git a/packages/react-ui/src/components/D3Charts/CalendarHeatmap/index.ts b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/index.ts
new file mode 100644
index 000000000..4b366dce0
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/index.ts
@@ -0,0 +1,2 @@
+export { CalendarHeatmap } from "./CalendarHeatmap";
+export type { CalendarHeatmapDatum, CalendarHeatmapProps } from "./types";
diff --git a/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/CalendarCells.tsx b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/CalendarCells.tsx
new file mode 100644
index 000000000..f86d1b08f
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/CalendarCells.tsx
@@ -0,0 +1,113 @@
+import React, { useCallback } from "react";
+
+import type { CalendarLeveledCell } from "../../hooks/cartesian/useCalendarHeatmapOrchestrator";
+import { entranceProps } from "../../utils/entranceUtils";
+import { cellStaggerDelayMs } from "./staggerSeed";
+
+const CELL_RADIUS = 2;
+
+interface CalendarCellsProps {
+ cells: CalendarLeveledCell[];
+ classPrefix: string;
+ pitchX: number;
+ pitchY: number;
+ cellW: number;
+ cellH: number;
+ gap: number;
+ /** Per-level fill string (`var(--…)` or `url(#pattern)`), indexed by level. */
+ levelFills: string[];
+ /** Per-column x-offset in px (separator gutters); length `weeks`. */
+ xOffsets: number[];
+ rowOpacity?: number | number[];
+ animate: boolean;
+ animationDuration: number;
+ onCellMouseMove: (event: React.MouseEvent, cell: CalendarLeveledCell) => void;
+ onCellMouseLeave: () => void;
+ onClick?: (date: Date, value: number) => void;
+}
+
+/** Per-row opacity multiplier: a flat number, an indexed array, or 1. */
+function resolveRowOpacity(row: number, rowOpacity: number | number[] | undefined): number {
+ if (rowOpacity === undefined) return 1;
+ if (Array.isArray(rowOpacity)) return rowOpacity[row] ?? 1;
+ return rowOpacity;
+}
+
+/**
+ * The cell grid: one `<rect>` per non-ghost calendar day. Fill comes from the
+ * per-level `levelFills` entry — a level CSS var
+ * (`--<prefix>-calendar-heatmap-level-N`) or a `url(#pattern)` when that level
+ * sets one — so a level can be restyled without re-rendering; the entrance is an
+ * opacity fade with a deterministic per-cell delay. Each cell x also picks up
+ * its column's separator-gutter offset. Hover highlight is pure CSS (`:hover`
+ * stroke) — these handlers only feed the tooltip/click state. `rowOpacity` dims
+ * via fill-opacity, NOT opacity, so it never fights the entrance keyframe's
+ * forwards `opacity`.
+ */
+export function CalendarCells({
+ cells,
+ classPrefix,
+ pitchX,
+ pitchY,
+ cellW,
+ cellH,
+ gap,
+ levelFills,
+ xOffsets,
+ rowOpacity,
+ animate,
+ animationDuration,
+ onCellMouseMove,
+ onCellMouseLeave,
+ onClick,
+}: CalendarCellsProps) {
+ const handleClick = useCallback(
+ (cell: CalendarLeveledCell) => {
+ onClick?.(cell.date, cell.value);
+ },
+ [onClick],
+ );
+
+ return (
+ <g>
+ {cells.map((cell) => {
+ const { className: animatedClass, animationDelay } = entranceProps(
+ animate,
+ `${classPrefix}-cell--animated`,
+ cellStaggerDelayMs(cell.col, cell.row, animationDuration),
+ );
+ const modifiers = [
+ animatedClass,
+ // Static per-level marker so the container can dim non-matching cells
+ // via CSS on level-hover (no per-cell JS style churn).
+ `${classPrefix}-cell--level-${cell.level}`,
+ cell.ghost ? `${classPrefix}-cell--ghost` : "",
+ ]
+ .filter(Boolean)
+ .join(" ");
+ const opacity = resolveRowOpacity(cell.row, rowOpacity);
+
+ return (
+ <rect
+ key={`${cell.col}-${cell.row}`}
+ className={`${classPrefix}-cell${modifiers ? ` ${modifiers}` : ""}`}
+ x={cell.col * pitchX + gap / 2 + (xOffsets[cell.col] ?? 0)}
+ y={cell.row * pitchY + gap / 2}
+ width={cellW}
+ height={cellH}
+ rx={CELL_RADIUS}
+ fillOpacity={opacity !== 1 ? opacity : undefined}
+ style={{
+ fill: levelFills[cell.level],
+ animationDelay,
+ cursor: onClick ? "pointer" : undefined,
+ }}
+ onMouseMove={(event) => onCellMouseMove(event, cell)}
+ onMouseLeave={onCellMouseLeave}
+ onClick={() => handleClick(cell)}
+ />
+ );
+ })}
+ </g>
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/CalendarLegend.tsx b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/CalendarLegend.tsx
new file mode 100644
index 000000000..9dd622b0b
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/CalendarLegend.tsx
@@ -0,0 +1,152 @@
+import { forwardRef } from "react";
+import type { CalendarLevelStyle } from "../types";
+import { calendarPatternId } from "./CalendarPatternDefs";
+
+/** Opacity of inactive swatches while a level is highlighted (bklit parity). */
+const INACTIVE_OPACITY = 0.3;
+const SWATCH_SIZE = 12;
+const SWATCH_RADIUS = 2;
+
+interface CalendarLegendProps {
+ /** Discrete squares or a continuous color bar. */
+ variant: "swatches" | "gradient";
+ /** Resolved level colors (length 5), low → high. */
+ levelColors: string[];
+ /** Resolved per-level styles (length 5) — drives swatch patterns. */
+ levelStyles: ReadonlyArray<CalendarLevelStyle | null>;
+ /** `useId` base shared with the chart's pattern `<defs>`. */
+ patternBaseId: string;
+ /** Bracketing labels. */
+ labels: { less: string; more: string };
+ /** The level currently highlighted (legend hover ∪ cell hover), or null. */
+ highlightedLevel: number | null;
+ /** Hover a level → drives the grid dim + swatch highlight. */
+ onLevelEnter: (level: number) => void;
+ onLevelLeave: () => void;
+ classPrefix: string;
+}
+
+const LEVELS = [0, 1, 2, 3, 4] as const;
+
+/** One legend square — a colored tile, or a patterned tile via the shared defs. */
+function LegendSwatch({
+ level,
+ color,
+ pattern,
+ patternBaseId,
+ classPrefix,
+}: {
+ level: number;
+ color: string;
+ pattern: boolean;
+ patternBaseId: string;
+ classPrefix: string;
+}) {
+ if (pattern) {
+ return (
+ <svg
+ className={`${classPrefix}-legend-swatch`}
+ width={SWATCH_SIZE}
+ height={SWATCH_SIZE}
+ aria-hidden="true"
+ >
+ <rect
+ width={SWATCH_SIZE}
+ height={SWATCH_SIZE}
+ rx={SWATCH_RADIUS}
+ fill={`url(#${calendarPatternId(patternBaseId, level)})`}
+ />
+ </svg>
+ );
+ }
+ return (
+ <span
+ className={`${classPrefix}-legend-swatch`}
+ style={{ backgroundColor: color }}
+ aria-hidden="true"
+ />
+ );
+}
+
+/**
+ * The Less→More scale legend. `swatches` renders five discrete tiles (patterned
+ * when a level sets one); `gradient` renders a continuous color bar with
+ * invisible per-level hit segments. Both bracket with the Less/More labels and
+ * are bidirectionally linked to the grid: hovering a level dims the non-matching
+ * cells and highlights that swatch, and (via `highlightedLevel`) a hovered cell
+ * highlights its swatch here. Forwards its ref so the shell can reserve height.
+ */
+export const CalendarLegend = forwardRef<HTMLDivElement, CalendarLegendProps>(
+ function CalendarLegend(
+ {
+ variant,
+ levelColors,
+ levelStyles,
+ patternBaseId,
+ labels,
+ highlightedLevel,
+ onLevelEnter,
+ onLevelLeave,
+ classPrefix,
+ },
+ ref,
+ ) {
+ const isDimming = highlightedLevel !== null;
+ const swatchOpacity = (level: number) =>
+ isDimming && highlightedLevel !== level ? INACTIVE_OPACITY : 1;
+
+ const gradientStops = levelColors
+ .map((color, index) => `${color} ${(index / (LEVELS.length - 1)) * 100}%`)
+ .join(", ");
+
+ return (
+ <div ref={ref} className={`${classPrefix}-legend`}>
+ <span className={`${classPrefix}-legend-label`}>{labels.less}</span>
+
+ {variant === "gradient" ? (
+ <div
+ className={`${classPrefix}-legend-gradient`}
+ style={{
+ background: `linear-gradient(to right, ${gradientStops})`,
+ }}
+ >
+ {LEVELS.map((level) => (
+ <span
+ key={level}
+ className={`${classPrefix}-legend-gradient-hit`}
+ style={{
+ left: `${(level / LEVELS.length) * 100}%`,
+ width: `${(1 / LEVELS.length) * 100}%`,
+ }}
+ onPointerEnter={() => onLevelEnter(level)}
+ onPointerLeave={onLevelLeave}
+ />
+ ))}
+ </div>
+ ) : (
+ <div className={`${classPrefix}-legend-swatches`}>
+ {LEVELS.map((level) => (
+ <span
+ key={level}
+ className={`${classPrefix}-legend-swatch-slot`}
+ style={{ opacity: swatchOpacity(level) }}
+ onPointerEnter={() => onLevelEnter(level)}
+ onPointerLeave={onLevelLeave}
+ >
+ <LegendSwatch
+ level={level}
+ color={levelColors[level] ?? "#000000"}
+ pattern={Boolean(levelStyles[level]?.pattern)}
+ patternBaseId={patternBaseId}
+ classPrefix={classPrefix}
+ />
+ </span>
+ ))}
+ </div>
+ )}
+
+ <span className={`${classPrefix}-legend-label`}>{labels.more}</span>
+ </div>
+ );
+ },
+);
diff --git a/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/CalendarPatternDefs.tsx b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/CalendarPatternDefs.tsx
new file mode 100644
index 000000000..60a00b2ba
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/CalendarPatternDefs.tsx
@@ -0,0 +1,136 @@
+import type { CalendarLevelPattern } from "../types";
+
+/** Default pattern stroke — a theme-adaptive contrast token over the tile. */
+const DEFAULT_PATTERN_STROKE = "var(--openui-foreground)";
+
+/** The SVG `<pattern>` id for a level, namespaced by the chart's `useId` base. */
+export function calendarPatternId(baseId: string, level: number): string {
+ return `${baseId}-pattern-level-${level}`;
+}
+
+interface PatternTile {
+ width: number;
+ height: number;
+ strokeWidth: number;
+ /** Line paths (hatch presets) drawn in the stroke color. */
+ paths?: string[];
+ /** Dot radius (dot preset) — a filled circle in the stroke color. */
+ dotRadius?: number;
+}
+
+// visx `PatternLines` path builders (orientation → tile path), reproduced as
+// pure SVG so the port carries no @visx dependency.
+function diagonalPath(w: number, h: number): string {
+ return `M 0,${h} l ${w},${-h} M ${-w / 4},${h / 4} l ${w / 2},${-h / 2} M ${(3 / 4) * w},${(5 / 4) * h} l ${w / 2},${-h / 2}`;
+}
+
+function diagonalRtlPath(w: number, h: number): string {
+ return `M 0,0 l ${w},${h} M ${-w / 4},${(3 / 4) * h} l ${w / 2},${h / 2} M ${(3 / 4) * w},${-h / 4} l ${w / 2},${h / 2}`;
+}
+
+/** Tile geometry per preset, mirroring bklit `patternPresetTileSize` (cross ×1.33). */
+function patternTile(pattern: CalendarLevelPattern): PatternTile {
+ switch (pattern) {
+ case "diagonal":
+ return {
+ width: 6,
+ height: 6,
+ strokeWidth: 1,
+ paths: [diagonalPath(6, 6)],
+ };
+ case "horizontal":
+ return { width: 6, height: 6, strokeWidth: 1, paths: [`M 0,3 l 6,0`] };
+ case "vertical":
+ return { width: 6, height: 6, strokeWidth: 1, paths: [`M 3,0 l 0,6`] };
+ case "cross": {
+ const w = 8 * 1.33;
+ const h = 8 * 1.33;
+ return {
+ width: w,
+ height: h,
+ strokeWidth: 1.33,
+ paths: [diagonalPath(w, h), diagonalRtlPath(w, h)],
+ };
+ }
+ case "dots":
+ return { width: 10, height: 10, strokeWidth: 0, dotRadius: 1.5 };
+ }
+}
+
+/** A single `<pattern>`: the level color as a background tile + the overlay. */
+function CalendarPattern({
+ id,
+ pattern,
+ tileBackground,
+ stroke,
+}: {
+ id: string;
+ pattern: CalendarLevelPattern;
+ tileBackground: string;
+ stroke: string;
+}) {
+ const tile = patternTile(pattern);
+ return (
+ <pattern id={id} width={tile.width} height={tile.height} patternUnits="userSpaceOnUse">
+ <rect width={tile.width} height={tile.height} fill={tileBackground} />
+ {tile.dotRadius != null ? (
+ <circle cx={tile.width / 2} cy={tile.height / 2} r={tile.dotRadius} fill={stroke} />
+ ) : (
+ tile.paths?.map((d, index) => (
+ <path
+ key={index}
+ d={d}
+ stroke={stroke}
+ strokeWidth={tile.strokeWidth}
+ strokeLinecap="square"
+ fill="transparent"
+ shapeRendering="auto"
+ />
+ ))
+ )}
+ </pattern>
+ );
+}
+
+interface CalendarPatternDefsProps {
+ /** `useId` base so ids stay unique across multiple charts on a page. */
+ baseId: string;
+ /** Resolved per-level styles (length 5); only entries with a pattern emit. */
+ levelStyles: ReadonlyArray<{
+ pattern?: CalendarLevelPattern;
+ patternColor?: string;
+ } | null>;
+ /** Resolved level colors (length 5) — each pattern tiles over its level color. */
+ levelColors: string[];
+}
+
+/**
+ * The `<defs>` of tile patterns for any level whose `levelStyle` sets a
+ * `pattern`. Each pattern paints the level's color as the tile background and
+ * overlays the hatch/dots in `patternColor` (defaulting to the theme foreground)
+ * — bklit's overlay-on-color look. Cells and legend swatches reference these by
+ * `url(#…)` via {@link calendarPatternId}. Renders nothing when no level
+ * carries a pattern.
+ */
+export function CalendarPatternDefs({
+ baseId,
+ levelStyles,
+ levelColors,
+}: CalendarPatternDefsProps) {
+ const patterns = levelStyles.flatMap((style, level) => {
+ const pattern = style?.pattern;
+ if (!pattern) return [];
+ return [
+ <CalendarPattern
+ key={level}
+ id={calendarPatternId(baseId, level)}
+ pattern={pattern}
+ tileBackground={levelColors[level] ?? "#000000"}
+ stroke={style?.patternColor?.trim() || DEFAULT_PATTERN_STROKE}
+ />,
+ ];
+ });
+
+ if (patterns.length === 0) return null;
+ return <defs>{patterns}</defs>;
+}
diff --git a/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/CalendarSeparators.tsx b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/CalendarSeparators.tsx
new file mode 100644
index 000000000..19f71785d
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/CalendarSeparators.tsx
@@ -0,0 +1,107 @@
+import type { CalendarSeparatorLabel } from "./separatorLayout";
+
+interface CalendarSeparatorsProps {
+ /** Columns a vertical rule is drawn at. */
+ columns: number[];
+ /** Per-column x-offset in px (length `weeks`); the rule follows its gutter. */
+ offsets: number[];
+ /** Column pitch in px. */
+ pitchX: number;
+ /** Gutter width; when 0 the rule sits in the inter-cell gap. */
+ spacing: number;
+ /** Inter-cell gap in px. */
+ gap: number;
+ /** Full grid height in px — the rule spans it top to bottom. */
+ plotHeight: number;
+ /** Line color (falls back to the theme border token in CSS). */
+ stroke?: string;
+ /** Dashed vs. solid rule. */
+ dashed?: boolean;
+ classPrefix: string;
+}
+
+/**
+ * The vertical column separators, drawn inside the plot group (already
+ * translated to the grid origin). A rule at column `c` sits in the gutter its
+ * offset opened — centered when `spacing > 0`, otherwise in the cell gap
+ * (bklit `getHeatmapSeparatorX` parity). Color/dash come from props; the base
+ * stroke token lives in CSS so an unstyled rule still reads in both themes.
+ */
+export function CalendarSeparators({
+ columns,
+ offsets,
+ pitchX,
+ spacing,
+ gap,
+ plotHeight,
+ stroke,
+ dashed,
+ classPrefix,
+}: CalendarSeparatorsProps) {
+ return (
+ <g>
+ {columns.map((col) => {
+ const x = col * pitchX + (offsets[col] ?? 0) - (spacing > 0 ? spacing / 2 : gap / 2);
+ return (
+ <line
+ key={col}
+ className={`${classPrefix}-separator`}
+ x1={x}
+ x2={x}
+ y1={0}
+ y2={plotHeight}
+ stroke={stroke}
+ strokeDasharray={dashed ? "4,4" : undefined}
+ />
+ );
+ })}
+ </g>
+ );
+}
+
+interface CalendarSeparatorLabelsProps {
+ /** Quarter labels anchored to the column that opens each group. */
+ labels: CalendarSeparatorLabel[];
+ /** Per-column x-offset in px (length `weeks`). */
+ offsets: number[];
+ /** Column pitch in px. */
+ pitchX: number;
+ /** Left gutter width (weekday axis) — labels share the grid's left origin. */
+ gutterLeft: number;
+ /** Formats the `Q{n} {year}` label text. */
+ format: (quarter: number, year: number) => string;
+ classPrefix: string;
+}
+
+/**
+ * The quarter labels for `groupBy: 'quarter'`, rendered as HTML positioned over
+ * the plot (absolute, relative to the plot wrapper which shares the SVG's left
+ * origin). Each label left-anchors to its group's opening column, matching the
+ * separator rule below it.
+ */
+export function CalendarSeparatorLabels({
+ labels,
+ offsets,
+ pitchX,
+ gutterLeft,
+ format,
+ classPrefix,
+}: CalendarSeparatorLabelsProps) {
+ return (
+ <>
+ {labels.map(({ col, quarter, year }) => (
+ <span
+ key={col}
+ className={`${classPrefix}-quarter-label`}
+ style={{
+ position: "absolute",
+ top: 0,
+ left: gutterLeft + col * pitchX + (offsets[col] ?? 0),
+ }}
+ >
+ {format(quarter, year)}
+ </span>
+ ))}
+ </>
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/MonthAxis.tsx b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/MonthAxis.tsx
new file mode 100644
index 000000000..60d53fc07
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/MonthAxis.tsx
@@ -0,0 +1,34 @@
+interface MonthAxisProps {
+ /** One short-month label per month, anchored to its first-of-month column. */
+ labels: Array<{ col: number; label: string }>;
+ /** Column pitch in px — the label is placed at the column's left edge. */
+ pitchX: number;
+ /** Per-column x-offset in px (separator gutters); length `weeks`. */
+ xOffsets: number[];
+ /** Baseline y for every month label (inside the reserved top gutter). */
+ y: number;
+ classPrefix: string;
+}
+
+/**
+ * The top month axis: an SVG `<text>` per month, left-anchored to the column
+ * that contains that month's 1st. Rendered inside a group already translated to
+ * the grid's left edge, so `col * pitchX` (plus its separator-gutter offset)
+ * lines each label up with its column.
+ */
+export function MonthAxis({ labels, pitchX, xOffsets, y, classPrefix }: MonthAxisProps) {
+ return (
+ <g>
+ {labels.map(({ col, label }) => (
+ <text
+ key={col}
+ x={col * pitchX + (xOffsets[col] ?? 0)}
+ y={y}
+ className={`${classPrefix}-month-label`}
+ >
+ {label}
+ </text>
+ ))}
+ </g>
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/WeekdayAxis.tsx b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/WeekdayAxis.tsx
new file mode 100644
index 000000000..ffaf0434f
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/WeekdayAxis.tsx
@@ -0,0 +1,33 @@
+interface WeekdayAxisProps {
+ /** The rows that get a label (already filtered), with their weekday text. */
+ ticks: Array<{ row: number; label: string }>;
+ /** Row pitch in px — the label centers on its row band. */
+ pitchY: number;
+ /** Right edge x for every weekday label (labels are end-anchored). */
+ x: number;
+ classPrefix: string;
+}
+
+/**
+ * The left weekday axis: an end-anchored SVG `<text>` per labeled row, centered
+ * on the row band. Rendered inside a group already translated down past the top
+ * month gutter, so `row * pitchY` lines each label up with its cell row.
+ */
+export function WeekdayAxis({ ticks, pitchY, x, classPrefix }: WeekdayAxisProps) {
+ return (
+ <g>
+ {ticks.map(({ row, label }) => (
+ <text
+ key={row}
+ x={x}
+ y={row * pitchY + pitchY / 2}
+ textAnchor="end"
+ dominantBaseline="central"
+ className={`${classPrefix}-weekday-label`}
+ >
+ {label}
+ </text>
+ ))}
+ </g>
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/calendarMath.test.ts b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/calendarMath.test.ts
new file mode 100644
index 000000000..eac2f3424
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/calendarMath.test.ts
@@ -0,0 +1,265 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import {
+ buildCalendarGrid,
+ type CalendarCell,
+ type CalendarGrid,
+ formatCalendarTooltipDate,
+ monthLabelColumns,
+ quarterBoundaryColumns,
+ resolveWeekRange,
+} from "./calendarMath";
+
+/** Local-midnight Date from y/m/d (m is 1-based), matching the module's parsing. */
+function local(y: number, m: number, d: number): Date {
+ return new Date(y, m - 1, d);
+}
+
+function cellOn(grid: CalendarGrid, date: Date): CalendarCell | undefined {
+ return grid.cells.find((c) => c.date.getTime() === date.getTime());
+}
+
+describe("buildCalendarGrid — data extent (range undefined)", () => {
+ // Brief case: data 2026-01-01..2026-03-31, weekStartDay=0.
+ // NOTE: the brief states grid.weeks === 13, but a Sunday-aligned grid spanning
+ // Jan 1's week (Sun Dec 28 2025) through Mar 31's week (Sun Mar 29 2026) is
+ // 14 columns (13 week-gaps + 1). 14 is the honest count — bklit's own
+ // getHeatmapWeekCount agrees. See task-3-report.md for the arithmetic.
+ const data = [
+ { date: "2026-01-01", value: 7 },
+ { date: "2026-01-15", value: 2 },
+ { date: "2026-01-15", value: 3 }, // duplicate day → sums to 5
+ { date: "2026-03-31", value: 4 },
+ ];
+
+ it("spans 14 week columns and week-aligns the start to the prior Sunday", () => {
+ const grid = buildCalendarGrid(data, {
+ weekStartDay: 0,
+ hideGhostCells: true,
+ });
+ expect(grid.weeks).toBe(14);
+ expect(grid.start.getDay()).toBe(0); // Sunday
+ expect(grid.start.getTime()).toBe(local(2025, 12, 28).getTime());
+ expect(grid.end.getTime()).toBe(local(2026, 3, 31).getTime());
+ });
+
+ it("places 2026-01-01 (Thursday) at {col:0,row:4} with its value, not a ghost", () => {
+ const grid = buildCalendarGrid(data, {
+ weekStartDay: 0,
+ hideGhostCells: true,
+ });
+ const jan1 = cellOn(grid, local(2026, 1, 1));
+ expect(jan1).toBeDefined();
+ expect(jan1!.col).toBe(0);
+ expect(jan1!.row).toBe(4);
+ expect(jan1!.value).toBe(7);
+ expect(jan1!.ghost).toBe(false);
+ });
+
+ it("sums duplicate dates and lands values on the right cells", () => {
+ const grid = buildCalendarGrid(data, {
+ weekStartDay: 0,
+ hideGhostCells: true,
+ });
+ expect(cellOn(grid, local(2026, 1, 15))!.value).toBe(5);
+ expect(cellOn(grid, local(2026, 3, 31))!.value).toBe(4);
+ });
+
+ it("gives missing dates value 0", () => {
+ const grid = buildCalendarGrid(data, {
+ weekStartDay: 0,
+ hideGhostCells: true,
+ });
+ expect(cellOn(grid, local(2026, 1, 2))!.value).toBe(0);
+ });
+
+ it("excludes ghost cells entirely when hideGhostCells is true", () => {
+ const grid = buildCalendarGrid(data, {
+ weekStartDay: 0,
+ hideGhostCells: true,
+ });
+ expect(grid.cells.some((c) => c.ghost)).toBe(false);
+ // Dec 28-31 2025 precede the data window → dropped.
+ expect(cellOn(grid, local(2025, 12, 28))).toBeUndefined();
+ // Apr 1-4 2026 trail the data window → dropped.
+ expect(cellOn(grid, local(2026, 4, 1))).toBeUndefined();
+ });
+
+ it("includes ghost cells (value 0) when hideGhostCells is false", () => {
+ const grid = buildCalendarGrid(data, {
+ weekStartDay: 0,
+ hideGhostCells: false,
+ });
+ // Columns unchanged whether ghosts are hidden or not.
+ expect(grid.weeks).toBe(14);
+ const leadGhost = cellOn(grid, local(2025, 12, 28));
+ expect(leadGhost).toBeDefined();
+ expect(leadGhost!.ghost).toBe(true);
+ expect(leadGhost!.value).toBe(0);
+ expect(leadGhost!.col).toBe(0);
+ expect(leadGhost!.row).toBe(0); // Sunday, display row 0
+ });
+
+ // Brief case: weekStartDay=1 (Monday-first) → 2026-01-01 row becomes 3.
+ it("rotates rows for a Monday-first week: 2026-01-01 lands on row 3", () => {
+ const grid = buildCalendarGrid(data, {
+ weekStartDay: 1,
+ hideGhostCells: true,
+ });
+ const jan1 = cellOn(grid, local(2026, 1, 1));
+ expect(jan1!.col).toBe(0);
+ expect(jan1!.row).toBe(3);
+ expect(grid.start.getDay()).toBe(1); // Monday
+ expect(grid.start.getTime()).toBe(local(2025, 12, 29).getTime());
+ });
+
+ // Supports the brief's intended "~13 weeks for Q1": when the last datapoint
+ // falls inside the 13th column, the honest count is exactly 13.
+ it("spans exactly 13 columns when the data ends within the 13th week", () => {
+ const grid = buildCalendarGrid(
+ [
+ { date: "2026-01-01", value: 1 },
+ { date: "2026-03-28", value: 1 }, // Sat, last day of column 12
+ ],
+ { weekStartDay: 0, hideGhostCells: true },
+ );
+ expect(grid.weeks).toBe(13);
+ expect(cellOn(grid, local(2026, 3, 28))!.col).toBe(12);
+ });
+});
+
+describe("buildCalendarGrid — GitHub window inference (range 6m/12m)", () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ // Brief case: range:'12m' with a single datapoint today → a full calendar-year
+ // window ending this week. Pinned to a late-month "today" so the 12 calendar
+ // months resolve to 53 week columns (bklit resolveHeatmapWeekRange semantics).
+ it("resolves '12m' to 53 columns ending on this week's today", () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date(2026, 11, 31, 12, 0, 0)); // Dec 31 2026, local noon
+ const today = local(2026, 12, 31);
+
+ const grid = buildCalendarGrid([{ date: today, value: 9 }], {
+ range: "12m",
+ weekStartDay: 0,
+ hideGhostCells: true,
+ });
+
+ expect(grid.weeks).toBe(53);
+ expect(grid.start.getDay()).toBe(0);
+ expect(grid.start.getTime()).toBe(local(2025, 12, 28).getTime());
+ expect(grid.end.getTime()).toBe(today.getTime());
+
+ const todayCell = cellOn(grid, today);
+ expect(todayCell).toBeDefined();
+ expect(todayCell!.value).toBe(9);
+ expect(todayCell!.ghost).toBe(false);
+ expect(todayCell!.col).toBe(52); // last column
+ });
+
+ it("resolves '6m' to a calendar-month window ending today", () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date(2026, 11, 31, 12, 0, 0));
+ const today = local(2026, 12, 31);
+
+ const grid = buildCalendarGrid([{ date: today, value: 1 }], {
+ range: "6m",
+ weekStartDay: 0,
+ hideGhostCells: true,
+ });
+
+ // Six-calendar-month window: start-of-week for Jun 1 2026 = Sun May 31 2026.
+ expect(grid.start.getTime()).toBe(local(2026, 5, 31).getTime());
+ expect(grid.end.getTime()).toBe(today.getTime());
+ expect(grid.weeks).toBe(31);
+ expect(cellOn(grid, today)!.ghost).toBe(false);
+ });
+});
+
+describe("resolveWeekRange — explicit [start,end] tuple", () => {
+ it("week-aligns the start and preserves the end, order-independent", () => {
+ const range = resolveWeekRange([], ["2026-01-01", "2026-03-31"], 0);
+ expect(range.start.getTime()).toBe(local(2025, 12, 28).getTime());
+ expect(range.end.getTime()).toBe(local(2026, 3, 31).getTime());
+
+ const swapped = resolveWeekRange([], ["2026-03-31", "2026-01-01"], 0);
+ expect(swapped.start.getTime()).toBe(local(2025, 12, 28).getTime());
+ expect(swapped.end.getTime()).toBe(local(2026, 3, 31).getTime());
+ });
+
+ it("ghosts cells outside an explicit tuple window", () => {
+ const grid = buildCalendarGrid([], {
+ range: [local(2026, 1, 1), local(2026, 3, 31)],
+ weekStartDay: 0,
+ hideGhostCells: false,
+ });
+ expect(cellOn(grid, local(2025, 12, 31))!.ghost).toBe(true);
+ expect(cellOn(grid, local(2026, 1, 1))!.ghost).toBe(false);
+ expect(cellOn(grid, local(2026, 3, 31))!.ghost).toBe(false);
+ });
+});
+
+describe("quarterBoundaryColumns", () => {
+ it("returns the columns that start a new calendar quarter (excludes col 0)", () => {
+ const grid = buildCalendarGrid(
+ [
+ { date: "2026-01-01", value: 1 },
+ { date: "2026-09-30", value: 1 },
+ ],
+ { weekStartDay: 0, hideGhostCells: true },
+ );
+ // Grid starts Sun Dec 28 2025 (col 0 holds Jan 1 = Q1 start, excluded).
+ // Apr 1 and Jul 1 open Q2 and Q3.
+ const cols = quarterBoundaryColumns(grid);
+ expect(cols).toEqual([13, 26]);
+ // Each boundary column contains the quarter's first day.
+ for (const col of cols) {
+ expect(col).toBeGreaterThan(0);
+ expect(col).toBeLessThan(grid.weeks);
+ }
+ });
+});
+
+describe("monthLabelColumns", () => {
+ it("emits one dedup label per month anchored to the column of the 1st", () => {
+ const grid = buildCalendarGrid(
+ [
+ { date: "2026-01-01", value: 1 },
+ { date: "2026-03-31", value: 1 },
+ ],
+ { weekStartDay: 0, hideGhostCells: true },
+ );
+ expect(monthLabelColumns(grid)).toEqual([
+ { col: 0, label: "Jan" },
+ { col: 5, label: "Feb" },
+ { col: 9, label: "Mar" },
+ ]);
+ });
+});
+
+describe("formatCalendarTooltipDate", () => {
+ // Brief ordinal table: 1→'1st', 2→'2nd', 3→'3rd', 11→'11th', 21→'21st',
+ // plus the teens-suffix exceptions (11/12/13 all take 'th').
+ it.each([
+ [1, "1st"],
+ [2, "2nd"],
+ [3, "3rd"],
+ [4, "4th"],
+ [11, "11th"],
+ [12, "12th"],
+ [13, "13th"],
+ [21, "21st"],
+ [22, "22nd"],
+ [23, "23rd"],
+ [31, "31st"],
+ ])('renders the %ith with the "%s" ordinal suffix', (day, expected) => {
+ // January 2026 so month/year are stable across the ordinal cases.
+ expect(formatCalendarTooltipDate(new Date(2026, 0, day))).toContain(`January ${expected} 2026`);
+ });
+
+ it('formats the full "Month Ordinal Year · Weekday" label', () => {
+ // Jan 20 2026 is a Tuesday (Jan 1 2026 is a Thursday).
+ expect(formatCalendarTooltipDate(new Date(2026, 0, 20))).toBe("January 20th 2026 · Tuesday");
+ });
+});
diff --git a/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/calendarMath.ts b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/calendarMath.ts
new file mode 100644
index 000000000..1a7b27827
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/calendarMath.ts
@@ -0,0 +1,340 @@
+// Calendar-grid math for the GitHub-contributions-style CalendarHeatmap.
+// Pure; no React/DOM/d3.
+//
+// LOCAL TIME, DELIBERATELY. A contribution calendar is about *calendar days* in
+// the viewer's own timezone, so every date is normalized to LOCAL midnight.
+// Note `new Date('2026-01-01')` parses as UTC midnight, which can land on the
+// previous local day west of UTC; we never rely on that. Date-only strings are
+// parsed field-wise via `new Date(y, m-1, d)` (local), and Date inputs are
+// cloned and floored with `setHours(0,0,0,0)`. Day arithmetic rounds elapsed
+// milliseconds to whole days so DST transitions (23h/25h days) can't drift a
+// cell into the wrong column.
+//
+// Window semantics are ported from bklit heatmap-utils.ts (resolveHeatmapWeekRange,
+// getHeatmapWeekStartAlignedToRange, resolveHeatmapDisplayRange) — logic, not code.
+
+const MS_PER_DAY = 24 * 60 * 60 * 1000;
+const DAYS_PER_WEEK = 7;
+
+/** Calendar-quarter start months (Jan, Apr, Jul, Oct). */
+const QUARTER_START_MONTHS = [0, 3, 6, 9] as const;
+
+/** Short month names, e.g. `Jan` — bklit month-label parity. */
+const MONTH_LABEL_FMT = new Intl.DateTimeFormat("en-US", { month: "short" });
+
+/** Long month name, e.g. `January` — tooltip header parity. */
+const TOOLTIP_MONTH_FMT = new Intl.DateTimeFormat("en-US", { month: "long" });
+
+/** Long weekday name, e.g. `Tuesday` — tooltip header parity. */
+const TOOLTIP_WEEKDAY_FMT = new Intl.DateTimeFormat("en-US", {
+ weekday: "long",
+});
+
+export interface CalendarCell {
+ col: number;
+ row: number;
+ date: Date;
+ value: number;
+ ghost: boolean;
+}
+
+export interface CalendarGrid {
+ cells: CalendarCell[];
+ weeks: number;
+ start: Date;
+ end: Date;
+}
+
+export type CalendarRange = "6m" | "12m" | [Date | string, Date | string];
+
+interface DisplayWindow {
+ start: Date | null;
+ end: Date | null;
+}
+
+// ── date helpers ────────────────────────────────────────────────────────────
+
+/** Normalize a Date or date-only string to LOCAL midnight (see module header). */
+function toLocalDate(value: Date | string): Date {
+ if (typeof value === "string") {
+ const match = /^(\d{4})-(\d{2})-(\d{2})/.exec(value);
+ if (match) {
+ return new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3]));
+ }
+ const parsed = new Date(value);
+ parsed.setHours(0, 0, 0, 0);
+ return parsed;
+ }
+ const clone = new Date(value);
+ clone.setHours(0, 0, 0, 0);
+ return clone;
+}
+
+/** Local midnight for the current day. */
+function localToday(): Date {
+ const today = new Date();
+ today.setHours(0, 0, 0, 0);
+ return today;
+}
+
+/** The `weekStartDay`-aligned start of `date`'s week (at or before it). */
+function startOfWeek(date: Date, weekStartDay: number): Date {
+ const aligned = new Date(date);
+ aligned.setHours(0, 0, 0, 0);
+ const offset = (aligned.getDay() - weekStartDay + DAYS_PER_WEEK) % DAYS_PER_WEEK;
+ aligned.setDate(aligned.getDate() - offset);
+ return aligned;
+}
+
+/** `date` shifted by `days`, re-floored to local midnight (DST-safe). */
+function addDays(date: Date, days: number): Date {
+ const shifted = new Date(date);
+ shifted.setDate(shifted.getDate() + days);
+ shifted.setHours(0, 0, 0, 0);
+ return shifted;
+}
+
+/** Whole calendar days between two local-midnight dates (rounded for DST). */
+function daysBetween(from: Date, to: Date): number {
+ return Math.round((to.getTime() - from.getTime()) / MS_PER_DAY);
+}
+
+/** Column index of the week containing `date`, relative to an aligned `start`. */
+function columnOf(date: Date, start: Date): number {
+ return Math.floor(daysBetween(start, date) / DAYS_PER_WEEK);
+}
+
+/** Inclusive count of week columns spanning [`start`, `end`]. */
+function weekCount(start: Date, end: Date, weekStartDay: number): number {
+ const endWeek = startOfWeek(end, weekStartDay);
+ return Math.round(daysBetween(start, endWeek) / DAYS_PER_WEEK) + 1;
+}
+
+/**
+ * First-of-month for the calendar-month window `months` back from `today`
+ * (bklit `getHeatmapCalendarRangeStart`). The 6-month window keeps bklit's quirk
+ * of offsetting by `months` (spanning ~7 calendar months) rather than `months-1`.
+ */
+function calendarRangeStart(today: Date, months: number): Date {
+ const monthOffset = months === 6 ? 6 : months - 1;
+ return new Date(today.getFullYear(), today.getMonth() - monthOffset, 1);
+}
+
+/** Local-midnight min/max of a date list (assumes non-empty). */
+function dateExtent(dates: Date[]): { min: Date; max: Date } {
+ let min = dates[0]!;
+ let max = dates[0]!;
+ for (const date of dates) {
+ if (date.getTime() < min.getTime()) min = date;
+ if (date.getTime() > max.getTime()) max = date;
+ }
+ return { min, max };
+}
+
+// ── range + grid ────────────────────────────────────────────────────────────
+
+/**
+ * Resolves the grid's aligned start column and end day for a range.
+ *
+ * - `'6m'` / `'12m'`: a calendar-month window ending on *today* (GitHub window
+ * inference); the datapoints don't move the window.
+ * - `[start, end]` tuple: an explicit window; the start is week-aligned.
+ * - `undefined`: the data's own [min, max] extent; the start is week-aligned.
+ *
+ * `start` is always aligned to `weekStartDay` (it opens column 0); `end` is the
+ * last in-window day and is left un-aligned.
+ */
+export function resolveWeekRange(
+ dates: Date[],
+ range: CalendarRange | undefined,
+ weekStartDay: number,
+): { start: Date; end: Date } {
+ if (Array.isArray(range)) {
+ const a = toLocalDate(range[0]);
+ const b = toLocalDate(range[1]);
+ const [low, high] = a.getTime() <= b.getTime() ? [a, b] : [b, a];
+ return { start: startOfWeek(low, weekStartDay), end: high };
+ }
+
+ if (range === "6m" || range === "12m") {
+ const today = localToday();
+ const months = range === "6m" ? 6 : 12;
+ const rangeStart = calendarRangeStart(today, months);
+ return { start: startOfWeek(rangeStart, weekStartDay), end: today };
+ }
+
+ const normalized = dates.map(toLocalDate);
+ if (normalized.length === 0) {
+ const today = localToday();
+ return { start: startOfWeek(today, weekStartDay), end: today };
+ }
+ const { min, max } = dateExtent(normalized);
+ return { start: startOfWeek(min, weekStartDay), end: max };
+}
+
+/**
+ * The display window used for ghost detection — days outside it are decorative
+ * ghosts (padding), not real inactive days (bklit `resolveHeatmapDisplayRange`).
+ * `'6m'`/`'12m'` clamp to [rangeStart, today]; a tuple clamps to its bounds; the
+ * data-extent case clamps to [min, max].
+ */
+function resolveDisplayWindow(
+ range: CalendarRange | undefined,
+ dates: Date[],
+ end: Date,
+): DisplayWindow {
+ if (Array.isArray(range)) {
+ const a = toLocalDate(range[0]);
+ const b = toLocalDate(range[1]);
+ return a.getTime() <= b.getTime() ? { start: a, end: b } : { start: b, end: a };
+ }
+ if (range === "6m" || range === "12m") {
+ const months = range === "6m" ? 6 : 12;
+ return { start: calendarRangeStart(end, months), end };
+ }
+ if (dates.length === 0) return { start: null, end: null };
+ const { min, max } = dateExtent(dates);
+ return { start: min, end: max };
+}
+
+/** Whether `date` falls outside the display window (a ghost/padding day). */
+function isGhost(date: Date, displayWindow: DisplayWindow): boolean {
+ const time = date.getTime();
+ if (displayWindow.end && time > displayWindow.end.getTime()) return true;
+ if (displayWindow.start && time < displayWindow.start.getTime()) return true;
+ return false;
+}
+
+/**
+ * Builds the full week-column grid for a contribution calendar.
+ *
+ * Columns run left→right (one per week); rows run top→bottom (one per weekday,
+ * rotated so row 0 is `weekStartDay`). Duplicate input dates SUM onto one cell;
+ * days with no datapoint get value 0. Days outside the display window are
+ * ghosts: omitted entirely when `hideGhostCells` is true, otherwise emitted with
+ * `ghost: true` and value 0. `weeks` counts columns either way.
+ */
+export function buildCalendarGrid(
+ data: ReadonlyArray<{ date: Date | string; value: number }>,
+ opts: {
+ range?: CalendarRange;
+ weekStartDay: number;
+ hideGhostCells: boolean;
+ },
+): CalendarGrid {
+ const { weekStartDay, hideGhostCells } = opts;
+ const normalizedDates = data.map((point) => toLocalDate(point.date));
+ const { start, end } = resolveWeekRange(normalizedDates, opts.range, weekStartDay);
+ const weeks = weekCount(start, end, weekStartDay);
+
+ const valueByDay = new Map<number, number>();
+ for (const point of data) {
+ const key = toLocalDate(point.date).getTime();
+ valueByDay.set(key, (valueByDay.get(key) ?? 0) + point.value);
+ }
+
+ const displayWindow = resolveDisplayWindow(opts.range, normalizedDates, end);
+
+ const cells: CalendarCell[] = [];
+ for (let col = 0; col < weeks; col++) {
+ for (let row = 0; row < DAYS_PER_WEEK; row++) {
+ const date = addDays(start, col * DAYS_PER_WEEK + row);
+ const ghost = isGhost(date, displayWindow);
+ if (ghost && hideGhostCells) continue;
+ cells.push({
+ col,
+ row,
+ date,
+ value: valueByDay.get(date.getTime()) ?? 0,
+ ghost,
+ });
+ }
+ }
+
+ return { cells, weeks, start, end };
+}
+
+// ── axis annotations ──────────────────────────────────────────────────────────
+
+/**
+ * Columns (excluding column 0) that open a new calendar quarter — the column
+ * containing a Jan/Apr/Jul/Oct 1 within the grid's [start, end] window. Used to
+ * draw quarter separators and anchor quarter labels.
+ */
+export function quarterBoundaryColumns(grid: CalendarGrid): number[] {
+ const columns = new Set<number>();
+ const startTime = grid.start.getTime();
+ const endTime = grid.end.getTime();
+
+ for (let year = grid.start.getFullYear(); year <= grid.end.getFullYear(); year++) {
+ for (const month of QUARTER_START_MONTHS) {
+ const quarterStart = new Date(year, month, 1);
+ const time = quarterStart.getTime();
+ if (time <= startTime || time > endTime) continue;
+ const col = columnOf(quarterStart, grid.start);
+ if (col > 0 && col < grid.weeks) columns.add(col);
+ }
+ }
+
+ return [...columns].sort((a, b) => a - b);
+}
+
+/**
+ * One short-month label per month, anchored to the column containing that
+ * month's 1st (bklit month-anchor parity). Months whose 1st falls outside the
+ * grid's [start, end] window are skipped; duplicate columns are deduped.
+ */
+export function monthLabelColumns(grid: CalendarGrid): Array<{ col: number; label: string }> {
+ const startTime = grid.start.getTime();
+ const endTime = grid.end.getTime();
+ const seenColumns = new Set<number>();
+ const labels: Array<{ col: number; label: string }> = [];
+
+ for (let year = grid.start.getFullYear(); year <= grid.end.getFullYear(); year++) {
+ for (let month = 0; month < 12; month++) {
+ const first = new Date(year, month, 1);
+ const time = first.getTime();
+ if (time < startTime || time > endTime) continue;
+ const col = columnOf(first, grid.start);
+ if (col < 0 || col >= grid.weeks || seenColumns.has(col)) continue;
+ seenColumns.add(col);
+ labels.push({ col, label: MONTH_LABEL_FMT.format(first) });
+ }
+ }
+
+ return labels.sort((a, b) => a.col - b.col);
+}
+
+// ── tooltip formatting ────────────────────────────────────────────────────────
+
+/**
+ * The English ordinal for a day-of-month: `1st`, `2nd`, `3rd`, `4th`… with the
+ * teens (`11th`, `12th`, `13th`) always taking `th` (ported from bklit
+ * `formatHeatmapOrdinalDay`).
+ */
+function ordinalDay(day: number): string {
+ if (day >= 11 && day <= 13) return `${day}th`;
+ switch (day % 10) {
+ case 1:
+ return `${day}st`;
+ case 2:
+ return `${day}nd`;
+ case 3:
+ return `${day}rd`;
+ default:
+ return `${day}th`;
+ }
+}
+
+/**
+ * The calendar tooltip's header line for a day, e.g.
+ * `"January 20th 2026 · Tuesday"` — long month, ordinal day, year, then the
+ * long weekday (bklit renders these as two lines; the shared portal tooltip has
+ * a single header slot, so they join with a middot).
+ */
+export function formatCalendarTooltipDate(date: Date): string {
+ const month = TOOLTIP_MONTH_FMT.format(date);
+ const day = ordinalDay(date.getDate());
+ const weekday = TOOLTIP_WEEKDAY_FMT.format(date);
+ return `${month} ${day} ${date.getFullYear()} · ${weekday}`;
+}
diff --git a/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/levelScale.test.ts b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/levelScale.test.ts
new file mode 100644
index 000000000..d7a979946
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/levelScale.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from "vitest";
+import { contributionLevel } from "./levelScale";
+
+describe("contributionLevel", () => {
+ // Brief: 0→0, 1→1, 2→2, 3→3, 4→4, 99→4 (default thresholds [1,2,3,4]).
+ it("maps default thresholds to GitHub levels 0..4", () => {
+ expect(contributionLevel(0)).toBe(0);
+ expect(contributionLevel(1)).toBe(1);
+ expect(contributionLevel(2)).toBe(2);
+ expect(contributionLevel(3)).toBe(3);
+ expect(contributionLevel(4)).toBe(4);
+ expect(contributionLevel(99)).toBe(4);
+ });
+
+ it("treats negatives and fractions below the first threshold as level 0", () => {
+ expect(contributionLevel(-5)).toBe(0);
+ expect(contributionLevel(0.5)).toBe(0);
+ });
+
+ // Brief: custom thresholds [10,20,30,40]: 15→1, 40→4.
+ it("honors custom thresholds", () => {
+ const thresholds = [10, 20, 30, 40] as const;
+ expect(contributionLevel(15, thresholds)).toBe(1);
+ expect(contributionLevel(40, thresholds)).toBe(4);
+ expect(contributionLevel(9, thresholds)).toBe(0);
+ expect(contributionLevel(29, thresholds)).toBe(2);
+ expect(contributionLevel(30, thresholds)).toBe(3);
+ expect(contributionLevel(1000, thresholds)).toBe(4);
+ });
+});
diff --git a/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/levelScale.ts b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/levelScale.ts
new file mode 100644
index 000000000..96d5ebf90
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/levelScale.ts
@@ -0,0 +1,24 @@
+// Value → GitHub-style contribution level (0..4). Pure; no React/DOM/d3.
+//
+// Ported from bklit's getHeatmapContributionLevel, generalized to configurable
+// thresholds. A value maps to the highest level whose threshold it meets or
+// exceeds; anything below the first threshold (including negatives) is level 0.
+
+/**
+ * Maps a contribution value to a legend level 0..4.
+ *
+ * `thresholds` is the ascending [t1,t2,t3,t4] cutoff for levels 1..4: a value
+ * `v` yields the largest `i` with `v >= t[i]`, or 0 if `v < t1`. Defaults to
+ * `[1,2,3,4]` — the GitHub scale where each of the first four counts is its own
+ * level and 4+ saturates.
+ */
+export function contributionLevel(
+ value: number,
+ thresholds: readonly [number, number, number, number] = [1, 2, 3, 4],
+): 0 | 1 | 2 | 3 | 4 {
+ if (value >= thresholds[3]) return 4;
+ if (value >= thresholds[2]) return 3;
+ if (value >= thresholds[1]) return 2;
+ if (value >= thresholds[0]) return 1;
+ return 0;
+}
diff --git a/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/separatorLayout.test.ts b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/separatorLayout.test.ts
new file mode 100644
index 000000000..dbb19104f
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/separatorLayout.test.ts
@@ -0,0 +1,106 @@
+import { describe, expect, it } from "vitest";
+import { buildCalendarGrid } from "./calendarMath";
+import { columnXOffsets, resolveCalendarSeparators, separatorColumns } from "./separatorLayout";
+
+describe("separatorColumns", () => {
+ const grid = buildCalendarGrid(
+ [
+ { date: "2026-01-01", value: 1 },
+ { date: "2026-09-30", value: 1 },
+ ],
+ { weekStartDay: 0, hideGhostCells: true },
+ );
+
+ it("places a separator every N columns (excludes col 0, stops before the end)", () => {
+ // grid.weeks === 40
+ expect(separatorColumns(grid, { groupBy: { every: 13 } })).toEqual([13, 26, 39]);
+ });
+
+ it("returns no separators when the interval meets or exceeds the width", () => {
+ expect(separatorColumns(grid, { groupBy: { every: 40 } })).toEqual([]);
+ expect(separatorColumns(grid, { groupBy: { every: 100 } })).toEqual([]);
+ expect(separatorColumns(grid, { groupBy: { every: 0 } })).toEqual([]);
+ });
+
+ it("groupBy 'quarter' delegates to calendar-quarter boundaries", () => {
+ expect(separatorColumns(grid, { groupBy: "quarter" })).toEqual([13, 26]);
+ });
+});
+
+describe("columnXOffsets", () => {
+ // Brief case: columnXOffsets(10, [4,8], 12) →
+ // cols 0-3 offset 0, cols 4-7 offset 12, cols 8-9 offset 24.
+ it("accumulates spacing for every separator at or before a column", () => {
+ expect(columnXOffsets(10, [4, 8], 12)).toEqual([0, 0, 0, 0, 12, 12, 12, 12, 24, 24]);
+ });
+
+ it("is all zeros when there are no separators", () => {
+ expect(columnXOffsets(4, [], 12)).toEqual([0, 0, 0, 0]);
+ });
+
+ it("is order-independent in the separator list", () => {
+ expect(columnXOffsets(10, [8, 4], 12)).toEqual(columnXOffsets(10, [4, 8], 12));
+ });
+});
+
+describe("resolveCalendarSeparators", () => {
+ // grid.weeks === 40, quarterBoundaryColumns === [13, 26].
+ const grid = buildCalendarGrid(
+ [
+ { date: "2026-01-01", value: 1 },
+ { date: "2026-09-30", value: 1 },
+ ],
+ { weekStartDay: 0, hideGhostCells: true },
+ );
+
+ it("maps 'quarter' to boundary columns, gutter offsets and consecutive Q labels", () => {
+ const resolved = resolveCalendarSeparators(grid, {
+ groupBy: "quarter",
+ spacing: 10,
+ showLabels: true,
+ });
+
+ expect(resolved.columns).toEqual([13, 26]);
+ expect(resolved.spacing).toBe(10);
+ // cols 0-12 offset 0, 13-25 offset 10, 26-39 offset 20.
+ expect(resolved.offsets).toHaveLength(40);
+ expect(resolved.offsets[12]).toBe(0);
+ expect(resolved.offsets[13]).toBe(10);
+ expect(resolved.offsets[26]).toBe(20);
+ expect(resolved.offsets[39]).toBe(20);
+ // The first group anchors at column 0; boundaries anchor the following
+ // quarters. Quarters advance consecutively across the window.
+ expect(resolved.labels).toEqual([
+ { col: 0, quarter: 1, year: 2026 },
+ { col: 13, quarter: 2, year: 2026 },
+ { col: 26, quarter: 3, year: 2026 },
+ ]);
+ });
+
+ it("omits labels when showLabels is not set", () => {
+ const resolved = resolveCalendarSeparators(grid, { groupBy: "quarter" });
+ expect(resolved.columns).toEqual([13, 26]);
+ expect(resolved.labels).toEqual([]);
+ });
+
+ it("maps '{ every: N }' to interval columns with zero-default spacing and no labels", () => {
+ const resolved = resolveCalendarSeparators(grid, {
+ groupBy: { every: 13 },
+ showLabels: true,
+ });
+ expect(resolved.columns).toEqual([13, 26, 39]);
+ expect(resolved.spacing).toBe(0);
+ expect(resolved.offsets).toEqual(new Array(40).fill(0));
+ // Quarter labels are a 'quarter'-mode feature; interval mode has none.
+ expect(resolved.labels).toEqual([]);
+ });
+
+ it("yields empty columns/labels and all-zero offsets when no separators apply", () => {
+ const resolved = resolveCalendarSeparators(grid, {
+ groupBy: { every: 40 },
+ });
+ expect(resolved.columns).toEqual([]);
+ expect(resolved.labels).toEqual([]);
+ expect(resolved.offsets).toEqual(new Array(40).fill(0));
+ });
+});
diff --git a/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/separatorLayout.ts b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/separatorLayout.ts
new file mode 100644
index 000000000..61cdbe11d
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/separatorLayout.ts
@@ -0,0 +1,125 @@
+// Column separator + gutter math for the CalendarHeatmap. Pure; no React/DOM/d3.
+//
+// Ported from bklit's separator layout (getHeatmapSeparatorColumnIndices,
+// getHeatmapColumnXOffset) — logic, not code. Separators split the week columns
+// into groups (a fixed interval or calendar quarters); each separator opens a
+// `spacing`-wide gutter, so columns to its right shift by that much.
+
+import { type CalendarGrid, quarterBoundaryColumns } from "./calendarMath";
+
+export interface SeparatorConfig {
+ /** Fixed interval (`{ every: N }`) or calendar-quarter boundaries. */
+ groupBy: { every: number } | "quarter";
+ /** Gutter width opened at each separator, in px (consumed by columnXOffsets). */
+ spacing?: number;
+ /** Emit calendar-quarter labels (only meaningful for `groupBy: 'quarter'`). */
+ showLabels?: boolean;
+}
+
+/** A quarter label anchored to the column that opens its group. */
+export interface CalendarSeparatorLabel {
+ /** Column the group opens at (`0` for the leading group). */
+ col: number;
+ /** Calendar quarter `1`–`4`. */
+ quarter: number;
+ /** Calendar year the quarter belongs to. */
+ year: number;
+}
+
+/** Everything the renderer needs to draw separators + shift the cell grid. */
+export interface ResolvedCalendarSeparators {
+ /** Columns a vertical separator is drawn at (see {@link separatorColumns}). */
+ columns: number[];
+ /** Per-column x-offset in px (see {@link columnXOffsets}); length `grid.weeks`. */
+ offsets: number[];
+ /** Resolved gutter width (defaults to 0). */
+ spacing: number;
+ /** Quarter labels, or `[]` when labels are off / not quarter mode. */
+ labels: CalendarSeparatorLabel[];
+}
+
+/**
+ * Column indices where a vertical separator is drawn.
+ *
+ * `'quarter'` delegates to the grid's calendar-quarter boundaries. `{ every: N }`
+ * places a separator before every Nth column (`N, 2N, …`), never at column 0 and
+ * never at/after the last column; a non-positive `N` or one that meets/exceeds
+ * the grid width yields none.
+ */
+export function separatorColumns(grid: CalendarGrid, cfg: SeparatorConfig): number[] {
+ if (cfg.groupBy === "quarter") {
+ return quarterBoundaryColumns(grid);
+ }
+
+ const { every } = cfg.groupBy;
+ if (every <= 0 || grid.weeks <= every) return [];
+
+ const columns: number[] = [];
+ for (let col = every; col < grid.weeks; col += every) {
+ columns.push(col);
+ }
+ return columns;
+}
+
+/**
+ * Per-column extra x-offset (px). Each column is shifted right by `spacing` for
+ * every separator at or before it, so the gutters accumulate left→right.
+ * Returns one offset per column, length `weeks`.
+ */
+export function columnXOffsets(weeks: number, separatorCols: number[], spacing: number): number[] {
+ const sorted = [...separatorCols].sort((a, b) => a - b);
+ const offsets: number[] = [];
+ for (let col = 0; col < weeks; col++) {
+ let crossed = 0;
+ for (const separator of sorted) {
+ if (separator <= col) crossed++;
+ else break;
+ }
+ offsets.push(crossed * spacing);
+ }
+ return offsets;
+}
+
+/**
+ * Quarter labels for a `'quarter'`-grouped grid. The leading group opens at
+ * column 0; each boundary column opens the next group. Because every in-window
+ * quarter start is a boundary, the groups are consecutive quarters — so labels
+ * advance one quarter per group from the leading group's quarter (the quarter
+ * containing the last day of column 0), rolling the year on the Q4→Q1 wrap.
+ */
+function quarterLabels(grid: CalendarGrid, boundaryCols: number[]): CalendarSeparatorLabel[] {
+ // The last day of column 0 (week-aligned start + 6 days); its quarter anchors
+ // the leading group even when the aligned start spills into the prior quarter.
+ const col0End = new Date(grid.start);
+ col0End.setDate(col0End.getDate() + 6);
+ const firstQuarter = Math.floor(col0End.getMonth() / 3) + 1; // 1..4
+ const firstYear = col0End.getFullYear();
+
+ const groupCols = [0, ...boundaryCols];
+ return groupCols.map((col, index) => {
+ // 0-based quarter count from `firstYear` Q1, advanced one per group.
+ const quarterOrdinal = firstQuarter - 1 + index;
+ return {
+ col,
+ quarter: (quarterOrdinal % 4) + 1,
+ year: firstYear + Math.floor(quarterOrdinal / 4),
+ };
+ });
+}
+
+/**
+ * Resolves a {@link SeparatorConfig} against the grid into the drawing inputs:
+ * the separator columns, the per-column gutter offsets, the resolved spacing,
+ * and (quarter mode + `showLabels` only) the quarter labels. `spacing` defaults
+ * to 0, matching a hairline separator that does not shift the grid.
+ */
+export function resolveCalendarSeparators(
+ grid: CalendarGrid,
+ cfg: SeparatorConfig,
+): ResolvedCalendarSeparators {
+ const spacing = cfg.spacing ?? 0;
+ const columns = separatorColumns(grid, cfg);
+ const offsets = columnXOffsets(grid.weeks, columns, spacing);
+ const labels = cfg.showLabels && cfg.groupBy === "quarter" ? quarterLabels(grid, columns) : [];
+ return { columns, offsets, spacing, labels };
+}
diff --git a/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/staggerSeed.test.ts b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/staggerSeed.test.ts
new file mode 100644
index 000000000..a2e8ae09b
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/staggerSeed.test.ts
@@ -0,0 +1,61 @@
+import { describe, expect, it } from "vitest";
+import { cellStaggerDelayMs, cellStaggerRatio } from "./staggerSeed";
+
+describe("cellStaggerRatio", () => {
+ // Brief: cellStaggerRatio(3,2) twice → identical (deterministic).
+ it("is deterministic for a given (col,row)", () => {
+ expect(cellStaggerRatio(3, 2)).toBe(cellStaggerRatio(3, 2));
+ expect(cellStaggerRatio(0, 0)).toBe(cellStaggerRatio(0, 0));
+ });
+
+ it("returns a value in [0,1)", () => {
+ for (let col = 0; col < 20; col++) {
+ for (let row = 0; row < 7; row++) {
+ const value = cellStaggerRatio(col, row);
+ expect(value).toBeGreaterThanOrEqual(0);
+ expect(value).toBeLessThan(1);
+ }
+ }
+ });
+
+ // Brief: values across a 7x20 grid spread over [0,1) with >50 distinct values.
+ it("spreads across a 7x20 grid with >50 distinct values", () => {
+ const seen = new Set<number>();
+ for (let col = 0; col < 20; col++) {
+ for (let row = 0; row < 7; row++) {
+ seen.add(cellStaggerRatio(col, row));
+ }
+ }
+ expect(seen.size).toBeGreaterThan(50);
+ });
+
+ it("varies with col and with row (seed combines both axes)", () => {
+ expect(cellStaggerRatio(3, 2)).not.toBe(cellStaggerRatio(4, 2));
+ expect(cellStaggerRatio(3, 2)).not.toBe(cellStaggerRatio(3, 3));
+ });
+});
+
+describe("cellStaggerDelayMs", () => {
+ it("scales the ratio by duration and the default 0.6 spread", () => {
+ const duration = 1000;
+ expect(cellStaggerDelayMs(3, 2, duration)).toBeCloseTo(cellStaggerRatio(3, 2) * duration * 0.6);
+ });
+
+ it("honors a custom spread", () => {
+ const duration = 1000;
+ expect(cellStaggerDelayMs(3, 2, duration, 0.3)).toBeCloseTo(
+ cellStaggerRatio(3, 2) * duration * 0.3,
+ );
+ });
+
+ it("stays within [0, duration*spread) across the grid", () => {
+ const duration = 1600;
+ for (let col = 0; col < 20; col++) {
+ for (let row = 0; row < 7; row++) {
+ const delay = cellStaggerDelayMs(col, row, duration);
+ expect(delay).toBeGreaterThanOrEqual(0);
+ expect(delay).toBeLessThan(duration * 0.6);
+ }
+ }
+ });
+});
diff --git a/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/staggerSeed.ts b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/staggerSeed.ts
new file mode 100644
index 000000000..70bea913f
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/staggerSeed.ts
@@ -0,0 +1,50 @@
+// Deterministic per-cell entrance stagger. Pure; no React/DOM/d3.
+//
+// The visual "scatter" of the contribution grid's fade-in is driven by a seeded
+// PRNG so it is stable across renders (streaming-safe) and reproducible in
+// tests. The seed combines column and row exactly as bklit's `heatmapCellSeed`
+// (`col*1009 + row*9176`) so the stagger pattern matches upstream. bklit ran a
+// Lehmer generator over that seed; here we use the classic Numerical-Recipes
+// linear congruential generator (`s*1664525 + 1013904223 mod 2^32`) specified
+// for this port. One LCG step per cell is enough for a well-spread [0,1) ratio.
+
+const LCG_MULTIPLIER = 1664525;
+const LCG_INCREMENT = 1013904223;
+const UINT32 = 2 ** 32;
+
+/** Default share of the entrance window spent on staggered per-cell delays. */
+const DEFAULT_STAGGER_SPREAD = 0.6;
+
+/** Combines grid coordinates into a seed (bklit `heatmapCellSeed` parity). */
+function cellSeed(col: number, row: number): number {
+ return col * 1009 + row * 9176;
+}
+
+/** One LCG step, kept in the unsigned 32-bit range. */
+function lcgNext(state: number): number {
+ return (state * LCG_MULTIPLIER + LCG_INCREMENT) % UINT32;
+}
+
+/**
+ * Deterministic pseudo-random ratio in `[0, 1)` for the cell at (`col`, `row`).
+ * Same inputs always yield the same ratio; distinct cells spread across the
+ * range so the entrance fade-in reads as an organic scatter, not a sweep.
+ */
+export function cellStaggerRatio(col: number, row: number): number {
+ return lcgNext(cellSeed(col, row)) / UINT32;
+}
+
+/**
+ * Per-cell entrance delay in milliseconds: `ratio * durationMs * spread`, so
+ * every cell begins fading within `durationMs * spread` of the animation start.
+ * `spread` (0..1, default 0.6) is the fraction of the window used for the
+ * scatter — smaller values tighten the cells toward a simultaneous reveal.
+ */
+export function cellStaggerDelayMs(
+ col: number,
+ row: number,
+ durationMs: number,
+ spread: number = DEFAULT_STAGGER_SPREAD,
+): number {
+ return cellStaggerRatio(col, row) * durationMs * spread;
+}
diff --git a/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/useDelayedHover.ts b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/useDelayedHover.ts
new file mode 100644
index 000000000..d6a084efa
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/parts/useDelayedHover.ts
@@ -0,0 +1,70 @@
+import { useEffect, useRef, useState } from "react";
+
+/**
+ * Show/hide-delayed passthrough for a hover payload, ported from bklit's
+ * `useDelayedTooltipData`. Returns `active` verbatim once shown, but debounces
+ * the transitions: the first appearance waits `show` ms, and after the pointer
+ * leaves (`active` → `null`) the last payload lingers for `hide` ms so a quick
+ * hop between adjacent cells doesn't flicker the tooltip.
+ *
+ * While already visible, position/value changes pass through immediately (only
+ * the show and hide edges are delayed). Not a pure module — timers + effect
+ * cleanup — so it carries no vitest (the bench smoke test drives the DOM).
+ */
+export function useDelayedHover<T>(
+ active: T | null,
+ delay?: { show?: number; hide?: number },
+): T | null {
+ const show = delay?.show ?? 0;
+ const hide = delay?.hide ?? 120;
+
+ const [display, setDisplay] = useState<T | null>(null);
+ const isShowingRef = useRef(false);
+ const showTimerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
+ const hideTimerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
+
+ useEffect(() => {
+ if (showTimerRef.current) {
+ clearTimeout(showTimerRef.current);
+ showTimerRef.current = undefined;
+ }
+ if (hideTimerRef.current) {
+ clearTimeout(hideTimerRef.current);
+ hideTimerRef.current = undefined;
+ }
+
+ if (active) {
+ // Already visible, or no show delay: update in place immediately.
+ if (isShowingRef.current || show === 0) {
+ isShowingRef.current = true;
+ setDisplay(active);
+ return;
+ }
+ showTimerRef.current = setTimeout(() => {
+ isShowingRef.current = true;
+ setDisplay(active);
+ }, show);
+ return;
+ }
+
+ if (hide === 0) {
+ isShowingRef.current = false;
+ setDisplay(null);
+ return;
+ }
+ hideTimerRef.current = setTimeout(() => {
+ isShowingRef.current = false;
+ setDisplay(null);
+ }, hide);
+ }, [active, show, hide]);
+
+ useEffect(
+ () => () => {
+ if (showTimerRef.current) clearTimeout(showTimerRef.current);
+ if (hideTimerRef.current) clearTimeout(hideTimerRef.current);
+ },
+ [],
+ );
+
+ return display;
+}
diff --git a/packages/react-ui/src/components/D3Charts/CalendarHeatmap/types.ts b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/types.ts
new file mode 100644
index 000000000..f79ae5b0b
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/CalendarHeatmap/types.ts
@@ -0,0 +1,180 @@
+export interface CalendarHeatmapDatum {
+ /**
+ * The calendar day this value falls on. Either a `Date` or a date-only string
+ * (`"2026-01-05"`); parsed in LOCAL time so a day never drifts across the
+ * timezone boundary. Multiple data points on the same day are SUMMED onto one
+ * cell.
+ */
+ date: string | Date;
+ /** The day's magnitude (e.g. commits, sales, events). Days with no datum are 0. */
+ value: number;
+}
+
+/** One of the five built-in tile patterns overlaid on a level's color. */
+export type CalendarLevelPattern = "diagonal" | "dots" | "cross" | "horizontal" | "vertical";
+
+/**
+ * Per-level style override (index 0..4, empty → most active). Any entry may be
+ * `null` / omitted to keep that level's default. `color` overrides the level's
+ * resolved fill; `pattern` overlays a hatch/dot tile on top of that fill;
+ * `patternColor` sets the pattern's stroke (defaults to the theme foreground).
+ */
+export interface CalendarLevelStyle {
+ /** Override this level's fill color. */
+ color?: string;
+ /** Overlay a tile pattern on the fill. */
+ pattern?: CalendarLevelPattern;
+ /** Pattern stroke/dot color. Default: the theme foreground token. */
+ patternColor?: string;
+}
+
+/**
+ * Column-separator config: split the week columns into groups by a fixed
+ * interval or by calendar quarter, drawing a vertical rule (and an optional
+ * gutter) at each boundary.
+ */
+export interface CalendarColumnSeparators {
+ /**
+ * Group by a fixed interval (`{ every: N }` → a rule before every Nth column)
+ * or by calendar quarter (`'quarter'` → a rule at each Jan/Apr/Jul/Oct start).
+ */
+ groupBy: { every: number } | "quarter";
+ /** Extra horizontal gap opened at each separator in px, shifting the columns
+ * apart. Default 0 (a hairline rule that does not move the grid). */
+ spacing?: number;
+ /** Separator line color. Default: the theme border token. */
+ stroke?: string;
+ /** Draw the separators dashed instead of solid. Default false. */
+ dashed?: boolean;
+ /** Draw a quarter label (e.g. `Q1 2026`) at each group start. Only meaningful
+ * for `groupBy: 'quarter'`. Default false. */
+ showLabels?: boolean;
+ /** Format a quarter label from its `1`–`4` quarter and calendar `year`.
+ * Default `` (q, year) => `Q${q} ${year}` ``. */
+ labelFormat?: (quarter: number, year: number) => string;
+}
+
+export interface CalendarHeatmapProps {
+ /** One `{ date, value }` per day. Sparse is fine — missing days render as level 0. */
+ data: CalendarHeatmapDatum[];
+ /**
+ * The window of days to show.
+ * - `"6m"` / `"12m"` — a calendar-month window ending on TODAY (GitHub-style;
+ * the data does not move the window).
+ * - `[start, end]` — an explicit range (Dates or date-only strings).
+ * - omitted — the data's own earliest→latest day.
+ * The first column is always aligned to `weekStartDay`.
+ */
+ range?: "6m" | "12m" | [Date | string, Date | string];
+ /**
+ * Ascending cutoffs `[t1, t2, t3, t4]` for contribution levels 1..4: a day's
+ * value maps to the highest level whose cutoff it meets, or level 0 below
+ * `t1`. Default `[1, 2, 3, 4]` — the GitHub scale where 4+ saturates.
+ */
+ thresholds?: [number, number, number, number];
+ /**
+ * Five explicit colors for levels 0..4 (empty → most active). Overrides the
+ * theme-derived ramp. When omitted, five stops are sampled from the theme's
+ * `defaultChartPalette` (or the built-in ramp), level 0 being the faint
+ * "empty" shade.
+ */
+ levelColors?: [string, string, string, string, string];
+ /**
+ * How the grid sizes to its container.
+ * - `"fluid"` (default) — square cells sized from the container WIDTH; the
+ * grid height hugs the seven rows (GitHub-style).
+ * - `"fill"` — cells stretch to fill BOTH the measured width and height.
+ */
+ layout?: "fluid" | "fill";
+ /**
+ * Fixed cell slot size in px, overriding the auto-size from `layout`. The
+ * drawn square is `binSize - gap`. Omit to let the container drive sizing.
+ */
+ binSize?: number;
+ /** Gap between cells in px. Default 3. */
+ gap?: number;
+ /**
+ * The weekday that opens each column (row 0). `0` = Sunday (GitHub default),
+ * `1` = Monday, … `6` = Saturday. Default 0.
+ */
+ weekStartDay?: 0 | 1 | 2 | 3 | 4 | 5 | 6;
+ /**
+ * Drop the decorative padding days that fall outside the window (the corners
+ * of the first/last week). Default true (GitHub-style). Set false to render
+ * them as level-0 cells.
+ */
+ hideGhostCells?: boolean;
+ /**
+ * Which weekday rows get a left-hand label. `"odd"` (default) labels every
+ * other row (Mon/Wed/Fri for a Sunday start); `"even"` labels the alternates;
+ * `"all"` labels every row.
+ */
+ weekdayTickFilter?: "all" | "odd" | "even";
+ /**
+ * Weekday label style. `"full"` (default) is the three-letter abbreviation
+ * (`"Mon"`); `"initial"` is the single narrow letter (`"M"`).
+ */
+ weekdayLabelFormat?: "full" | "initial";
+ /** Show the short month labels along the top. Default true. */
+ showMonthLabels?: boolean;
+ /**
+ * Per-row opacity multiplier applied as fill-opacity. A single number dims
+ * every row equally; an array is indexed by display row (row 0 = top). Rows
+ * without an entry stay fully opaque.
+ */
+ rowOpacity?: number | number[];
+ /**
+ * Play the entrance animation. Gates the entrance ONLY — any hover or
+ * data-update motion is independent of this flag, and printing always
+ * disables it.
+ * Default false (streaming-safe: marks mounted while data streams in don't
+ * replay staggered entrances).
+ */
+ isAnimationActive?: boolean;
+ /**
+ * Entrance window in ms — the span over which the per-cell stagger scatters
+ * the fade-ins. Only meaningful when `isAnimationActive`. Default 1600.
+ */
+ animationDuration?: number;
+ width?: number | string;
+ height?: number | string;
+ /**
+ * Ordered color ramp the level scale is sampled from (low → high); overrides
+ * the theme palette. Superseded by `levelColors` when that is also given.
+ */
+ customPalette?: string[];
+ /**
+ * Per-level style overrides, indexed by level 0..4 (empty → most active).
+ * Each entry may be `null` to keep that level's default. Use it to recolor a
+ * level or overlay one of the built-in tile patterns; a level's `color` here
+ * supersedes the corresponding `levelColors` / palette stop.
+ */
+ levelStyles?: Array<CalendarLevelStyle | null>;
+ /**
+ * Split the week columns into groups with vertical separators — by a fixed
+ * interval (`{ every: N }`) or by calendar quarter (`'quarter'`), optionally
+ * opening a gutter and labeling each quarter. Omit for an ungrouped grid.
+ */
+ columnSeparators?: CalendarColumnSeparators;
+ /**
+ * The Less→More scale legend under the grid: `"swatches"` (five discrete
+ * squares, default), `"gradient"` (a continuous color bar), or `"none"`.
+ */
+ legendVariant?: "swatches" | "gradient" | "none";
+ /** Override the legend's bracketing labels. Default `{ less: 'Less', more: 'More' }`. */
+ legendLabels?: { less?: string; more?: string };
+ /**
+ * Format the tooltip's contribution value from the day's summed `value` and
+ * its `Date` (e.g. add units or a currency symbol). Default: the raw value.
+ */
+ formatTooltipLabel?: (value: number, date: Date) => string;
+ /**
+ * Tooltip show/hide delays in ms. The hide grace period keeps the tooltip
+ * alive while the pointer crosses between adjacent cells. Default
+ * `{ show: 0, hide: 120 }`.
+ */
+ tooltipDelay?: { show?: number; hide?: number };
+ /** Click on a day: its `Date` and summed `value`. */
+ onClick?: (date: Date, value: number) => void;
+ className?: string;
+}
diff --git a/packages/react-ui/src/components/D3Charts/FunnelChart/FunnelChart.tsx b/packages/react-ui/src/components/D3Charts/FunnelChart/FunnelChart.tsx
new file mode 100644
index 000000000..38ba87483
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/FunnelChart/FunnelChart.tsx
@@ -0,0 +1,127 @@
+import { useEffectiveAnimation } from "../hooks";
+import { useFunnelChartOrchestrator } from "../hooks/cartesian/useFunnelChartOrchestrator";
+import { ChartShell } from "../shared/core/ChartShell";
+import { DefaultLegend } from "../shared/core/DefaultLegend/DefaultLegend";
+import { ChartTooltip } from "../shared/core/PortalTooltip/ChartTooltip";
+import { CHART_CLASS_PREFIX } from "../utils/constants";
+import { FunnelStages } from "./parts/FunnelStages";
+import type { FunnelChartData, FunnelChartProps } from "./types";
+
+const CLASS_PREFIX = `${CHART_CLASS_PREFIX}-funnel-chart`;
+// Gap between stage cells (px). Internal — a flat public `gap` prop can be
+// added later if a consumer needs it; no demand yet.
+const STAGE_GAP = 4;
+
+export function FunnelChart<T extends FunnelChartData>(props: FunnelChartProps<T>) {
+ const {
+ data,
+ categoryKey,
+ dataKey,
+ orientation = "horizontal",
+ edges = "curved",
+ layers = 3,
+ customPalette,
+ showLabels = true,
+ showValues = true,
+ showPercentage = true,
+ legend: showLegend = true,
+ isAnimationActive = false,
+ height,
+ width,
+ fitLegendInHeight,
+ className,
+ onClick,
+ } = props;
+
+ const orch = useFunnelChartOrchestrator({
+ data,
+ categoryKey,
+ dataKey,
+ // No funnelChartPalette token on react-ui's ChartColorPalette yet (same
+ // gap as heatmap/scatter) — the catch-all default palette is the token.
+ themePaletteName: "defaultChartPalette",
+ customPalette,
+ orientation,
+ gap: STAGE_GAP,
+ showLabels,
+ showLegend,
+ height,
+ width,
+ fitLegendInHeight,
+ });
+
+ const animate = useEffectiveAnimation(isAnimationActive);
+
+ const {
+ dimensions: { W, H, ringW, ringH, labelColWidth, labelAngle },
+ } = orch;
+
+ return (
+ <ChartShell
+ containerRef={orch.refs.containerRef}
+ classPrefix={CLASS_PREFIX}
+ className={className}
+ style={orch.style.containerStyle}
+ isEmpty={orch.isEmpty}
+ >
+ {() => (
+ <>
+ <svg
+ width={W}
+ height={H}
+ viewBox={`0 0 ${W} ${H}`}
+ style={{ overflow: "visible" }}
+ role="img"
+ aria-label="Funnel chart"
+ >
+ {W > 0 && H > 0 && (
+ <FunnelStages
+ stages={orch.data.visibleStages}
+ rows={orch.data.visibleRows}
+ orientation={orientation}
+ edges={edges}
+ layers={layers}
+ W={W}
+ H={H}
+ ringW={ringW}
+ ringH={ringH}
+ labelColWidth={labelColWidth}
+ labelAngle={labelAngle}
+ gap={STAGE_GAP}
+ showLabels={showLabels}
+ showValues={showValues}
+ showPercentage={showPercentage}
+ animate={animate}
+ staticRender={orch.isPrinting}
+ hoveredIndex={orch.hover.hoveredIndex}
+ onMouseMove={orch.hover.handleMouseMove}
+ onMouseLeave={orch.hover.handleMouseLeave}
+ onClick={onClick}
+ />
+ )}
+ </svg>
+
+ {showLegend && (
+ <DefaultLegend
+ ref={orch.refs.legendRef}
+ items={orch.data.legendItems}
+ containerWidth={orch.dimensions.containerWidth}
+ isExpanded={orch.legend.isLegendExpanded}
+ setIsExpanded={orch.legend.setIsLegendExpanded}
+ onItemClick={orch.data.toggleStage}
+ hiddenSeries={orch.data.hiddenStages}
+ />
+ )}
+
+ {orch.tooltip.tooltipPayload && orch.hover.mousePos && (
+ <ChartTooltip
+ label={orch.tooltip.tooltipPayload.label}
+ items={orch.tooltip.tooltipPayload.items}
+ viewportPosition={orch.hover.mousePos}
+ />
+ )}
+ </>
+ )}
+ </ChartShell>
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/FunnelChart/funnelChart.scss b/packages/react-ui/src/components/D3Charts/FunnelChart/funnelChart.scss
new file mode 100644
index 000000000..73067ca6b
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/FunnelChart/funnelChart.scss
@@ -0,0 +1,95 @@
+@use "../../../cssUtils" as cssUtils;
+@use "../shared/cartesian/chartBase" as base;
+@use "../prefix" as brand;
+
+@include base.centered-container("funnel-chart");
+
+// Channel-3 update transitions (ungated, like line/area/bar's d/height
+// tweens): as a stream extends the data, the geometry-max shifts and every
+// stage rescales — tween the path + dim instead of hard-snapping. Width/shape
+// encodes the value, so a print snapshot must catch the settled frame.
+.#{brand.$prefix}-funnel-chart-ring {
+ transition:
+ d 0.3s ease,
+ fill-opacity 0.2s ease;
+}
+
+// Spring-driven hover bloom. The spring writes the scale MAGNITUDE into
+// `--funnel-ring-scale`; the AXIS is chosen here by the orientation class, so
+// an orientation flip can't leave a stale scaleX/scaleY on an at-rest ring.
+// The scale pivots on the ring's own centre, and `transform` is deliberately
+// NOT in the channel-3 transition above (the spring owns it; a CSS transition
+// would fight the rAF loop). At rest the var is unset → scale 1 (identity).
+.#{brand.$prefix}-funnel-chart-ring--springy {
+ transform-box: fill-box;
+ transform-origin: center;
+}
+
+.#{brand.$prefix}-funnel-chart-ring--bloom-y {
+ transform: scaleY(var(--funnel-ring-scale, 1));
+}
+
+.#{brand.$prefix}-funnel-chart-ring--bloom-x {
+ transform: scaleX(var(--funnel-ring-scale, 1));
+}
+
+.#{brand.$prefix}-funnel-chart-stage {
+ transition: filter 0.2s ease;
+}
+
+@media print {
+ .#{brand.$prefix}-funnel-chart-ring,
+ .#{brand.$prefix}-funnel-chart-stage {
+ transition: none;
+ }
+}
+
+// In-stage text. Value + label use the chart label typography; the percentage
+// is the headline, set in an inverting pill (foreground fill, background text)
+// so it reads over the solid core.
+.#{brand.$prefix}-funnel-chart-value {
+ @include cssUtils.typography(label, small);
+ fill: cssUtils.$text-neutral-primary;
+ font-weight: 600;
+}
+
+.#{brand.$prefix}-funnel-chart-label {
+ @include base.svg-tick-label;
+}
+
+// The percentage pill inverts against the surface: a high-contrast ink fill
+// with surface-colored text. Both tokens flip with the theme, so the pill
+// stays legible in light and dark. (react-ui's $foreground/$background are
+// both light neutrals here — $text-neutral-primary is the actual ink.)
+.#{brand.$prefix}-funnel-chart-pct {
+ @include cssUtils.typography(label, extra-small);
+ fill: cssUtils.$background;
+ font-weight: 700;
+}
+
+.#{brand.$prefix}-funnel-chart-pct-pill {
+ fill: cssUtils.$text-neutral-primary;
+}
+
+// Entrances are decorative: gate the WHOLE rule (pre-state included) behind
+// reduced-motion so users who opt out get the natural static state immediately
+// — gating only the animation would strand stages at opacity: 0.
+@media (prefers-reduced-motion: no-preference) {
+ .#{brand.$prefix}-funnel-chart-stage--animated {
+ opacity: 0;
+ transform-box: fill-box;
+ transform-origin: center;
+ animation: #{brand.$prefix}-funnel-appear 0.5s ease-out forwards;
+ }
+}
+
+@keyframes #{brand.$prefix}-funnel-appear {
+ from {
+ opacity: 0;
+ transform: scale(0.85);
+ }
+ to {
+ opacity: 1;
+ transform: scale(1);
+ }
+}
diff --git a/packages/react-ui/src/components/D3Charts/FunnelChart/index.ts b/packages/react-ui/src/components/D3Charts/FunnelChart/index.ts
new file mode 100644
index 000000000..3c5fc9fc1
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/FunnelChart/index.ts
@@ -0,0 +1,2 @@
+export { FunnelChart } from "./FunnelChart";
+export type { FunnelChartData, FunnelChartProps, FunnelEdges, FunnelOrientation } from "./types";
diff --git a/packages/react-ui/src/components/D3Charts/FunnelChart/parts/FunnelStages.tsx b/packages/react-ui/src/components/D3Charts/FunnelChart/parts/FunnelStages.tsx
new file mode 100644
index 000000000..9e3614f32
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/FunnelChart/parts/FunnelStages.tsx
@@ -0,0 +1,388 @@
+import React, { useMemo, useRef } from "react";
+
+import type { FunnelStage } from "../../hooks/cartesian/useFunnelChartOrchestrator";
+import { useCanvasContextForLabelSize } from "../../hooks/core/useCanvasContextForLabelSize";
+import { useIndexedClickHandler } from "../../hooks/core/useIndexedClickHandler";
+import { useIsomorphicLayoutEffect, useSpring } from "../../shared/core/spring";
+import { CHART_CLASS_PREFIX } from "../../utils/constants";
+import { entranceProps } from "../../utils/entranceUtils";
+import {
+ MAX_LABEL_LINES,
+ parseLineHeight,
+ truncateToWidth,
+ wrapLabelLines,
+} from "../../utils/labelWrap";
+import { numberTickFormatter } from "../../utils/styleUtils";
+import {
+ type FunnelEdges,
+ type FunnelOrientation,
+ funnelHaloRamp,
+ hSegmentPath,
+ vSegmentPath,
+} from "./funnelGeometry";
+
+const CLASS = `${CHART_CLASS_PREFIX}-funnel-chart`;
+// Non-hovered stages dim to this fill-opacity multiplier.
+const DIM = 0.4;
+// Below this cell size (px on the stacking axis) the in-cell value/percentage
+// are dropped — they'd overflow. Labels live in their own axis band and are
+// always shown (angled/wrapped/truncated to fit).
+const MIN_TEXT_CELL = 44;
+// Gap between the funnel plot and its label band/column (matches the
+// orchestrator's reservation).
+const LABEL_GAP = 6;
+// Rough per-char width for the percentage pill background (no canvas measure).
+const PILL_CHAR_PX = 8;
+
+interface FunnelStagesProps<T> {
+ stages: FunnelStage[];
+ rows: T[];
+ orientation: FunnelOrientation;
+ edges: FunnelEdges;
+ layers: number;
+ /** Full plot extent (stages tile along the main axis across this). */
+ W: number;
+ H: number;
+ /** Ring (plot) area — the container minus the reserved label band/column.
+ * The reserved band is implicitly H−ringH (horizontal) / W−ringW (vertical). */
+ ringW: number;
+ ringH: number;
+ /** Width of the reserved vertical label column (for multi-line wrapping). */
+ labelColWidth: number;
+ /** Shared rotation (deg) for horizontal labels that don't fit; 0 = upright. */
+ labelAngle: number;
+ gap: number;
+ showLabels: boolean;
+ showValues: boolean;
+ showPercentage: boolean;
+ /** Play the entrance (pre-folded with ¬printing at the entry). */
+ animate: boolean;
+ /** Print/static: no hitbox, no entrance. */
+ staticRender: boolean;
+ hoveredIndex: number | null;
+ onMouseMove: (event: React.MouseEvent, index: number) => void;
+ onMouseLeave: () => void;
+ onClick?: (row: T, index: number) => void;
+}
+
+/**
+ * The funnel painter. Each stage is a `<g transform>` (positioning) wrapping an
+ * inner `<g>` of N concentric halo rings drawn OUTERMOST-FIRST (SVG order is
+ * z-order → the solid core paints last). The halo is built from `fill-opacity`
+ * per ring — NEVER `opacity` (the entrance keyframe's forwards fill holds
+ * `opacity:1` and would defeat an opacity dim). Stage labels live in a reserved
+ * axis band (bottom for horizontal, right column for vertical) and reuse the
+ * library's label machinery: angled when a horizontal label can't fit its cell
+ * (`useAutoAngleCalculation` in the orchestrator), multi-line wrapped when a
+ * vertical label is too long. Value/percentage stay in-cell. A transparent
+ * full-cell hitbox owns the pointer.
+ */
+export function FunnelStages<T>({
+ stages,
+ rows,
+ orientation,
+ edges,
+ layers,
+ W,
+ H,
+ ringW,
+ ringH,
+ labelColWidth,
+ labelAngle,
+ gap,
+ showLabels,
+ showValues,
+ showPercentage,
+ animate,
+ staticRender,
+ hoveredIndex,
+ onMouseMove,
+ onMouseLeave,
+ onClick,
+}: FunnelStagesProps<T>) {
+ const ctx = useCanvasContextForLabelSize();
+
+ const handleClick = useIndexedClickHandler(rows, onClick);
+
+ const horiz = orientation === "horizontal";
+ const straight = edges === "straight";
+ const n = stages.length;
+ const totalGap = gap * Math.max(0, n - 1);
+ // mainSize = each cell's size along the stacking axis; crossSize = the ring's
+ // span on the other axis (the plot area minus the reserved label band).
+ // n is ≥ 1 in practice (useSeriesVisibility keeps a stage visible, and empty
+ // data hits the placeholder), but guard the divide so n=0 can't yield ∞.
+ const mainSize = n > 0 ? Math.max(0, (horiz ? W - totalGap : H - totalGap) / n) : 0;
+ const crossSize = horiz ? ringH : ringW;
+ const rings = funnelHaloRamp(layers);
+ // In-cell value/pct need room on BOTH axes — crossSize collapses to 0 when
+ // the label column eats the whole width (extreme-narrow vertical funnel),
+ // which would paint the centered pill at a negative x.
+ const showInCell = mainSize >= MIN_TEXT_CELL && crossSize > 0;
+ const lineHeight = parseLineHeight(ctx.font);
+ const isAngled = horiz && labelAngle !== 0;
+
+ return (
+ <g>
+ {stages.map((stage, i) => {
+ const offset = (mainSize + gap) * i;
+ const transform = horiz ? `translate(${offset}, 0)` : `translate(0, ${offset})`;
+ const isHovered = hoveredIndex === i;
+ const dimFactor = hoveredIndex !== null && !isHovered ? DIM : 1;
+
+ const ringPaths = rings.map((r) =>
+ horiz
+ ? hSegmentPath(stage.norm, stage.normEnd, mainSize, crossSize, r.layerScale, straight)
+ : vSegmentPath(stage.norm, stage.normEnd, mainSize, crossSize, r.layerScale, straight),
+ );
+
+ // In-cell anchors (value top/left, percentage centered on the ring).
+ const valueX = horiz ? mainSize / 2 : 8;
+ const valueY = horiz ? 14 : mainSize / 2;
+ const pctX = horiz ? mainSize / 2 : crossSize / 2;
+ const pctY = horiz ? crossSize / 2 : mainSize / 2;
+ const pctText = `${Math.round(stage.pct)}%`;
+ const pillW = pctText.length * PILL_CHAR_PX + 16;
+
+ // Label anchor — at the start of the reserved band/column.
+ const labelX = horiz ? mainSize / 2 : crossSize + LABEL_GAP;
+ const labelY = horiz ? crossSize + LABEL_GAP : mainSize / 2;
+ const labelLines =
+ showLabels && !horiz
+ ? wrapLabelLines(
+ ctx,
+ stage.label,
+ Math.max(0, labelColWidth - LABEL_GAP * 2),
+ MAX_LABEL_LINES,
+ )
+ : null;
+ const horizLabel =
+ showLabels && horiz
+ ? isAngled
+ ? stage.label
+ : truncateToWidth(ctx, stage.label, mainSize)
+ : null;
+
+ const { className: stageAnimatedClass, animationDelay } = entranceProps(
+ animate,
+ `${CLASS}-stage--animated`,
+ i * 60,
+ );
+
+ return (
+ <g key={stage.key} transform={transform}>
+ <g
+ className={`${CLASS}-stage${stageAnimatedClass ? ` ${stageAnimatedClass}` : ""}`}
+ style={{
+ animationDelay,
+ filter: isHovered ? "brightness(1.08)" : undefined,
+ pointerEvents: "none",
+ }}
+ >
+ {ringPaths.map((d, ri) =>
+ // Print/static: inert paths, no springs (the bklit-style hover
+ // bloom is interaction feedback). Otherwise each ring owns a
+ // spring that scales it on the cross axis when its stage is
+ // hovered. ri is a stable position in the fixed-length ramp.
+ staticRender ? (
+ <path
+ key={ri}
+ className={`${CLASS}-ring`}
+ d={d}
+ fill={stage.color}
+ fillOpacity={rings[ri]!.ringOpacity * dimFactor}
+ />
+ ) : (
+ <FunnelRing
+ key={ri}
+ d={d}
+ color={stage.color}
+ fillOpacity={rings[ri]!.ringOpacity * dimFactor}
+ hovered={isHovered}
+ ringIndex={ri}
+ totalRings={rings.length}
+ horizontal={horiz}
+ />
+ ),
+ )}
+ </g>
+
+ {/* In-cell value + percentage (dropped when the cell is too small;
+ the tooltip still gives exact values). */}
+ {showInCell && (
+ <g
+ className={`${CLASS}-readouts`}
+ style={{
+ pointerEvents: "none",
+ opacity: dimFactor === DIM ? 0.55 : 1,
+ }}
+ >
+ {showValues && (
+ <text
+ className={`${CLASS}-value`}
+ x={valueX}
+ y={valueY}
+ textAnchor={horiz ? "middle" : "start"}
+ dominantBaseline={horiz ? "hanging" : "central"}
+ >
+ {numberTickFormatter(stage.value)}
+ </text>
+ )}
+ {showPercentage && (
+ <>
+ <rect
+ className={`${CLASS}-pct-pill`}
+ x={pctX - pillW / 2}
+ y={pctY - 10}
+ width={pillW}
+ height={20}
+ rx={10}
+ />
+ <text
+ className={`${CLASS}-pct`}
+ x={pctX}
+ y={pctY}
+ textAnchor="middle"
+ dominantBaseline="central"
+ >
+ {pctText}
+ </text>
+ </>
+ )}
+ </g>
+ )}
+
+ {/* Stage label in the reserved axis band — always shown. */}
+ {showLabels && (
+ <g
+ className={`${CLASS}-labels`}
+ style={{
+ pointerEvents: "none",
+ opacity: dimFactor === DIM ? 0.55 : 1,
+ }}
+ >
+ {horiz ? (
+ <text
+ className={`${CLASS}-label`}
+ x={labelX}
+ y={labelY}
+ textAnchor={isAngled ? "end" : "middle"}
+ dominantBaseline="hanging"
+ transform={isAngled ? `rotate(${labelAngle}, ${labelX}, ${labelY})` : undefined}
+ >
+ {horizLabel}
+ </text>
+ ) : (
+ <text
+ className={`${CLASS}-label`}
+ x={labelX}
+ y={labelY - ((labelLines!.length - 1) * lineHeight) / 2}
+ textAnchor="start"
+ dominantBaseline="central"
+ >
+ {labelLines!.map((line, li) => (
+ <tspan key={li} x={labelX} dy={li === 0 ? 0 : lineHeight}>
+ {line}
+ </tspan>
+ ))}
+ </text>
+ )}
+ </g>
+ )}
+
+ {/* Transparent hitbox: owns the pointer for the whole cell
+ (including the label band). fill MUST be a painted region
+ (`transparent`, not `none`) or hover dies under the default
+ `visiblePainted`. Dropped in print. */}
+ {!staticRender && (
+ <rect
+ x={0}
+ y={0}
+ width={horiz ? mainSize : W}
+ height={horiz ? H : mainSize}
+ fill="transparent"
+ style={{
+ pointerEvents: "all",
+ cursor: onClick ? "pointer" : undefined,
+ }}
+ onMouseMove={(e) => onMouseMove(e, i)}
+ onMouseLeave={onMouseLeave}
+ onClick={() => handleClick(i)}
+ />
+ )}
+ </g>
+ );
+ })}
+ </g>
+ );
+}
+
+interface FunnelRingProps {
+ d: string;
+ color: string;
+ fillOpacity: number;
+ hovered: boolean;
+ ringIndex: number;
+ totalRings: number;
+ horizontal: boolean;
+}
+
+/**
+ * One halo ring with bklit's hover bloom, driven by the vanilla spring instead
+ * of motion. The inner rings scale up more (up to +12%) and SOFTER (lower
+ * stiffness), the outer halo barely moves — so the solid core swells outward
+ * through the halo on hover; a lone ring (layers=1) blooms as the core.
+ *
+ * The spring drives a CSS variable (the scale MAGNITUDE) off the render path;
+ * the AXIS lives in CSS, picked by the orientation class (--bloom-y scales
+ * height, --bloom-x scales width). Keeping the axis in CSS — rather than
+ * baking scaleX/scaleY into the written string — means an orientation flip
+ * (which React applies via the class) can never strand a stale axis on an
+ * at-rest ring. The origin is the ring's own centre (transform-box: fill-box).
+ * Rest IS home (scale 1), so there's no seeded jump — the first hover is the
+ * bloom. Mounted only off the print path (FunnelStages branches on static).
+ */
+function FunnelRing({
+ d,
+ color,
+ fillOpacity,
+ hovered,
+ ringIndex,
+ totalRings,
+ horizontal,
+}: FunnelRingProps) {
+ const ref = useRef<SVGPathElement>(null);
+ // Inner rings bloom more (the solid core most); a lone ring is the core. The
+ // 0.12 headroom matches the 0.44 cross-axis factor (segments span 0.88 of
+ // the cross axis), so the bloom never clips the cell.
+ const extraScale = totalRings <= 1 ? 1.12 : 1 + (ringIndex / (totalRings - 1)) * 0.12;
+ const config = useMemo(
+ () => ({
+ stiffness: Math.max(80, 300 - ringIndex * 60),
+ damping: Math.max(6, 24 - ringIndex * 3),
+ }),
+ [ringIndex],
+ );
+ const spring = useSpring(
+ config,
+ (s) => {
+ ref.current?.style.setProperty("--funnel-ring-scale", String(s));
+ },
+ 1,
+ );
+ useIsomorphicLayoutEffect(() => {
+ spring.set(hovered ? extraScale : 1);
+ }, [hovered, extraScale]);
+
+ return (
+ <path
+ ref={ref}
+ className={`${CLASS}-ring ${CLASS}-ring--springy ${
+ horizontal ? `${CLASS}-ring--bloom-y` : `${CLASS}-ring--bloom-x`
+ }`}
+ d={d}
+ fill={color}
+ fillOpacity={fillOpacity}
+ />
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/FunnelChart/parts/funnelGeometry.test.ts b/packages/react-ui/src/components/D3Charts/FunnelChart/parts/funnelGeometry.test.ts
new file mode 100644
index 000000000..1390b944e
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/FunnelChart/parts/funnelGeometry.test.ts
@@ -0,0 +1,92 @@
+import { describe, expect, it } from "vitest";
+import { funnelHaloRamp, funnelPercentage, hSegmentPath, vSegmentPath } from "./funnelGeometry";
+
+describe("funnelHaloRamp", () => {
+ it("default 3 layers: outermost-first, the bklit opacity ramp", () => {
+ const rings = funnelHaloRamp(3);
+ expect(rings.map((r) => r.ringOpacity)).toEqual([
+ 0.18,
+ 0.18 + (1 / 2) * 0.65, // 0.505
+ 0.18 + (2 / 2) * 0.65, // 0.83
+ ]);
+ // Outermost (index 0) is the largest scale; the core (last) is full size.
+ expect(rings[0]!.layerScale).toBe(1);
+ expect(rings[2]!.layerScale).toBeCloseTo(1 - (2 / 3) * 0.35);
+ // Core is the most opaque.
+ expect(rings[2]!.ringOpacity).toBeGreaterThan(rings[0]!.ringOpacity);
+ });
+
+ it("single layer is fully opaque (not the raw 0.18 floor)", () => {
+ const rings = funnelHaloRamp(1);
+ expect(rings).toHaveLength(1);
+ expect(rings[0]!.ringOpacity).toBe(1);
+ expect(rings[0]!.layerScale).toBe(1);
+ });
+
+ it("clamps and rounds the layer count to >= 1", () => {
+ expect(funnelHaloRamp(0)).toHaveLength(1);
+ expect(funnelHaloRamp(-5)).toHaveLength(1);
+ expect(funnelHaloRamp(2.6)).toHaveLength(3);
+ });
+});
+
+describe("funnelPercentage (relative to first stage)", () => {
+ it("first stage is always 100%", () => {
+ expect(funnelPercentage(1000, 1000)).toBe(100);
+ });
+
+ it("downstream stages are retention vs the first", () => {
+ expect(funnelPercentage(250, 1000)).toBe(25);
+ });
+
+ it("non-monotonic data can exceed 100% (informative, not clamped)", () => {
+ expect(funnelPercentage(1200, 1000)).toBe(120);
+ });
+
+ it("guards a zero / non-finite reference", () => {
+ expect(funnelPercentage(50, 0)).toBe(0);
+ expect(funnelPercentage(50, Number.NaN)).toBe(0);
+ });
+});
+
+describe("segment paths", () => {
+ it("horizontal curved path tapers between the two norms", () => {
+ // normStart 1 (full), normEnd 0.5, segW 100, H 200, layerScale 1.
+ // my = 100; h0 = 1*200*0.44 = 88; h1 = 0.5*200*0.44 = 44.
+ const d = hSegmentPath(1, 0.5, 100, 200, 1, false);
+ expect(d.startsWith("M 0 12")).toBe(true); // my - h0 = 100 - 88 = 12
+ expect(d).toContain("C"); // curved → has bezier commands
+ expect(d.endsWith("Z")).toBe(true);
+ });
+
+ it("horizontal straight path uses only line commands", () => {
+ const d = hSegmentPath(1, 0.5, 100, 200, 1, true);
+ expect(d).not.toContain("C");
+ // Top-right corner: x=segW=100, y=my-h1 = 100-44 = 56.
+ expect(d).toContain("L 100 56");
+ expect(d.endsWith("Z")).toBe(true);
+ });
+
+ it("vertical path swaps the taper onto the cross axis", () => {
+ // normStart 1, normEnd 0.5, segH 100, W 200, layerScale 1.
+ // mx = 100; w0 = 88; w1 = 44.
+ const d = vSegmentPath(1, 0.5, 100, 200, 1, false);
+ expect(d.startsWith("M 12 0")).toBe(true); // mx - w0 = 12, top edge y=0
+ expect(d).toContain("C");
+ expect(d.endsWith("Z")).toBe(true);
+ });
+
+ it("a degenerate (zero) norm collapses to a flat line, never NaN", () => {
+ const d = hSegmentPath(0, 0, 100, 200, 1, false);
+ expect(d).not.toContain("NaN");
+ expect(d).toContain("M 0 100"); // both half-heights 0 → centered
+ });
+
+ it("layerScale shrinks the cross-axis extent", () => {
+ const full = hSegmentPath(1, 1, 100, 200, 1, true);
+ const inner = hSegmentPath(1, 1, 100, 200, 0.5, true);
+ // full: h0 = 88 → top at 12; inner: h0 = 44 → top at 56 (closer to center)
+ expect(full).toContain("M 0 12");
+ expect(inner).toContain("M 0 56");
+ });
+});
diff --git a/packages/react-ui/src/components/D3Charts/FunnelChart/parts/funnelGeometry.ts b/packages/react-ui/src/components/D3Charts/FunnelChart/parts/funnelGeometry.ts
new file mode 100644
index 000000000..e74110127
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/FunnelChart/parts/funnelGeometry.ts
@@ -0,0 +1,99 @@
+// Pure path/ramp math for the funnel's multi-ring halo. Kept out of the
+// component so the trapezoid geometry, the layer ramp, and the percentage
+// semantic are unit-testable in isolation.
+
+export type FunnelOrientation = "horizontal" | "vertical";
+export type FunnelEdges = "curved" | "straight";
+
+// Cross-axis half-extent factor: the widest ring spans 0.88 of the cross-axis
+// (2 × 0.44), leaving a 12% margin — the headroom a hover scale-pop would use.
+const HALF_EXTENT = 0.44;
+// Bezier control factor: > 0.5 pushes the curve's inflection past center for a
+// fuller "belly" on the tapered edge.
+const BEZIER_CONTROL = 0.55;
+
+/**
+ * One ring's SVG path for a HORIZONTAL funnel cell (local coords, origin at the
+ * cell's top-left; the cell tapers from `normStart` on the left edge to
+ * `normEnd` on the right). `layerScale` shrinks the ring toward the core.
+ */
+export function hSegmentPath(
+ normStart: number,
+ normEnd: number,
+ segW: number,
+ H: number,
+ layerScale: number,
+ straight = false,
+): string {
+ const my = H / 2;
+ const h0 = normStart * H * HALF_EXTENT * layerScale;
+ const h1 = normEnd * H * HALF_EXTENT * layerScale;
+
+ if (straight) {
+ return `M 0 ${my - h0} L ${segW} ${my - h1} L ${segW} ${my + h1} L 0 ${my + h0} Z`;
+ }
+
+ const cx = segW * BEZIER_CONTROL;
+ const top = `M 0 ${my - h0} C ${cx} ${my - h0}, ${segW - cx} ${my - h1}, ${segW} ${my - h1}`;
+ const bot = `L ${segW} ${my + h1} C ${segW - cx} ${my + h1}, ${cx} ${my + h0}, 0 ${my + h0}`;
+ return `${top} ${bot} Z`;
+}
+
+/**
+ * One ring's SVG path for a VERTICAL funnel cell (local coords, origin at the
+ * cell's top-left; the cell tapers from `normStart` on the top edge to
+ * `normEnd` on the bottom).
+ */
+export function vSegmentPath(
+ normStart: number,
+ normEnd: number,
+ segH: number,
+ W: number,
+ layerScale: number,
+ straight = false,
+): string {
+ const mx = W / 2;
+ const w0 = normStart * W * HALF_EXTENT * layerScale;
+ const w1 = normEnd * W * HALF_EXTENT * layerScale;
+
+ if (straight) {
+ return `M ${mx - w0} 0 L ${mx - w1} ${segH} L ${mx + w1} ${segH} L ${mx + w0} 0 Z`;
+ }
+
+ const cy = segH * BEZIER_CONTROL;
+ const left = `M ${mx - w0} 0 C ${mx - w0} ${cy}, ${mx - w1} ${segH - cy}, ${mx - w1} ${segH}`;
+ const right = `L ${mx + w1} ${segH} C ${mx + w1} ${segH - cy}, ${mx + w0} ${cy}, ${mx + w0} 0`;
+ return `${left} ${right} Z`;
+}
+
+export interface FunnelRing {
+ /** Multiplier on the cross-axis extent; outer rings are larger (scale 1). */
+ layerScale: number;
+ /** The ring's own opacity in the halo ramp, before any hover dim. */
+ ringOpacity: number;
+}
+
+/**
+ * The halo ramp: `layers` concentric rings, OUTERMOST FIRST (so the solid core
+ * paints last — SVG render order is z-order). Outer rings are larger and
+ * fainter; the innermost (last) ring is the solid core. A single ring
+ * (`layers === 1`) is fully opaque — the raw ramp would otherwise leave a lone
+ * core at 0.18, near-invisible.
+ */
+export function funnelHaloRamp(layers: number): FunnelRing[] {
+ const L = Math.max(1, Math.round(layers));
+ return Array.from({ length: L }, (_, l) => ({
+ layerScale: 1 - (l / L) * 0.35,
+ ringOpacity: L === 1 ? 1 : 0.18 + (l / (L - 1)) * 0.65,
+ }));
+}
+
+/**
+ * Funnel percentage: relative to the FIRST stage (stage 0 = 100% = retention),
+ * NOT share-of-total. `reference` is the first stage's value. Can exceed 100%
+ * or go negative for non-monotonic data — that is informative, not a bug.
+ */
+export function funnelPercentage(value: number, reference: number): number {
+ if (!Number.isFinite(reference) || reference === 0) return 0;
+ return (value / reference) * 100;
+}
diff --git a/packages/react-ui/src/components/D3Charts/FunnelChart/types.ts b/packages/react-ui/src/components/D3Charts/FunnelChart/types.ts
new file mode 100644
index 000000000..876360528
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/FunnelChart/types.ts
@@ -0,0 +1,68 @@
+import type { ChartData } from "../types";
+import type { FunnelEdges, FunnelOrientation } from "./parts/funnelGeometry";
+
+export type { FunnelEdges, FunnelOrientation } from "./parts/funnelGeometry";
+export type FunnelChartData = ChartData;
+
+export interface FunnelChartProps<T extends FunnelChartData> {
+ /**
+ * Row-shaped data, same contract as Pie/Radial: one row per funnel stage,
+ * in order from the top (widest) stage to the bottom. `categoryKey` names
+ * the stage-label field; `dataKey` names the numeric value field.
+ */
+ data: T;
+ categoryKey: keyof T[number];
+ dataKey: keyof T[number];
+ /**
+ * Funnel flow direction. `'horizontal'` stacks stages left→right (each a
+ * full-height column); `'vertical'` stacks them top→bottom. Default
+ * `'horizontal'`.
+ */
+ orientation?: FunnelOrientation;
+ /**
+ * Stage-to-stage edge shape. `'curved'` tapers smoothly between stages with
+ * a bezier belly; `'straight'` uses flat trapezoid sides. Default
+ * `'curved'`.
+ */
+ edges?: FunnelEdges;
+ /**
+ * Number of concentric halo rings drawn per stage — the funnel's layered
+ * glow. Each outer ring is larger and fainter; the core is solid. `1`
+ * disables the halo (a single solid shape). Clamped to ≥ 1. Default `3`.
+ */
+ layers?: number;
+ /**
+ * Ordered colors for the stages, top→bottom; overrides the theme palette.
+ * One hue per stage (the halo is built from opacity, not extra hues).
+ */
+ customPalette?: string[];
+ /** Show each stage's name. Default true. */
+ showLabels?: boolean;
+ /** Show each stage's raw value. Default true. */
+ showValues?: boolean;
+ /**
+ * Show each stage's percentage RELATIVE TO THE FIRST STAGE (the first stage
+ * is 100%) — i.e. funnel retention, NOT share of total. Default true.
+ */
+ showPercentage?: boolean;
+ /** Show the legend (one swatch per stage); clicking toggles a stage. Default true. */
+ legend?: boolean;
+ /**
+ * Play the entrance animation. Gates the entrance ONLY — any hover or
+ * data-update motion is independent of this flag, and printing always
+ * disables it.
+ * Default false (streaming-safe: marks mounted while data streams in don't
+ * replay staggered entrances).
+ */
+ isAnimationActive?: boolean;
+ height?: number | string;
+ width?: number | string;
+ fitLegendInHeight?: boolean;
+ className?: string;
+ /**
+ * Click on a stage: the original data row and its index among the currently
+ * VISIBLE stages (top = 0; the index shifts if stages are hidden via the
+ * legend). The row is always the original data row.
+ */
+ onClick?: (row: T[number], index: number) => void;
+}
diff --git a/packages/react-ui/src/components/D3Charts/HeatmapChart/HeatmapChart.tsx b/packages/react-ui/src/components/D3Charts/HeatmapChart/HeatmapChart.tsx
new file mode 100644
index 000000000..648bc373c
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/HeatmapChart/HeatmapChart.tsx
@@ -0,0 +1,162 @@
+import { useEffectiveAnimation } from "../hooks";
+import { useHeatmapChartOrchestrator } from "../hooks/cartesian/useHeatmapChartOrchestrator";
+import { XAxis } from "../shared/cartesian/axes/XAxis";
+import { ChartShell } from "../shared/core/ChartShell";
+import { DefaultLegend } from "../shared/core/DefaultLegend/DefaultLegend";
+import { ChartTooltip } from "../shared/core/PortalTooltip/ChartTooltip";
+import { CHART_CLASS_PREFIX } from "../utils/constants";
+import { HeatmapCells } from "./parts/HeatmapCells";
+import { HeatmapColorScale } from "./parts/HeatmapColorScale";
+import { HeatmapYAxis } from "./parts/HeatmapYAxis";
+import type { HeatmapChartData, HeatmapChartProps } from "./types";
+
+const CLASS_PREFIX = `${CHART_CLASS_PREFIX}-heatmap-chart`;
+
+export function HeatmapChart<T extends HeatmapChartData>(props: HeatmapChartProps<T>) {
+ const {
+ data,
+ categoryKey,
+ customPalette,
+ rampMode = "sequential",
+ legend: showLegend = true,
+ showColorScale = true,
+ showCellLabels = false,
+ showYAxis = true,
+ isAnimationActive = false,
+ cellGap = 2,
+ cellRadius = 2,
+ height,
+ width,
+ fitLegendInHeight,
+ className,
+ onClick,
+ } = props;
+
+ const orch = useHeatmapChartOrchestrator({
+ data,
+ categoryKey,
+ // No heatmap token exists on react-ui's ChartColorPalette yet (same
+ // situation as scatter) — the catch-all palette is the per-type token.
+ themePaletteName: "defaultChartPalette",
+ customPalette,
+ rampMode,
+ showLegend,
+ showColorScale,
+ showYAxis,
+ height,
+ width,
+ fitLegendInHeight,
+ });
+
+ const animate = useEffectiveAnimation(isAnimationActive);
+
+ const {
+ dimensions: {
+ effectiveYAxisWidth,
+ chartAreaWidth,
+ chartInnerHeight,
+ totalSvgWidth,
+ totalSvgHeight,
+ xAxisHeight,
+ CHART_MARGIN_TOP: marginTop,
+ },
+ scales: { xScale, yScale, colorScale },
+ } = orch;
+
+ return (
+ <ChartShell
+ containerRef={orch.refs.containerRef}
+ classPrefix={CLASS_PREFIX}
+ className={className}
+ style={orch.style.containerStyle}
+ isEmpty={orch.isEmpty}
+ >
+ {() => (
+ <>
+ <svg
+ width={totalSvgWidth}
+ height={totalSvgHeight}
+ style={{ overflow: "visible" }}
+ role="img"
+ aria-label="Heatmap chart"
+ >
+ {showYAxis && (
+ <g transform={`translate(0, ${marginTop})`}>
+ <HeatmapYAxis
+ scale={yScale}
+ width={effectiveYAxisWidth}
+ classPrefix={CLASS_PREFIX}
+ />
+ </g>
+ )}
+
+ <g
+ transform={`translate(${effectiveYAxisWidth}, ${marginTop})`}
+ onMouseLeave={orch.hover.handleMouseLeave}
+ >
+ <rect width={chartAreaWidth} height={chartInnerHeight} fill="transparent" />
+
+ <HeatmapCells
+ data={data}
+ catKey={orch.data.catKey}
+ columnKeys={orch.data.columnKeys}
+ visibleRowKeys={orch.data.visibleRowKeys}
+ xScale={xScale}
+ yScale={yScale}
+ colorScale={colorScale}
+ cellGap={cellGap}
+ cellRadius={cellRadius}
+ showCellLabels={showCellLabels}
+ animate={animate}
+ onCellMouseMove={orch.hover.handleCellMouseMove}
+ onCellMouseLeave={orch.hover.handleMouseLeave}
+ onClick={onClick}
+ />
+ </g>
+
+ <g transform={`translate(${effectiveYAxisWidth}, ${chartInnerHeight + marginTop})`}>
+ <XAxis
+ scale={xScale}
+ tickVariant="singleLine"
+ labelHeight={xAxisHeight}
+ labelInterval={orch.dimensions.labelInterval}
+ classPrefix={CLASS_PREFIX}
+ />
+ </g>
+ </svg>
+
+ {showColorScale && (
+ <HeatmapColorScale
+ ref={orch.refs.colorScaleRef}
+ buckets={orch.colorScaleLegend.buckets}
+ domainMin={orch.colorScaleLegend.domainMin}
+ domainMax={orch.colorScaleLegend.domainMax}
+ diverging={rampMode === "diverging"}
+ classPrefix={CLASS_PREFIX}
+ />
+ )}
+
+ {showLegend && (
+ <DefaultLegend
+ ref={orch.refs.legendRef}
+ items={orch.legend.legendItems}
+ containerWidth={orch.dimensions.containerWidth}
+ isExpanded={orch.legend.isLegendExpanded}
+ setIsExpanded={orch.legend.setIsLegendExpanded}
+ onItemClick={orch.data.toggleRow}
+ hiddenSeries={orch.data.hiddenRows}
+ />
+ )}
+
+ {orch.tooltip.tooltipPayload && orch.hover.mousePos && (
+ <ChartTooltip
+ label={orch.tooltip.tooltipPayload.label}
+ items={orch.tooltip.tooltipPayload.items}
+ viewportPosition={orch.hover.mousePos}
+ />
+ )}
+ </>
+ )}
+ </ChartShell>
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/HeatmapChart/heatmapChart.scss b/packages/react-ui/src/components/D3Charts/HeatmapChart/heatmapChart.scss
new file mode 100644
index 000000000..68065c6e3
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/HeatmapChart/heatmapChart.scss
@@ -0,0 +1,108 @@
+@use "../../../cssUtils" as cssUtils;
+@use "../shared/cartesian/chartBase" as base;
+@use "../prefix" as brand;
+
+@include base.centered-container("heatmap-chart");
+
+.#{brand.$prefix}-heatmap-chart-x-tick {
+ @include base.svg-tick-label;
+}
+
+.#{brand.$prefix}-heatmap-chart-y-tick {
+ @include base.svg-tick-label;
+}
+
+// Channel-3 update transition (ungated, like line/area/bar's d/height
+// tweens): streamed chunks shift the quantize domain and recolor settled
+// cells — tween the recolor instead of hard-snapping the whole grid every
+// chunk. Also smooths recolors from legend toggles changing the extent.
+// The label shares the transition so its auto-contrast fill crossfades WITH
+// the cell underneath instead of snapping against a mid-tween background.
+.#{brand.$prefix}-heatmap-chart-cell,
+.#{brand.$prefix}-heatmap-chart-cell-label {
+ transition: fill 0.2s ease;
+}
+
+// Color IS the value encoding here — a print snapshot taken mid-tween (e.g.
+// while a stream recolors the grid) would print wrong values. Snap in print.
+@media print {
+ .#{brand.$prefix}-heatmap-chart-cell,
+ .#{brand.$prefix}-heatmap-chart-cell-label {
+ transition: none;
+ }
+}
+
+.#{brand.$prefix}-heatmap-chart-cell:hover {
+ stroke: cssUtils.$foreground;
+ stroke-width: 1.5;
+}
+
+// In-cell value labels: never a hover target (the cell beneath owns hover),
+// fill set inline per cell (auto-contrast against the bucket color).
+.#{brand.$prefix}-heatmap-chart-cell-label {
+ @include cssUtils.typography(label, extra-small);
+ pointer-events: none;
+ user-select: none;
+}
+
+// No numeric value for this cell. Dim via fill-opacity, NOT opacity — the
+// entrance keyframe's forwards fill holds `opacity: 1` and would silently
+// defeat an opacity dim on the same element.
+.#{brand.$prefix}-heatmap-chart-cell--empty {
+ fill: cssUtils.$border-default;
+ fill-opacity: 0.35;
+}
+
+// Entrances are decorative: gate the whole rule (pre-state included) behind
+// reduced-motion so users who opt out get the natural static state immediately
+// — gating only the animation would strand elements at the opacity: 0 start.
+@media (prefers-reduced-motion: no-preference) {
+ .#{brand.$prefix}-heatmap-chart-cell--animated,
+ .#{brand.$prefix}-heatmap-chart-cell-label--animated {
+ opacity: 0;
+ animation: #{brand.$prefix}-fade-appear 0.4s ease-out forwards;
+ }
+}
+
+// The value→color key under the grid. HTML (like the row legend) so it
+// survives print; height is measured and deducted by the orchestrator.
+.#{brand.$prefix}-heatmap-chart-color-scale {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ width: 100%;
+ padding: 6px 0 2px;
+}
+
+.#{brand.$prefix}-heatmap-chart-color-scale-label {
+ @include cssUtils.typography(label, extra-small);
+ color: cssUtils.$text-neutral-secondary;
+ white-space: nowrap;
+}
+
+.#{brand.$prefix}-heatmap-chart-color-scale-ramp {
+ position: relative;
+ display: flex;
+ flex: 1;
+ height: 8px;
+ border-radius: 4px;
+ overflow: hidden;
+}
+
+.#{brand.$prefix}-heatmap-chart-color-scale-bucket {
+ flex: 1;
+}
+
+// Diverging ramps pin zero to the strip's exact center (the domain is
+// symmetric by construction) — mark it.
+.#{brand.$prefix}-heatmap-chart-color-scale-ramp--diverging::after {
+ content: "";
+ position: absolute;
+ left: 50%;
+ top: 0;
+ bottom: 0;
+ width: 2px;
+ transform: translateX(-50%);
+ background: cssUtils.$foreground;
+ opacity: 0.55;
+}
diff --git a/packages/react-ui/src/components/D3Charts/HeatmapChart/index.ts b/packages/react-ui/src/components/D3Charts/HeatmapChart/index.ts
new file mode 100644
index 000000000..870db5ee6
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/HeatmapChart/index.ts
@@ -0,0 +1,2 @@
+export { HeatmapChart } from "./HeatmapChart";
+export type { HeatmapChartData, HeatmapChartProps } from "./types";
diff --git a/packages/react-ui/src/components/D3Charts/HeatmapChart/parts/HeatmapCells.tsx b/packages/react-ui/src/components/D3Charts/HeatmapChart/parts/HeatmapCells.tsx
new file mode 100644
index 000000000..2af6d678c
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/HeatmapChart/parts/HeatmapCells.tsx
@@ -0,0 +1,191 @@
+import type { ScaleBand, ScaleQuantize } from "d3-scale";
+import React, { useCallback } from "react";
+
+import type { HoveredHeatmapCell } from "../../hooks/cartesian/useHeatmapChartOrchestrator";
+import { heatmapCellValue } from "../../hooks/cartesian/useHeatmapChartOrchestrator";
+import { useCanvasContextForLabelSize } from "../../hooks/core/useCanvasContextForLabelSize";
+import { useHydrated } from "../../hooks/core/useHydrated";
+import { getColorLuminance, LUMINANCE_TEXT_PIVOT } from "../../utils/colorLuminance";
+import { CHART_CLASS_PREFIX } from "../../utils/constants";
+import { entranceProps } from "../../utils/entranceUtils";
+import { parseLineHeight } from "../../utils/labelWrap";
+import { numberTickFormatter } from "../../utils/styleUtils";
+
+// Entrance stagger: a left-to-right column wave, capped so wide (streamed)
+// datasets don't push late columns into seconds of delay.
+const STAGGER_MS = 15;
+const STAGGER_CAP_MS = 300;
+
+// Breathing room a label needs inside its cell before it auto-hides.
+const LABEL_PAD_X = 6;
+const LABEL_PAD_Y = 2;
+
+// In-cell label colors are picked per cell against the bucket color (WCAG
+// pivot), not themed: theme text tokens don't know what they'd sit on.
+const LABEL_ON_LIGHT = "rgba(20, 24, 28, 0.85)";
+const LABEL_ON_DARK = "rgba(255, 255, 255, 0.92)";
+
+interface HeatmapCellsProps<T extends Record<string, string | number>> {
+ data: T[];
+ catKey: string;
+ /** Per-column React keys, duplicate labels already disambiguated. */
+ columnKeys: string[];
+ visibleRowKeys: string[];
+ xScale: ScaleBand<string>;
+ yScale: ScaleBand<string>;
+ colorScale: ScaleQuantize<string>;
+ cellGap: number;
+ cellRadius: number;
+ showCellLabels: boolean;
+ animate: boolean;
+ onCellMouseMove: (event: React.MouseEvent, cell: HoveredHeatmapCell) => void;
+ onCellMouseLeave: () => void;
+ onClick?: (row: T, columnIndex: number, rowKey: string) => void;
+}
+
+/**
+ * The cell grid. One <rect> per (column, visible row); fill = the quantized
+ * value color; non-numeric/missing values get the muted --empty modifier
+ * (dimmed via fill-opacity, NOT opacity — the entrance keyframe's forwards
+ * fill holds opacity and would override an opacity dim forever). Hover
+ * highlight is pure CSS (:hover stroke); these handlers only feed the
+ * tooltip/click state.
+ *
+ * Cell labels (opt-in) are hydration-gated: the canvas measurer is an SSR
+ * stub returning zero widths, which would pass every fit check and hydrate
+ * labels the server never rendered. Each label auto-hides when its formatted
+ * value doesn't fit its cell, and picks dark/light text against its own
+ * bucket color — that auto-degradation is what makes the boolean safe to
+ * enable blindly (an LLM will).
+ */
+export function HeatmapCells<T extends Record<string, string | number>>({
+ data,
+ catKey,
+ columnKeys,
+ visibleRowKeys,
+ xScale,
+ yScale,
+ colorScale,
+ cellGap,
+ cellRadius,
+ showCellLabels,
+ animate,
+ onCellMouseMove,
+ onCellMouseLeave,
+ onClick,
+}: HeatmapCellsProps<T>) {
+ const hydrated = useHydrated();
+ const context = useCanvasContextForLabelSize();
+
+ const handleClick = useCallback(
+ (row: T, columnIndex: number, rowKey: string) => {
+ onClick?.(row, columnIndex, rowKey);
+ },
+ [onClick],
+ );
+
+ // Never let the gap eat more than half the band — at extreme density a
+ // fixed gap would otherwise zero every cell out (blank plot, intact axes).
+ const gapX = Math.min(cellGap, xScale.bandwidth() / 2);
+ const gapY = Math.min(cellGap, yScale.bandwidth() / 2);
+ const cellWidth = Math.max(0, xScale.bandwidth() - gapX);
+ const cellHeight = Math.max(0, yScale.bandwidth() - gapY);
+
+ const labelsActive = showCellLabels && hydrated;
+ const labelLineHeight = labelsActive ? parseLineHeight(context.font) : 0;
+
+ const renderCellLabel = (
+ value: number,
+ x: number,
+ y: number,
+ animationDelay: string | undefined,
+ ) => {
+ const text = numberTickFormatter(value);
+ if (
+ context.measureText(text).width > cellWidth - LABEL_PAD_X ||
+ labelLineHeight > cellHeight - LABEL_PAD_Y
+ ) {
+ return null;
+ }
+ const luminance = getColorLuminance(colorScale(value));
+ const fill =
+ luminance !== null && luminance > LUMINANCE_TEXT_PIVOT ? LABEL_ON_LIGHT : LABEL_ON_DARK;
+ return (
+ <text
+ x={x + cellWidth / 2}
+ y={y + cellHeight / 2}
+ textAnchor="middle"
+ dominantBaseline="central"
+ className={`${CHART_CLASS_PREFIX}-heatmap-chart-cell-label${
+ animate ? ` ${CHART_CLASS_PREFIX}-heatmap-chart-cell-label--animated` : ""
+ }`}
+ style={{ fill, animationDelay }}
+ >
+ {text}
+ </text>
+ );
+ };
+
+ return (
+ <g>
+ {data.map((row, columnIndex) => {
+ const columnLabel = String(row[catKey]);
+ const x = (xScale(columnLabel) ?? 0) + gapX / 2;
+ const { className: cellAnimatedClass, animationDelay } = entranceProps(
+ animate,
+ `${CHART_CLASS_PREFIX}-heatmap-chart-cell--animated`,
+ Math.min(columnIndex * STAGGER_MS, STAGGER_CAP_MS),
+ );
+
+ return (
+ // Keyed per-column group so removing/inserting a middle column
+ // reconciles by identity instead of remounting every later column
+ // (which would replay entrances). Matches BarSeries' grouped shape.
+ // Keys come pre-deduplicated — LLMs re-emit duplicate labels.
+ <g key={columnKeys[columnIndex] ?? columnIndex}>
+ {visibleRowKeys.map((rowKey) => {
+ const y = (yScale(rowKey) ?? 0) + gapY / 2;
+ const value = heatmapCellValue(row[rowKey]);
+
+ const modifiers = [
+ value === null ? `${CHART_CLASS_PREFIX}-heatmap-chart-cell--empty` : "",
+ cellAnimatedClass,
+ ]
+ .filter(Boolean)
+ .join(" ");
+
+ return (
+ <React.Fragment key={rowKey}>
+ <rect
+ className={`${CHART_CLASS_PREFIX}-heatmap-chart-cell ${modifiers}`.trim()}
+ x={x}
+ y={y}
+ width={cellWidth}
+ height={cellHeight}
+ rx={cellRadius}
+ fill={value === null ? undefined : colorScale(value)}
+ style={{
+ animationDelay,
+ cursor: onClick ? "pointer" : undefined,
+ }}
+ onMouseMove={(event) =>
+ onCellMouseMove(event, {
+ rowKey,
+ columnIndex,
+ columnLabel,
+ value,
+ })
+ }
+ onMouseLeave={onCellMouseLeave}
+ onClick={() => handleClick(row, columnIndex, rowKey)}
+ />
+ {labelsActive && value !== null && renderCellLabel(value, x, y, animationDelay)}
+ </React.Fragment>
+ );
+ })}
+ </g>
+ );
+ })}
+ </g>
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/HeatmapChart/parts/HeatmapColorScale.tsx b/packages/react-ui/src/components/D3Charts/HeatmapChart/parts/HeatmapColorScale.tsx
new file mode 100644
index 000000000..49af122a1
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/HeatmapChart/parts/HeatmapColorScale.tsx
@@ -0,0 +1,56 @@
+import React from "react";
+
+import { numberTickFormatter } from "../../utils/styleUtils";
+
+export interface HeatmapColorScaleBucket {
+ color: string;
+ /** Bucket bounds, derived by index from thresholds() + the domain. */
+ lo: number;
+ hi: number;
+}
+
+interface HeatmapColorScaleProps {
+ buckets: HeatmapColorScaleBucket[];
+ domainMin: number;
+ domainMax: number;
+ /** Diverging ramps get a zero notch at the strip's center. */
+ diverging: boolean;
+ classPrefix: string;
+}
+
+/**
+ * The value→color key: a non-interactive bucket strip with the domain's
+ * endpoints labeled. Each swatch is one quantize bucket and carries its exact
+ * value range as a native title — honest by construction (the buckets come
+ * from invertExtent, never re-derived). HTML below the svg (like the row
+ * legend) so it survives print and needs no plot space; the orchestrator
+ * measures its height and deducts it from the grid in fit mode.
+ *
+ * This exists because the tooltip is the only other value readout and it's
+ * mouse-only: on touch and in print/PDF a heatmap without this strip cannot
+ * be decoded at all.
+ */
+export const HeatmapColorScale = React.forwardRef<HTMLDivElement, HeatmapColorScaleProps>(
+ ({ buckets, domainMin, domainMax, diverging, classPrefix }, ref) => (
+ <div ref={ref} className={`${classPrefix}-color-scale`}>
+ <span className={`${classPrefix}-color-scale-label`}>{numberTickFormatter(domainMin)}</span>
+ <div
+ className={`${classPrefix}-color-scale-ramp${
+ diverging ? ` ${classPrefix}-color-scale-ramp--diverging` : ""
+ }`}
+ >
+ {buckets.map((bucket, index) => (
+ <span
+ key={index}
+ className={`${classPrefix}-color-scale-bucket`}
+ style={{ backgroundColor: bucket.color }}
+ title={`${numberTickFormatter(bucket.lo)} – ${numberTickFormatter(bucket.hi)}`}
+ />
+ ))}
+ </div>
+ <span className={`${classPrefix}-color-scale-label`}>{numberTickFormatter(domainMax)}</span>
+ </div>
+ ),
+);
+
+HeatmapColorScale.displayName = "HeatmapColorScale";
diff --git a/packages/react-ui/src/components/D3Charts/HeatmapChart/parts/HeatmapYAxis.tsx b/packages/react-ui/src/components/D3Charts/HeatmapChart/parts/HeatmapYAxis.tsx
new file mode 100644
index 000000000..b59e68624
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/HeatmapChart/parts/HeatmapYAxis.tsx
@@ -0,0 +1,58 @@
+import type { ScaleBand } from "d3-scale";
+
+import { useCanvasContextForLabelSize } from "../../hooks/core/useCanvasContextForLabelSize";
+import { LabelTooltip } from "../../shared/core/LabelTooltip/LabelTooltip";
+import { truncateToWidth } from "../../utils/labelWrap";
+
+// Mirrors the y-axis text inset used by the numeric YAxis (text at width − 8)
+// and the measurement padding the orchestrator reserves.
+const TEXT_INSET = 8;
+const LABEL_PADDING = 10;
+
+interface HeatmapYAxisProps {
+ scale: ScaleBand<string>;
+ /** Reserved y-axis width (the orchestrator measured the row labels). */
+ width: number;
+ classPrefix: string;
+}
+
+/**
+ * Categorical row labels for the heatmap. The shared YAxis is linear-only
+ * (`scale.ticks()`), so this hand-rolls its geometry: right-aligned text
+ * centered in each band, truncated to the reserved width with a LabelTooltip
+ * on truncation (the XAxis pattern). Needs a LabelTooltipProvider ancestor.
+ */
+export function HeatmapYAxis({ scale, width, classPrefix }: HeatmapYAxisProps) {
+ const context = useCanvasContextForLabelSize();
+ const maxTextWidth = Math.max(0, width - LABEL_PADDING);
+
+ return (
+ <g className={`${classPrefix}-y-axis`}>
+ {scale.domain().map((rowKey) => {
+ const label = truncateToWidth(context, rowKey, maxTextWidth);
+ const truncated = label !== rowKey;
+ const bandY = scale(rowKey) ?? 0;
+ const centerY = bandY + scale.bandwidth() / 2;
+
+ return (
+ <LabelTooltip key={rowKey} content={rowKey} disabled={!truncated}>
+ <g>
+ {truncated && (
+ <rect x={0} y={bandY} width={width} height={scale.bandwidth()} fill="transparent" />
+ )}
+ <text
+ x={width - TEXT_INSET}
+ y={centerY}
+ textAnchor="end"
+ dominantBaseline="middle"
+ className={`${classPrefix}-y-tick`}
+ >
+ {label}
+ </text>
+ </g>
+ </LabelTooltip>
+ );
+ })}
+ </g>
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/HeatmapChart/types.ts b/packages/react-ui/src/components/D3Charts/HeatmapChart/types.ts
new file mode 100644
index 000000000..58f001312
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/HeatmapChart/types.ts
@@ -0,0 +1,68 @@
+import type { ChartData } from "../types";
+import type { HeatmapRampMode } from "../utils/heatmapUtils";
+
+export type HeatmapChartData = ChartData;
+
+export interface HeatmapChartProps<T extends HeatmapChartData> {
+ /**
+ * Row-shaped data, same contract as the other charts: `categoryKey` names the
+ * COLUMN (x-axis) label field; every other key of `data[0]` becomes a heatmap
+ * ROW (y-axis); `row[key]` is the cell value. Non-numeric / missing cell
+ * values render as muted "no value" cells.
+ */
+ data: T;
+ categoryKey: keyof T[number];
+ /**
+ * Ordered color ramp for the value scale (low → high). Overrides the theme
+ * palette. Otherwise the theme's `defaultChartPalette` (or the built-in
+ * ocean ramp) is used in its given order.
+ */
+ customPalette?: string[];
+ /**
+ * How values map onto the ramp. Use `"diverging"` when values are signed
+ * around a meaningful zero — profit/loss, deltas, correlation — so zero
+ * sits on the neutral middle color and the two signs get opposing hues
+ * (the domain is forced symmetric: ±max absolute value). `"sequential"`
+ * (default) spreads the ramp over the plain min→max extent. With a
+ * `customPalette`, diverging mode reads it as the full low→neutral→high
+ * ramp (odd length keeps zero on one exact middle color).
+ */
+ rampMode?: HeatmapRampMode;
+ /** Show the legend. Legend items are the rows; clicking toggles a row. Default true. */
+ legend?: boolean;
+ /**
+ * Show the value→color key under the grid: a bucket strip labeled with the
+ * domain's endpoints. Default true — the hover tooltip is mouse-only, so
+ * without this strip a reader on touch or in print cannot map color to
+ * magnitude at all. Turn off only when an outer surface provides its own
+ * key.
+ */
+ showColorScale?: boolean;
+ /**
+ * Draw each cell's value inside the cell. Default false. Safe to enable on
+ * any data: labels auto-hide per cell when the formatted value doesn't fit,
+ * and text color auto-contrasts against each cell's color. Off in the
+ * default because dense matrices read better through color alone.
+ */
+ showCellLabels?: boolean;
+ /**
+ * Play the entrance animation. Gates the entrance ONLY — any hover or
+ * data-update motion is independent of this flag, and printing always
+ * disables it.
+ * Default false (streaming-safe: marks mounted while data streams in don't
+ * replay staggered entrances).
+ */
+ isAnimationActive?: boolean;
+ /** Show the row labels on the left. Default true. */
+ showYAxis?: boolean;
+ /** Gap between cells in px. Default 2. */
+ cellGap?: number;
+ /** Cell corner radius in px. Default 2. */
+ cellRadius?: number;
+ height?: number | string;
+ width?: number | string;
+ fitLegendInHeight?: boolean;
+ className?: string;
+ /** Click on a cell: the original data row (column), its index, and the row key. */
+ onClick?: (row: T[number], columnIndex: number, rowKey: string) => void;
+}
diff --git a/packages/react-ui/src/components/D3Charts/LineChart/LineChart.tsx b/packages/react-ui/src/components/D3Charts/LineChart/LineChart.tsx
new file mode 100644
index 000000000..a694fabda
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/LineChart/LineChart.tsx
@@ -0,0 +1,198 @@
+import clsx from "clsx";
+import { useCallback } from "react";
+
+import {
+ useCartesianChartOrchestrator,
+ useEffectiveAnimation,
+ useExportChartData,
+ useXScale,
+ useYScale,
+} from "../hooks";
+import { CartesianXAxis } from "../shared/cartesian/axes/CartesianXAxis";
+import { ClipDefs } from "../shared/cartesian/ClipDefs";
+import { CartesianChartLayout } from "../shared/cartesian/layouts/CartesianChartLayout";
+import { LineDotCrosshair } from "../shared/cartesian/LineDotCrosshair";
+import { findNearestDataIndex } from "../utils/mouseUtils";
+import { LineSeries } from "./parts/LineSeries";
+
+import { CHART_CLASS_PREFIX } from "../utils/constants";
+import type { LineChartData, LineChartProps } from "./types";
+
+/**
+ * Empty-data guard lives here, in a hook-free dispatcher: the chart impl below
+ * calls hooks unconditionally, so the "no data" branch must short-circuit
+ * *before* any hook runs (a count → 0 transition on a mounted chart would
+ * otherwise break the Rules of Hooks).
+ */
+export function LineChart<T extends LineChartData>(props: LineChartProps<T>) {
+ if (!props.data || props.data.length === 0) {
+ return (
+ <div
+ className={clsx(
+ `${CHART_CLASS_PREFIX}-line-chart-container ${CHART_CLASS_PREFIX}-chart-empty`,
+ props.className,
+ )}
+ >
+ <span className={`${CHART_CLASS_PREFIX}-chart-empty-text`}>No data available</span>
+ </div>
+ );
+ }
+ return <LineChartImpl {...props} />;
+}
+
+function LineChartImpl<T extends LineChartData>({
+ data,
+ categoryKey,
+ customPalette,
+ variant = "natural",
+ tickVariant: tickVariantProp,
+ showDots = false,
+ dotRadius = 3,
+ grid = true,
+ legend: showLegend = true,
+ icons,
+ isAnimationActive = false,
+ showYAxis = true,
+ xAxisLabel,
+ yAxisLabel,
+ className,
+ height,
+ width: fixedWidth,
+ fitLegendInHeight,
+ condensed = false,
+ density,
+ onClick,
+ crosshair = false,
+ highlight = false,
+ activeDots = true,
+ yTickCount,
+}: LineChartProps<T>) {
+ const animate = useEffectiveAnimation(isAnimationActive);
+ const mode = condensed ? "fit" : "scroll";
+
+ const orch = useCartesianChartOrchestrator({
+ layout: mode,
+ data,
+ categoryKey,
+ themePaletteName: "lineChartPalette",
+ customPalette,
+ showLegend,
+ showYAxis,
+ height,
+ fixedWidth,
+ fitLegendInHeight,
+ tickVariantProp: tickVariantProp ?? (condensed ? "singleLine" : "multiLine"),
+ chartIdPrefix: "d3lc",
+ icons,
+ onClick,
+ density,
+ yTickCount,
+ });
+
+ const xScale = useXScale(
+ data,
+ orch.data.catKey,
+ orch.dimensions.chartAreaWidth,
+ orch.dimensions.widthOfGroup,
+ );
+ const yScale = useYScale(data, orch.data.dataKeys, orch.dimensions.chartInnerHeight, false);
+
+ const getYValue = useCallback(
+ (row: Record<string, string | number>, key: string) => Number(row[key]) || 0,
+ [],
+ );
+
+ const findIndex = useCallback((mouseX: number) => findNearestDataIndex(xScale, mouseX), [xScale]);
+ const mouseHandlers = orch.hover.createMouseHandlers(findIndex);
+
+ // PPTX print-export JSON — mirrors react-ui's LineChart call (type:'line').
+ // react-ui also passes `extraOptions: { lineSize: strokeWidth }`, but viz's
+ // LineChart exposes no stroke-width prop (stroke is CSS-driven), so there is
+ // no real value to emit — the field is omitted rather than faked. Undefined
+ // off the print path.
+ const exportData = useExportChartData({
+ type: "line",
+ data,
+ categoryKey: orch.data.catKey,
+ dataKeys: orch.data.dataKeys,
+ colors: orch.data.colors,
+ legend: showLegend,
+ xAxisLabel,
+ yAxisLabel,
+ });
+
+ return (
+ <CartesianChartLayout
+ orch={orch}
+ yScale={yScale}
+ mouseHandlers={mouseHandlers}
+ classPrefix="line-chart"
+ chartType="line"
+ exportData={exportData}
+ ariaLabel="Line chart"
+ showYAxis={showYAxis}
+ grid={grid}
+ showLegend={showLegend}
+ xAxisLabel={xAxisLabel}
+ yAxisLabel={yAxisLabel}
+ yTickCount={yTickCount}
+ className={className}
+ defs={
+ <defs>
+ <ClipDefs
+ chartId={orch.identity.chartId}
+ chartWidth={orch.dimensions.chartAreaWidth}
+ chartHeight={orch.dimensions.chartInnerHeight}
+ />
+ </defs>
+ }
+ series={
+ <>
+ <LineSeries
+ data={data}
+ dataKeys={orch.data.dataKeys}
+ xScale={xScale}
+ yScale={yScale}
+ variant={variant}
+ categoryKey={orch.data.catKey}
+ colors={orch.data.colorMap}
+ showDots={showDots}
+ dotRadius={dotRadius}
+ isAnimationActive={animate}
+ />
+ <LineDotCrosshair
+ hoveredIndex={orch.hover.hoveredIndex}
+ xScale={xScale}
+ yScale={yScale}
+ data={data}
+ dataKeys={orch.data.dataKeys}
+ categoryKey={orch.data.catKey}
+ colors={orch.data.colorMap}
+ chartHeight={orch.dimensions.chartInnerHeight}
+ getYValue={getYValue}
+ classPrefix={`${CHART_CLASS_PREFIX}-line-chart`}
+ crosshair={crosshair}
+ highlight={highlight}
+ activeDots={activeDots}
+ />
+ </>
+ }
+ xAxis={
+ <CartesianXAxis
+ mode={mode}
+ scale={xScale}
+ classPrefix={`${CHART_CLASS_PREFIX}-line-chart`}
+ tickVariant={orch.dimensions.tickVariant}
+ widthOfGroup={orch.dimensions.widthOfGroup}
+ labelHeight={orch.xAxis.xAxisHeight}
+ labelWidth={orch.xAxis.labelWidth}
+ maxLines={orch.xAxis.maxLines}
+ labelInterval={orch.dimensions.labelInterval}
+ angle={orch.xAxis.angle}
+ chartWidth={orch.dimensions.chartAreaWidth}
+ yAxisWidth={orch.dimensions.effectiveYAxisWidth}
+ />
+ }
+ />
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/LineChart/index.ts b/packages/react-ui/src/components/D3Charts/LineChart/index.ts
new file mode 100644
index 000000000..3f5501445
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/LineChart/index.ts
@@ -0,0 +1,2 @@
+export { LineChart } from "./LineChart";
+export type { LineChartData, LineChartProps, LineChartVariant } from "./types";
diff --git a/packages/react-ui/src/components/D3Charts/LineChart/lineChart.scss b/packages/react-ui/src/components/D3Charts/LineChart/lineChart.scss
new file mode 100644
index 000000000..2b7609de7
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/LineChart/lineChart.scss
@@ -0,0 +1,31 @@
+@use "../../../cssUtils" as cssUtils;
+@use "../shared/cartesian/chartBase" as base;
+@use "../prefix" as brand;
+
+@include base.chart-base("line-chart");
+@include base.crosshair-styles("line-chart");
+
+// No `transition: d/cx/cy` here: data-change motion is the spring data morph
+// in LineSeries (gated on isAnimationActive). A CSS transition restarted from
+// progress 0 on every attribute write, so per-frame streaming rewrites pinned
+// the rendered geometry (and would fight the morph's per-tick writes).
+.#{brand.$prefix}-line-chart-line {
+ fill: none;
+ stroke-width: 2;
+}
+
+.#{brand.$prefix}-line-chart-dot {
+ stroke: cssUtils.$foreground;
+ stroke-width: 1;
+}
+
+// Entrances are decorative: gate the whole rule (pre-state included) behind
+// reduced-motion so users who opt out get the natural static state immediately
+// — gating only the animation would strand elements at the opacity: 0 start.
+@media (prefers-reduced-motion: no-preference) {
+ .#{brand.$prefix}-line-chart-line--animated {
+ stroke-dasharray: var(--path-length);
+ stroke-dashoffset: var(--path-length);
+ animation: #{brand.$prefix}-draw-line 1s ease-out forwards;
+ }
+}
diff --git a/packages/react-ui/src/components/D3Charts/LineChart/parts/LineSeries.tsx b/packages/react-ui/src/components/D3Charts/LineChart/parts/LineSeries.tsx
new file mode 100644
index 000000000..a12b3c97c
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/LineChart/parts/LineSeries.tsx
@@ -0,0 +1,158 @@
+import type { ScaleLinear, ScalePoint } from "d3-scale";
+import { type CurveFactory, curveLinear, curveMonotoneX, curveStepAfter } from "d3-shape";
+import React, { useMemo, useRef } from "react";
+import { AnimatedPath } from "../../shared/cartesian/AnimatedPath";
+import { buildLineD, LINE_STRIDE } from "../../shared/cartesian/seriesGeometry";
+import { springPresets, useDataMorph, useIsomorphicLayoutEffect } from "../../shared/core/spring";
+import { CHART_CLASS_PREFIX } from "../../utils/constants";
+import type { LineChartVariant } from "../types";
+
+const curveMap = {
+ linear: curveLinear,
+ natural: curveMonotoneX,
+ step: curveStepAfter,
+};
+
+interface LineSeriesProps {
+ data: Array<Record<string, string | number>>;
+ dataKeys: string[];
+ xScale: ScalePoint<string>;
+ yScale: ScaleLinear<number, number>;
+ variant: LineChartVariant;
+ categoryKey: string;
+ colors: Record<string, string>;
+ showDots: boolean;
+ dotRadius: number;
+ isAnimationActive?: boolean;
+}
+
+export const LineSeries: React.FC<LineSeriesProps> = ({
+ data,
+ dataKeys,
+ xScale,
+ yScale,
+ variant,
+ categoryKey,
+ colors,
+ showDots,
+ dotRadius,
+ isAnimationActive,
+}) => {
+ // Fall back to the default curve for any variant not in the map — during
+ // streaming the parser can hand us a placeholder (e.g. "") before the real
+ // enum value arrives, and `curveMap[""]` would otherwise be `undefined`,
+ // making d3-shape's `line().curve(undefined)` throw "curve is not a
+ // function" on that transient first render. `natural` mirrors the chart's
+ // own `variant = 'natural'` default.
+ const curve = curveMap[variant] ?? curveMap.natural;
+
+ // Target geometry per series: flat point pixels + the d built from them.
+ // React commits these as the attributes (SSR/print/snap correct by
+ // construction); the morph only ever writes BETWEEN target states.
+ const seriesGeom = useMemo(() => {
+ return dataKeys.map((key) => {
+ const points = new Float64Array(data.length * LINE_STRIDE);
+ data.forEach((row, i) => {
+ points[i * LINE_STRIDE] = xScale(String(row[categoryKey])) ?? 0;
+ points[i * LINE_STRIDE + 1] = yScale(Number(row[key]) || 0);
+ });
+ return { key, points, linePath: buildLineD(points, curve) };
+ });
+ }, [data, dataKeys, xScale, yScale, categoryKey, curve]);
+
+ return (
+ <g className={`${CHART_CLASS_PREFIX}-line-chart-lines`}>
+ {seriesGeom.map(({ key, points, linePath }) => (
+ <LineSeriesItem
+ key={key}
+ points={points}
+ linePath={linePath}
+ curve={curve}
+ color={colors[key] ?? "#000"}
+ showDots={showDots}
+ dotRadius={dotRadius}
+ isAnimationActive={isAnimationActive}
+ />
+ ))}
+ </g>
+ );
+};
+
+/**
+ * One series' line (+ optional dots) under the spring data morph. When target
+ * geometry changes with `isAnimationActive` on, the point vector springs from
+ * its live position/velocity and `d` (and dot cx/cy) regenerate per ticker
+ * tick — per-frame data churn (streaming) retargets the spring mid-flight and
+ * converges, where the removed CSS `transition: d` restarted at progress 0 on
+ * every write and pinned the rendered geometry. With the flag off (the
+ * default, and every c1 surface) there is no morph at all: React's own
+ * attribute commit IS the snap. The dots ride the same scalars, so stroke and
+ * dots can never seam apart.
+ */
+function LineSeriesItem({
+ points,
+ linePath,
+ curve,
+ color,
+ showDots,
+ dotRadius,
+ isAnimationActive,
+}: {
+ points: Float64Array;
+ linePath: string;
+ curve: CurveFactory;
+ color: string;
+ showDots: boolean;
+ dotRadius: number;
+ isAnimationActive?: boolean;
+}) {
+ const pathRef = useRef<SVGPathElement | null>(null);
+ const dotsRef = useRef<SVGGElement | null>(null);
+ const curveRef = useRef(curve);
+ curveRef.current = curve;
+
+ const aim = useDataMorph(springPresets.dataMorph, (values) => {
+ pathRef.current?.setAttribute("d", buildLineD(values, curveRef.current));
+ const dots = dotsRef.current?.children;
+ if (dots) {
+ const n = Math.min(dots.length, Math.floor(values.length / LINE_STRIDE));
+ for (let i = 0; i < n; i++) {
+ const dot = dots[i] as SVGCircleElement;
+ dot.setAttribute("cx", String(values[i * LINE_STRIDE]));
+ dot.setAttribute("cy", String(values[i * LINE_STRIDE + 1]));
+ }
+ }
+ });
+
+ // Pre-paint so a mid-glide retarget restores the animated geometry before
+ // the freshly committed target attributes can flash.
+ useIsomorphicLayoutEffect(() => {
+ aim(points, !isAnimationActive);
+ }, [points, isAnimationActive, aim]);
+
+ return (
+ <g>
+ <AnimatedPath
+ d={linePath}
+ color={color}
+ className={`${CHART_CLASS_PREFIX}-line-chart-line`}
+ isAnimationActive={isAnimationActive}
+ pathRef={pathRef}
+ />
+ {showDots && (
+ <g ref={dotsRef}>
+ {Array.from({ length: points.length / LINE_STRIDE }, (_, i) => (
+ <circle
+ key={i}
+ cx={points[i * LINE_STRIDE]}
+ cy={points[i * LINE_STRIDE + 1]}
+ r={dotRadius}
+ fill={color}
+ className={`${CHART_CLASS_PREFIX}-line-chart-dot`}
+ />
+ ))}
+ </g>
+ )}
+ </g>
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/LineChart/stories/lineChart.stories.tsx b/packages/react-ui/src/components/D3Charts/LineChart/stories/lineChart.stories.tsx
new file mode 100644
index 000000000..550d60f74
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/LineChart/stories/lineChart.stories.tsx
@@ -0,0 +1,1295 @@
+// Copy of Charts/LineChart/stories/lineChart.stories.tsx with only the chart import and the title changed:
+// the same args and renders, rendering the D3Charts chart via
+// ../../stories/rechartsStoryAdapters.
+import type { Meta, StoryObj } from "@storybook/react";
+import {
+ Calendar,
+ Globe,
+ Laptop,
+ Monitor,
+ Smartphone,
+ TabletSmartphone,
+ Tv,
+ Watch,
+} from "lucide-react";
+import { useState } from "react";
+import { Card } from "../../../Card";
+import { LineChart, LineChartProps } from "../../stories/rechartsStoryAdapters";
+
+const customColorPalette = [
+ "#0A0E60",
+ "#14197B",
+ "#272DA6",
+ "#383FC9",
+ "#444CE7",
+ "#5F67F4",
+ "#7884FF",
+ "#97A9FF",
+ "#B4C6FF",
+ "#CBD7FF",
+];
+
+// 🔥 COMPREHENSIVE DATA VARIATIONS - Designed to test label collision scenarios
+const dataVariations = {
+ default: [
+ { month: "January", desktop: 150, mobile: 90, tablet: 120 },
+ { month: "February", desktop: 280, mobile: 180, tablet: 140 },
+ { month: "March", desktop: 220, mobile: 140, tablet: 160 },
+ { month: "April", desktop: 180, mobile: 160, tablet: 180 },
+ { month: "May", desktop: 250, mobile: 120, tablet: 140 },
+ { month: "June", desktop: 300, mobile: 180, tablet: 160 },
+ { month: "July", desktop: 350, mobile: 220, tablet: 180 },
+ { month: "August", desktop: 400, mobile: 240, tablet: 200 },
+ { month: "September", desktop: 450, mobile: 260, tablet: 220 },
+ { month: "October", desktop: 500, mobile: 280, tablet: 240 },
+ { month: "November", desktop: 550, mobile: 300, tablet: 260 },
+ { month: "December", desktop: 600, mobile: 320, tablet: 280 },
+ ],
+ // 🏷️ BIG LABELS - Testing collision detection and truncation
+ bigLabels: [
+ {
+ category: "Very Long Category Name That Should Be Truncated",
+ sales: 150,
+ revenue: 90,
+ profit: 120,
+ },
+ {
+ category: "Another Extremely Long Label That Causes Collisions",
+ sales: 280,
+ revenue: 180,
+ profit: 140,
+ },
+ {
+ category: "Super Duper Long Category Name That Tests Truncation",
+ sales: 220,
+ revenue: 140,
+ profit: 160,
+ },
+ {
+ category: "Incredibly Long Text That Should Trigger Collision Detection",
+ sales: 180,
+ revenue: 160,
+ profit: 180,
+ },
+ {
+ category: "Maximum Length Category Name That Tests All Edge Cases",
+ sales: 250,
+ revenue: 120,
+ profit: 140,
+ },
+ {
+ category: "Extra Long Business Category Name With Many Words",
+ sales: 300,
+ revenue: 180,
+ profit: 160,
+ },
+ {
+ category: "Comprehensive Long Label For Testing Horizontal Offset",
+ sales: 350,
+ revenue: 220,
+ profit: 180,
+ },
+ {
+ category: "Extended Category Name That Pushes Truncation Limits",
+ sales: 400,
+ revenue: 240,
+ profit: 200,
+ },
+ ],
+ // 📅 DENSE TIMELINE - Many items with medium-length labels
+ denseTimeline: [
+ { period: "Q1 2022 Jan-Mar", visitors: 120, conversions: 15, revenue: 1200 },
+ { period: "Q1 2022 Apr-Jun", visitors: 150, conversions: 22, revenue: 1800 },
+ { period: "Q2 2022 Jul-Sep", visitors: 180, conversions: 28, revenue: 2100 },
+ { period: "Q2 2022 Oct-Dec", visitors: 200, conversions: 35, revenue: 2500 },
+ { period: "Q3 2023 Jan-Mar", visitors: 160, conversions: 18, revenue: 1600 },
+ { period: "Q3 2023 Apr-Jun", visitors: 190, conversions: 32, revenue: 2300 },
+ { period: "Q4 2023 Jul-Sep", visitors: 220, conversions: 40, revenue: 2800 },
+ { period: "Q4 2023 Oct-Dec", visitors: 240, conversions: 45, revenue: 3200 },
+ { period: "Q1 2024 Jan-Mar", visitors: 210, conversions: 38, revenue: 2700 },
+ { period: "Q1 2024 Apr-Jun", visitors: 230, conversions: 42, revenue: 3000 },
+ { period: "Q2 2024 Jul-Sep", visitors: 250, conversions: 48, revenue: 3400 },
+ { period: "Q2 2024 Oct-Dec", visitors: 270, conversions: 52, revenue: 3800 },
+ { period: "Q3 2024 Jan-Mar", visitors: 260, conversions: 50, revenue: 3600 },
+ { period: "Q3 2024 Apr-Jun", visitors: 280, conversions: 55, revenue: 4000 },
+ { period: "Q4 2024 Jul-Sep", visitors: 300, conversions: 60, revenue: 4300 },
+ { period: "Q4 2024 Oct-Dec", visitors: 290, conversions: 58, revenue: 4100 },
+ ],
+ // 🏢 COMPANY NAMES - Real-world long business names
+ companyNames: [
+ { company: "Apple Inc.", revenue: 394328000000, profit: 99803000000, marketCap: 3500000000000 },
+ {
+ company: "Microsoft Corporation",
+ revenue: 211915000000,
+ profit: 83383000000,
+ marketCap: 2800000000000,
+ },
+ {
+ company: "Alphabet Inc. (Google)",
+ revenue: 307394000000,
+ profit: 76033000000,
+ marketCap: 2100000000000,
+ },
+ {
+ company: "Amazon.com Inc.",
+ revenue: 574785000000,
+ profit: 33364000000,
+ marketCap: 1600000000000,
+ },
+ {
+ company: "Tesla Motors Inc.",
+ revenue: 96773000000,
+ profit: 15000000000,
+ marketCap: 800000000000,
+ },
+ {
+ company: "Meta Platforms Inc.",
+ revenue: 134902000000,
+ profit: 39370000000,
+ marketCap: 900000000000,
+ },
+ {
+ company: "NVIDIA Corporation",
+ revenue: 60922000000,
+ profit: 29760000000,
+ marketCap: 1800000000000,
+ },
+ {
+ company: "Berkshire Hathaway Inc.",
+ revenue: 364482000000,
+ profit: 96223000000,
+ marketCap: 780000000000,
+ },
+ ],
+ // 🌍 COUNTRY NAMES - Geographic labels with varying lengths
+ countryData: [
+ { country: "United States of America", population: 331900000, gdp: 17700000000000 },
+ { country: "People's Republic of China", population: 1412000000, gdp: 17700000000000 },
+ { country: "Federal Republic of Germany", population: 83200000, gdp: 4300000000000 },
+ { country: "United Kingdom of Great Britain", population: 67500000, gdp: 3100000000000 },
+ { country: "French Republic", population: 68000000, gdp: 2900000000000 },
+ { country: "Republic of India", population: 1380000000, gdp: 3700000000000 },
+ { country: "Federative Republic of Brazil", population: 215000000, gdp: 2100000000000 },
+ { country: "Russian Federation", population: 146000000, gdp: 1800000000000 },
+ ],
+ // 📈 FINANCIAL QUARTERS - Testing medium-density scenarios
+ financialQuarters: [
+ { quarter: "Q1 FY2022", revenue: 1200000, expenses: 800000, profit: 400000 },
+ { quarter: "Q2 FY2022", revenue: 1500000, expenses: 950000, profit: 550000 },
+ { quarter: "Q3 FY2022", revenue: 1800000, expenses: 1100000, profit: 700000 },
+ { quarter: "Q4 FY2022", revenue: 2000000, expenses: 1300000, profit: 700000 },
+ { quarter: "Q1 FY2023", revenue: 2200000, expenses: 1400000, profit: 800000 },
+ { quarter: "Q2 FY2023", revenue: 2500000, expenses: 1600000, profit: 900000 },
+ { quarter: "Q3 FY2023", revenue: 2800000, expenses: 1800000, profit: 1000000 },
+ { quarter: "Q4 FY2023", revenue: 3000000, expenses: 1900000, profit: 1100000 },
+ ],
+ // 🔤 MIXED LENGTHS - Testing various label length scenarios
+ mixedLengths: [
+ { item: "A", valueA: 100, valueB: 80 },
+ { item: "Short", valueA: 150, valueB: 120 },
+ { item: "Medium Length Item", valueA: 200, valueB: 160 },
+ { item: "Very Long Item Name That Tests Truncation", valueA: 250, valueB: 200 },
+ { item: "B", valueA: 180, valueB: 140 },
+ { item: "Another Really Long Category Name", valueA: 220, valueB: 180 },
+ { item: "XL", valueA: 190, valueB: 150 },
+ ],
+ // 🎯 EDGE CASES - Extreme scenarios
+ edgeCases: [
+ {
+ name: "SinglePointDataSetForTestingEdgeCasesInCollisionDetectionAndLabelTruncationFunctionality",
+ value: 500,
+ },
+ {
+ name: "SecondExtremelyLongDataPointNameThatShouldDefinitelyTriggerTruncationMechanisms",
+ value: 600,
+ },
+ ],
+ // 📱 MINIMAL - Small dataset for baseline testing
+ minimal: [
+ { category: "Mobile Devices", users: 150, sessions: 90 },
+ { category: "Desktop Computers", users: 280, sessions: 180 },
+ { category: "Tablet Devices", users: 220, sessions: 140 },
+ ],
+ // 🔄 EXPAND/COLLAPSE - Marketing channels dataset for legend overflow testing
+ expandCollapseMarketing: [
+ {
+ channel: "Website Traffic and Organic Search Results",
+ impressions: 120000,
+ clicks: 15000,
+ conversions: 1200,
+ cost: 8500,
+ revenue: 24000,
+ roi: 182,
+ ctr: 12.5,
+ cpc: 0.57,
+ cpa: 7.08,
+ reach: 95000,
+ engagement: 8200,
+ shares: 420,
+ saves: 180,
+ comments: 650,
+ videoViews: 0,
+ },
+ {
+ channel: "Social Media Engagement and Brand Awareness",
+ impressions: 85000,
+ clicks: 12000,
+ conversions: 950,
+ cost: 6200,
+ revenue: 19000,
+ roi: 206,
+ ctr: 14.1,
+ cpc: 0.52,
+ cpa: 6.53,
+ reach: 72000,
+ engagement: 15400,
+ shares: 890,
+ saves: 340,
+ comments: 1200,
+ videoViews: 28000,
+ },
+ {
+ channel: "Email Marketing Campaign Performance",
+ impressions: 45000,
+ clicks: 8500,
+ conversions: 800,
+ cost: 2100,
+ revenue: 16000,
+ roi: 562,
+ ctr: 18.9,
+ cpc: 0.25,
+ cpa: 2.63,
+ reach: 42000,
+ engagement: 6800,
+ shares: 120,
+ saves: 85,
+ comments: 240,
+ videoViews: 0,
+ },
+ {
+ channel: "Paid Advertising and PPC Campaign ROI",
+ impressions: 95000,
+ clicks: 18000,
+ conversions: 1500,
+ cost: 12500,
+ revenue: 30000,
+ roi: 140,
+ ctr: 18.9,
+ cpc: 0.69,
+ cpa: 8.33,
+ reach: 88000,
+ engagement: 12600,
+ shares: 320,
+ saves: 150,
+ comments: 480,
+ videoViews: 5200,
+ },
+ {
+ channel: "Content Marketing and Blog Performance",
+ impressions: 60000,
+ clicks: 9500,
+ conversions: 750,
+ cost: 4800,
+ revenue: 15000,
+ roi: 213,
+ ctr: 15.8,
+ cpc: 0.51,
+ cpa: 6.4,
+ reach: 55000,
+ engagement: 7800,
+ shares: 680,
+ saves: 420,
+ comments: 950,
+ videoViews: 12000,
+ },
+ {
+ channel: "Mobile Application Downloads and Usage",
+ impressions: 70000,
+ clicks: 11000,
+ conversions: 1100,
+ cost: 5500,
+ revenue: 22000,
+ roi: 300,
+ ctr: 15.7,
+ cpc: 0.5,
+ cpa: 5.0,
+ reach: 65000,
+ engagement: 9200,
+ shares: 180,
+ saves: 95,
+ comments: 320,
+ videoViews: 8500,
+ },
+ {
+ channel: "Customer Support Response Time and Quality",
+ impressions: 35000,
+ clicks: 5500,
+ conversions: 450,
+ cost: 2800,
+ revenue: 9000,
+ roi: 221,
+ ctr: 15.7,
+ cpc: 0.51,
+ cpa: 6.22,
+ reach: 32000,
+ engagement: 4200,
+ shares: 45,
+ saves: 25,
+ comments: 180,
+ videoViews: 0,
+ },
+ {
+ channel: "Sales Funnel Conversion and Lead Generation",
+ impressions: 110000,
+ clicks: 22000,
+ conversions: 1800,
+ cost: 15000,
+ revenue: 36000,
+ roi: 140,
+ ctr: 20.0,
+ cpc: 0.68,
+ cpa: 8.33,
+ reach: 98000,
+ engagement: 18500,
+ shares: 420,
+ saves: 280,
+ comments: 750,
+ videoViews: 3200,
+ },
+ {
+ channel: "User Retention and Churn Rate Analysis",
+ impressions: 80000,
+ clicks: 14000,
+ conversions: 1200,
+ cost: 7200,
+ revenue: 24000,
+ roi: 233,
+ ctr: 17.5,
+ cpc: 0.51,
+ cpa: 6.0,
+ reach: 75000,
+ engagement: 11200,
+ shares: 280,
+ saves: 150,
+ comments: 420,
+ videoViews: 6800,
+ },
+ {
+ channel: "Product Feature Usage and Performance Metrics",
+ impressions: 65000,
+ clicks: 10500,
+ conversions: 900,
+ cost: 5200,
+ revenue: 18000,
+ roi: 246,
+ ctr: 16.2,
+ cpc: 0.5,
+ cpa: 5.78,
+ reach: 58000,
+ engagement: 8500,
+ shares: 320,
+ saves: 180,
+ comments: 650,
+ videoViews: 4200,
+ },
+ {
+ channel: "Market Research and Competitive Analysis",
+ impressions: 40000,
+ clicks: 6500,
+ conversions: 500,
+ cost: 3200,
+ revenue: 10000,
+ roi: 213,
+ ctr: 16.3,
+ cpc: 0.49,
+ cpa: 6.4,
+ reach: 36000,
+ engagement: 5200,
+ shares: 95,
+ saves: 65,
+ comments: 220,
+ videoViews: 1800,
+ },
+ {
+ channel: "Brand Sentiment and Public Relations Impact",
+ impressions: 55000,
+ clicks: 8000,
+ conversions: 650,
+ cost: 4100,
+ revenue: 13000,
+ roi: 217,
+ ctr: 14.5,
+ cpc: 0.51,
+ cpa: 6.31,
+ reach: 48000,
+ engagement: 6800,
+ shares: 520,
+ saves: 280,
+ comments: 950,
+ videoViews: 15000,
+ },
+ ],
+};
+
+// Category key mappings for different datasets
+const categoryKeys = {
+ default: "month",
+ bigLabels: "category",
+ denseTimeline: "period",
+ companyNames: "company",
+ countryData: "country",
+ financialQuarters: "quarter",
+ mixedLengths: "item",
+ edgeCases: "name",
+ minimal: "category",
+ expandCollapseMarketing: "channel",
+};
+
+// 🔥 ACTIVE DATA - For backward compatibility
+const lineChartV2Data = dataVariations.default;
+
+const icons = {
+ desktop: Monitor,
+ mobile: TabletSmartphone,
+ tablet: Calendar,
+ sales: Globe,
+ revenue: Smartphone,
+ profit: Laptop,
+ visitors: Tv,
+ conversions: Watch,
+ users: Monitor,
+ sessions: TabletSmartphone,
+} as const;
+
+/**
+ * # ScrollableLineChart Component Documentation
+ *
+ * The LineChart component is a powerful and flexible tool for visualizing trends over time or comparing continuous data.
+ * It's ideal for:
+ *
+ * - **Time-Series Analysis**: Tracking metrics over days, months, or years.
+ * - **Comparative Analysis**: Comparing the performance of multiple data series.
+ * - **Trend Identification**: Spotting upward or downward trends, and patterns in datasets.
+ *
+ * ## Key Features
+ *
+ * ### Advanced Label Handling
+ * - **Collision Detection**: Automatically detects and prevents overlapping X-axis labels.
+ * - **Intelligent Truncation**: Truncates long labels with an ellipsis (...) to keep the chart clean.
+ * - **Horizontal Offset**: Ensures truncated labels remain horizontally centered for readability.
+ *
+ * ### Interactive & Responsive
+ * - **Interactive Legend**: Allows toggling data series visibility and adapts with a "Show More" feature for many items.
+ * - **Hover Tooltips**: Provides detailed data points on hover for enhanced user interaction.
+ * - **Responsive Design**: Fluidly adjusts to any container size, from small widgets to large dashboards.
+ *
+ * ### Customization
+ * - **Theming**: Six pre-built color palettes to fit your application's design, or use custom colors with `customPalette`.
+ * - **Line Styles**: Supports `linear`, `natural` (smooth), and `step` variants.
+ * - **Styling Options**: Control stroke width, grid visibility, and more.
+ */
+const meta: Meta<LineChartProps<typeof lineChartV2Data>> = {
+ title: "Components/D3Charts/ScrollableLineChart",
+ component: LineChart,
+ parameters: {
+ layout: "centered",
+ docs: {
+ description: {
+ component: `
+## Installation and Basic Usage
+
+\`\`\`tsx
+import { ScrollableLineChart } from '@openuidev/react-ui';
+
+const timeSeriesData = [
+ { month: "January", desktop: 150, mobile: 90 },
+ { month: "February", desktop: 280, mobile: 180 },
+ { month: "March", desktop: 220, mobile: 140 },
+];
+
+// Basic implementation
+<ScrollableLineChart
+ data={timeSeriesData}
+ categoryKey="month"
+ theme="ocean"
+/>
+
+// With custom colors
+<ScrollableLineChart
+ data={timeSeriesData}
+ categoryKey="month"
+ customPalette={["#FF6B6B", "#4ECDC4", "#45B7D1"]}
+/>
+\`\`\`
+
+## Data Structure Requirements
+
+Your data should be an array of objects. Each object must contain:
+- A **category field** (string or number): This will be used for the X-axis labels (e.g., dates, names, etc.).
+- One or more **data series fields** (number): These are the values that will be plotted on the Y-axis. The key of the field will be used as the series name in the legend and tooltip.
+
+\`\`\`tsx
+const salesData = [
+ { date: "2023-01-01", productA: 4000, productB: 2400 },
+ { date: "2023-02-01", productA: 3000, productB: 1398 },
+ { date: "2023-03-01", productA: 2000, productB: 9800 },
+];
+\`\`\`
+
+## Performance Considerations
+- **Data Density**: While the chart can handle many data points, performance may degrade with thousands of points, especially with animations enabled.
+- **Responsiveness**: The chart is fully responsive, but consider the visual clarity of labels on very small screens.
+- **Animation**: Can be disabled via \`isAnimationActive={false}\` for performance-critical applications.
+`,
+ },
+ },
+ },
+ tags: ["!dev", "autodocs"],
+ argTypes: {
+ data: {
+ description: `
+**Required.** An array of data objects for the line chart. Each object should contain:
+- A category identifier (string/number) for the X-axis.
+- One or more numeric values for the Y-axis.
+
+**Best Practices:**
+- Ensure consistent data structure across all objects.
+- For time-series data, ensure items are sorted chronologically.
+`,
+ control: false,
+ table: {
+ type: { summary: "Array<Record<string, string | number>>" },
+ category: "📊 Data Configuration",
+ },
+ },
+ categoryKey: {
+ description:
+ "**Required.** The key in your data object that represents the category for the X-axis (e.g., 'date', 'month').",
+ control: false,
+ table: {
+ type: { summary: "string" },
+ category: "📊 Data Configuration",
+ },
+ },
+ theme: {
+ description:
+ "Specifies the color palette for the chart's lines, tooltips, and legend. Ignored when customPalette is provided.",
+ control: "select",
+ options: ["ocean", "orchid", "emerald", "sunset", "spectrum", "vivid"],
+ table: {
+ defaultValue: { summary: "ocean" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ customPalette: {
+ description:
+ "Custom array of colors to use instead of the theme palette. Overrides the theme prop when provided.",
+ control: "object",
+ table: {
+ type: { summary: "string[]" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ variant: {
+ description: "Determines the line interpolation method, affecting the shape of the lines.",
+ control: "radio",
+ options: ["linear", "natural", "step"],
+ table: {
+ defaultValue: { summary: "natural" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ strokeWidth: {
+ description: "Controls the thickness of the lines in pixels.",
+ control: { type: "number", min: 1, max: 10, step: 1 },
+ table: {
+ defaultValue: { summary: "2" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ grid: {
+ description: "Toggles the visibility of the background grid lines.",
+ control: "boolean",
+ table: {
+ defaultValue: { summary: "true" },
+ category: "📱 Display Options",
+ },
+ },
+ legend: {
+ description: "Toggles the visibility of the chart legend.",
+ control: "boolean",
+ table: {
+ defaultValue: { summary: "true" },
+ category: "📱 Display Options",
+ },
+ },
+ showYAxis: {
+ description: "Toggles the visibility of the Y-axis line and labels.",
+ control: "boolean",
+ table: {
+ defaultValue: { summary: "true" },
+ category: "📱 Display Options",
+ },
+ },
+ isAnimationActive: {
+ description: "Enables or disables the initial loading animation for the lines.",
+ control: "boolean",
+ table: {
+ defaultValue: { summary: "true" },
+ category: "🎬 Animation & Interaction",
+ },
+ },
+ icons: {
+ description:
+ "An object mapping data series keys to React components to be used as icons in the legend.",
+ control: false,
+ table: {
+ type: { summary: "Record<string, React.ReactNode>" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ xAxisLabel: {
+ description: "A label to display below the X-axis.",
+ control: "text",
+ table: {
+ type: { summary: "React.ReactNode" },
+ category: "📱 Display Options",
+ },
+ },
+ yAxisLabel: {
+ description: "A label to display beside the Y-axis.",
+ control: "text",
+ table: {
+ type: { summary: "React.ReactNode" },
+ category: "📱 Display Options",
+ },
+ },
+ className: {
+ description: "Custom CSS class to apply to the chart's container.",
+ control: "text",
+ table: {
+ type: { summary: "string" },
+ category: "Layout & Sizing",
+ },
+ },
+ height: {
+ description: "Sets the height of the chart container.",
+ control: "number",
+ table: {
+ type: { summary: "number" },
+ category: "Layout & Sizing",
+ },
+ },
+ width: {
+ description: "Sets the width of the chart container.",
+ control: "number",
+ table: {
+ type: { summary: "number" },
+ category: "Layout & Sizing",
+ },
+ },
+ },
+} satisfies Meta<typeof LineChart>;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+/**
+ * ## Comprehensive Data Explorer
+ *
+ * This story serves as a comprehensive test suite for the LineChart component.
+ * Use the buttons to switch between various datasets designed to test edge cases in:
+ *
+ * - **Label Collision**: Datasets with long, dense, or overlapping labels.
+ * - **Data Density**: Scenarios with few or many data points.
+ * - **Legend Overflow**: A dataset with many series to test legend expand/collapse functionality.
+ *
+ * It's an excellent tool for developers to see how the chart behaves under different conditions.
+ */
+export const DataExplorer: Story = {
+ name: "🎛️ Comprehensive Data Explorer",
+ args: {
+ data: lineChartV2Data,
+ categoryKey: "month",
+ theme: "ocean",
+ variant: "natural",
+ grid: true,
+ legend: true,
+ isAnimationActive: true,
+ showYAxis: true,
+ strokeWidth: 2,
+ },
+ render: (args: any) => {
+ const [selectedDataType, setSelectedDataType] =
+ useState<keyof typeof dataVariations>("default");
+
+ const currentData = dataVariations[selectedDataType];
+ const currentCategoryKey = categoryKeys[selectedDataType];
+
+ const buttonStyle = {
+ margin: "2px",
+ padding: "6px 12px",
+ fontSize: "12px",
+ border: "1px solid #ddd",
+ borderRadius: "4px",
+ cursor: "pointer",
+ background: "#fff",
+ fontFamily: "monospace",
+ };
+
+ const activeButtonStyle = {
+ ...buttonStyle,
+ background: "#007acc",
+ color: "white",
+ border: "1px solid #007acc",
+ };
+
+ return (
+ <div>
+ <div
+ style={{
+ marginBottom: "16px",
+ padding: "12px",
+ background: "#f8f9fa",
+ borderRadius: "8px",
+ border: "1px solid #e9ecef",
+ width: "600px",
+ }}
+ >
+ <strong>📈 Line Chart Test Suite:</strong>
+ <div style={{ marginTop: "8px", display: "flex", flexWrap: "wrap", gap: "4px" }}>
+ <button
+ onClick={() => setSelectedDataType("default")}
+ style={selectedDataType === "default" ? activeButtonStyle : buttonStyle}
+ >
+ 📅 Default (12 months)
+ </button>
+ <button
+ onClick={() => setSelectedDataType("bigLabels")}
+ style={selectedDataType === "bigLabels" ? activeButtonStyle : buttonStyle}
+ >
+ 🏷️ Big Labels
+ </button>
+ <button
+ onClick={() => setSelectedDataType("denseTimeline")}
+ style={selectedDataType === "denseTimeline" ? activeButtonStyle : buttonStyle}
+ >
+ 📅 Dense Timeline (16 periods)
+ </button>
+ <button
+ onClick={() => setSelectedDataType("companyNames")}
+ style={selectedDataType === "companyNames" ? activeButtonStyle : buttonStyle}
+ >
+ 🏢 Company Names
+ </button>
+ <button
+ onClick={() => setSelectedDataType("countryData")}
+ style={selectedDataType === "countryData" ? activeButtonStyle : buttonStyle}
+ >
+ 🌍 Country Names
+ </button>
+ <button
+ onClick={() => setSelectedDataType("financialQuarters")}
+ style={selectedDataType === "financialQuarters" ? activeButtonStyle : buttonStyle}
+ >
+ 📈 Financial Quarters
+ </button>
+ <button
+ onClick={() => setSelectedDataType("mixedLengths")}
+ style={selectedDataType === "mixedLengths" ? activeButtonStyle : buttonStyle}
+ >
+ 🔤 Mixed Lengths
+ </button>
+ <button
+ onClick={() => setSelectedDataType("edgeCases")}
+ style={selectedDataType === "edgeCases" ? activeButtonStyle : buttonStyle}
+ >
+ 🎯 Edge Cases
+ </button>
+ <button
+ onClick={() => setSelectedDataType("minimal")}
+ style={selectedDataType === "minimal" ? activeButtonStyle : buttonStyle}
+ >
+ 📱 Minimal
+ </button>
+ <button
+ onClick={() => setSelectedDataType("expandCollapseMarketing")}
+ style={
+ selectedDataType === "expandCollapseMarketing" ? activeButtonStyle : buttonStyle
+ }
+ >
+ 🔄 Marketing Channels
+ </button>
+ </div>
+ </div>
+ <Card style={{ width: "600px" }}>
+ <LineChart {...args} data={currentData} categoryKey={currentCategoryKey} />
+ </Card>
+ </div>
+ );
+ },
+};
+
+/**
+ * ## Big Labels
+ *
+ * This story demonstrates the chart's ability to handle very long category labels.
+ * The chart's intelligent truncation and collision detection should be visible here.
+ * X-axis labels that are too long to fit will be gracefully truncated with an ellipsis.
+ */
+export const BigLabelsStory: Story = {
+ name: "🏷️ Big Labels",
+ args: {
+ data: dataVariations.bigLabels as any,
+ categoryKey: "category" as any,
+ theme: "emerald",
+ variant: "natural",
+ grid: true,
+ legend: true,
+ showYAxis: true,
+ strokeWidth: 3,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "600px" }}>
+ <LineChart {...args} />
+ </Card>
+ ),
+};
+
+/**
+ * ## Dense Timeline
+ *
+ * Tests how the chart handles many data points with medium-length period labels.
+ * The chart should enable horizontal scrolling and apply intelligent label truncation.
+ * This scenario is common in financial or analytical dashboards where many time periods are displayed.
+ */
+export const DenseTimelineStory: Story = {
+ name: "📅 Dense Timeline (Many Periods)",
+ args: {
+ data: dataVariations.denseTimeline as any,
+ categoryKey: "period" as any,
+ theme: "sunset",
+ variant: "natural",
+ grid: true,
+ legend: true,
+ isAnimationActive: true,
+ showYAxis: true,
+ strokeWidth: 2,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "500px" }}>
+ <LineChart {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests how the chart handles many data points with medium-length period labels. The chart should enable horizontal scrolling and apply intelligent label truncation.",
+ },
+ },
+ },
+};
+
+/**
+ * ## Stroke and Style Customization
+ *
+ * This story showcases how to customize the appearance of the lines.
+ * You can adjust properties like `strokeWidth` to create different visual effects.
+ */
+export const StrokeCustomizationStory: Story = {
+ name: "🎨 Stroke Customization",
+ args: {
+ data: dataVariations.default as any,
+ categoryKey: "month" as any,
+ theme: "vivid",
+ variant: "natural",
+ grid: true,
+ legend: true,
+ showYAxis: true,
+ },
+ render: (args: any) => (
+ <div style={{ display: "flex", flexDirection: "column", gap: "20px" }}>
+ <div>
+ <h4>Default Lines (strokeWidth: 2)</h4>
+ <Card style={{ width: "500px" }}>
+ <LineChart {...args} strokeWidth={2} />
+ </Card>
+ </div>
+ <div>
+ <h4>Thick Lines (strokeWidth: 4)</h4>
+ <Card style={{ width: "500px" }}>
+ <LineChart {...args} strokeWidth={4} />
+ </Card>
+ </div>
+ </div>
+ ),
+};
+
+/**
+ * ## Line Variants
+ *
+ * Compares the three available line variants:
+ * - **Linear**: Straight lines connecting data points.
+ * - **Natural**: Smooth curves for a softer, organic look.
+ * - **Step**: Stepped lines, useful for showing discrete changes.
+ */
+export const VariantComparisonStory: Story = {
+ name: "📐 Line Variants",
+ args: {
+ data: dataVariations.minimal as any,
+ categoryKey: "category" as any,
+ theme: "orchid",
+ grid: true,
+ legend: true,
+ isAnimationActive: true,
+ showYAxis: true,
+ strokeWidth: 3,
+ },
+ render: (args: any) => (
+ <div style={{ display: "flex", flexDirection: "column", gap: "20px" }}>
+ <div>
+ <h4 style={{ margin: "0 0 8px 0", fontSize: "14px", fontWeight: "600" }}>Linear Variant</h4>
+ <Card style={{ width: "500px" }}>
+ <LineChart {...args} variant="linear" />
+ </Card>
+ </div>
+ <div>
+ <h4 style={{ margin: "0 0 8px 0", fontSize: "14px", fontWeight: "600" }}>
+ Natural Variant (Smooth Curves)
+ </h4>
+ <Card style={{ width: "500px" }}>
+ <LineChart {...args} variant="natural" />
+ </Card>
+ </div>
+ <div>
+ <h4 style={{ margin: "0 0 8px 0", fontSize: "14px", fontWeight: "600" }}>Step Variant</h4>
+ <Card style={{ width: "500px" }}>
+ <LineChart {...args} variant="step" />
+ </Card>
+ </div>
+ </div>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Compares the three available line variants: linear (straight lines), natural (smooth curves), and step (stepped lines).",
+ },
+ },
+ },
+};
+
+/**
+ * ## Custom Palette
+ *
+ * This story demonstrates how to use the customPalette prop to provide your own color scheme
+ * for the chart. This is useful when you need to match your brand colors or create
+ * specific visual themes.
+ */
+export const CustomPaletteStory: Story = {
+ name: "🎨 Custom Palette",
+ args: {
+ data: dataVariations.default as any,
+ categoryKey: "month" as any,
+ customPalette: customColorPalette,
+ theme: "ocean", // This will be overridden by customPalette
+ variant: "natural",
+ grid: true,
+ legend: true,
+ isAnimationActive: true,
+ showYAxis: true,
+ strokeWidth: 2,
+ xAxisLabel: "Month",
+ yAxisLabel: "Traffic",
+ },
+ render: (args: any) => (
+ <div>
+ <div
+ style={{
+ marginBottom: "16px",
+ padding: "12px",
+ background: "#f8f9fa",
+ borderRadius: "8px",
+ border: "1px solid #e9ecef",
+ }}
+ >
+ <h4 style={{ margin: "0 0 8px 0", color: "#333" }}>🎨 Custom Color Palette</h4>
+ <p style={{ margin: "0 0 12px 0", fontSize: "14px", color: "#666" }}>
+ This chart uses a custom color palette instead of the default theme colors.
+ </p>
+ <div style={{ display: "flex", gap: "8px", flexWrap: "wrap" }}>
+ {args.customPalette?.map((color: string, index: number) => (
+ <div
+ key={index}
+ style={{
+ display: "flex",
+ alignItems: "center",
+ gap: "4px",
+ padding: "4px 8px",
+ background: "white",
+ borderRadius: "4px",
+ border: "1px solid #ddd",
+ fontSize: "12px",
+ }}
+ >
+ <div
+ style={{
+ width: "12px",
+ height: "12px",
+ borderRadius: "2px",
+ backgroundColor: color,
+ border: "1px solid #ccc",
+ }}
+ />
+ <span style={{ fontFamily: "monospace" }}>{color}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ <Card style={{ width: "600px" }}>
+ <LineChart {...args} />
+ </Card>
+ </div>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'Demonstrates how to use the `customPalette` prop to provide your own color scheme for the chart. When `customPalette` is provided, it overrides the `theme` prop and uses your specified colors instead of the predefined theme palettes.\n\n**Key Features:**\n- 🎨 **Custom Colors**: Override default theme colors with your own palette\n- 🔄 **Theme Override**: The `theme` prop is ignored when `customPalette` is provided\n- 📊 **Consistent Distribution**: Colors are distributed evenly across data series\n- 🎯 **Brand Matching**: Perfect for matching your application\'s brand colors\n\n**Usage:**\n```tsx\n<LineChart\n data={data}\n categoryKey="month"\n customPalette={["#FF6B6B", "#4ECDC4", "#45B7D1"]}\n // theme prop is ignored when customPalette is provided\n/>\n```',
+ },
+ },
+ },
+};
+
+/**
+ * ## Legend Expand/Collapse
+ *
+ * Tests the legend's expand/collapse functionality with a large number of data series.
+ * The legend should automatically show a "Show More" button when items overflow,
+ * allowing users to toggle between a collapsed and expanded view.
+ */
+export const ExpandCollapseMarketingStory: Story = {
+ name: "🔄 Legend Expand/Collapse",
+ args: {
+ data: dataVariations.expandCollapseMarketing as any,
+ categoryKey: "channel" as any,
+ theme: "spectrum",
+ variant: "natural",
+ grid: true,
+ legend: true,
+ isAnimationActive: true,
+ showYAxis: true,
+ strokeWidth: 2,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "600px" }}>
+ <LineChart {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests the legend expand/collapse functionality with 12 marketing channels that have long descriptive names. The legend should automatically show a 'Show More' button when items overflow the container width, allowing users to toggle between collapsed and expanded states.",
+ },
+ },
+ },
+};
+
+/**
+ * ## Responsive Behavior Demo
+ *
+ * This story demonstrates the responsive capabilities of the LineChart. Drag the handles
+ * on the container to resize it and observe how the chart adapts.
+ *
+ * **Responsive Features:**
+ * - **Label Truncation**: More aggressive truncation on smaller container widths.
+ * - **Layout Adaptation**: Chart elements adjust to fit the available space.
+ * - **Legend Behavior**: The legend may wrap or show expand/collapse buttons as needed.
+ */
+export const ResponsiveBehaviorDemo: Story = {
+ name: "📱 Responsive Behavior Demo",
+ args: {
+ data: dataVariations.bigLabels as any,
+ categoryKey: "category" as any,
+ theme: "sunset",
+ variant: "natural",
+ grid: true,
+ legend: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ strokeWidth: 2,
+ },
+ render: (args: any) => {
+ const [dimensions, setDimensions] = useState<{ width: number; height: number | string }>({
+ width: 700,
+ height: "auto",
+ });
+
+ const handleMouseDown = (e: React.MouseEvent<HTMLDivElement>, handle: string) => {
+ e.preventDefault();
+ e.stopPropagation();
+ const startX = e.clientX;
+ const startY = e.clientY;
+ const startWidth = dimensions.width;
+ const startHeight = (e.currentTarget.parentElement as HTMLElement).offsetHeight;
+
+ const doDrag = (e: MouseEvent) => {
+ const dx = e.clientX - startX;
+ const dy = e.clientY - startY;
+ let newWidth = startWidth;
+ let newHeight = startHeight;
+
+ if (handle.includes("e")) newWidth = startWidth + dx;
+ if (handle.includes("w")) newWidth = startWidth - dx;
+ if (handle.includes("s")) newHeight = startHeight + dy;
+ if (handle.includes("n")) newHeight = startHeight - dy;
+
+ setDimensions({
+ width: Math.max(300, newWidth),
+ height: "auto",
+ });
+ };
+
+ const stopDrag = () => {
+ document.removeEventListener("mousemove", doDrag);
+ document.removeEventListener("mouseup", stopDrag);
+ };
+
+ document.addEventListener("mousemove", doDrag);
+ document.addEventListener("mouseup", stopDrag);
+ };
+
+ const handleStyle: React.CSSProperties = {
+ position: "absolute",
+ background: "#3b82f6",
+ opacity: 0.6,
+ zIndex: 10,
+ transition: "opacity 0.2s ease",
+ };
+
+ return (
+ <div style={{ padding: "20px" }}>
+ <div style={{ marginBottom: "20px" }}>
+ <h3 style={{ margin: "0 0 8px 0", fontSize: "18px", fontWeight: "600" }}>
+ Responsive Behavior Demonstration
+ </h3>
+ <p style={{ margin: "0 0 12px 0", color: "#666", fontSize: "14px" }}>
+ Drag the edges or corners of the container below to see how the chart adapts
+ </p>
+ <div
+ style={{
+ padding: "12px",
+ backgroundColor: "#e3f2fd",
+ borderRadius: "6px",
+ fontSize: "12px",
+ color: "#1565c0",
+ }}
+ >
+ <strong>🎯 Try This:</strong> Resize the container to see automatic label truncation and
+ layout adjustments.
+ </div>
+ </div>
+
+ <Card
+ style={{
+ position: "relative",
+ width: `${dimensions.width}px`,
+ height:
+ typeof dimensions.height === "number" ? `${dimensions.height}px` : dimensions.height,
+ border: "2px dashed #9ca3af",
+ padding: "20px",
+ boxSizing: "border-box",
+ overflow: "hidden",
+ cursor: "default",
+ }}
+ >
+ <LineChart {...args} />
+
+ {/* Resize Handles */}
+ <div
+ style={{ ...handleStyle, top: -2, left: 0, right: 0, height: 12, cursor: "ns-resize" }}
+ onMouseDown={(e) => handleMouseDown(e, "n")}
+ />
+ <div
+ style={{
+ ...handleStyle,
+ bottom: -2,
+ left: 0,
+ right: 0,
+ height: 12,
+ cursor: "ns-resize",
+ }}
+ onMouseDown={(e) => handleMouseDown(e, "s")}
+ />
+ <div
+ style={{ ...handleStyle, top: 0, bottom: 0, left: -2, width: 12, cursor: "ew-resize" }}
+ onMouseDown={(e) => handleMouseDown(e, "w")}
+ />
+ <div
+ style={{ ...handleStyle, top: 0, bottom: 0, right: -2, width: 12, cursor: "ew-resize" }}
+ onMouseDown={(e) => handleMouseDown(e, "e")}
+ />
+
+ {/* Corner Handles */}
+ <div
+ style={{
+ ...handleStyle,
+ top: -2,
+ left: -2,
+ width: 20,
+ height: 20,
+ cursor: "nwse-resize",
+ borderRadius: "2px",
+ }}
+ onMouseDown={(e) => handleMouseDown(e, "nw")}
+ />
+ <div
+ style={{
+ ...handleStyle,
+ top: -2,
+ right: -2,
+ width: 20,
+ height: 20,
+ cursor: "nesw-resize",
+ borderRadius: "2px",
+ }}
+ onMouseDown={(e) => handleMouseDown(e, "ne")}
+ />
+ <div
+ style={{
+ ...handleStyle,
+ bottom: -2,
+ right: -2,
+ width: 20,
+ height: 20,
+ cursor: "nwse-resize",
+ borderRadius: "2px",
+ }}
+ onMouseDown={(e) => handleMouseDown(e, "se")}
+ />
+
+ {/* Dimension Display */}
+ <div
+ style={{
+ position: "absolute",
+ bottom: 8,
+ right: 8,
+ background: "rgba(0,0,0,0.8)",
+ color: "white",
+ padding: "4px 8px",
+ borderRadius: "4px",
+ fontSize: "11px",
+ fontFamily: "monospace",
+ fontWeight: "500",
+ }}
+ >
+ {dimensions.width}px ×{" "}
+ {typeof dimensions.height === "number" ? `${dimensions.height}px` : "auto"}
+ </div>
+ </Card>
+ </div>
+ );
+ },
+};
diff --git a/packages/react-ui/src/components/D3Charts/LineChart/stories/lineChartCondensed.stories.tsx b/packages/react-ui/src/components/D3Charts/LineChart/stories/lineChartCondensed.stories.tsx
new file mode 100644
index 000000000..0e0a8763c
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/LineChart/stories/lineChartCondensed.stories.tsx
@@ -0,0 +1,1511 @@
+// Copy of Charts/LineChartCondensed/stories/lineChartCondensed.stories.tsx with only the chart import and the title changed:
+// the same args and renders, rendering the D3Charts chart via
+// ../../stories/rechartsStoryAdapters.
+import type { Meta, StoryObj } from "@storybook/react";
+import {
+ Calendar,
+ Globe,
+ Laptop,
+ Monitor,
+ Smartphone,
+ TabletSmartphone,
+ Tv,
+ Watch,
+} from "lucide-react";
+import { useState } from "react";
+import { Card } from "../../../Card";
+import { LineChartCondensed, LineChartCondensedProps } from "../../stories/rechartsStoryAdapters";
+
+// 🔥 COMPREHENSIVE DATA VARIATIONS - Designed to test various scenarios
+const dataVariations = {
+ default: [
+ { month: "January", desktop: 150, mobile: 90, tablet: 120 },
+ { month: "February", desktop: 280, mobile: 180, tablet: 140 },
+ { month: "March", desktop: 220, mobile: 140, tablet: 160 },
+ { month: "April", desktop: 180, mobile: 160, tablet: 180 },
+ { month: "May", desktop: 250, mobile: 120, tablet: 140 },
+ { month: "June", desktop: 300, mobile: 180, tablet: 160 },
+ { month: "July", desktop: 350, mobile: 220, tablet: 180 },
+ { month: "August", desktop: 400, mobile: 240, tablet: 200 },
+ { month: "September", desktop: 450, mobile: 260, tablet: 220 },
+ { month: "October", desktop: 500, mobile: 280, tablet: 240 },
+ { month: "November", desktop: 550, mobile: 300, tablet: 260 },
+ { month: "December", desktop: 600, mobile: 320, tablet: 280 },
+ ],
+ // 🏷️ BIG LABELS - Testing angled tick labels
+ bigLabels: [
+ {
+ category: "Very Long Category Name That Should Be Truncated",
+ sales: 150,
+ revenue: 90,
+ profit: 120,
+ },
+ {
+ category: "Another Extremely Long Label That Causes Collisions",
+ sales: 280,
+ revenue: 180,
+ profit: 140,
+ },
+ {
+ category: "Super Duper Long Category Name That Tests Truncation",
+ sales: 220,
+ revenue: 140,
+ profit: 160,
+ },
+ {
+ category: "Incredibly Long Text That Should Trigger Collision Detection",
+ sales: 180,
+ revenue: 160,
+ profit: 180,
+ },
+ {
+ category: "Maximum Length Category Name That Tests All Edge Cases",
+ sales: 250,
+ revenue: 120,
+ profit: 140,
+ },
+ {
+ category: "Extra Long Business Category Name With Many Words",
+ sales: 300,
+ revenue: 180,
+ profit: 160,
+ },
+ {
+ category: "Comprehensive Long Label For Testing Horizontal Offset",
+ sales: 350,
+ revenue: 220,
+ profit: 180,
+ },
+ {
+ category: "Extended Category Name That Pushes Truncation Limits",
+ sales: 400,
+ revenue: 240,
+ profit: 200,
+ },
+ ],
+ // 📅 DENSE TIMELINE - Many items with medium-length labels
+ denseTimeline: [
+ { period: "Q1 2022 Jan-Mar", visitors: 120, conversions: 15, revenue: 1200 },
+ { period: "Q1 2022 Apr-Jun", visitors: 150, conversions: 22, revenue: 1800 },
+ { period: "Q2 2022 Jul-Sep", visitors: 180, conversions: 28, revenue: 2100 },
+ { period: "Q2 2022 Oct-Dec", visitors: 200, conversions: 35, revenue: 2500 },
+ { period: "Q3 2023 Jan-Mar", visitors: 160, conversions: 18, revenue: 1600 },
+ { period: "Q3 2023 Apr-Jun", visitors: 190, conversions: 32, revenue: 2300 },
+ { period: "Q4 2023 Jul-Sep", visitors: 220, conversions: 40, revenue: 2800 },
+ { period: "Q4 2023 Oct-Dec", visitors: 240, conversions: 45, revenue: 3200 },
+ { period: "Q1 2024 Jan-Mar", visitors: 210, conversions: 38, revenue: 2700 },
+ { period: "Q1 2024 Apr-Jun", visitors: 230, conversions: 42, revenue: 3000 },
+ { period: "Q2 2024 Jul-Sep", visitors: 250, conversions: 48, revenue: 3400 },
+ { period: "Q2 2024 Oct-Dec", visitors: 270, conversions: 52, revenue: 3800 },
+ { period: "Q3 2024 Jan-Mar", visitors: 260, conversions: 50, revenue: 3600 },
+ { period: "Q3 2024 Apr-Jun", visitors: 280, conversions: 55, revenue: 4000 },
+ { period: "Q4 2024 Jul-Sep", visitors: 300, conversions: 60, revenue: 4300 },
+ { period: "Q4 2024 Oct-Dec", visitors: 290, conversions: 58, revenue: 4100 },
+ ],
+ // 🏢 COMPANY NAMES - Real-world long business names
+ companyNames: [
+ { company: "Apple Inc.", revenue: 394328000000, profit: 99803000000, marketCap: 3500000000000 },
+ {
+ company: "Microsoft Corporation",
+ revenue: 211915000000,
+ profit: 83383000000,
+ marketCap: 2800000000000,
+ },
+ {
+ company: "Alphabet Inc. (Google)",
+ revenue: 307394000000,
+ profit: 76033000000,
+ marketCap: 2100000000000,
+ },
+ {
+ company: "Amazon.com Inc.",
+ revenue: 574785000000,
+ profit: 33364000000,
+ marketCap: 1600000000000,
+ },
+ {
+ company: "Tesla Motors Inc.",
+ revenue: 96773000000,
+ profit: 15000000000,
+ marketCap: 800000000000,
+ },
+ {
+ company: "Meta Platforms Inc.",
+ revenue: 134902000000,
+ profit: 39370000000,
+ marketCap: 900000000000,
+ },
+ {
+ company: "NVIDIA Corporation",
+ revenue: 60922000000,
+ profit: 29760000000,
+ marketCap: 1800000000000,
+ },
+ {
+ company: "Berkshire Hathaway Inc.",
+ revenue: 364482000000,
+ profit: 96223000000,
+ marketCap: 780000000000,
+ },
+ ],
+ // 🌍 COUNTRY NAMES - Geographic labels with varying lengths
+ countryData: [
+ { country: "United States of America", population: 331900000, gdp: 26900000000000 },
+ { country: "People's Republic of China", population: 1412000000, gdp: 17700000000000 },
+ { country: "Federal Republic of Germany", population: 83200000, gdp: 4300000000000 },
+ { country: "United Kingdom of Great Britain", population: 67500000, gdp: 3100000000000 },
+ { country: "French Republic", population: 68000000, gdp: 2900000000000 },
+ { country: "Republic of India", population: 1380000000, gdp: 3700000000000 },
+ { country: "Federative Republic of Brazil", population: 215000000, gdp: 2100000000000 },
+ { country: "Russian Federation", population: 146000000, gdp: 1800000000000 },
+ ],
+ // 📈 FINANCIAL QUARTERS - Testing medium-density scenarios
+ financialQuarters: [
+ { quarter: "Q1 FY2022", revenue: 1200000, expenses: 800000, profit: 400000 },
+ { quarter: "Q2 FY2022", revenue: 1500000, expenses: 950000, profit: 550000 },
+ { quarter: "Q3 FY2022", revenue: 1800000, expenses: 1100000, profit: 700000 },
+ { quarter: "Q4 FY2022", revenue: 2000000, expenses: 1300000, profit: 700000 },
+ { quarter: "Q1 FY2023", revenue: 2200000, expenses: 1400000, profit: 800000 },
+ { quarter: "Q2 FY2023", revenue: 2500000, expenses: 1600000, profit: 900000 },
+ { quarter: "Q3 FY2023", revenue: 2800000, expenses: 1800000, profit: 1000000 },
+ { quarter: "Q4 FY2023", revenue: 3000000, expenses: 1900000, profit: 1100000 },
+ ],
+ // 🔤 MIXED LENGTHS - Testing various label length scenarios
+ mixedLengths: [
+ { item: "A", valueA: 100, valueB: 80 },
+ { item: "Short", valueA: 150, valueB: 120 },
+ { item: "Medium Length Item", valueA: 200, valueB: 160 },
+ { item: "Very Long Item Name That Tests Truncation", valueA: 250, valueB: 200 },
+ { item: "B", valueA: 180, valueB: 140 },
+ { item: "Another Really Long Category Name", valueA: 220, valueB: 180 },
+ { item: "XL", valueA: 190, valueB: 150 },
+ ],
+ // 🎯 EDGE CASES - Extreme scenarios
+ edgeCases: [
+ {
+ name: "SinglePointDataSetForTestingEdgeCasesInCollisionDetectionAndLabelTruncationFunctionality",
+ value: 500,
+ },
+ {
+ name: "SecondExtremelyLongDataPointNameThatShouldDefinitelyTriggerTruncationMechanisms",
+ value: 600,
+ },
+ ],
+ // 📱 MINIMAL - Small dataset for baseline testing
+ minimal: [
+ { category: "Mobile Devices", users: 150, sessions: 90 },
+ { category: "Desktop Computers", users: 280, sessions: 180 },
+ { category: "Tablet Devices", users: 220, sessions: 140 },
+ ],
+};
+
+// Category key mappings for different datasets
+const categoryKeys = {
+ default: "month",
+ bigLabels: "category",
+ denseTimeline: "period",
+ companyNames: "company",
+ countryData: "country",
+ financialQuarters: "quarter",
+ mixedLengths: "item",
+ edgeCases: "name",
+ minimal: "category",
+};
+
+// 🔥 ACTIVE DATA - For backward compatibility
+const lineChartCondensedData = dataVariations.default;
+
+const icons = {
+ desktop: Monitor,
+ mobile: TabletSmartphone,
+ tablet: Calendar,
+ sales: Globe,
+ revenue: Smartphone,
+ profit: Laptop,
+ visitors: Tv,
+ conversions: Watch,
+ users: Monitor,
+ sessions: TabletSmartphone,
+ expenses: Calendar,
+ marketCap: Globe,
+ population: Monitor,
+ gdp: Smartphone,
+ valueA: Monitor,
+ valueB: TabletSmartphone,
+ value: Calendar,
+} as const;
+
+/**
+ * # LineChart Component Documentation
+ *
+ * The LineChart is a compact chart designed for space-constrained layouts
+ * like dashboards and sidebars. It's ideal for:
+ *
+ * - **Compact Dashboards**: Showing multiple trends in limited space
+ * - **Sidebar Analytics**: Quick trend visualization without taking up too much room
+ * - **Dense Data Display**: Efficiently showing many data points in a small area
+ *
+ * ## Key Features
+ *
+ * ### Space-Efficient Design
+ * - **Compact Height**: Default 200px height for tight layouts
+ * - **Minimal Legend**: Legend is compact and doesn't take up vertical space
+ * - **Adjustable Tick Variants**: Choose between horizontal or angled labels for better space usage
+ *
+ * ### Flexible Label Handling
+ * - **Single Line Ticks**: Horizontal labels with automatic collision detection
+ * - **Angled Ticks**: Optimal rotation angle for longer labels that need more space
+ * - **Smart Angle Calculation**: Automatically calculates optimal rotation based on label width
+ *
+ * ### Interactive & Responsive
+ * - **Hover Tooltips**: Standard tooltip showing all data series
+ * - **Responsive Design**: Adapts fluidly to its container's size
+ * - **Line Customization**: Control line thickness with strokeWidth prop
+ *
+ * ### Customization
+ * - **Theming**: Comes with six pre-built color palettes
+ * - **Line Styles**: Supports `linear`, `natural` (smooth), and `step` interpolation
+ * - **Styling Options**: Control grid visibility, axes, stroke width, and more
+ */
+const meta: Meta<LineChartCondensedProps<typeof lineChartCondensedData>> = {
+ title: "Components/D3Charts/LineChart",
+ component: LineChartCondensed,
+ parameters: {
+ layout: "centered",
+ docs: {
+ description: {
+ component: `
+## Installation and Basic Usage
+
+\`\`\`tsx
+import { LineChart } from '@openuidev/react-ui';
+
+const trafficData = [
+ { date: "2023-01-01", visits: 2200 },
+ { date: "2023-01-02", visits: 2500 },
+ { date: "2023-01-03", visits: 2300 },
+];
+
+// Basic implementation
+<LineChart
+ data={trafficData}
+ categoryKey="date"
+ theme="ocean"
+ height={200}
+/>
+\`\`\`
+
+## Data Structure Requirements
+
+Your data should be an array of objects. Each object must contain:
+- A **category field** (string or number): This will be used for the X-axis labels (e.g., dates, names, etc.).
+- One or more **data series fields** (number): These are the values that will be plotted on the Y-axis.
+
+\`\`\`tsx
+const salesData = [
+ { month: "January", desktop: 150, mobile: 90 },
+ { month: "February", desktop: 280, mobile: 180 },
+ { month: "March", desktop: 220, mobile: 140 },
+];
+\`\`\`
+
+## Key Differences from LineChart
+
+- **Compact**: Designed for smaller spaces with a default height of 200px
+- **No Interactive Legend**: Legend is simplified and non-interactive
+- **Tick Variants**: Supports both horizontal (singleLine) and angled labels
+- **Performance**: Optimized for quick rendering in dashboards
+- **Stroke Width Control**: Customize line thickness with strokeWidth prop
+
+## Performance Considerations
+- **Data Density**: For very large datasets, consider disabling animations
+- **Responsiveness**: The chart is fully responsive, but test label visibility on small screens
+- **Animation**: Controlled via \`isAnimationActive={false}\`
+`,
+ },
+ },
+ },
+ tags: ["!dev", "autodocs"],
+ argTypes: {
+ data: {
+ description: `
+**Required.** An array of data objects for the line chart. Each object should contain:
+- A category identifier (string/number) for the X-axis.
+- One or more numeric values for the Y-axis.
+`,
+ control: false,
+ table: {
+ type: { summary: "Array<Record<string, string | number>>" },
+ category: "📊 Data Configuration",
+ },
+ },
+ categoryKey: {
+ description:
+ "**Required.** The key in your data object that represents the category for the X-axis.",
+ control: false,
+ table: {
+ type: { summary: "string" },
+ category: "📊 Data Configuration",
+ },
+ },
+ theme: {
+ description:
+ "Specifies the color palette for the chart's lines and tooltips. Ignored when customPalette is provided.",
+ control: "select",
+ options: ["ocean", "orchid", "emerald", "sunset", "spectrum", "vivid"],
+ table: {
+ defaultValue: { summary: "ocean" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ customPalette: {
+ description:
+ "Custom array of colors to use instead of the theme palette. Overrides the theme prop when provided.",
+ control: "object",
+ table: {
+ type: { summary: "string[]" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ variant: {
+ description: "Determines the line interpolation method, affecting the shape of the curves.",
+ control: "radio",
+ options: ["linear", "natural", "step"],
+ table: {
+ defaultValue: { summary: "natural" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ tickVariant: {
+ description:
+ "X-axis tick label style. Choose between 'singleLine' (horizontal) or 'angled' (rotated at optimal angle).",
+ control: "radio",
+ options: ["singleLine", "angled"],
+ table: {
+ defaultValue: { summary: "singleLine" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ strokeWidth: {
+ description: "Line thickness in pixels. Controls the width of the line strokes.",
+ control: { type: "number", min: 1, max: 10, step: 0.5 },
+ table: {
+ defaultValue: { summary: "2" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ icons: {
+ description:
+ "An object mapping data series keys to React components to be used as icons in the legend.",
+ control: false,
+ table: {
+ type: { summary: "Record<string, React.ReactNode>" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ grid: {
+ description: "Toggles the visibility of the background grid lines.",
+ control: "boolean",
+ table: {
+ defaultValue: { summary: "true" },
+ category: "📱 Display Options",
+ },
+ },
+ showYAxis: {
+ description: "Toggles the visibility of the Y-axis line and labels.",
+ control: "boolean",
+ table: {
+ defaultValue: { summary: "true" },
+ category: "📱 Display Options",
+ },
+ },
+ xAxisLabel: {
+ description: "A label to display below the X-axis.",
+ control: "text",
+ table: {
+ type: { summary: "React.ReactNode" },
+ category: "📱 Display Options",
+ },
+ },
+ yAxisLabel: {
+ description: "A label to display beside the Y-axis.",
+ control: "text",
+ table: {
+ type: { summary: "React.ReactNode" },
+ category: "📱 Display Options",
+ },
+ },
+ isAnimationActive: {
+ description: "Enables or disables the initial loading animation for the lines.",
+ control: "boolean",
+ table: {
+ defaultValue: { summary: "false" },
+ category: "🎬 Animation & Interaction",
+ },
+ },
+ height: {
+ description: "Sets a fixed height for the chart container in pixels.",
+ control: "number",
+ table: {
+ defaultValue: { summary: "200" },
+ type: { summary: "number" },
+ category: "Layout & Sizing",
+ },
+ },
+ width: {
+ description: "Sets a fixed width for the chart container in pixels.",
+ control: "number",
+ table: {
+ type: { summary: "number" },
+ category: "Layout & Sizing",
+ },
+ },
+ className: {
+ description: "Custom CSS class to apply to the chart's container.",
+ control: "text",
+ table: {
+ type: { summary: "string" },
+ category: "Layout & Sizing",
+ },
+ },
+ },
+} satisfies Meta<typeof LineChartCondensed>;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+/**
+ * ## Comprehensive Data Explorer
+ *
+ * This story serves as a comprehensive test suite for the LineChartCondensed component.
+ * Use the buttons to switch between various datasets designed to test edge cases in:
+ *
+ * - **Label Handling**: Datasets with long, dense, or overlapping labels.
+ * - **Data Density**: Scenarios with few or many data points.
+ * - **Tick Variants**: Toggle between horizontal and angled label orientations.
+ *
+ * It's an excellent tool for developers to see how the chart behaves under different conditions.
+ */
+export const DataExplorer: Story = {
+ name: "🎛️ Comprehensive Data Explorer",
+ args: {
+ data: lineChartCondensedData,
+ categoryKey: "month",
+ theme: "ocean",
+ variant: "natural",
+ tickVariant: "singleLine",
+ strokeWidth: 2,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ xAxisLabel: "Time Period",
+ yAxisLabel: "Values",
+ height: 200,
+ },
+ render: (args: any) => {
+ const [selectedDataType, setSelectedDataType] =
+ useState<keyof typeof dataVariations>("default");
+ const [tickVariant, setTickVariant] = useState<"singleLine" | "angled">("singleLine");
+
+ const currentData = dataVariations[selectedDataType];
+ const currentCategoryKey = categoryKeys[selectedDataType];
+
+ const buttonStyle = {
+ margin: "2px",
+ padding: "6px 12px",
+ fontSize: "12px",
+ border: "1px solid #ddd",
+ borderRadius: "4px",
+ cursor: "pointer",
+ background: "#fff",
+ fontFamily: "monospace",
+ };
+
+ const activeButtonStyle = {
+ ...buttonStyle,
+ background: "#007acc",
+ color: "white",
+ border: "1px solid #007acc",
+ };
+
+ return (
+ <div>
+ <div
+ style={{
+ marginBottom: "16px",
+ padding: "12px",
+ background: "#f8f9fa",
+ borderRadius: "8px",
+ border: "1px solid #e9ecef",
+ width: "600px",
+ }}
+ >
+ <strong>🏷️ Dataset Selection:</strong>
+ <div style={{ marginTop: "8px", display: "flex", flexWrap: "wrap", gap: "4px" }}>
+ <button
+ onClick={() => setSelectedDataType("default")}
+ style={selectedDataType === "default" ? activeButtonStyle : buttonStyle}
+ >
+ 📅 Default (12 months)
+ </button>
+ <button
+ onClick={() => setSelectedDataType("bigLabels")}
+ style={selectedDataType === "bigLabels" ? activeButtonStyle : buttonStyle}
+ >
+ 🏷️ Big Labels
+ </button>
+ <button
+ onClick={() => setSelectedDataType("denseTimeline")}
+ style={selectedDataType === "denseTimeline" ? activeButtonStyle : buttonStyle}
+ >
+ 📅 Dense Timeline (16)
+ </button>
+ <button
+ onClick={() => setSelectedDataType("companyNames")}
+ style={selectedDataType === "companyNames" ? activeButtonStyle : buttonStyle}
+ >
+ 🏢 Company Names
+ </button>
+ <button
+ onClick={() => setSelectedDataType("countryData")}
+ style={selectedDataType === "countryData" ? activeButtonStyle : buttonStyle}
+ >
+ 🌍 Country Names
+ </button>
+ <button
+ onClick={() => setSelectedDataType("financialQuarters")}
+ style={selectedDataType === "financialQuarters" ? activeButtonStyle : buttonStyle}
+ >
+ 📈 Financial Quarters
+ </button>
+ <button
+ onClick={() => setSelectedDataType("mixedLengths")}
+ style={selectedDataType === "mixedLengths" ? activeButtonStyle : buttonStyle}
+ >
+ 🔤 Mixed Lengths
+ </button>
+ <button
+ onClick={() => setSelectedDataType("edgeCases")}
+ style={selectedDataType === "edgeCases" ? activeButtonStyle : buttonStyle}
+ >
+ 🎯 Edge Cases
+ </button>
+ <button
+ onClick={() => setSelectedDataType("minimal")}
+ style={selectedDataType === "minimal" ? activeButtonStyle : buttonStyle}
+ >
+ 📱 Minimal (3 items)
+ </button>
+ </div>
+ <div style={{ marginTop: "12px" }}>
+ <strong>📐 Tick Variant:</strong>
+ <div style={{ marginTop: "8px", display: "flex", gap: "4px" }}>
+ <button
+ onClick={() => setTickVariant("singleLine")}
+ style={tickVariant === "singleLine" ? activeButtonStyle : buttonStyle}
+ >
+ Horizontal Labels
+ </button>
+ <button
+ onClick={() => setTickVariant("angled")}
+ style={tickVariant === "angled" ? activeButtonStyle : buttonStyle}
+ >
+ Angled Labels
+ </button>
+ </div>
+ </div>
+ <div
+ style={{ marginTop: "12px", fontSize: "12px", color: "#666", fontFamily: "monospace" }}
+ >
+ <div>
+ <strong>Current Dataset:</strong> {selectedDataType}
+ </div>
+ <div>
+ <strong>Items:</strong> {currentData.length} | <strong>Category Key:</strong>{" "}
+ {currentCategoryKey} | <strong>Tick:</strong> {tickVariant}
+ </div>
+ </div>
+ </div>
+ <Card style={{ width: "600px" }}>
+ <LineChartCondensed
+ {...args}
+ data={currentData}
+ categoryKey={currentCategoryKey}
+ tickVariant={tickVariant}
+ />
+ </Card>
+ </div>
+ );
+ },
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "**🎛️ Interactive Explorer:** This story allows you to explore different datasets and tick variants interactively. Use the buttons to switch between:\n\n**Datasets:**\n- **Default**: Standard 12-month data\n- **Big Labels**: Extremely long category names\n- **Dense Timeline**: Many items with medium-length labels\n- **Company Names**: Real-world business names\n- **Country Names**: Geographic labels\n- **Financial Quarters**: Quarterly financial data\n- **Mixed Lengths**: Combination of short and long labels\n- **Edge Cases**: Extreme scenarios\n- **Minimal**: Baseline with 3 items\n\n**Tick Variants:**\n- **Horizontal Labels**: Standard single-line labels with collision detection\n- **Angled Labels**: Rotated labels for better space utilization",
+ },
+ },
+ },
+};
+
+/**
+ * ## Large Dataset with Sidebar Tooltip
+ *
+ * This story demonstrates the sidebar tooltip feature that appears when you have
+ * more than 10 data series. Click on any point in the chart to see the sidebar
+ * tooltip in action. This provides a better UX for viewing many data series at once.
+ */
+export const LargeDatasetWithSidebarTooltip: Story = {
+ name: "🎯 Large Dataset (>10 Series) - Sidebar Tooltip",
+ args: {
+ data: [
+ {
+ month: "Jan",
+ line1: 120,
+ line2: 150,
+ line3: 180,
+ line4: 200,
+ line5: 160,
+ line6: 190,
+ line7: 220,
+ line8: 240,
+ line9: 210,
+ line10: 230,
+ line11: 250,
+ line12: 270,
+ line13: 260,
+ line14: 280,
+ line15: 300,
+ },
+ {
+ month: "Feb",
+ line1: 140,
+ line2: 170,
+ line3: 200,
+ line4: 220,
+ line5: 180,
+ line6: 210,
+ line7: 240,
+ line8: 260,
+ line9: 230,
+ line10: 250,
+ line11: 270,
+ line12: 290,
+ line13: 280,
+ line14: 300,
+ line15: 320,
+ },
+ {
+ month: "Mar",
+ line1: 160,
+ line2: 190,
+ line3: 220,
+ line4: 240,
+ line5: 200,
+ line6: 230,
+ line7: 260,
+ line8: 280,
+ line9: 250,
+ line10: 270,
+ line11: 290,
+ line12: 310,
+ line13: 300,
+ line14: 320,
+ line15: 340,
+ },
+ {
+ month: "Apr",
+ line1: 180,
+ line2: 210,
+ line3: 240,
+ line4: 260,
+ line5: 220,
+ line6: 250,
+ line7: 280,
+ line8: 300,
+ line9: 270,
+ line10: 290,
+ line11: 310,
+ line12: 330,
+ line13: 320,
+ line14: 340,
+ line15: 360,
+ },
+ {
+ month: "May",
+ line1: 200,
+ line2: 230,
+ line3: 260,
+ line4: 280,
+ line5: 240,
+ line6: 270,
+ line7: 300,
+ line8: 320,
+ line9: 290,
+ line10: 310,
+ line11: 330,
+ line12: 350,
+ line13: 340,
+ line14: 360,
+ line15: 380,
+ },
+ {
+ month: "Jun",
+ line1: 220,
+ line2: 250,
+ line3: 280,
+ line4: 300,
+ line5: 260,
+ line6: 290,
+ line7: 320,
+ line8: 340,
+ line9: 310,
+ line10: 330,
+ line11: 350,
+ line12: 370,
+ line13: 360,
+ line14: 380,
+ line15: 400,
+ },
+ {
+ month: "Jul",
+ line1: 240,
+ line2: 270,
+ line3: 300,
+ line4: 320,
+ line5: 280,
+ line6: 310,
+ line7: 340,
+ line8: 360,
+ line9: 330,
+ line10: 350,
+ line11: 370,
+ line12: 390,
+ line13: 380,
+ line14: 400,
+ line15: 420,
+ },
+ {
+ month: "Aug",
+ line1: 260,
+ line2: 290,
+ line3: 320,
+ line4: 340,
+ line5: 300,
+ line6: 330,
+ line7: 360,
+ line8: 380,
+ line9: 350,
+ line10: 370,
+ line11: 390,
+ line12: 410,
+ line13: 400,
+ line14: 420,
+ line15: 440,
+ },
+ {
+ month: "Sep",
+ line1: 280,
+ line2: 310,
+ line3: 340,
+ line4: 360,
+ line5: 320,
+ line6: 350,
+ line7: 380,
+ line8: 400,
+ line9: 370,
+ line10: 390,
+ line11: 410,
+ line12: 430,
+ line13: 420,
+ line14: 440,
+ line15: 460,
+ },
+ {
+ month: "Oct",
+ line1: 300,
+ line2: 330,
+ line3: 360,
+ line4: 380,
+ line5: 340,
+ line6: 370,
+ line7: 400,
+ line8: 420,
+ line9: 390,
+ line10: 410,
+ line11: 430,
+ line12: 450,
+ line13: 440,
+ line14: 460,
+ line15: 480,
+ },
+ {
+ month: "Nov",
+ line1: 320,
+ line2: 350,
+ line3: 380,
+ line4: 400,
+ line5: 360,
+ line6: 390,
+ line7: 420,
+ line8: 440,
+ line9: 410,
+ line10: 430,
+ line11: 450,
+ line12: 470,
+ line13: 460,
+ line14: 480,
+ line15: 500,
+ },
+ {
+ month: "Dec",
+ line1: 340,
+ line2: 370,
+ line3: 400,
+ line4: 420,
+ line5: 380,
+ line6: 410,
+ line7: 440,
+ line8: 460,
+ line9: 430,
+ line10: 450,
+ line11: 470,
+ line12: 490,
+ line13: 480,
+ line14: 500,
+ line15: 520,
+ },
+ ] as any,
+ categoryKey: "month" as any,
+ theme: "ocean",
+ variant: "natural",
+ tickVariant: "singleLine",
+ strokeWidth: 2,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ xAxisLabel: "Months",
+ yAxisLabel: "Performance Metrics",
+ height: 300,
+ },
+ render: (args: any) => (
+ <div>
+ <div
+ style={{
+ marginBottom: "16px",
+ padding: "16px",
+ background: "#e3f2fd",
+ borderRadius: "8px",
+ border: "2px solid #2196f3",
+ maxWidth: "700px",
+ }}
+ >
+ <div style={{ fontSize: "14px", marginBottom: "8px" }}>
+ <strong>🎯 Sidebar Tooltip Demo</strong>
+ </div>
+ <div style={{ fontSize: "13px", color: "#1565c0", lineHeight: "1.6" }}>
+ This chart has <strong>15 data series</strong> (more than 10). <br />
+ <strong>✨ Click on any point</strong> in the chart to open the sidebar tooltip on the
+ right side.
+ <br />
+ The sidebar provides a scrollable list of all series values at that point, making it easy
+ to view large datasets.
+ <br />
+ <em>
+ 💡 Try hovering first (shows inline tooltip), then click to see the sidebar version!
+ </em>
+ </div>
+ </div>
+ <Card style={{ width: "700px" }}>
+ <LineChartCondensed {...args} />
+ </Card>
+ </div>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "**🎯 Large Dataset Handling:** When your chart has more than 10 data series, the inline tooltip becomes too crowded. This story demonstrates the sidebar tooltip feature:\n\n**Features:**\n- **15 data series** to showcase the sidebar tooltip\n- **Click interaction:** Click any point to open the sidebar\n- **Scrollable view:** All series values in an organized, scrollable list\n- **Better UX:** Cleaner way to view many data points simultaneously\n- **Color-coded:** Each series maintains its color for easy identification\n\n**Usage:**\n1. Hover over the chart to see the inline tooltip (works for smaller datasets)\n2. Click on any data point to open the sidebar tooltip\n3. Scroll through all 15 series values\n4. Click outside or on the X button to close the sidebar",
+ },
+ },
+ },
+};
+
+/**
+ * ## Big Labels
+ *
+ * This story demonstrates the chart's ability to handle very long category labels.
+ * The angled tick variant is particularly useful here for preventing label overlap.
+ */
+export const BigLabelsStory: Story = {
+ name: "🏷️ Big Labels (Angled Ticks)",
+ args: {
+ data: dataVariations.bigLabels as any,
+ categoryKey: "category" as any,
+ theme: "emerald",
+ variant: "natural",
+ tickVariant: "angled",
+ strokeWidth: 2,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 250,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "700px" }}>
+ <LineChartCondensed {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests the chart with extremely long category names. The angled tick variant automatically rotates labels at an optimal angle to prevent overlapping and maximize readability.",
+ },
+ },
+ },
+};
+
+/**
+ * ## Dense Timeline
+ *
+ * Tests how the chart handles many data points with medium-length period labels.
+ * The angled tick variant helps display more labels without collision.
+ */
+export const DenseTimelineStory: Story = {
+ name: "📅 Dense Timeline (Many Periods)",
+ args: {
+ data: dataVariations.denseTimeline as any,
+ categoryKey: "period" as any,
+ theme: "sunset",
+ variant: "natural",
+ tickVariant: "angled",
+ strokeWidth: 2,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 250,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "700px" }}>
+ <LineChartCondensed {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests how the chart handles many data points (16 periods) with medium-length labels. The angled tick variant provides better label visibility compared to horizontal labels.",
+ },
+ },
+ },
+};
+
+/**
+ * ## Company Names
+ *
+ * This story tests the chart with real-world company names that have varying lengths.
+ * It demonstrates how the chart handles business data with naturally occurring long labels.
+ */
+export const CompanyNamesStory: Story = {
+ name: "🏢 Company Names (Real-world Labels)",
+ args: {
+ data: dataVariations.companyNames as any,
+ categoryKey: "company" as any,
+ theme: "vivid",
+ variant: "natural",
+ tickVariant: "angled",
+ strokeWidth: 2,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 250,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "700px" }}>
+ <LineChartCondensed {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests with real-world company names that have varying lengths. Demonstrates how the chart handles business data with naturally occurring long labels.",
+ },
+ },
+ },
+};
+
+/**
+ * ## Country Names
+ *
+ * This story tests the chart with official country names, which are often long.
+ * It shows how geographic data is handled by the angled tick system.
+ */
+export const CountryDataStory: Story = {
+ name: "🌍 Country Names (Geographic Labels)",
+ args: {
+ data: dataVariations.countryData as any,
+ categoryKey: "country" as any,
+ theme: "orchid",
+ variant: "natural",
+ tickVariant: "angled",
+ strokeWidth: 2,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 250,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "700px" }}>
+ <LineChartCondensed {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests with official country names that include full formal names. Shows how geographic data with naturally long names is handled.",
+ },
+ },
+ },
+};
+
+/**
+ * ## Mixed Lengths
+ *
+ * This story tests the chart's ability to handle a mix of very short and very long labels
+ * within the same dataset, demonstrating its adaptive behavior.
+ */
+export const MixedLengthsStory: Story = {
+ name: "🔤 Mixed Lengths (Varied Label Sizes)",
+ args: {
+ data: dataVariations.mixedLengths as any,
+ categoryKey: "item" as any,
+ theme: "spectrum",
+ variant: "linear",
+ tickVariant: "singleLine",
+ strokeWidth: 2,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 200,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "500px" }}>
+ <LineChartCondensed {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests the chart's ability to handle a mix of very short and very long labels within the same dataset.",
+ },
+ },
+ },
+};
+
+/**
+ * ## Edge Cases
+ *
+ * This story tests extreme edge cases with exceptionally long labels and minimal data points.
+ */
+export const EdgeCasesStory: Story = {
+ name: "🎯 Edge Cases (Extreme Scenarios)",
+ args: {
+ data: dataVariations.edgeCases as any,
+ categoryKey: "name" as any,
+ theme: "ocean",
+ variant: "step",
+ tickVariant: "angled",
+ strokeWidth: 2,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 250,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "500px" }}>
+ <LineChartCondensed {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Tests extreme edge cases with exceptionally long labels and minimal data points. Pushes the label handling system to its limits.",
+ },
+ },
+ },
+};
+
+/**
+ * ## Minimal Data
+ *
+ * A baseline test with a small dataset and standard-length labels. This serves as a control
+ * case to compare against the more complex label scenarios.
+ */
+export const MinimalDataStory: Story = {
+ name: "📱 Minimal Data (Baseline)",
+ args: {
+ data: dataVariations.minimal as any,
+ categoryKey: "category" as any,
+ theme: "emerald",
+ variant: "natural",
+ tickVariant: "singleLine",
+ strokeWidth: 2,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 200,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "400px" }}>
+ <LineChartCondensed {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Baseline test with minimal data and standard-length labels. Provides a control case to compare against complex scenarios.",
+ },
+ },
+ },
+};
+
+/**
+ * ## Custom Palette
+ *
+ * This story demonstrates how to use the customPalette prop to provide your own color scheme
+ * for the chart. This is useful when you need to match your brand colors.
+ */
+export const CustomPaletteStory: Story = {
+ name: "🎨 Custom Palette",
+ args: {
+ data: dataVariations.default as any,
+ categoryKey: "month" as any,
+ theme: "ocean", // This will be overridden by customPalette
+ variant: "natural",
+ tickVariant: "singleLine",
+ strokeWidth: 2,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ xAxisLabel: "Month",
+ yAxisLabel: "Traffic",
+ customPalette: ["#FF6B6B", "#4ECDC4", "#45B7D1"],
+ height: 200,
+ },
+ render: (args: any) => (
+ <div>
+ <div
+ style={{
+ marginBottom: "16px",
+ padding: "12px",
+ background: "#f8f9fa",
+ borderRadius: "8px",
+ border: "1px solid #e9ecef",
+ width: "600px",
+ }}
+ >
+ <h4 style={{ margin: "0 0 8px 0", color: "#333" }}>🎨 Custom Color Palette</h4>
+ <p style={{ margin: "0 0 12px 0", fontSize: "14px", color: "#666" }}>
+ This chart uses a custom color palette instead of the default theme colors.
+ </p>
+ <div style={{ display: "flex", gap: "8px", flexWrap: "wrap" }}>
+ {args.customPalette?.map((color: string, index: number) => (
+ <div
+ key={index}
+ style={{
+ display: "flex",
+ alignItems: "center",
+ gap: "4px",
+ padding: "4px 8px",
+ background: "white",
+ borderRadius: "4px",
+ border: "1px solid #ddd",
+ fontSize: "12px",
+ }}
+ >
+ <div
+ style={{
+ width: "12px",
+ height: "12px",
+ borderRadius: "2px",
+ backgroundColor: color,
+ border: "1px solid #ccc",
+ }}
+ />
+ <span style={{ fontFamily: "monospace" }}>{color}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ <Card style={{ width: "600px" }}>
+ <LineChartCondensed {...args} />
+ </Card>
+ </div>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'Demonstrates how to use the `customPalette` prop to provide your own color scheme. When `customPalette` is provided, it overrides the `theme` prop.\n\n**Usage:**\n```tsx\n<LineChartCondensed\n data={data}\n categoryKey="month"\n customPalette={["#FF6B6B", "#4ECDC4", "#45B7D1"]}\n/>\n```',
+ },
+ },
+ },
+};
+
+/**
+ * ## Stroke Width Comparison
+ *
+ * Compare different line thickness options to find the right visual weight for your data.
+ */
+export const StrokeWidthComparison: Story = {
+ name: "📏 Stroke Width Comparison",
+ render: () => (
+ <div style={{ display: "flex", flexDirection: "column", gap: "24px" }}>
+ <Card style={{ width: "700px", padding: "16px" }}>
+ <div style={{ marginBottom: "12px" }}>
+ <div style={{ fontSize: "16px", fontWeight: "600", marginBottom: "4px" }}>
+ Thin Lines (1px)
+ </div>
+ <div style={{ fontSize: "13px", color: "#666" }}>Subtle, minimal visual weight</div>
+ </div>
+ <LineChartCondensed
+ data={dataVariations.default as any}
+ categoryKey="month"
+ theme="ocean"
+ strokeWidth={1}
+ height={180}
+ />
+ </Card>
+ <Card style={{ width: "700px", padding: "16px" }}>
+ <div style={{ marginBottom: "12px" }}>
+ <div style={{ fontSize: "16px", fontWeight: "600", marginBottom: "4px" }}>
+ Default Lines (2px)
+ </div>
+ <div style={{ fontSize: "13px", color: "#666" }}>Balanced, standard weight</div>
+ </div>
+ <LineChartCondensed
+ data={dataVariations.default as any}
+ categoryKey="month"
+ theme="emerald"
+ strokeWidth={2}
+ height={180}
+ />
+ </Card>
+ <Card style={{ width: "700px", padding: "16px" }}>
+ <div style={{ marginBottom: "12px" }}>
+ <div style={{ fontSize: "16px", fontWeight: "600", marginBottom: "4px" }}>
+ Thick Lines (4px)
+ </div>
+ <div style={{ fontSize: "13px", color: "#666" }}>Bold, high emphasis</div>
+ </div>
+ <LineChartCondensed
+ data={dataVariations.default as any}
+ categoryKey="month"
+ theme="sunset"
+ strokeWidth={4}
+ height={180}
+ />
+ </Card>
+ </div>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "**Side-by-side comparison** of stroke widths:\n\n- **1px**: Thin, subtle lines perfect for dense data or multiple overlapping series\n- **2px**: Default weight, balanced for most use cases\n- **4px**: Thick, bold lines for high emphasis or presentations\n\n**When to use each:**\n- Use **1px** for many overlapping series or subtle trends\n- Use **2px** (default) for general purpose visualization\n- Use **4px** for presentations or when emphasizing specific trends",
+ },
+ },
+ },
+};
+
+/**
+ * ## Tick Variant Comparison
+ *
+ * Side-by-side comparison of single-line (horizontal) and angled tick variants.
+ * This helps you choose the right variant for your data.
+ */
+export const TickVariantComparison: Story = {
+ name: "📐 Tick Variant Comparison",
+ render: () => (
+ <div style={{ display: "flex", flexDirection: "column", gap: "24px" }}>
+ <Card style={{ width: "700px", padding: "16px" }}>
+ <div style={{ marginBottom: "12px" }}>
+ <div style={{ fontSize: "16px", fontWeight: "600", marginBottom: "4px" }}>
+ Single Line Variant (Horizontal)
+ </div>
+ <div style={{ fontSize: "13px", color: "#666" }}>
+ Standard horizontal labels. Recharts automatically hides overlapping labels.
+ </div>
+ </div>
+ <LineChartCondensed
+ data={dataVariations.bigLabels as any}
+ categoryKey="category"
+ tickVariant="singleLine"
+ theme="ocean"
+ strokeWidth={2}
+ height={200}
+ />
+ </Card>
+ <Card style={{ width: "700px", padding: "16px" }}>
+ <div style={{ marginBottom: "12px" }}>
+ <div style={{ fontSize: "16px", fontWeight: "600", marginBottom: "4px" }}>
+ Angled Variant (Rotated)
+ </div>
+ <div style={{ fontSize: "13px", color: "#666" }}>
+ Automatically rotates labels at an optimal angle. Shows more labels without collision.
+ </div>
+ </div>
+ <LineChartCondensed
+ data={dataVariations.bigLabels as any}
+ categoryKey="category"
+ tickVariant="angled"
+ theme="emerald"
+ strokeWidth={2}
+ height={260}
+ />
+ </Card>
+ </div>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "**Side-by-side comparison** of tick variants:\n\n- **Single Line**: Standard horizontal labels with automatic collision detection. Recharts hides overlapping labels.\n- **Angled**: Rotates labels at an optimal angle calculated based on label width and available space. Shows more labels without collision.\n\n**When to use each:**\n- Use **singleLine** for short labels or when you have few data points\n- Use **angled** for long labels or many data points where horizontal labels would overlap",
+ },
+ },
+ },
+};
+
+/**
+ * ## Responsive Behavior Demo
+ *
+ * This story demonstrates the responsive capabilities of the LineChartCondensed.
+ * Drag the handles on the container to resize it and observe how the chart adapts.
+ */
+export const ResponsiveBehaviorDemo: Story = {
+ name: "📱 Responsive Behavior Demo",
+ args: {
+ data: dataVariations.bigLabels as any,
+ categoryKey: "category" as any,
+ theme: "sunset",
+ variant: "natural",
+ tickVariant: "angled",
+ strokeWidth: 2,
+ grid: true,
+ isAnimationActive: false,
+ showYAxis: true,
+ height: 250,
+ },
+ render: (args: any) => {
+ const [dimensions, setDimensions] = useState<{ width: number }>({
+ width: 700,
+ });
+
+ const handleMouseDown = (e: React.MouseEvent<HTMLDivElement>, handle: string) => {
+ e.preventDefault();
+ e.stopPropagation();
+ const startX = e.clientX;
+ const startWidth = dimensions.width;
+
+ const doDrag = (e: MouseEvent) => {
+ const dx = e.clientX - startX;
+ let newWidth = startWidth;
+
+ if (handle.includes("e")) newWidth = startWidth + dx;
+ if (handle.includes("w")) newWidth = startWidth - dx;
+
+ setDimensions({
+ width: Math.max(300, newWidth),
+ });
+ };
+
+ const stopDrag = () => {
+ document.removeEventListener("mousemove", doDrag);
+ document.removeEventListener("mouseup", stopDrag);
+ };
+
+ document.addEventListener("mousemove", doDrag);
+ document.addEventListener("mouseup", stopDrag);
+ };
+
+ const handleStyle: React.CSSProperties = {
+ position: "absolute",
+ background: "#3b82f6",
+ opacity: 0.6,
+ zIndex: 10,
+ transition: "opacity 0.2s ease",
+ };
+
+ return (
+ <div style={{ padding: "20px" }}>
+ <div style={{ marginBottom: "20px" }}>
+ <h3 style={{ margin: "0 0 8px 0", fontSize: "18px", fontWeight: "600" }}>
+ Responsive Behavior Demonstration
+ </h3>
+ <p style={{ margin: "0 0 12px 0", color: "#666", fontSize: "14px" }}>
+ Drag the left or right edges of the container to see how the chart adapts
+ </p>
+ <div
+ style={{
+ padding: "12px",
+ backgroundColor: "#e3f2fd",
+ borderRadius: "6px",
+ fontSize: "12px",
+ color: "#1565c0",
+ }}
+ >
+ <strong>🎯 Try This:</strong> Resize the container to see how angled labels adapt to
+ available space.
+ </div>
+ </div>
+
+ <Card
+ style={{
+ position: "relative",
+ width: `${dimensions.width}px`,
+ border: "2px dashed #9ca3af",
+ padding: "20px",
+ boxSizing: "border-box",
+ overflow: "hidden",
+ cursor: "default",
+ }}
+ >
+ <LineChartCondensed {...args} />
+
+ {/* Resize Handles */}
+ <div
+ style={{ ...handleStyle, top: 0, bottom: 0, left: -2, width: 12, cursor: "ew-resize" }}
+ onMouseDown={(e) => handleMouseDown(e, "w")}
+ />
+ <div
+ style={{ ...handleStyle, top: 0, bottom: 0, right: -2, width: 12, cursor: "ew-resize" }}
+ onMouseDown={(e) => handleMouseDown(e, "e")}
+ />
+
+ {/* Dimension Display */}
+ <div
+ style={{
+ position: "absolute",
+ bottom: 8,
+ right: 8,
+ background: "rgba(0,0,0,0.8)",
+ color: "white",
+ padding: "4px 8px",
+ borderRadius: "4px",
+ fontSize: "11px",
+ fontFamily: "monospace",
+ fontWeight: "500",
+ }}
+ >
+ {dimensions.width}px
+ </div>
+ </Card>
+ </div>
+ );
+ },
+};
diff --git a/packages/react-ui/src/components/D3Charts/LineChart/types.ts b/packages/react-ui/src/components/D3Charts/LineChart/types.ts
new file mode 100644
index 000000000..00de3e00a
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/LineChart/types.ts
@@ -0,0 +1,13 @@
+import type { BaseChartProps, ChartData, HoverOverlayProps } from "../types";
+
+export type LineChartData = ChartData;
+
+export type LineChartVariant = "linear" | "natural" | "step";
+
+export interface LineChartProps<T extends LineChartData>
+ extends BaseChartProps<T>, HoverOverlayProps {
+ variant?: LineChartVariant;
+ showDots?: boolean;
+ dotRadius?: number;
+ onClick?: (row: T[number], index: number) => void;
+}
diff --git a/packages/react-ui/src/components/D3Charts/MiniAreaChart/MiniAreaChart.tsx b/packages/react-ui/src/components/D3Charts/MiniAreaChart/MiniAreaChart.tsx
new file mode 100644
index 000000000..3e621db0e
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/MiniAreaChart/MiniAreaChart.tsx
@@ -0,0 +1,82 @@
+import { area, line } from "d3-shape";
+import { useId } from "react";
+import { useEffectiveAnimation } from "../hooks/core/useEffectiveAnimation";
+import { MiniChartFrame } from "../shared/mini/MiniChartFrame";
+import { type MiniChartPoint, miniCurves, miniLineGeometry } from "../shared/mini/miniChartUtils";
+import { CHART_CLASS_PREFIX } from "../utils/constants";
+import { useChartPalette } from "../utils/paletteUtils";
+import type { MiniAreaChartProps } from "./types";
+
+const CLASS = `${CHART_CLASS_PREFIX}-mini-area-chart`;
+
+/**
+ * A compact, axis-free area sparkline — react-ui's Recharts `MiniAreaChart`:
+ * the most recent values that fit, one series, a gradient fill under a 1.5px
+ * line.
+ */
+export function MiniAreaChart({
+ data,
+ customPalette,
+ variant = "natural",
+ opacity = 0.5,
+ isAnimationActive = false,
+ onAreaClick,
+ size = "100%",
+ className,
+ areaColor,
+ useGradient = true,
+}: MiniAreaChartProps) {
+ const animate = useEffectiveAnimation(isAnimationActive);
+ const [color = ""] = useChartPalette({
+ customPalette: customPalette ?? (areaColor ? [areaColor] : undefined),
+ themePaletteName: "areaChartPalette",
+ dataLength: 1,
+ });
+ const gradientId = `${CLASS}-gradient-${useId().replace(/:/g, "")}`;
+ const curve = miniCurves[variant] ?? miniCurves.natural;
+ const animated = animate ? ` ${CHART_CLASS_PREFIX}-mini-chart-mark--animated` : "";
+
+ return (
+ <MiniChartFrame chart="area" size={size} className={className} onClick={onAreaClick}>
+ {(width, height) => {
+ const { points, x, y } = miniLineGeometry(data, width, height);
+ const areaD =
+ area<MiniChartPoint>()
+ .x((_, i) => x(i))
+ .y0(y(0))
+ .y1((p) => y(p.value))
+ .curve(curve)(points) ?? "";
+ const lineD =
+ line<MiniChartPoint>()
+ .x((_, i) => x(i))
+ .y((p) => y(p.value))
+ .curve(curve)(points) ?? "";
+ return (
+ <>
+ {useGradient && (
+ <defs>
+ <linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">
+ <stop offset="5%" stopColor={color} stopOpacity={0.6} />
+ <stop offset="95%" stopColor={color} stopOpacity={0} />
+ </linearGradient>
+ </defs>
+ )}
+ <path
+ className={`${CLASS}-area${animated}`}
+ d={areaD}
+ fill={useGradient ? `url(#${gradientId})` : color}
+ fillOpacity={useGradient ? 1 : opacity}
+ />
+ <path
+ className={`${CLASS}-line${animated}`}
+ d={lineD}
+ fill="none"
+ stroke={color}
+ strokeWidth={1.5}
+ />
+ </>
+ );
+ }}
+ </MiniChartFrame>
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/MiniAreaChart/index.ts b/packages/react-ui/src/components/D3Charts/MiniAreaChart/index.ts
new file mode 100644
index 000000000..bacf1d659
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/MiniAreaChart/index.ts
@@ -0,0 +1,2 @@
+export { MiniAreaChart } from "./MiniAreaChart";
+export type { MiniAreaChartData, MiniAreaChartProps } from "./types";
diff --git a/packages/react-ui/src/components/D3Charts/MiniAreaChart/stories/MiniAreaChart.stories.tsx b/packages/react-ui/src/components/D3Charts/MiniAreaChart/stories/MiniAreaChart.stories.tsx
new file mode 100644
index 000000000..5e00024f2
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/MiniAreaChart/stories/MiniAreaChart.stories.tsx
@@ -0,0 +1,406 @@
+// Copy of Charts/MiniAreaChart/stories/MiniAreaChart.stories.tsx with only the chart import and the title changed:
+// the same args and renders, rendering the D3Charts chart via
+// ../../stories/rechartsStoryAdapters.
+import type { Meta, StoryObj } from "@storybook/react";
+import { Card } from "../../../Card";
+import { MiniAreaChart } from "../../stories/rechartsStoryAdapters";
+
+// Simple array of numbers for 1D area chart
+const simpleAreaChartData = [
+ 12, 45, 78, 32, 67, 89, 23, 56, 91, 34, 76, 28, 85, 42, 19, 63, 87, 31, 74, 58, 92, 26, 49, 83,
+ 37, 50,
+];
+
+// Array of objects with value and label
+const labeledAreaChartData = [
+ { value: 150, label: "January" },
+ { value: 280, label: "February" },
+ { value: 220, label: "March" },
+ { value: 180, label: "April" },
+ { value: 250, label: "May" },
+ { value: 300, label: "June" },
+ { value: 320, label: "July" },
+ { value: 280, label: "August" },
+ { value: 310, label: "September" },
+ { value: 290, label: "October" },
+ { value: 340, label: "November" },
+ { value: 360, label: "December" },
+ // { value: 360, label: "December" },
+ // { value: 360, label: "December" },
+];
+
+const meta: Meta<typeof MiniAreaChart> = {
+ title: "Components/D3Charts/MiniAreaChart",
+ component: MiniAreaChart,
+ parameters: {
+ layout: "centered",
+ docs: {
+ description: {
+ component:
+ "```tsx\nimport { MiniAreaChart } from '@openuidev/react-ui/Charts/AreaCharts/MiniAreaChart';\n```\n\nA responsive mini area chart component that accepts 1D data (numbers or objects with value/label) with automatic data filtering for space-constrained containers. Features linear gradient fills from color to transparent.",
+ },
+ },
+ },
+ tags: ["!autodocs"],
+ argTypes: {
+ data: {
+ description:
+ "An array of numbers or an array of objects with value and optional label. Each entry represents a single point in the area chart.",
+ control: false,
+ table: {
+ type: { summary: "Array<number> | Array<{ value: number; label?: string }>" },
+ defaultValue: { summary: "[]" },
+ category: "Data",
+ },
+ },
+ theme: {
+ description:
+ "The color palette theme for the chart. Each theme provides a different color for the area.",
+ control: "select",
+ options: ["ocean", "orchid", "emerald", "sunset", "spectrum", "vivid"],
+ table: {
+ defaultValue: { summary: "ocean" },
+ category: "Appearance",
+ },
+ },
+ variant: {
+ description:
+ "The interpolation method used to create the area curves. 'linear' creates straight lines between points, 'natural' creates smooth curves, and 'step' creates a stepped area.",
+ control: "radio",
+ options: ["linear", "natural", "step"],
+ table: {
+ defaultValue: { summary: "natural" },
+ category: "Appearance",
+ },
+ },
+ opacity: {
+ description:
+ "The opacity of the filled area beneath the line (0 = fully transparent, 1 = fully opaque). Only used when useGradient is false.",
+ control: "number",
+ table: {
+ type: { summary: "number" },
+ defaultValue: { summary: "0.5" },
+ category: "Appearance",
+ },
+ },
+ useGradient: {
+ description:
+ "Whether to use a linear gradient fill that goes from the area color at the top to transparent at the bottom.",
+ control: "boolean",
+ table: {
+ type: { summary: "boolean" },
+ defaultValue: { summary: "true" },
+ category: "Appearance",
+ },
+ },
+ isAnimationActive: {
+ description: "Whether to animate the chart when it first renders",
+ control: "boolean",
+ table: {
+ type: { summary: "boolean" },
+ defaultValue: { summary: "true" },
+ category: "Display",
+ },
+ },
+ size: {
+ description: "The width and height of the chart",
+ control: "text",
+ table: {
+ type: { summary: "number | string" },
+ defaultValue: { summary: "100%" },
+ category: "Appearance",
+ },
+ },
+ areaColor: {
+ description: "Custom color for the area fill and stroke",
+ control: "color",
+ table: {
+ type: { summary: "string" },
+ category: "Appearance",
+ },
+ },
+ },
+} satisfies Meta<typeof MiniAreaChart>;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+export const SimpleNumberArray: Story = {
+ name: "Simple Number Array (With Gradient)",
+ args: {
+ data: simpleAreaChartData,
+ theme: "ocean",
+ variant: "natural",
+ opacity: 0.5,
+ useGradient: true,
+ isAnimationActive: true,
+ size: "100%",
+ },
+ render: (args: any) => (
+ <Card style={{ width: "280px", padding: "20px" }}>
+ <h3 style={{ marginBottom: "16px", fontSize: "16px", fontWeight: "600" }}>Daily Activity</h3>
+ <MiniAreaChart {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ source: {
+ code: `
+const activityData = [12, 45, 78, 32, 67, 89, 23, 56, 91, 34];
+
+<MiniAreaChart
+ data={activityData}
+ theme="ocean"
+ variant="natural"
+ useGradient={true}
+ isAnimationActive={true}
+ size="100%"
+/>
+`,
+ },
+ },
+ },
+};
+
+export const LabeledData: Story = {
+ name: "Labeled Data (With Gradient)",
+ args: {
+ data: labeledAreaChartData,
+ theme: "emerald",
+ variant: "natural",
+ opacity: 0.6,
+ useGradient: true,
+ isAnimationActive: true,
+ size: "100%",
+ },
+ render: (args: any) => (
+ <Card style={{ width: "320px", padding: "20px" }}>
+ <h3 style={{ marginBottom: "16px", fontSize: "16px", fontWeight: "600" }}>Monthly Revenue</h3>
+ <MiniAreaChart {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ source: {
+ code: `
+const revenueData = [
+ { value: 150, label: "January" },
+ { value: 280, label: "February" },
+ { value: 220, label: "March" },
+ // ...
+];
+
+<MiniAreaChart
+ data={revenueData}
+ theme="emerald"
+ variant="natural"
+ useGradient={true}
+ size="100%"
+/>
+`,
+ },
+ },
+ },
+};
+
+export const WithoutGradient: Story = {
+ name: "Solid Fill (Without Gradient)",
+ args: {
+ data: simpleAreaChartData.slice(0, 15),
+ theme: "sunset",
+ variant: "natural",
+ opacity: 0.4,
+ useGradient: false,
+ isAnimationActive: true,
+ size: "100%",
+ },
+ render: (args: any) => (
+ <Card style={{ width: "280px", padding: "20px" }}>
+ <h3 style={{ marginBottom: "16px", fontSize: "16px", fontWeight: "600" }}>Solid Fill Area</h3>
+ <MiniAreaChart {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ source: {
+ code: `
+<MiniAreaChart
+ data={data}
+ theme="sunset"
+ variant="natural"
+ opacity={0.4}
+ useGradient={false}
+ size="100%"
+/>
+`,
+ },
+ },
+ },
+};
+
+export const GradientComparison: Story = {
+ name: "Gradient vs Solid Comparison",
+ render: () => (
+ <div style={{ display: "flex", gap: "20px" }}>
+ <Card style={{ width: "250px", padding: "16px" }}>
+ <h4 style={{ marginBottom: "12px", fontSize: "14px", fontWeight: "600" }}>
+ With Gradient (Default)
+ </h4>
+ <MiniAreaChart
+ data={[20, 45, 35, 80, 60, 90, 45, 70, 85, 30]}
+ theme="orchid"
+ variant="natural"
+ useGradient={true}
+ size={200}
+ />
+ </Card>
+ <Card style={{ width: "250px", padding: "16px" }}>
+ <h4 style={{ marginBottom: "12px", fontSize: "14px", fontWeight: "600" }}>Solid Fill</h4>
+ <MiniAreaChart
+ data={[20, 45, 35, 80, 60, 90, 45, 70, 85, 30]}
+ theme="orchid"
+ variant="natural"
+ useGradient={false}
+ opacity={0.3}
+ size={200}
+ />
+ </Card>
+ </div>
+ ),
+};
+
+export const ResponsiveData: Story = {
+ name: "Responsive Data Filtering",
+ args: {
+ data: simpleAreaChartData,
+ theme: "orchid",
+ variant: "natural",
+ opacity: 0.4,
+ useGradient: true,
+ isAnimationActive: true,
+ size: "100%",
+ },
+ render: (args: any) => (
+ <div style={{ display: "flex", gap: "20px", flexDirection: "column" }}>
+ <Card style={{ width: "200px", padding: "16px" }}>
+ <h4 style={{ marginBottom: "12px", fontSize: "14px", fontWeight: "600" }}>Small (200px)</h4>
+ <MiniAreaChart {...args} />
+ </Card>
+ <Card style={{ width: "400px", padding: "16px" }}>
+ <h4 style={{ marginBottom: "12px", fontSize: "14px", fontWeight: "600" }}>
+ Medium (400px)
+ </h4>
+ <MiniAreaChart {...args} />
+ </Card>
+ <Card style={{ width: "600px", padding: "16px" }}>
+ <h4 style={{ marginBottom: "12px", fontSize: "14px", fontWeight: "600" }}>Large (600px)</h4>
+ <MiniAreaChart {...args} />
+ </Card>
+ </div>
+ ),
+};
+
+export const DifferentSizes: Story = {
+ name: "Different Sizes",
+ render: () => (
+ <div style={{ display: "flex", gap: "20px", alignItems: "center" }}>
+ <Card style={{ width: "120px", padding: "12px" }}>
+ <h4 style={{ marginBottom: "8px", fontSize: "12px", fontWeight: "600" }}>Small</h4>
+ <MiniAreaChart data={[15, 25, 20, 35, 30, 18, 22]} theme="sunset" size={80} />
+ </Card>
+ <Card style={{ width: "200px", padding: "16px" }}>
+ <h4 style={{ marginBottom: "12px", fontSize: "14px", fontWeight: "600" }}>Medium</h4>
+ <MiniAreaChart data={simpleAreaChartData.slice(0, 10)} theme="spectrum" size={160} />
+ </Card>
+ <Card style={{ width: "280px", padding: "20px" }}>
+ <h4 style={{ marginBottom: "16px", fontSize: "16px", fontWeight: "600" }}>Large</h4>
+ <MiniAreaChart data={simpleAreaChartData} theme="vivid" size={240} />
+ </Card>
+ </div>
+ ),
+};
+
+export const DifferentThemes: Story = {
+ name: "Different Themes (All With Gradients)",
+ render: () => (
+ <div style={{ display: "flex", gap: "20px", flexWrap: "wrap" }}>
+ {(["ocean", "orchid", "emerald", "sunset", "spectrum", "vivid"] as const).map((theme) => (
+ <Card key={theme} style={{ width: "200px", padding: "16px" }}>
+ <h4
+ style={{
+ marginBottom: "12px",
+ fontSize: "14px",
+ fontWeight: "600",
+ textTransform: "capitalize",
+ }}
+ >
+ {theme} Theme
+ </h4>
+ <MiniAreaChart
+ data={[15, 25, 20, 35, 30, 18, 22, 28, 33, 19]}
+ theme={theme}
+ variant="natural"
+ useGradient={true}
+ size={160}
+ />
+ </Card>
+ ))}
+ </div>
+ ),
+};
+
+export const DifferentVariants: Story = {
+ name: "Different Variants",
+ render: () => (
+ <div style={{ display: "flex", gap: "20px" }}>
+ {(["linear", "natural", "step"] as const).map((variant) => (
+ <Card key={variant} style={{ width: "220px", padding: "16px" }}>
+ <h4
+ style={{
+ marginBottom: "12px",
+ fontSize: "14px",
+ fontWeight: "600",
+ textTransform: "capitalize",
+ }}
+ >
+ {variant} Variant
+ </h4>
+ <MiniAreaChart
+ data={[15, 35, 25, 45, 30, 50, 28, 42, 38, 29]}
+ theme="spectrum"
+ variant={variant}
+ useGradient={true}
+ size={180}
+ />
+ </Card>
+ ))}
+ </div>
+ ),
+};
+
+export const CustomColor: Story = {
+ name: "Custom Color with Gradient",
+ args: {
+ data: [20, 45, 28, 80, 99, 43, 67, 23, 89, 56],
+ theme: "ocean",
+ variant: "natural",
+ opacity: 0.7,
+ areaColor: "#ff6b6b",
+ useGradient: true,
+ size: 200,
+ },
+ render: (args: any) => (
+ <Card
+ style={{
+ width: "280px",
+ padding: "20px",
+ display: "flex",
+ flexDirection: "column",
+ alignItems: "center",
+ }}
+ >
+ <h3 style={{ marginBottom: "16px", fontSize: "16px", fontWeight: "600" }}>Custom Red Area</h3>
+ <MiniAreaChart {...args} />
+ </Card>
+ ),
+};
diff --git a/packages/react-ui/src/components/D3Charts/MiniAreaChart/types.ts b/packages/react-ui/src/components/D3Charts/MiniAreaChart/types.ts
new file mode 100644
index 000000000..771aadf79
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/MiniAreaChart/types.ts
@@ -0,0 +1,20 @@
+export type MiniAreaChartData = Array<number> | Array<{ value: number; label?: string }>;
+
+export interface MiniAreaChartProps {
+ data: MiniAreaChartData;
+ customPalette?: string[];
+ variant?: "linear" | "natural" | "step";
+ /** Fill opacity when `useGradient` is false. Default 0.5. */
+ opacity?: number;
+ /** Fade the chart in on mount. Default false; printing always disables it. */
+ isAnimationActive?: boolean;
+ /** Called with the click event when the chart is clicked. */
+ onAreaClick?: (data: any) => void;
+ /** Width and height (the chart stays square, at least 100px). Default "100%". */
+ size?: number | string;
+ className?: string;
+ /** Single color override; `customPalette` wins when both are set. */
+ areaColor?: string;
+ /** Fade the fill from the line down. Default true. */
+ useGradient?: boolean;
+}
diff --git a/packages/react-ui/src/components/D3Charts/MiniBarChart/MiniBarChart.tsx b/packages/react-ui/src/components/D3Charts/MiniBarChart/MiniBarChart.tsx
new file mode 100644
index 000000000..c6002534b
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/MiniBarChart/MiniBarChart.tsx
@@ -0,0 +1,76 @@
+import { useTheme } from "../../ThemeProvider";
+import { useEffectiveAnimation } from "../hooks/core/useEffectiveAnimation";
+import { roundedBarPath } from "../shared/cartesian/roundedBarPath";
+import { MiniChartFrame } from "../shared/mini/MiniChartFrame";
+import { MINI_BAR_WIDTH, miniBarGeometry } from "../shared/mini/miniChartUtils";
+import { CHART_CLASS_PREFIX } from "../utils/constants";
+import { useChartPalette } from "../utils/paletteUtils";
+import type { MiniBarChartProps } from "./types";
+
+const CLASS = `${CHART_CLASS_PREFIX}-mini-bar-chart`;
+// The thin line down each bar's middle, inset from both ends — shown only on
+// bars tall enough to hold it (as react-ui's Recharts MiniBarChart).
+const INNER_LINE_INSET = 6;
+const INNER_LINE_MIN_HEIGHT = 8;
+
+/**
+ * Compact, axis-free bars — react-ui's Recharts `MiniBarChart`: the most
+ * recent values that fit, 8px bars right-aligned, rounded outer corners, and
+ * a thin inner line.
+ */
+export function MiniBarChart({
+ data,
+ customPalette,
+ radius = 1,
+ isAnimationActive = false,
+ onBarsClick,
+ size = "100%",
+ className,
+ barColor,
+}: MiniBarChartProps) {
+ const animate = useEffectiveAnimation(isAnimationActive);
+ const [color = ""] = useChartPalette({
+ customPalette: customPalette ?? (barColor ? [barColor] : undefined),
+ themePaletteName: "barChartPalette",
+ dataLength: 1,
+ });
+ const { mode } = useTheme();
+ const innerLineColor = mode === "light" ? "rgba(255, 255, 255, 0.3)" : "rgba(0, 0, 0, 0.3)";
+ const animated = animate ? ` ${CHART_CLASS_PREFIX}-mini-chart-mark--animated` : "";
+
+ return (
+ <MiniChartFrame chart="bar" size={size} className={className} onClick={onBarsClick}>
+ {(width, height) =>
+ miniBarGeometry(data, width, height).map((bar, i) =>
+ bar.height > 0 ? (
+ <g key={i} className={`${CLASS}-bar-group${animated}`}>
+ <path
+ className={`${CLASS}-bar`}
+ d={roundedBarPath(
+ bar.x,
+ bar.y,
+ MINI_BAR_WIDTH,
+ bar.height,
+ bar.negative ? [0, 0, radius, radius] : [radius, radius, 0, 0],
+ )}
+ fill={color}
+ />
+ {bar.height >= INNER_LINE_MIN_HEIGHT && (
+ <line
+ className={`${CLASS}-inner-line`}
+ x1={bar.x + MINI_BAR_WIDTH / 2}
+ y1={bar.y + INNER_LINE_INSET}
+ x2={bar.x + MINI_BAR_WIDTH / 2}
+ y2={bar.y + bar.height - INNER_LINE_INSET}
+ stroke={innerLineColor}
+ strokeWidth={1}
+ strokeLinecap="round"
+ />
+ )}
+ </g>
+ ) : null,
+ )
+ }
+ </MiniChartFrame>
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/MiniBarChart/index.ts b/packages/react-ui/src/components/D3Charts/MiniBarChart/index.ts
new file mode 100644
index 000000000..02c487261
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/MiniBarChart/index.ts
@@ -0,0 +1,2 @@
+export { MiniBarChart } from "./MiniBarChart";
+export type { MiniBarChartData, MiniBarChartProps } from "./types";
diff --git a/packages/react-ui/src/components/D3Charts/MiniBarChart/stories/MiniBarChart.stories.tsx b/packages/react-ui/src/components/D3Charts/MiniBarChart/stories/MiniBarChart.stories.tsx
new file mode 100644
index 000000000..af07428fb
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/MiniBarChart/stories/MiniBarChart.stories.tsx
@@ -0,0 +1,218 @@
+// Copy of Charts/MiniBarChart/stories/MiniBarChart.stories.tsx with only the chart import and the title changed:
+// the same args and renders, rendering the D3Charts chart via
+// ../../stories/rechartsStoryAdapters.
+import type { Meta, StoryObj } from "@storybook/react";
+import { Monitor } from "lucide-react";
+import { Card } from "../../../Card";
+import { MiniBarChart, MiniBarChartProps } from "../../stories/rechartsStoryAdapters";
+
+// Simple array of numbers for 1D bar chart
+const simpleBarChartData = [
+ 1, 1893456, 3456789, 2987654, 1765432, 4321098, 3789012, 2654321, 4123567, 3234567, 2876543,
+ 3987654, 2347891, 1893456, 3456789, 2987654, 1765432, 4321098, 3789012, 2654321, 4123567, 3234567,
+ 2876543, 3987654, 2347891, 1893456, 3456789, 2987654, 1765432, 4321098, 3789012, 2654321, 4123567,
+ 3234567, 2876543, 3987654, 2347891, 1893456, 3456789, 2987654, 1765432, 4321098, 3789012, 2654321,
+ 4123567, 3234567, 2876543, 100000,
+];
+
+// Array of objects with value and label
+const labeledBarChartData = [
+ { value: 2347891, label: "January" },
+ { value: 1893456, label: "February" },
+ { value: 3456789, label: "March" },
+ { value: 2987654, label: "April" },
+ { value: 1765432, label: "May" },
+ { value: 4321098, label: "June" },
+ { value: 3789012, label: "July" },
+ { value: 2654321, label: "August" },
+ { value: 4123567, label: "September" },
+ { value: 3234567, label: "October" },
+ { value: 2876543, label: "November" },
+ { value: 3987654, label: "December" },
+];
+
+const icons = {
+ desktop: Monitor,
+} as const;
+
+const meta: Meta<MiniBarChartProps> = {
+ title: "Components/D3Charts/MiniBarChart",
+ component: MiniBarChart,
+ parameters: {
+ layout: "centered",
+ docs: {
+ description: {
+ component:
+ "```tsx\nimport { MiniBarChart } from '@openuidev/react-ui/Charts/BarCharts/MiniBarChart';\n```",
+ },
+ },
+ },
+ tags: ["!autodocs"],
+ argTypes: {
+ data: {
+ description:
+ "An array of numbers or an array of objects with value and optional label. Each entry represents a single bar in the chart.",
+ control: false,
+ table: {
+ type: { summary: "Array<number> | Array<{ value: number; label?: string }>" },
+ defaultValue: { summary: "[]" },
+ category: "Data",
+ },
+ },
+ theme: {
+ description:
+ "The color palette theme for the chart. Each theme provides a different set of colors for the bars.",
+ control: "select",
+ options: ["ocean", "orchid", "emerald", "sunset", "spectrum", "vivid"],
+ table: {
+ defaultValue: { summary: "ocean" },
+ category: "Appearance",
+ },
+ },
+ radius: {
+ description: "The radius of the rounded corners of the bars",
+ control: "number",
+ table: {
+ type: { summary: "number" },
+ defaultValue: { summary: "1" },
+ category: "Appearance",
+ },
+ },
+ isAnimationActive: {
+ description: "Whether to animate the chart when it first renders",
+ control: "boolean",
+ table: {
+ type: { summary: "boolean" },
+ defaultValue: { summary: "true" },
+ category: "Display",
+ },
+ },
+ size: {
+ description: "The width and height of the chart",
+ control: "number",
+ table: {
+ type: { summary: "number | string" },
+ defaultValue: { summary: "160" },
+ category: "Appearance",
+ },
+ },
+ },
+} satisfies Meta<typeof MiniBarChart>;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+export const SimpleNumberArray: Story = {
+ name: "Simple Number Array",
+ args: {
+ data: simpleBarChartData,
+ theme: "ocean",
+ radius: 2,
+ isAnimationActive: true,
+ size: "100%",
+ },
+ render: (args: any) => (
+ <Card style={{ width: "280px", padding: "20px" }}>
+ <h3 style={{ marginBottom: "16px", fontSize: "16px", fontWeight: "600" }}>
+ Monthly Sales Data
+ </h3>
+ <MiniBarChart {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ source: {
+ code: `
+const salesData = [2347891, 1893456, 3456789, 2987654, 1765432, 4321098];
+
+<MiniBarChart
+ data={salesData}
+ theme="ocean"
+ radius={2}
+ isAnimationActive={true}
+ size={200}
+/>
+`,
+ },
+ },
+ },
+};
+
+export const LabeledData: Story = {
+ name: "Labeled Data",
+ args: {
+ data: labeledBarChartData,
+ theme: "emerald",
+ radius: 1,
+ isAnimationActive: true,
+ size: 200,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "280px", padding: "20px" }}>
+ <h3 style={{ marginBottom: "16px", fontSize: "16px", fontWeight: "600" }}>Monthly Revenue</h3>
+ <MiniBarChart {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ source: {
+ code: `
+const revenueData = [
+ { value: 2347891, label: "January" },
+ { value: 1893456, label: "February" },
+ { value: 3456789, label: "March" },
+ // ...
+];
+
+<MiniBarChart
+ data={revenueData}
+ theme="emerald"
+ radius={1}
+ isAnimationActive={true}
+ size={200}
+/>
+`,
+ },
+ },
+ },
+};
+
+export const SmallSize: Story = {
+ name: "Small Size",
+ args: {
+ data: [10, 20, 15, 30, 25, 35, 18],
+ theme: "sunset",
+ radius: 1,
+ isAnimationActive: true,
+ size: 120,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "200px", padding: "16px" }}>
+ <h4 style={{ marginBottom: "12px", fontSize: "14px", fontWeight: "600" }}>Weekly Stats</h4>
+ <MiniBarChart {...args} />
+ </Card>
+ ),
+};
+
+export const DifferentThemes: Story = {
+ name: "Different Themes",
+ render: () => (
+ <div style={{ display: "flex", gap: "20px", flexWrap: "wrap" }}>
+ {(["ocean", "orchid", "emerald", "sunset", "spectrum", "vivid"] as const).map((theme) => (
+ <Card key={theme} style={{ width: "200px", padding: "16px" }}>
+ <h4
+ style={{
+ marginBottom: "12px",
+ fontSize: "14px",
+ fontWeight: "600",
+ textTransform: "capitalize",
+ }}
+ >
+ {theme} Theme
+ </h4>
+ <MiniBarChart data={[15, 25, 20, 35, 30, 18, 22]} theme={theme} radius={2} size={160} />
+ </Card>
+ ))}
+ </div>
+ ),
+};
diff --git a/packages/react-ui/src/components/D3Charts/MiniBarChart/types.ts b/packages/react-ui/src/components/D3Charts/MiniBarChart/types.ts
new file mode 100644
index 000000000..d2a597357
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/MiniBarChart/types.ts
@@ -0,0 +1,17 @@
+export type MiniBarChartData = Array<number> | Array<{ value: number; label?: string }>;
+
+export interface MiniBarChartProps {
+ data: MiniBarChartData;
+ customPalette?: string[];
+ /** Corner radius of each bar's outer end. Default 1. */
+ radius?: number;
+ /** Fade the chart in on mount. Default false; printing always disables it. */
+ isAnimationActive?: boolean;
+ /** Called with the click event when the chart is clicked. */
+ onBarsClick?: (data: any) => void;
+ /** Width and height (the chart stays square, at least 100px). Default "100%". */
+ size?: number | string;
+ className?: string;
+ /** Single color override; `customPalette` wins when both are set. */
+ barColor?: string;
+}
diff --git a/packages/react-ui/src/components/D3Charts/MiniLineChart/MiniLineChart.tsx b/packages/react-ui/src/components/D3Charts/MiniLineChart/MiniLineChart.tsx
new file mode 100644
index 000000000..8d99838dc
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/MiniLineChart/MiniLineChart.tsx
@@ -0,0 +1,56 @@
+import { line } from "d3-shape";
+import { useEffectiveAnimation } from "../hooks/core/useEffectiveAnimation";
+import { MiniChartFrame } from "../shared/mini/MiniChartFrame";
+import { type MiniChartPoint, miniCurves, miniLineGeometry } from "../shared/mini/miniChartUtils";
+import { CHART_CLASS_PREFIX } from "../utils/constants";
+import { useChartPalette } from "../utils/paletteUtils";
+import type { MiniLineChartProps } from "./types";
+
+const CLASS = `${CHART_CLASS_PREFIX}-mini-line-chart`;
+
+/**
+ * A compact, axis-free line sparkline — react-ui's Recharts `MiniLineChart`:
+ * the most recent values that fit, one series, no dots.
+ */
+export function MiniLineChart({
+ data,
+ customPalette,
+ variant = "natural",
+ strokeWidth = 2,
+ isAnimationActive = false,
+ onLineClick,
+ size = "100%",
+ className,
+ lineColor,
+}: MiniLineChartProps) {
+ const animate = useEffectiveAnimation(isAnimationActive);
+ const [color = ""] = useChartPalette({
+ customPalette: customPalette ?? (lineColor ? [lineColor] : undefined),
+ themePaletteName: "lineChartPalette",
+ dataLength: 1,
+ });
+ const curve = miniCurves[variant] ?? miniCurves.natural;
+ const animated = animate ? ` ${CHART_CLASS_PREFIX}-mini-chart-mark--animated` : "";
+
+ return (
+ <MiniChartFrame chart="line" size={size} className={className} onClick={onLineClick}>
+ {(width, height) => {
+ const { points, x, y } = miniLineGeometry(data, width, height);
+ const lineD =
+ line<MiniChartPoint>()
+ .x((_, i) => x(i))
+ .y((p) => y(p.value))
+ .curve(curve)(points) ?? "";
+ return (
+ <path
+ className={`${CLASS}-line${animated}`}
+ d={lineD}
+ fill="none"
+ stroke={color}
+ strokeWidth={strokeWidth}
+ />
+ );
+ }}
+ </MiniChartFrame>
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/MiniLineChart/index.ts b/packages/react-ui/src/components/D3Charts/MiniLineChart/index.ts
new file mode 100644
index 000000000..7faf3a5cb
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/MiniLineChart/index.ts
@@ -0,0 +1,2 @@
+export { MiniLineChart } from "./MiniLineChart";
+export type { MiniLineChartData, MiniLineChartProps } from "./types";
diff --git a/packages/react-ui/src/components/D3Charts/MiniLineChart/stories/MiniLineChart.stories.tsx b/packages/react-ui/src/components/D3Charts/MiniLineChart/stories/MiniLineChart.stories.tsx
new file mode 100644
index 000000000..76186b63f
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/MiniLineChart/stories/MiniLineChart.stories.tsx
@@ -0,0 +1,189 @@
+// Copy of Charts/MiniLineChart/stories/MiniLineChart.stories.tsx with only the chart import and the title changed:
+// the same args and renders, rendering the D3Charts chart via
+// ../../stories/rechartsStoryAdapters.
+import type { Meta, StoryObj } from "@storybook/react";
+import { Card } from "../../../Card";
+import { MiniLineChart } from "../../stories/rechartsStoryAdapters";
+
+// Simple array of numbers for 1D line chart
+const simpleLineChartData = [
+ 12, 45, 78, 32, 67, 89, 23, 56, 91, 34, 76, 28, 85, 42, 19, 63, 87, 31, 74, 58, 92, 26, 49, 83,
+ 37, 50, 1,
+];
+
+// Array of objects with value and label
+const labeledLineChartData = [
+ { value: 150, label: "January" },
+ { value: 280, label: "February" },
+ { value: 220, label: "March" },
+ { value: 180, label: "April" },
+ { value: 250, label: "May" },
+ { value: 300, label: "June" },
+ { value: 320, label: "July" },
+ { value: 280, label: "August" },
+ { value: 310, label: "September" },
+ { value: 290, label: "October" },
+ { value: 340, label: "November" },
+ { value: 360, label: "December" },
+];
+
+const meta: Meta<typeof MiniLineChart> = {
+ title: "Components/D3Charts/MiniLineChart",
+ component: MiniLineChart,
+ parameters: {
+ layout: "centered",
+ docs: {
+ description: {
+ component:
+ "```tsx\nimport { MiniLineChart } from '@openuidev/react-ui/Charts/LineCharts/MiniLineChart';\n```\n\nA responsive mini line chart component that accepts 1D data (numbers or objects with value/label) with automatic data filtering for space-constrained containers. Features smooth line interpolation and customizable styling.",
+ },
+ },
+ },
+ tags: ["!autodocs"],
+ argTypes: {
+ data: {
+ description:
+ "An array of numbers or an array of objects with value and optional label. Each entry represents a single point in the line chart.",
+ control: false,
+ table: {
+ type: { summary: "Array<number> | Array<{ value: number; label?: string }>" },
+ defaultValue: { summary: "[]" },
+ category: "Data",
+ },
+ },
+ theme: {
+ description:
+ "The color palette theme for the chart. Each theme provides a different color for the line.",
+ control: "select",
+ options: ["ocean", "orchid", "emerald", "sunset", "spectrum", "vivid"],
+ table: {
+ defaultValue: { summary: "ocean" },
+ category: "Appearance",
+ },
+ },
+ variant: {
+ description:
+ "The interpolation method used to create the line curves. 'linear' creates straight lines between points, 'natural' creates smooth curves, and 'step' creates a stepped line.",
+ control: "radio",
+ options: ["linear", "natural", "step"],
+ table: {
+ defaultValue: { summary: "natural" },
+ category: "Appearance",
+ },
+ },
+ strokeWidth: {
+ description: "The width of the line stroke",
+ control: "number",
+ table: {
+ type: { summary: "number" },
+ defaultValue: { summary: "2" },
+ category: "Appearance",
+ },
+ },
+ isAnimationActive: {
+ description: "Whether to animate the chart when it first renders",
+ control: "boolean",
+ table: {
+ type: { summary: "boolean" },
+ defaultValue: { summary: "true" },
+ category: "Display",
+ },
+ },
+ size: {
+ description: "The width and height of the chart",
+ control: "text",
+ table: {
+ type: { summary: "number | string" },
+ defaultValue: { summary: "100%" },
+ category: "Appearance",
+ },
+ },
+ lineColor: {
+ description: "Custom color for the line stroke",
+ control: "color",
+ table: {
+ type: { summary: "string" },
+ category: "Appearance",
+ },
+ },
+ },
+} satisfies Meta<typeof MiniLineChart>;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+export const SimpleNumberArray: Story = {
+ name: "Simple Number Array",
+ args: {
+ data: simpleLineChartData,
+ theme: "ocean",
+ variant: "natural",
+ strokeWidth: 2,
+ isAnimationActive: true,
+ size: "100%",
+ },
+ render: (args: any) => (
+ <Card style={{ width: "280px", padding: "20px" }}>
+ <h3 style={{ marginBottom: "16px", fontSize: "16px", fontWeight: "600" }}>Daily Activity</h3>
+ <MiniLineChart {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ source: {
+ code: `
+const activityData = [12, 45, 78, 32, 67, 89, 23, 56, 91, 34];
+
+<MiniLineChart
+ data={activityData}
+ theme="ocean"
+ variant="natural"
+ strokeWidth={2}
+ isAnimationActive={true}
+ size="100%"
+/>
+`,
+ },
+ },
+ },
+};
+
+export const LabeledData: Story = {
+ name: "Labeled Data",
+ args: {
+ data: labeledLineChartData,
+ theme: "emerald",
+ variant: "natural",
+ strokeWidth: 2,
+ isAnimationActive: true,
+ size: "100%",
+ },
+ render: (args: any) => (
+ <Card style={{ width: "320px", padding: "20px" }}>
+ <h3 style={{ marginBottom: "16px", fontSize: "16px", fontWeight: "600" }}>Monthly Revenue</h3>
+ <MiniLineChart {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ source: {
+ code: `
+const revenueData = [
+ { value: 150, label: "January" },
+ { value: 280, label: "February" },
+ { value: 220, label: "March" },
+ // ...
+];
+
+<MiniLineChart
+ data={revenueData}
+ theme="emerald"
+ variant="natural"
+ strokeWidth={2}
+ size="100%"
+/>
+`,
+ },
+ },
+ },
+};
diff --git a/packages/react-ui/src/components/D3Charts/MiniLineChart/types.ts b/packages/react-ui/src/components/D3Charts/MiniLineChart/types.ts
new file mode 100644
index 000000000..acbe25864
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/MiniLineChart/types.ts
@@ -0,0 +1,18 @@
+export type MiniLineChartData = Array<number> | Array<{ value: number; label?: string }>;
+
+export interface MiniLineChartProps {
+ data: MiniLineChartData;
+ customPalette?: string[];
+ variant?: "linear" | "natural" | "step";
+ /** Line width in px. Default 2. */
+ strokeWidth?: number;
+ /** Fade the chart in on mount. Default false; printing always disables it. */
+ isAnimationActive?: boolean;
+ /** Called with the click event when the chart is clicked. */
+ onLineClick?: (data: any) => void;
+ /** Width and height (the chart stays square, at least 100px). Default "100%". */
+ size?: number | string;
+ className?: string;
+ /** Single color override; `customPalette` wins when both are set. */
+ lineColor?: string;
+}
diff --git a/packages/react-ui/src/components/D3Charts/PieChart/PieChart.tsx b/packages/react-ui/src/components/D3Charts/PieChart/PieChart.tsx
new file mode 100644
index 000000000..a97d9fb4b
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/PieChart/PieChart.tsx
@@ -0,0 +1,186 @@
+import { arc, pie, type PieArcDatum } from "d3-shape";
+import { useMemo } from "react";
+
+import {
+ type CategoricalSlice,
+ useCategoricalChartOrchestrator,
+ useEffectiveAnimation,
+ useExportChartData,
+} from "../hooks";
+import { ChartShell } from "../shared/core/ChartShell";
+import { DefaultLegend } from "../shared/core/DefaultLegend/DefaultLegend";
+import { useResolvedLegendKey } from "../shared/core/legend/LegendStoreProvider";
+import { ChartTooltip } from "../shared/core/PortalTooltip/ChartTooltip";
+import { ChartWithStackedLegend } from "../shared/core/StackedLegend/ChartWithStackedLegend";
+import { CHART_CLASS_PREFIX } from "../utils/constants";
+import { PieSlices } from "./parts/PieSlices";
+import type { PieChartData, PieChartProps } from "./types";
+
+/**
+ * `legendVariant="stacked"` (the default, as in react-ui's Recharts PieChart)
+ * lays the chart out with its built-in stacked legend. The inline legend is
+ * used for `"default"`, and none when the chart publishes to an external
+ * legend (`legendKey`, or a surrounding `LegendStoreProvider`'s key).
+ */
+export function PieChart<T extends PieChartData>(props: PieChartProps<T>) {
+ const { legend = true, legendVariant = "stacked", legendKey, width, height, className } = props;
+ const externalLegendKey = useResolvedLegendKey(legendKey);
+
+ if (legend && legendVariant === "stacked" && externalLegendKey === undefined) {
+ return (
+ <ChartWithStackedLegend width={width} height={height} className={className}>
+ <PieChartImpl {...props} width={undefined} height={undefined} className={undefined} />
+ </ChartWithStackedLegend>
+ );
+ }
+ return <PieChartImpl {...props} />;
+}
+
+function PieChartImpl<T extends PieChartData>(props: PieChartProps<T>) {
+ const {
+ data,
+ categoryKey,
+ dataKey,
+ customPalette,
+ variant = "pie",
+ appearance = "circular",
+ format = "number",
+ legend: showLegend = true,
+ isAnimationActive = false,
+ cornerRadius = 0,
+ paddingAngle = 0,
+ maxChartSize = 500,
+ minChartSize = 150,
+ height,
+ width,
+ fitLegendInHeight,
+ className,
+ onClick,
+ legendKey,
+ } = props;
+
+ const isSemiCircular = appearance === "semiCircular";
+
+ const orch = useCategoricalChartOrchestrator({
+ data,
+ categoryKey,
+ dataKey,
+ themePaletteName: "pieChartPalette",
+ customPalette,
+ format,
+ showLegend,
+ isSemiCircular,
+ maxChartSize,
+ minChartSize,
+ height,
+ width,
+ fitLegendInHeight,
+ legendKey,
+ });
+
+ const animate = useEffectiveAnimation(isAnimationActive);
+
+ // Pie-specific geometry
+ const outerRadius = orch.dimensions.chartSize * 0.45;
+ const innerRadius = variant === "donut" ? outerRadius * 0.6 : 0;
+
+ const startAngle = isSemiCircular ? -Math.PI / 2 : 0;
+ const endAngle = isSemiCircular ? Math.PI / 2 : 2 * Math.PI;
+
+ const pieGenerator = useMemo(
+ () =>
+ pie<CategoricalSlice>()
+ .value((d) => d.value)
+ .sort(null)
+ .startAngle(startAngle)
+ .endAngle(endAngle)
+ .padAngle((paddingAngle * Math.PI) / 180),
+ [startAngle, endAngle, paddingAngle],
+ );
+
+ const arcGenerator = useMemo(
+ () =>
+ arc<unknown, PieArcDatum<CategoricalSlice>>()
+ .innerRadius(innerRadius)
+ .outerRadius(outerRadius)
+ .cornerRadius(cornerRadius),
+ [innerRadius, outerRadius, cornerRadius],
+ );
+
+ const arcs = useMemo(
+ () => pieGenerator(orch.data.visibleSlices),
+ [pieGenerator, orch.data.visibleSlices],
+ );
+
+ // PPTX print-export JSON — mirrors react-ui's PieChart call (type:'pie',
+ // single series = [dataKey], no extraOptions). Colors are the resolved slice
+ // palette in sorted-data order. Undefined off the print path.
+ const exportData = useExportChartData({
+ type: "pie",
+ data: orch.data.sortedData,
+ categoryKey: orch.data.catKey,
+ dataKeys: [orch.data.valKey],
+ colors: orch.data.slices.map((s) => s.color),
+ legend: showLegend,
+ });
+
+ return (
+ <ChartShell
+ containerRef={orch.refs.containerRef}
+ classPrefix={`${CHART_CLASS_PREFIX}-pie-chart`}
+ className={className}
+ style={orch.style.containerStyle}
+ isEmpty={orch.isEmpty}
+ exportData={exportData}
+ >
+ {() => (
+ <>
+ <div className={`${CHART_CLASS_PREFIX}-pie-chart-svg-wrapper`}>
+ <svg
+ width={orch.dimensions.svgWidth}
+ height={orch.dimensions.svgHeight}
+ viewBox={`0 0 ${orch.dimensions.svgWidth} ${orch.dimensions.svgHeight}`}
+ role="img"
+ aria-label="Pie chart"
+ >
+ <g transform={`translate(${orch.dimensions.centerX}, ${orch.dimensions.centerY})`}>
+ <PieSlices
+ arcs={arcs}
+ arcGenerator={arcGenerator}
+ slices={orch.data.visibleSlices}
+ hoveredIndex={orch.hover.hoveredIndex}
+ entrance={animate}
+ staticRender={orch.isPrinting}
+ data={orch.data.visibleRows}
+ onMouseMove={orch.hover.handleMouseMove}
+ onMouseLeave={orch.hover.handleMouseLeave}
+ onClick={onClick}
+ />
+ </g>
+ </svg>
+ </div>
+
+ {showLegend && !orch.usesRemoteLegend && (
+ <DefaultLegend
+ ref={orch.refs.legendRef}
+ items={orch.data.legendItems}
+ containerWidth={orch.dimensions.containerWidth}
+ isExpanded={orch.legend.isLegendExpanded}
+ setIsExpanded={orch.legend.setIsLegendExpanded}
+ onItemClick={orch.data.toggleSlice}
+ hiddenSeries={orch.data.hiddenSlices}
+ />
+ )}
+
+ {orch.tooltip.tooltipPayload && orch.hover.mousePos && (
+ <ChartTooltip
+ label={orch.tooltip.tooltipPayload.label}
+ items={orch.tooltip.tooltipPayload.items}
+ viewportPosition={orch.hover.mousePos}
+ />
+ )}
+ </>
+ )}
+ </ChartShell>
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/PieChart/index.ts b/packages/react-ui/src/components/D3Charts/PieChart/index.ts
new file mode 100644
index 000000000..713249dea
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/PieChart/index.ts
@@ -0,0 +1,2 @@
+export { PieChart } from "./PieChart";
+export type { PieChartData, PieChartProps } from "./types";
diff --git a/packages/react-ui/src/components/D3Charts/PieChart/parts/PieSlices.tsx b/packages/react-ui/src/components/D3Charts/PieChart/parts/PieSlices.tsx
new file mode 100644
index 000000000..780d3aac4
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/PieChart/parts/PieSlices.tsx
@@ -0,0 +1,189 @@
+import type { Arc, PieArcDatum } from "d3-shape";
+import React from "react";
+import type { CategoricalSlice } from "../../hooks";
+import { useIndexedClickHandler } from "../../hooks/core/useIndexedClickHandler";
+import { springPresets, useIsomorphicLayoutEffect, useTranslate } from "../../shared/core/spring";
+import { CHART_CLASS_PREFIX } from "../../utils/constants";
+import { entranceProps } from "../../utils/entranceUtils";
+import { getSliceStyle, POLAR_HOVER_TRANSITION } from "../../utils/polarUtils";
+
+// How far the hovered wedge pops out along its radial bisector (px).
+const PIE_HOVER_OFFSET = 8;
+
+// Outward direction of a slice. d3 angles start at 12 o'clock and increase clockwise,
+// so the radial bisector points to (sin(mid), -cos(mid)).
+function sliceOffset(startAngle: number, endAngle: number, distance: number) {
+ // A near-full-circle slice has no meaningful bisector — don't slide it in an arbitrary
+ // direction; getSliceStyle still conveys the hover.
+ if (endAngle - startAngle >= 2 * Math.PI - 1e-9) return { x: 0, y: 0 };
+ const mid = (startAngle + endAngle) / 2;
+ return { x: Math.sin(mid) * distance, y: -Math.cos(mid) * distance };
+}
+
+interface PieSlicesProps<T> {
+ arcs: PieArcDatum<CategoricalSlice>[];
+ arcGenerator: Arc<unknown, PieArcDatum<CategoricalSlice>>;
+ slices: CategoricalSlice[];
+ hoveredIndex: number | null;
+ /** Play the entrance animation (pre-folded with ¬printing at the entry). */
+ entrance: boolean;
+ /** Render the inert print path: no hitbox, no spring, no entrance. */
+ staticRender: boolean;
+ data: T[];
+ onMouseMove: (event: React.MouseEvent, index: number) => void;
+ onMouseLeave: () => void;
+ onClick?: (row: T, index: number) => void;
+}
+
+export function PieSlices<T>({
+ arcs,
+ arcGenerator,
+ slices,
+ hoveredIndex,
+ entrance,
+ staticRender,
+ data,
+ onMouseMove,
+ onMouseLeave,
+ onClick,
+}: PieSlicesProps<T>) {
+ const handleClick = useIndexedClickHandler(data, onClick);
+
+ return (
+ <g>
+ {arcs.map((arc, i) => {
+ const slice = slices[i];
+ if (!slice) return null;
+ const pathD = arcGenerator(arc);
+ if (!pathD) return null;
+
+ // Print: one inert path, handlers on it, no hitbox, no spring.
+ // Branching here (rather than inside <Slice>) keeps the spring
+ // machinery off the print path entirely. The hover pop-out spring is
+ // NOT gated by isAnimationActive — hover glide is interaction
+ // feedback, not decoration (decision D-1); only the entrance is.
+ if (staticRender) {
+ return (
+ <path
+ key={slice.label}
+ d={pathD}
+ fill={slice.color}
+ style={{
+ ...getSliceStyle(i, hoveredIndex),
+ cursor: onClick ? "pointer" : undefined,
+ transition: POLAR_HOVER_TRANSITION,
+ }}
+ onMouseMove={(e) => onMouseMove(e, i)}
+ onMouseLeave={onMouseLeave}
+ onClick={() => handleClick(i)}
+ />
+ );
+ }
+
+ return (
+ <Slice
+ key={slice.label}
+ pathD={pathD}
+ color={slice.color}
+ sliceStyle={getSliceStyle(i, hoveredIndex)}
+ hovered={hoveredIndex === i}
+ offset={sliceOffset(arc.startAngle, arc.endAngle, PIE_HOVER_OFFSET)}
+ entrance={entrance}
+ animationDelay={i * 50}
+ clickable={!!onClick}
+ onMouseMove={(e) => onMouseMove(e, i)}
+ onMouseLeave={onMouseLeave}
+ onClick={() => handleClick(i)}
+ />
+ );
+ })}
+ </g>
+ );
+}
+
+interface SliceProps {
+ pathD: string;
+ color: string;
+ sliceStyle: React.CSSProperties;
+ hovered: boolean;
+ offset: { x: number; y: number };
+ entrance: boolean;
+ animationDelay: number;
+ clickable: boolean;
+ onMouseMove: (event: React.MouseEvent) => void;
+ onMouseLeave: () => void;
+ onClick: () => void;
+}
+
+/**
+ * One animated pie wedge. The hovered wedge GLIDES outward along its radial bisector via
+ * its own spring; every other wedge always springs back to home, so a legend toggle that
+ * shifts the positional `hovered` can never leave a wedge stuck popped-out. An invisible
+ * hitbox holds the base geometry under the cursor while the visible wedge moves; the
+ * spring's `translate` lives on a wrapper <g> so it composes with — rather than fights —
+ * the CSS entrance `scale` keyframe (which uses `forwards` and would otherwise override
+ * an inline transform on the same element). Mounted whenever not printing — the spring
+ * is hover feedback, independent of isAnimationActive; `entrance` only gates the
+ * keyframe class. The print path is a plain <path> in PieSlices (no spring).
+ */
+function Slice({
+ pathD,
+ color,
+ sliceStyle,
+ hovered,
+ offset,
+ entrance,
+ animationDelay,
+ clickable,
+ onMouseMove,
+ onMouseLeave,
+ onClick,
+}: SliceProps) {
+ const follow = useTranslate(springPresets.popOut);
+
+ // Glide to the offset when hovered, always glide home otherwise (rest IS home, so no
+ // seeded jump — the first hover is the pop-out itself).
+ useIsomorphicLayoutEffect(() => {
+ follow.to(hovered ? offset.x : 0, hovered ? offset.y : 0);
+ }, [hovered, offset.x, offset.y]);
+
+ const baseStyle: React.CSSProperties = {
+ ...sliceStyle,
+ transition: POLAR_HOVER_TRANSITION,
+ };
+
+ const { className: entranceClass, animationDelay: entranceDelay } = entranceProps(
+ entrance,
+ `${CHART_CLASS_PREFIX}-pie-chart-slice--animated`,
+ animationDelay,
+ );
+
+ return (
+ <g>
+ {/* Invisible hitbox: base geometry, owns the pointer, never moves. fill MUST stay
+ `transparent` (a painted region) — `none` would make the interior non-painted
+ and silently kill hover under the default `visiblePainted`. */}
+ <path
+ d={pathD}
+ fill="transparent"
+ style={{
+ pointerEvents: "all",
+ cursor: clickable ? "pointer" : undefined,
+ }}
+ onMouseMove={onMouseMove}
+ onMouseLeave={onMouseLeave}
+ onClick={onClick}
+ />
+ {/* Visible wedge: spring-translated; pointer-events:none on the wrapper falls
+ through to the hitbox so hover stays anchored to the un-popped footprint. */}
+ <g ref={follow.bind} style={{ pointerEvents: "none" }}>
+ <path
+ d={pathD}
+ fill={color}
+ className={entranceClass || undefined}
+ style={{ ...baseStyle, animationDelay: entranceDelay }}
+ />
+ </g>
+ </g>
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/PieChart/pieChart.scss b/packages/react-ui/src/components/D3Charts/PieChart/pieChart.scss
new file mode 100644
index 000000000..8fac0e63a
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/PieChart/pieChart.scss
@@ -0,0 +1,27 @@
+@use "../shared/cartesian/chartBase" as base;
+@use "../prefix" as brand;
+
+@include base.centered-container("pie-chart");
+@include base.centered-svg-wrapper("pie-chart");
+
+// Entrances are decorative: gate the whole rule (pre-state included) behind
+// reduced-motion so users who opt out get the natural static state immediately
+// — gating only the animation would strand elements at the opacity: 0 start.
+@media (prefers-reduced-motion: no-preference) {
+ .#{brand.$prefix}-pie-chart-slice--animated {
+ opacity: 0;
+ transform-origin: center center;
+ animation: #{brand.$prefix}-pie-appear 0.6s ease-out forwards;
+ }
+}
+
+@keyframes #{brand.$prefix}-pie-appear {
+ from {
+ opacity: 0;
+ transform: scale(0.8);
+ }
+ to {
+ opacity: 1;
+ transform: scale(1);
+ }
+}
diff --git a/packages/react-ui/src/components/D3Charts/PieChart/stories/PieChart.stories.tsx b/packages/react-ui/src/components/D3Charts/PieChart/stories/PieChart.stories.tsx
new file mode 100644
index 000000000..03f259163
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/PieChart/stories/PieChart.stories.tsx
@@ -0,0 +1,680 @@
+// Copy of Charts/PieChart/stories/PieChart.stories.tsx with only the chart import and the title changed:
+// the same args and renders, rendering the D3Charts chart via
+// ../../stories/rechartsStoryAdapters.
+import type { Meta, StoryObj } from "@storybook/react";
+import { useState } from "react";
+import { Card } from "../../../Card";
+import { PieChart, PieChartProps } from "../../stories/rechartsStoryAdapters";
+
+const monthlySalesData = [
+ { month: "January", value: 1250 },
+ { month: "February", value: 980 },
+ { month: "March", value: 1450 },
+ { month: "April", value: 1320 },
+ { month: "May", value: 1680 },
+ { month: "June", value: 2100 },
+];
+
+const comprehensiveData = [
+ { category: "Electronics", sales: 12500 },
+ { category: "Apparel", sales: 9800 },
+ { category: "Groceries", sales: 14500 },
+ { category: "Home Goods", sales: 13200 },
+ { category: "Books", sales: 8800 },
+ { category: "Toys", sales: 7600 },
+ { category: "Automotive", sales: 6500 },
+ { category: "Health", sales: 11200 },
+ { category: "Beauty", sales: 9300 },
+ { category: "Sports", sales: 8100 },
+ { category: "Outdoors", sales: 7200 },
+ { category: "Music", sales: 4500 },
+ { category: "Software", sales: 10500 },
+];
+
+/**
+ * # PieChart Component Documentation
+ *
+ * The PieChart component is a versatile and intuitive tool for visualizing
+ * part-to-whole relationships in a dataset. It's highly effective for:
+ *
+ * - **Proportional Analysis**: Showing how individual segments contribute to a total
+ * - **Category Comparison**: Comparing the relative size of different categories
+ * - **Dashboard KPIs**: Displaying key metrics like market share or budget allocation
+ *
+ * ## Key Features
+ *
+ * ### Chart Types
+ * - **Pie**: Classic circular chart for proportional representation
+ * - **Donut**: Pie chart with a center cutout, useful for displaying a central metric or for a modern look
+ *
+ * ### Layout Variants
+ * - **Circular**: Full 360-degree display for a complete data overview
+ * - **Semicircle**: Half-circle (180-degree) layout, ideal for compact dashboard widgets
+ *
+ * ### Data Formatting
+ * - **Percentage Mode**: Automatically calculates and displays segment values as percentages
+ * - **Number Mode**: Shows raw data values with appropriate formatting
+ *
+ * ### Interactive & Responsive
+ * - **Interactive Legend**: Adapts to container size with carousel navigation for large datasets
+ * - **Hover Tooltips**: Provides detailed information on hover for better user engagement
+ * - **Responsive Design**: Fluidly adjusts to the size of its container
+ *
+ * ### Customization
+ * - **Theming**: Six pre-built color palettes to match your application's design
+ * - **Styling Options**: Control corner radius, padding between slices, and more
+
+ */
+
+const meta: Meta<PieChartProps<typeof monthlySalesData>> = {
+ title: "Components/D3Charts/PieChart",
+ component: PieChart,
+ parameters: {
+ layout: "centered",
+ docs: {
+ description: {
+ component: `
+## Installation and Basic Usage
+
+\`\`\`tsx
+import { PieChart } from '@openuidev/react-ui/Charts/PieChart';
+
+// Basic implementation
+<PieChart
+ data={yourData}
+ categoryKey="category"
+ dataKey="value"
+ theme="ocean"
+/>
+\`\`\`
+
+## Data Structure Requirements
+
+Your data should be an array of objects where each object contains:
+- A **category field** (string): Used for labels and legend items
+- A **value field** (number): Used to determine slice sizes
+
+\`\`\`tsx
+const salesData = [
+ { category: "Electronics", value: 4500 },
+ { category: "Apparel", value: 3200 },
+ { category: "Groceries", value: 6800 }
+];
+\`\`\`
+
+## Performance Considerations
+- **Data Size**: Best for 3-12 data points for readability.
+- **Responsiveness**: Fully responsive and adapts to its container.
+- **Animation**: Can be disabled for performance with very large or complex charts.
+ `,
+ },
+ },
+ },
+ tags: ["dev", "autodocs"],
+ argTypes: {
+ data: {
+ description: `
+**Required.** An array of data objects representing your dataset. Each object should contain:
+- A category identifier (string)
+- A numeric value
+
+**Best Practices:**
+- Use 3-12 data points for optimal readability.
+- Ensure consistent data structure across all objects.
+`,
+ control: false,
+ table: {
+ type: { summary: "Array<Record<string, string | number>>" },
+ defaultValue: { summary: "[]" },
+ category: "📊 Data Configuration",
+ },
+ },
+ categoryKey: {
+ description:
+ "**Required.** The key in your data object that represents the category label (e.g., 'month', 'department').",
+ control: false,
+ table: {
+ type: { summary: "string" },
+ category: "📊 Data Configuration",
+ },
+ },
+ dataKey: {
+ description:
+ "**Required.** The key in your data object that contains the numeric value for each slice (e.g., 'value', 'sales').",
+ control: false,
+ table: {
+ type: { summary: "string" },
+ category: "📊 Data Configuration",
+ },
+ },
+ theme: {
+ description:
+ "The color palette for the chart. Provides a set of aesthetically pleasing colors.",
+ control: "select",
+ options: ["ocean", "orchid", "emerald", "sunset", "spectrum", "vivid"],
+ table: {
+ defaultValue: { summary: "ocean" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ customPalette: {
+ description:
+ "An array of color strings to use as a custom palette for the chart. This overrides the `theme` prop.",
+ control: "object",
+ table: {
+ type: { summary: "string[]" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ appearance: {
+ description: "The overall shape of the chart: a full circle or a semicircle.",
+ control: "radio",
+ options: ["circular", "semiCircular"],
+ table: {
+ defaultValue: { summary: "circular" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ variant: {
+ description: "The style of the chart: a standard pie or a donut with a cutout center.",
+ control: "radio",
+ options: ["pie", "donut"],
+ table: {
+ defaultValue: { summary: "pie" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ format: {
+ description:
+ "The format for displaying data values, either as raw numbers or as percentages.",
+ control: "radio",
+ options: ["percentage", "number"],
+ table: {
+ defaultValue: { summary: "number" },
+ category: "📱 Display Options",
+ },
+ },
+ legend: {
+ description: "Controls the visibility of the chart's legend.",
+ control: "boolean",
+ table: {
+ type: { summary: "boolean" },
+ defaultValue: { summary: "true" },
+ category: "📱 Display Options",
+ },
+ },
+ legendVariant: {
+ description: "The layout of the legend: a horizontal list or a responsive vertical stack.",
+ control: "radio",
+ options: ["default", "stacked"],
+ table: {
+ defaultValue: { summary: "default" },
+ category: "📱 Display Options",
+ },
+ },
+ isAnimationActive: {
+ description: "Enables or disables the initial loading animation.",
+ control: "boolean",
+ table: {
+ type: { summary: "boolean" },
+ defaultValue: { summary: "true" },
+ category: "🎬 Animation & Interaction",
+ },
+ },
+ cornerRadius: {
+ description: "The radius for rounding the corners of each pie slice.",
+ control: { type: "number", min: 0, max: 20 },
+ table: {
+ type: { summary: "number" },
+ defaultValue: { summary: "0" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ paddingAngle: {
+ description: "The spacing angle between each pie slice.",
+ control: { type: "number", min: 0, max: 10 },
+ table: {
+ type: { summary: "number" },
+ defaultValue: { summary: "0" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ height: {
+ description: "The height of the chart.",
+ control: "text",
+ table: {
+ type: { summary: "string | number" },
+ category: "📱 Display Options",
+ },
+ },
+ width: {
+ description: "The width of the chart.",
+ control: "text",
+ table: {
+ type: { summary: "string | number" },
+ category: "📱 Display Options",
+ },
+ },
+ },
+} satisfies Meta<typeof PieChart>;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+/**
+ * ## Interactive Playground
+ *
+ * This is a minimal story that renders just the PieChart component without any wrapper.
+ * Use the Controls panel to interactively test all available props and see how they
+ * affect the chart's appearance and behavior.
+ *
+ * **Perfect for:**
+ * - Testing different prop combinations
+ * - Exploring chart customization options
+ * - Understanding prop behaviors
+ */
+export const InteractivePlayground: Story = {
+ name: "🎮 Interactive Playground",
+ args: {
+ data: monthlySalesData,
+ categoryKey: "month",
+ dataKey: "value",
+ theme: "ocean",
+ variant: "pie",
+ format: "number",
+ legend: true,
+ legendVariant: "default",
+ isAnimationActive: true,
+ appearance: "circular",
+ cornerRadius: 0,
+ paddingAngle: 0,
+ height: undefined,
+ width: undefined,
+ },
+ render: (args: any) => <PieChart {...args} />,
+};
+
+/**
+ * ## Default Configuration
+ *
+ * This example showcases the PieChart with its standard settings, making it an
+ * ideal starting point for most data visualization needs.
+ *
+ * **Key Features Shown:**
+ * - Standard circular pie layout
+ * - Professional 'ocean' color theme
+ * - Responsive stacked legend for clarity
+ * - Smooth animations on load
+ */
+export const DefaultConfiguration: Story = {
+ name: "📊 Default Configuration",
+ args: {
+ data: monthlySalesData,
+ categoryKey: "month",
+ dataKey: "value",
+ theme: "ocean",
+ variant: "pie",
+ format: "number",
+ legend: true,
+ legendVariant: "stacked",
+ isAnimationActive: true,
+ appearance: "circular",
+ cornerRadius: 0,
+ paddingAngle: 0,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "400px", height: "fit-content", padding: "24px" }}>
+ <h3 style={{ marginBottom: "20px", fontSize: "18px", fontWeight: 600 }}>
+ Monthly Sales Performance
+ </h3>
+ <PieChart {...args} />
+ </Card>
+ ),
+};
+
+/**
+ * ## Layout and Variant Options
+ *
+ * This story demonstrates the different layout (`appearance`) and style (`variant`)
+ * options available in the PieChart component.
+ *
+ * **Options Shown:**
+ * - **Pie vs. Donut**: See the difference between a full pie and one with a center cutout.
+ * - **Circular vs. Semicircle**: Compare the full 360° layout with the space-saving 180° version.
+ */
+export const LayoutAndVariantOptions: Story = {
+ name: "🎨 Layout & Variant Options",
+ args: {
+ data: monthlySalesData.slice(0, 4),
+ categoryKey: "month",
+ dataKey: "value",
+ theme: "emerald",
+ legend: true,
+ legendVariant: "stacked",
+ isAnimationActive: false,
+ cornerRadius: 0,
+ paddingAngle: 0,
+ },
+ render: (args: any) => (
+ <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "40px", width: "800px" }}>
+ <div>
+ <h4 style={{ textAlign: "center", marginBottom: "16px" }}>Pie - Circular</h4>
+ <Card style={{ padding: "20px" }}>
+ <PieChart {...args} variant="pie" appearance="circular" />
+ </Card>
+ </div>
+ <div>
+ <h4 style={{ textAlign: "center", marginBottom: "16px" }}>Donut - Circular</h4>
+ <Card style={{ padding: "20px" }}>
+ <PieChart {...args} variant="donut" appearance="circular" />
+ </Card>
+ </div>
+ <div>
+ <h4 style={{ textAlign: "center", marginBottom: "16px" }}>Pie - Semicircle</h4>
+ <Card style={{ padding: "20px" }}>
+ <PieChart {...args} variant="pie" appearance="semiCircular" />
+ </Card>
+ </div>
+ <div>
+ <h4 style={{ textAlign: "center", marginBottom: "16px" }}>Donut - Semicircle</h4>
+ <Card style={{ padding: "20px" }}>
+ <PieChart {...args} variant="donut" appearance="semiCircular" />
+ </Card>
+ </div>
+ </div>
+ ),
+};
+
+/**
+ * ## Custom Palette
+ *
+ * This example demonstrates how to use a custom color palette.
+ *
+ * **Feature Highlight:**
+ * - The `customPalette` prop allows you to define your own array of colors.
+ */
+export const CustomPalette: Story = {
+ name: "🎨 Custom Palette",
+ args: {
+ data: monthlySalesData,
+ categoryKey: "month",
+ dataKey: "value",
+ variant: "donut",
+ legend: true,
+ legendVariant: "stacked",
+ cornerRadius: 4,
+ paddingAngle: 2,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "650px", height: "auto", padding: "24px" }}>
+ <h3 style={{ marginBottom: "20px", fontSize: "18px", fontWeight: 600 }}>
+ Chart with Custom Palette
+ </h3>
+ <PieChart {...args} />
+ </Card>
+ ),
+};
+
+/**
+ * ## Large Dataset with Carousel
+ *
+ * The PieChart's legend intelligently handles a large number of items by
+ * enabling a scrollable carousel with up/down navigation.
+ *
+ * **Feature Highlight:**
+ * - The legend's carousel appears automatically when items overflow the available space, ensuring all data points remain accessible without cluttering the UI.
+ */
+export const LargeDatasetWithCarousel: Story = {
+ name: "📈 Large Dataset with Carousel",
+ args: {
+ data: comprehensiveData,
+ categoryKey: "category",
+ dataKey: "sales",
+ theme: "spectrum",
+ variant: "donut",
+ legend: true,
+ legendVariant: "stacked",
+ cornerRadius: 4,
+ paddingAngle: 1,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "700px", padding: "24px" }}>
+ <PieChart {...args} />
+ </Card>
+ ),
+};
+
+export const ResponsiveDemo: Story = {
+ name: "📱 Responsive Behavior Demo",
+ args: {
+ data: comprehensiveData,
+ categoryKey: "category",
+ dataKey: "sales",
+ theme: "spectrum",
+ variant: "circular",
+ format: "number",
+ legend: true,
+ legendVariant: "stacked",
+ isAnimationActive: false,
+ cornerRadius: 8,
+ },
+ render: (args: any) => {
+ const [dimensions, setDimensions] = useState<{ width: number; height: number | string }>({
+ width: 700,
+ height: "auto",
+ });
+
+ const handleMouseDown = (e: React.MouseEvent<HTMLDivElement>, handle: string) => {
+ e.preventDefault();
+ e.stopPropagation();
+ const startX = e.clientX;
+ const startY = e.clientY;
+ const startWidth = dimensions.width;
+ const startHeight = (e.currentTarget.parentElement as HTMLElement).offsetHeight;
+
+ const doDrag = (e: MouseEvent) => {
+ const dx = e.clientX - startX;
+ const dy = e.clientY - startY;
+ let newWidth = startWidth;
+ let newHeight = startHeight;
+
+ if (handle.includes("e")) newWidth = startWidth + dx;
+ if (handle.includes("w")) newWidth = startWidth - dx;
+ if (handle.includes("s")) newHeight = startHeight + dy;
+ if (handle.includes("n")) newHeight = startHeight - dy;
+
+ setDimensions({
+ width: Math.max(300, newWidth),
+ height: "auto",
+ });
+ };
+
+ const stopDrag = () => {
+ document.removeEventListener("mousemove", doDrag);
+ document.removeEventListener("mouseup", stopDrag);
+ };
+
+ document.addEventListener("mousemove", doDrag);
+ document.addEventListener("mouseup", stopDrag);
+ };
+
+ const handleStyle: React.CSSProperties = {
+ position: "absolute",
+ background: "#3b82f6",
+ opacity: 0.6,
+ zIndex: 10,
+ transition: "opacity 0.2s ease",
+ };
+
+ return (
+ <div style={{ padding: "20px" }}>
+ <div style={{ marginBottom: "20px" }}>
+ <h3 style={{ margin: "0 0 8px 0", fontSize: "18px", fontWeight: "600" }}>
+ Responsive Behavior Demonstration
+ </h3>
+ <p style={{ margin: "0 0 12px 0", color: "#666", fontSize: "14px" }}>
+ Drag the edges or corners of the container below to see how the chart adapts
+ </p>
+ <div
+ style={{
+ padding: "12px",
+ backgroundColor: "#e3f2fd",
+ borderRadius: "6px",
+ fontSize: "12px",
+ color: "#1565c0",
+ }}
+ >
+ <strong>🎯 Try This:</strong> Resize the container to see automatic legend layout
+ changes, chart proportion adjustments, and responsive breakpoint behaviors.
+ </div>
+ </div>
+
+ <Card
+ style={{
+ position: "relative",
+ width: `${dimensions.width}px`,
+ height:
+ typeof dimensions.height === "number" ? `${dimensions.height}px` : dimensions.height,
+ border: "2px dashed #9ca3af",
+ padding: "20px",
+ boxSizing: "border-box",
+ overflow: "hidden",
+ cursor: "default",
+ }}
+ >
+ <PieChart {...args} />
+
+ {/* Resize Handles */}
+ <div
+ style={{ ...handleStyle, top: -2, left: 0, right: 0, height: 12, cursor: "ns-resize" }}
+ onMouseDown={(e) => handleMouseDown(e, "n")}
+ />
+ <div
+ style={{
+ ...handleStyle,
+ bottom: -2,
+ left: 0,
+ right: 0,
+ height: 12,
+ cursor: "ns-resize",
+ }}
+ onMouseDown={(e) => handleMouseDown(e, "s")}
+ />
+ <div
+ style={{ ...handleStyle, top: 0, bottom: 0, left: -2, width: 12, cursor: "ew-resize" }}
+ onMouseDown={(e) => handleMouseDown(e, "w")}
+ />
+ <div
+ style={{ ...handleStyle, top: 0, bottom: 0, right: -2, width: 12, cursor: "ew-resize" }}
+ onMouseDown={(e) => handleMouseDown(e, "e")}
+ />
+
+ {/* Corner Handles */}
+ <div
+ style={{
+ ...handleStyle,
+ top: -2,
+ left: -2,
+ width: 20,
+ height: 20,
+ cursor: "nwse-resize",
+ borderRadius: "2px",
+ }}
+ onMouseDown={(e) => handleMouseDown(e, "nw")}
+ />
+ <div
+ style={{
+ ...handleStyle,
+ top: -2,
+ right: -2,
+ width: 20,
+ height: 20,
+ cursor: "nesw-resize",
+ borderRadius: "2px",
+ }}
+ onMouseDown={(e) => handleMouseDown(e, "ne")}
+ />
+ <div
+ style={{
+ ...handleStyle,
+ bottom: -2,
+ right: -2,
+ width: 20,
+ height: 20,
+ cursor: "nwse-resize",
+ borderRadius: "2px",
+ }}
+ onMouseDown={(e) => handleMouseDown(e, "se")}
+ />
+
+ {/* Dimension Display */}
+ <div
+ style={{
+ position: "absolute",
+ bottom: 8,
+ right: 8,
+ background: "rgba(0,0,0,0.8)",
+ color: "white",
+ padding: "4px 8px",
+ borderRadius: "4px",
+ fontSize: "11px",
+ fontFamily: "monospace",
+ fontWeight: "500",
+ }}
+ >
+ {dimensions.width}px ×{" "}
+ {typeof dimensions.height === "number" ? `${dimensions.height}px` : "auto"}
+ </div>
+ </Card>
+
+ <div
+ style={{
+ marginTop: "16px",
+ padding: "12px",
+ backgroundColor: "#f8f9fa",
+ borderRadius: "6px",
+ fontSize: "12px",
+ color: "#666",
+ }}
+ >
+ <strong>📊 Responsive Features Demonstrated:</strong>
+ <ul style={{ margin: "8px 0 0 0", paddingLeft: "16px" }}>
+ <li>Automatic chart scaling and proportion maintenance</li>
+ <li>Legend layout adaptation (stacked ↔ horizontal)</li>
+ <li>Text size and spacing adjustments</li>
+ <li>Optimal space utilization at any container size</li>
+ </ul>
+ </div>
+ </div>
+ );
+ },
+ parameters: {
+ docs: {
+ description: {
+ story: `
+**Responsive Design Philosophy:**
+
+**Automatic Adaptation:**
+- Chart dimensions automatically adjust to container size
+- Legend layout switches between horizontal and stacked based on available space
+- Text and spacing scale appropriately for readability
+
+**Breakpoint Behavior:**
+- **Large Containers (>600px)**: Side-by-side chart and legend layout
+- **Medium Containers (400-600px)**: Stacked layout with optimized proportions
+- **Small Containers (<400px)**: Compact layout with essential elements only
+
+**Performance Optimizations:**
+- Efficient re-rendering during resize operations
+- Debounced resize calculations to prevent performance issues
+- Optimized SVG scaling for crisp display at any size
+
+**Implementation Notes:**
+- Uses ResizeObserver API for precise container size detection
+- Maintains aspect ratios while maximizing space utilization
+- Supports both fixed and flexible container sizing strategies
+ `,
+ },
+ },
+ },
+};
diff --git a/packages/react-ui/src/components/D3Charts/PieChart/types.ts b/packages/react-ui/src/components/D3Charts/PieChart/types.ts
new file mode 100644
index 000000000..159c8da46
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/PieChart/types.ts
@@ -0,0 +1,43 @@
+import type { ChartData } from "../types";
+
+export type PieChartData = ChartData;
+
+export interface PieChartProps<T extends PieChartData> {
+ data: T;
+ categoryKey: keyof T[number];
+ dataKey: keyof T[number];
+ customPalette?: string[];
+ variant?: "pie" | "donut";
+ appearance?: "circular" | "semiCircular";
+ format?: "percentage" | "number";
+ legend?: boolean;
+ /**
+ * `"stacked"` (default): the chart with a stacked legend listing each item's
+ * share — side by side from 400px wide, below the chart when narrower.
+ * `"default"`: the compact legend under the chart. Matches react-ui's
+ * Recharts PieChart.
+ */
+ legendVariant?: "default" | "stacked";
+ /** When set, this chart publishes its legend to the shared legend store under
+ * this key instead of rendering an inline legend. Place a
+ * `<StackedLegend legendKey="…" />` (under a `LegendStoreProvider`) anywhere to
+ * render + drive it. Keys must be unique per chart instance. */
+ legendKey?: string;
+ /**
+ * Play the entrance animation. Gates the entrance ONLY — any hover or
+ * data-update motion is independent of this flag, and printing always
+ * disables it.
+ * Default false (streaming-safe: marks mounted while data streams in don't
+ * replay staggered entrances).
+ */
+ isAnimationActive?: boolean;
+ cornerRadius?: number;
+ paddingAngle?: number;
+ maxChartSize?: number;
+ minChartSize?: number;
+ height?: number | string;
+ width?: number | string;
+ fitLegendInHeight?: boolean;
+ className?: string;
+ onClick?: (row: T[number], index: number) => void;
+}
diff --git a/packages/react-ui/src/components/D3Charts/RadarChart/RadarChart.tsx b/packages/react-ui/src/components/D3Charts/RadarChart/RadarChart.tsx
new file mode 100644
index 000000000..a5787d554
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/RadarChart/RadarChart.tsx
@@ -0,0 +1,157 @@
+import { useCallback, useMemo } from "react";
+
+import { useEffectiveAnimation, useRadarChartOrchestrator } from "../hooks";
+import { ChartShell } from "../shared/core/ChartShell";
+import { DefaultLegend } from "../shared/core/DefaultLegend/DefaultLegend";
+import { ChartTooltip } from "../shared/core/PortalTooltip/ChartTooltip";
+import { CHART_CLASS_PREFIX } from "../utils/constants";
+import { RadarAxisLabels } from "./parts/RadarAxisLabels";
+import { RadarGrid } from "./parts/RadarGrid";
+import { RadarSeries } from "./parts/RadarSeries";
+import type { RadarChartData, RadarChartProps } from "./types";
+
+export function RadarChart<T extends RadarChartData>(props: RadarChartProps<T>) {
+ const {
+ data,
+ categoryKey,
+ customPalette,
+ gridShape = "polygon",
+ gridLevels = 5,
+ grid: showGrid = true,
+ legend: showLegend = true,
+ icons,
+ isAnimationActive = false,
+ variant = "line",
+ areaOpacity = 0.2,
+ showDots = false,
+ dotRadius = 4,
+ fillOpacity,
+ maxChartSize = 500,
+ minChartSize = 150,
+ height,
+ width,
+ fitLegendInHeight,
+ className,
+ onClick,
+ } = props;
+
+ const orch = useRadarChartOrchestrator({
+ data,
+ categoryKey,
+ themePaletteName: "radarChartPalette",
+ customPalette,
+ icons,
+ showLegend,
+ maxChartSize,
+ minChartSize,
+ height,
+ width,
+ fitLegendInHeight,
+ onClick,
+ });
+
+ const animate = useEffectiveAnimation(isAnimationActive);
+
+ const numAxes = data.length;
+
+ const findIndex = useCallback(
+ (mouseX: number, mouseY: number) => {
+ if (numAxes === 0) return -1;
+ let angle = Math.atan2(mouseY, mouseX) + Math.PI / 2;
+ if (angle < 0) angle += 2 * Math.PI;
+ return Math.round(angle / ((2 * Math.PI) / numAxes)) % numAxes;
+ },
+ [numAxes],
+ );
+
+ // Destructured so the memo depends on the callback identity itself (a
+ // stable useCallback), not the whole orch.hover object.
+ const { createMouseHandlers } = orch.hover;
+ const mouseHandlers = useMemo(
+ () => createMouseHandlers(findIndex),
+ [createMouseHandlers, findIndex],
+ );
+
+ return (
+ <ChartShell
+ containerRef={orch.refs.containerRef}
+ classPrefix={`${CHART_CLASS_PREFIX}-radar-chart`}
+ className={className}
+ style={orch.style.containerStyle}
+ isEmpty={orch.isEmpty}
+ >
+ {() => (
+ <>
+ <div className={`${CHART_CLASS_PREFIX}-radar-chart-svg-wrapper`}>
+ <svg
+ width={orch.dimensions.svgWidth}
+ height={orch.dimensions.svgHeight}
+ viewBox={`0 0 ${orch.dimensions.svgWidth} ${orch.dimensions.svgHeight}`}
+ role="img"
+ aria-label="Radar chart"
+ >
+ <g
+ transform={`translate(${orch.dimensions.centerX}, ${orch.dimensions.centerY})`}
+ onMouseMove={mouseHandlers.handleMouseMove}
+ onMouseLeave={mouseHandlers.handleMouseLeave}
+ onTouchMove={mouseHandlers.handleTouchMove}
+ onTouchEnd={mouseHandlers.handleTouchEnd}
+ onClick={mouseHandlers.handleClick}
+ >
+ {showGrid && (
+ <RadarGrid
+ maxRadius={orch.dimensions.maxRadius}
+ gridLevels={gridLevels}
+ gridShape={gridShape}
+ numAxes={numAxes}
+ />
+ )}
+ <RadarSeries
+ data={data}
+ dataKeys={orch.data.dataKeys}
+ catKey={orch.data.catKey}
+ radialScale={orch.dimensions.radialScale}
+ numAxes={numAxes}
+ colorMap={orch.data.colorMap}
+ fillOpacity={fillOpacity ?? (variant === "area" ? areaOpacity : 0)}
+ showDots={showDots}
+ dotRadius={dotRadius}
+ hoveredIndex={orch.hover.hoveredIndex}
+ animate={animate}
+ />
+ <RadarAxisLabels
+ data={data}
+ catKey={orch.data.catKey}
+ numAxes={numAxes}
+ maxRadius={orch.dimensions.maxRadius}
+ chartSize={orch.dimensions.chartSize}
+ containerWidth={orch.dimensions.containerWidth}
+ />
+ </g>
+ </svg>
+ </div>
+
+ {showLegend && (
+ <DefaultLegend
+ ref={orch.refs.legendRef}
+ items={orch.legend.legendItems}
+ containerWidth={orch.dimensions.containerWidth}
+ isExpanded={orch.legend.isLegendExpanded}
+ setIsExpanded={orch.legend.setIsLegendExpanded}
+ onItemClick={orch.legend.toggleSeries}
+ hiddenSeries={orch.legend.hiddenSeries}
+ />
+ )}
+
+ {orch.tooltip.tooltipPayload && orch.hover.mousePos && (
+ <ChartTooltip
+ label={orch.tooltip.tooltipPayload.label}
+ items={orch.tooltip.tooltipPayload.items}
+ viewportPosition={orch.hover.mousePos}
+ />
+ )}
+ </>
+ )}
+ </ChartShell>
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/RadarChart/index.ts b/packages/react-ui/src/components/D3Charts/RadarChart/index.ts
new file mode 100644
index 000000000..ffed6f64a
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/RadarChart/index.ts
@@ -0,0 +1,2 @@
+export { RadarChart } from "./RadarChart";
+export type { RadarChartData, RadarChartProps } from "./types";
diff --git a/packages/react-ui/src/components/D3Charts/RadarChart/parts/RadarAxisLabels.tsx b/packages/react-ui/src/components/D3Charts/RadarChart/parts/RadarAxisLabels.tsx
new file mode 100644
index 000000000..3e523511e
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/RadarChart/parts/RadarAxisLabels.tsx
@@ -0,0 +1,130 @@
+import { useCanvasContextForLabelSize } from "../../hooks/core/useCanvasContextForLabelSize";
+import { LabelTooltip } from "../../shared/core/LabelTooltip/LabelTooltip";
+import type { ChartData } from "../../types";
+import { CHART_CLASS_PREFIX } from "../../utils/constants";
+import { parseLineHeight, truncateToWidth, wrapLabelLines } from "../../utils/labelWrap";
+import { MIN_RADAR_LABEL_BUDGET, radarLabelLayout } from "../../utils/radarLabelLayout";
+
+interface RadarAxisLabelsProps<T extends ChartData> {
+ data: T;
+ catKey: string;
+ numAxes: number;
+ maxRadius: number;
+ chartSize: number;
+ containerWidth: number;
+}
+
+const BASELINE = {
+ top: "hanging",
+ middle: "middle",
+ bottom: "auto",
+} as const;
+
+// Truncated labels get a LabelTooltip; stop chart-hover events on their group
+// so the axis ChartTooltip doesn't co-fire underneath it (labels live inside
+// the hover-owning <g> in RadarChart.tsx).
+// Known follow-up: if a browser doesn't deliver pointer events on overflow-painted svg content (Safari/Firefox unverified), truncated labels fall back to aria-label only — the axis tooltip is deliberately stopped here.
+const stop = (e: { stopPropagation: () => void }) => e.stopPropagation();
+
+/**
+ * Category labels as native SVG text (multi-line via tspans, measured-trim
+ * ellipsis — the XAxis pattern). Budgets come from radarLabelLayout and are
+ * container-relative: the svg has overflow:visible (radarChart.scss), so
+ * labels legitimately paint outside the square chart, bounded by the
+ * container edges. Pre-hydration the measuring ctx is a zero-width stub, so
+ * everything "fits": full labels render server-side and one post-hydration
+ * re-render applies real truncation.
+ */
+export function RadarAxisLabels<T extends ChartData>({
+ data,
+ catKey,
+ numAxes,
+ maxRadius,
+ chartSize,
+ containerWidth,
+}: RadarAxisLabelsProps<T>) {
+ const ctx = useCanvasContextForLabelSize();
+ const lineHeight = parseLineHeight(ctx.font);
+
+ return (
+ <g className={`${CHART_CLASS_PREFIX}-radar-chart-axis-labels`}>
+ {data.map((row, i) => {
+ const label = String(row[catKey]);
+ const layout = radarLabelLayout(i, numAxes, {
+ chartSize,
+ maxRadius,
+ containerWidth,
+ lineHeight,
+ });
+ if (layout.maxWidth < MIN_RADAR_LABEL_BUDGET) return null;
+
+ const lines =
+ layout.maxLines === 1
+ ? [truncateToWidth(ctx, label, layout.maxWidth)]
+ : wrapLabelLines(ctx, label, layout.maxWidth, layout.maxLines);
+ const truncated = lines.some((line) => line.endsWith("…"));
+
+ // First-line dy places the whole wrapped block per vAlign: 'top'
+ // (hanging) grows down, 'bottom' (auto) grows up so the LAST baseline
+ // sits at the anchor, 'middle' splits the block across the anchor.
+ const firstDy =
+ layout.vAlign === "top"
+ ? 0
+ : layout.vAlign === "bottom"
+ ? -(lines.length - 1) * lineHeight
+ : (-(lines.length - 1) / 2) * lineHeight;
+
+ const text = (
+ <text
+ x={layout.x}
+ y={layout.y}
+ textAnchor={layout.hAlign}
+ dominantBaseline={BASELINE[layout.vAlign]}
+ className={`${CHART_CLASS_PREFIX}-radar-chart-axis-label`}
+ aria-label={truncated ? label : undefined}
+ >
+ {lines.map((line, li) => (
+ <tspan key={li} x={layout.x} dy={li === 0 ? firstDy : lineHeight}>
+ {line}
+ </tspan>
+ ))}
+ </text>
+ );
+
+ if (!truncated) {
+ return <g key={`${label}-${i}`}>{text}</g>;
+ }
+
+ const blockWidth = Math.max(...lines.map((line) => ctx.measureText(line).width));
+ const blockHeight = lines.length * lineHeight;
+ const rectX =
+ layout.hAlign === "start"
+ ? layout.x
+ : layout.hAlign === "end"
+ ? layout.x - blockWidth
+ : layout.x - blockWidth / 2;
+ const rectY =
+ layout.vAlign === "top"
+ ? layout.y
+ : layout.vAlign === "bottom"
+ ? layout.y - blockHeight
+ : layout.y - blockHeight / 2;
+
+ return (
+ <LabelTooltip key={`${label}-${i}`} content={label} disabled={false}>
+ <g onMouseMove={stop} onTouchMove={stop}>
+ <rect
+ x={rectX}
+ y={rectY}
+ width={blockWidth}
+ height={blockHeight}
+ fill="transparent"
+ />
+ {text}
+ </g>
+ </LabelTooltip>
+ );
+ })}
+ </g>
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/RadarChart/parts/RadarGrid.tsx b/packages/react-ui/src/components/D3Charts/RadarChart/parts/RadarGrid.tsx
new file mode 100644
index 000000000..254040c43
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/RadarChart/parts/RadarGrid.tsx
@@ -0,0 +1,57 @@
+import { CHART_CLASS_PREFIX } from "../../utils/constants";
+import { radarAxisAngle } from "../../utils/polarUtils";
+
+interface RadarGridProps {
+ maxRadius: number;
+ gridLevels: number;
+ gridShape: "circle" | "polygon";
+ numAxes: number;
+}
+
+function buildPolygonPoints(radius: number, numAxes: number): string {
+ return Array.from({ length: numAxes }, (_, i) => {
+ const angle = radarAxisAngle(i, numAxes);
+ return `${radius * Math.cos(angle)},${radius * Math.sin(angle)}`;
+ }).join(" ");
+}
+
+export function RadarGrid({ maxRadius, gridLevels, gridShape, numAxes }: RadarGridProps) {
+ const levels = Array.from({ length: gridLevels }, (_, i) => ((i + 1) / gridLevels) * maxRadius);
+
+ return (
+ <g className={`${CHART_CLASS_PREFIX}-radar-chart-grid`}>
+ {levels.map((r) =>
+ gridShape === "circle" ? (
+ <circle
+ key={r}
+ cx={0}
+ cy={0}
+ r={r}
+ className={`${CHART_CLASS_PREFIX}-radar-chart-grid-ring`}
+ fill="none"
+ />
+ ) : (
+ <polygon
+ key={r}
+ points={buildPolygonPoints(r, numAxes)}
+ className={`${CHART_CLASS_PREFIX}-radar-chart-grid-ring`}
+ fill="none"
+ />
+ ),
+ )}
+ {Array.from({ length: numAxes }, (_, i) => {
+ const angle = radarAxisAngle(i, numAxes);
+ return (
+ <line
+ key={i}
+ x1={0}
+ y1={0}
+ x2={maxRadius * Math.cos(angle)}
+ y2={maxRadius * Math.sin(angle)}
+ className={`${CHART_CLASS_PREFIX}-radar-chart-grid-spoke`}
+ />
+ );
+ })}
+ </g>
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/RadarChart/parts/RadarSeries.tsx b/packages/react-ui/src/components/D3Charts/RadarChart/parts/RadarSeries.tsx
new file mode 100644
index 000000000..b85f72894
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/RadarChart/parts/RadarSeries.tsx
@@ -0,0 +1,100 @@
+import type { ScaleLinear } from "d3-scale";
+
+import type { ChartData } from "../../types";
+import { CHART_CLASS_PREFIX } from "../../utils/constants";
+import { entranceProps } from "../../utils/entranceUtils";
+import { radarAxisAngle } from "../../utils/polarUtils";
+
+interface RadarSeriesProps<T extends ChartData> {
+ data: T;
+ dataKeys: string[];
+ catKey: string;
+ radialScale: ScaleLinear<number, number>;
+ numAxes: number;
+ colorMap: Record<string, string>;
+ fillOpacity: number;
+ showDots: boolean;
+ dotRadius: number;
+ hoveredIndex: number | null;
+ /** Pre-folded "animation on AND not printing" — computed at the chart entry via useEffectiveAnimation. */
+ animate: boolean;
+}
+
+function computeVertices(
+ data: ChartData,
+ key: string,
+ numAxes: number,
+ radialScale: ScaleLinear<number, number>,
+): Array<{ x: number; y: number }> {
+ return data.map((row, i) => {
+ const angle = radarAxisAngle(i, numAxes);
+ const r = radialScale(Number(row[key]) || 0);
+ return { x: r * Math.cos(angle), y: r * Math.sin(angle) };
+ });
+}
+
+export function RadarSeries<T extends ChartData>({
+ data,
+ dataKeys,
+ catKey: _catKey,
+ radialScale,
+ numAxes,
+ colorMap,
+ fillOpacity,
+ showDots,
+ dotRadius,
+ hoveredIndex,
+ animate,
+}: RadarSeriesProps<T>) {
+ return (
+ <g className={`${CHART_CLASS_PREFIX}-radar-chart-series`}>
+ {dataKeys.map((key, seriesIdx) => {
+ const color = colorMap[key] ?? "#000";
+ const vertices = computeVertices(data, key, numAxes, radialScale);
+ const points = vertices.map((v) => `${v.x},${v.y}`).join(" ");
+
+ const { className: animationClass, animationDelay } = entranceProps(
+ animate,
+ `${CHART_CLASS_PREFIX}-radar-chart-polygon--animated`,
+ seriesIdx * 80,
+ );
+
+ return (
+ <g key={key}>
+ <polygon
+ points={points}
+ fill={color}
+ fillOpacity={fillOpacity}
+ className={`${CHART_CLASS_PREFIX}-radar-chart-polygon-area ${animationClass}`}
+ style={{ animationDelay }}
+ />
+ <polygon
+ points={points}
+ className={`${CHART_CLASS_PREFIX}-radar-chart-polygon-stroke ${animationClass}`}
+ stroke={color}
+ style={{ animationDelay }}
+ />
+ {showDots &&
+ vertices.map((v, i) => {
+ const isHoveredAxis = hoveredIndex === i;
+ const r = isHoveredAxis ? dotRadius * 1.5 : dotRadius;
+ const opacity = hoveredIndex !== null && !isHoveredAxis ? 0.3 : 1;
+
+ return (
+ <circle
+ key={i}
+ cx={v.x}
+ cy={v.y}
+ r={r}
+ fill={color}
+ className={`${CHART_CLASS_PREFIX}-radar-chart-dot`}
+ style={{ opacity }}
+ />
+ );
+ })}
+ </g>
+ );
+ })}
+ </g>
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/RadarChart/radarChart.scss b/packages/react-ui/src/components/D3Charts/RadarChart/radarChart.scss
new file mode 100644
index 000000000..d04534493
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/RadarChart/radarChart.scss
@@ -0,0 +1,69 @@
+@use "../../../cssUtils" as cssUtils;
+@use "../shared/cartesian/chartBase" as base;
+@use "../prefix" as brand;
+
+@include base.centered-container("radar-chart");
+@include base.centered-svg-wrapper("radar-chart");
+
+// Labels are budgeted against the CONTAINER width (radarLabelLayout.ts) and
+// legitimately paint outside the square svg viewport; the polar container
+// column deliberately does not clip (chartBase.scss centered-container).
+// Vertical extent stays inside the svg via radarLabelPadding + line caps.
+.#{brand.$prefix}-radar-chart-svg-wrapper > svg {
+ overflow: visible;
+}
+
+// Solid rings and spokes in the interactive border tone, as react-ui's
+// Recharts RadarChart draws its polar grid.
+.#{brand.$prefix}-radar-chart-grid-ring {
+ stroke: cssUtils.$border-interactive;
+ stroke-width: 1;
+}
+
+.#{brand.$prefix}-radar-chart-grid-spoke {
+ stroke: cssUtils.$border-interactive;
+ stroke-width: 1;
+}
+
+.#{brand.$prefix}-radar-chart-polygon-area {
+ transition: opacity 0.2s ease;
+}
+
+.#{brand.$prefix}-radar-chart-polygon-stroke {
+ fill: none;
+ stroke-width: 2;
+}
+
+.#{brand.$prefix}-radar-chart-dot {
+ stroke: cssUtils.$foreground;
+ stroke-width: 1.5;
+ transition:
+ r 0.15s ease,
+ opacity 0.15s ease;
+}
+
+.#{brand.$prefix}-radar-chart-axis-label {
+ @include base.svg-tick-label;
+}
+
+// Entrances are decorative: gate the whole rule (pre-state included) behind
+// reduced-motion so users who opt out get the natural static state immediately
+// — gating only the animation would strand elements at the opacity: 0 start.
+@media (prefers-reduced-motion: no-preference) {
+ .#{brand.$prefix}-radar-chart-polygon--animated {
+ opacity: 0;
+ transform-origin: center center;
+ animation: #{brand.$prefix}-radar-polygon-appear 0.5s ease-out forwards;
+ }
+}
+
+@keyframes #{brand.$prefix}-radar-polygon-appear {
+ from {
+ opacity: 0;
+ transform: scale(0.3);
+ }
+ to {
+ opacity: 1;
+ transform: scale(1);
+ }
+}
diff --git a/packages/react-ui/src/components/D3Charts/RadarChart/stories/RadarChart.stories.tsx b/packages/react-ui/src/components/D3Charts/RadarChart/stories/RadarChart.stories.tsx
new file mode 100644
index 000000000..d89f4cce9
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/RadarChart/stories/RadarChart.stories.tsx
@@ -0,0 +1,722 @@
+// Copy of Charts/RadarChart/stories/RadarChart.stories.tsx with only the chart import and the title changed:
+// the same args and renders, rendering the D3Charts chart via
+// ../../stories/rechartsStoryAdapters.
+import type { Meta, StoryObj } from "@storybook/react";
+import { Shield, Star, Target } from "lucide-react";
+import { useState } from "react";
+import { Card } from "../../../Card";
+import { RadarChart, RadarChartProps } from "../../stories/rechartsStoryAdapters";
+
+// 📊 COMPREHENSIVE DATA VARIATIONS - Designed to test various radar chart scenarios
+const dataVariations = {
+ default: [
+ { skill: "JavaScript", beginner: 3, intermediate: 7, advanced: 9 },
+ { skill: "React", beginner: 4, intermediate: 8, advanced: 8 },
+ { skill: "TypeScript", beginner: 2, intermediate: 6, advanced: 9 },
+ { skill: "Node.js", beginner: 3, intermediate: 7, advanced: 7 },
+ { skill: "CSS", beginner: 5, intermediate: 8, advanced: 6 },
+ { skill: "Git", beginner: 4, intermediate: 6, advanced: 8 },
+ ],
+ performance: [
+ { metric: "Speed", team_a: 85, team_b: 92, team_c: 78 },
+ { metric: "Quality", team_a: 90, team_b: 88, team_c: 95 },
+ { metric: "Efficiency", team_a: 78, team_b: 85, team_c: 82 },
+ { metric: "Innovation", team_a: 92, team_b: 75, team_c: 88 },
+ { metric: "Collaboration", team_a: 88, team_b: 94, team_c: 85 },
+ { metric: "Reliability", team_a: 95, team_b: 87, team_c: 90 },
+ ],
+ businessMetrics: [
+ { department: "Sales", q1: 85, q2: 92, q3: 78, q4: 95 },
+ { department: "Marketing", q1: 78, q2: 85, q3: 90, q4: 88 },
+ { department: "Support", q1: 92, q2: 88, q3: 85, q4: 90 },
+ { department: "Product", q1: 88, q2: 90, q3: 92, q4: 85 },
+ { department: "Engineering", q1: 90, q2: 85, q3: 88, q4: 92 },
+ ],
+ gameStats: [
+ { attribute: "Strength", player1: 95, player2: 78, player3: 85 },
+ { attribute: "Speed", player1: 82, player2: 95, player3: 88 },
+ { attribute: "Intelligence", player1: 88, player2: 85, player3: 92 },
+ { attribute: "Defense", player1: 90, player2: 82, player3: 78 },
+ { attribute: "Magic", player1: 75, player2: 92, player3: 88 },
+ { attribute: "Luck", player1: 85, player2: 88, player3: 90 },
+ ],
+ productFeatures: [
+ { feature: "Usability", current: 8, competitor_a: 7, competitor_b: 9 },
+ { feature: "Performance", current: 9, competitor_a: 8, competitor_b: 7 },
+ { feature: "Design", current: 8, competitor_a: 9, competitor_b: 8 },
+ { feature: "Features", current: 7, competitor_a: 8, competitor_b: 9 },
+ { feature: "Price", current: 9, competitor_a: 6, competitor_b: 8 },
+ { feature: "Support", current: 8, competitor_a: 7, competitor_b: 6 },
+ ],
+ minimal: [
+ { category: "Category A", value1: 8, value2: 6 },
+ { category: "Category B", value1: 7, value2: 9 },
+ { category: "Category C", value1: 9, value2: 7 },
+ ],
+ singleMetric: [
+ { dimension: "North", score: 85 },
+ { dimension: "South", score: 72 },
+ { dimension: "East", score: 90 },
+ { dimension: "West", score: 78 },
+ { dimension: "Center", score: 88 },
+ ],
+ manyDimensions: [
+ { aspect: "UX Design and User Experience", mobile: 8, web: 9, desktop: 7, tablet: 8 },
+ { aspect: "Performance and Optimization", mobile: 9, web: 8, desktop: 9, tablet: 8 },
+ { aspect: "Accessibility and Inclusivity", mobile: 7, web: 8, desktop: 9, tablet: 7 },
+ { aspect: "Security and Compliance", mobile: 8, web: 9, desktop: 8, tablet: 8 },
+ { aspect: "Scalability and Performance", mobile: 7, web: 9, desktop: 8, tablet: 7 },
+ { aspect: "Maintenance and Support", mobile: 8, web: 7, desktop: 8, tablet: 8 },
+ { aspect: "Testing and Quality Assurance", mobile: 9, web: 8, desktop: 7, tablet: 8 },
+ { aspect: "Documentation and Support", mobile: 6, web: 8, desktop: 9, tablet: 7 },
+ ],
+};
+
+// Map data variations to their category keys
+const categoryKeys = {
+ default: "skill",
+ performance: "metric",
+ businessMetrics: "department",
+ gameStats: "attribute",
+ productFeatures: "feature",
+ minimal: "category",
+ singleMetric: "dimension",
+ manyDimensions: "aspect",
+} as const;
+
+// Default data for the main story
+const radarChartData = dataVariations.default;
+
+const meta: Meta<RadarChartProps<typeof radarChartData>> = {
+ title: "Components/D3Charts/RadarChart",
+ component: RadarChart,
+ parameters: {
+ layout: "centered",
+ docs: {
+ description: {
+ component: `
+## Installation and Basic Usage
+
+\`\`\`tsx
+import { RadarChart } from '@openuidev/react-ui/Charts/RadarChart';
+
+// Basic implementation
+<RadarChart
+ data={yourData}
+ categoryKey="category"
+ theme="ocean"
+ variant="line"
+/>
+
+// With custom colors
+<RadarChart
+ data={yourData}
+ categoryKey="category"
+ customPalette={["#FF6B6B", "#4ECDC4", "#45B7D1"]}
+ variant="line"
+/>
+\`\`\`
+
+## Data Structure Requirements
+
+Your data should be an array of objects where each object contains:
+- A **category field** (string): Used for the radar's axes (e.g., 'skill', 'metric').
+- One or more **value fields** (number): Each numeric key represents a data series to be plotted.
+
+\`\`\`tsx
+const exampleData = [
+ { skill: "JavaScript", team_a: 90, team_b: 75 },
+ { skill: "React", team_a: 85, team_b: 95 },
+ { skill: "Node.js", team_a: 80, team_b: 70 },
+];
+\`\`\`
+
+## Key Features
+
+- **Multiple Data Series**: Compare several datasets on the same chart.
+- **Two Visual Variants**: Choose between 'line' and 'area' styles.
+- **Customizable Appearance**: Control colors, stroke width, and area opacity.
+- **Custom Color Palettes**: Use predefined themes or provide your own custom colors.
+- **Interactive Legend**: Toggle visibility of data series.
+- **Icon Support**: Add custom icons to legend items for better visual identification.
+- **Animation**: Smooth animations for loading and data transitions.
+`,
+ },
+ },
+ },
+ tags: ["dev", "autodocs"],
+ argTypes: {
+ data: {
+ description: `
+**Required.** An array of data objects. Each object represents a point on the radar axes and should contain:
+- A category identifier (string).
+- One or more numeric values, where each key represents a data series.
+
+**Best Practices:**
+- Use 3-8 axes (categories) for optimal readability.
+- Keep data series count low (2-4) to avoid clutter.
+`,
+ control: false,
+ table: {
+ type: { summary: "Array<Record<string, string | number>>" },
+ defaultValue: { summary: "[]" },
+ category: "📊 Data Configuration",
+ },
+ },
+ categoryKey: {
+ description: `
+**Required.** The key in your data objects that corresponds to the radar axis labels.
+
+**Examples:**
+- "skill" for a skills assessment chart.
+- "metric" for a performance comparison chart.
+`,
+ control: false,
+ table: {
+ type: { summary: "string" },
+ category: "📊 Data Configuration",
+ },
+ },
+ theme: {
+ description: `
+**Color Theme Selection.** Choose from professionally designed color palettes. Ignored when customPalette is provided.
+
+- **ocean**: Cool blues and teals (professional, corporate)
+- **orchid**: Purple and pink tones (creative, modern)
+- **emerald**: Green variations (nature, growth, finance)
+- **sunset**: Warm oranges and reds (energy, attention-grabbing)
+- **spectrum**: Full color range (diverse, comprehensive)
+- **vivid**: High-contrast colors (accessibility, clarity)
+`,
+ control: "select",
+ options: ["ocean", "orchid", "emerald", "sunset", "spectrum", "vivid"],
+ table: {
+ defaultValue: { summary: "ocean" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ customPalette: {
+ description:
+ "Custom array of colors to use instead of the theme palette. Overrides the theme prop when provided.",
+ control: "object",
+ table: {
+ type: { summary: "string[]" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ variant: {
+ description: `
+**Chart Style Variant:**
+
+- **line**: Displays only the outlines of the data series. Best for comparing multiple series without obstruction.
+- **area**: Fills the area covered by each data series. Good for showing the magnitude of values.
+`,
+ control: "radio",
+ options: ["line", "area"],
+ table: {
+ defaultValue: { summary: "line" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ grid: {
+ description: `
+**Grid Visibility.** Toggles the display of the background polar grid.
+
+**When to use:**
+- To help estimate values along the axes.
+- For a more technical, data-driven look.
+`,
+ control: "boolean",
+ table: {
+ type: { summary: "boolean" },
+ defaultValue: { summary: "true" },
+ category: "📱 Display Options",
+ },
+ },
+ legend: {
+ description: `
+**Legend Visibility.** Controls whether the legend is displayed.
+
+**When to disable:**
+- When charting a single data series.
+- For minimal, clean dashboard widgets.
+`,
+ control: "boolean",
+ table: {
+ type: { summary: "boolean" },
+ defaultValue: { summary: "true" },
+ category: "📱 Display Options",
+ },
+ },
+ strokeWidth: {
+ description: `
+**Line Thickness.** Sets the width of the radar lines for the 'line' variant and the border for the 'area' variant.
+`,
+ control: { type: "number", min: 1, max: 10 },
+ table: {
+ type: { summary: "number" },
+ defaultValue: { summary: "2" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ areaOpacity: {
+ description: `
+**Area Fill Opacity.** Controls the transparency of the filled areas when \`variant\` is 'area'.
+
+**Tip:** Use lower opacity (e.g., 0.2-0.5) when displaying multiple overlapping area series.
+`,
+ control: { type: "range", min: 0, max: 1, step: 0.1 },
+ table: {
+ type: { summary: "number" },
+ defaultValue: { summary: "0.5" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ icons: {
+ description: `
+An object mapping data keys to React components to display as icons in the legend.
+
+**Example:**
+\`\`\`jsx
+import { Shield, Target } from 'lucide-react';
+
+const icons = {
+ team_a: Shield,
+ team_b: Target,
+};
+\`\`\`
+`,
+ control: false,
+ table: {
+ type: { summary: "Record<string, React.ComponentType>" },
+ defaultValue: { summary: "{}" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ isAnimationActive: {
+ description: `
+**Animation Control.** Enables or disables chart animations on load and update.
+
+**Performance note:** Disable for highly complex charts or in performance-critical applications.
+`,
+ control: "boolean",
+ table: {
+ type: { summary: "boolean" },
+ defaultValue: { summary: "true" },
+ category: "🎬 Animation & Interaction",
+ },
+ },
+ height: {
+ description: "The height of the chart.",
+ control: "text",
+ table: {
+ type: { summary: "string | number" },
+ category: "📱 Display Options",
+ },
+ },
+ width: {
+ description: "The width of the chart.",
+ control: "text",
+ table: {
+ type: { summary: "string | number" },
+ category: "📱 Display Options",
+ },
+ },
+ },
+} satisfies Meta<typeof RadarChart>;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+export const DefaultConfiguration: Story = {
+ name: "📊 Default Configuration",
+ args: {
+ data: dataVariations.performance,
+ categoryKey: "metric",
+ theme: "ocean",
+ variant: "line",
+ grid: true,
+ legend: true,
+ strokeWidth: 2,
+ isAnimationActive: true,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "500px", height: "auto", padding: "24px" }}>
+ <div style={{ marginBottom: "16px" }}>
+ <h3 style={{ margin: "0 0 8px 0", fontSize: "18px", fontWeight: "600" }}>
+ Team Performance Analysis
+ </h3>
+ <p style={{ margin: 0, color: "#666", fontSize: "14px" }}>
+ Comparing key performance indicators across three teams.
+ </p>
+ </div>
+ <RadarChart {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story: `
+This is the recommended starting configuration for most use cases. The chart displays multiple data series in a clear, professional manner.
+
+**Configuration Details:**
+- **Data**: Team performance metrics.
+- **Variant**: 'line' for clear comparison between series.
+- **Colors**: 'ocean' theme (blues and teals).
+- **Legend**: Enabled to identify data series.
+- **Animations**: Enabled for smooth interactions.
+ `,
+ },
+ },
+ },
+};
+
+export const SkillsAssessment: Story = {
+ name: "📚 Skills Assessment",
+ args: {
+ data: dataVariations.default,
+ categoryKey: "skill",
+ theme: "orchid",
+ variant: "area",
+ grid: true,
+ legend: true,
+ strokeWidth: 2,
+ areaOpacity: 0.4,
+ isAnimationActive: true,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "500px", height: "auto", padding: "24px" }}>
+ <div style={{ marginBottom: "16px" }}>
+ <h3 style={{ margin: "0 0 8px 0", fontSize: "18px", fontWeight: "600" }}>
+ Developer Skill Levels
+ </h3>
+ <p style={{ margin: 0, color: "#666", fontSize: "14px" }}>
+ Visualizing proficiency across different programming skills for various experience levels.
+ </p>
+ </div>
+ <RadarChart {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "This example uses the 'area' variant to represent different skill levels. The transparency allows for easy comparison of overlapping areas, providing a clear view of strengths and weaknesses across different roles.",
+ },
+ },
+ },
+};
+
+export const TeamPerformance: Story = {
+ name: "🏆 Team Performance with Icons",
+ args: {
+ data: dataVariations.performance,
+ categoryKey: "metric",
+ theme: "emerald",
+ variant: "line",
+ grid: true,
+ legend: true,
+ strokeWidth: 3,
+ isAnimationActive: true,
+ icons: {
+ team_a: Shield,
+ team_b: Target,
+ team_c: Star,
+ },
+ },
+ render: (args: any) => (
+ <Card style={{ width: "500px", height: "auto", padding: "24px" }}>
+ <div style={{ marginBottom: "16px" }}>
+ <h3 style={{ margin: "0 0 8px 0", fontSize: "18px", fontWeight: "600" }}>
+ Team Performance Comparison
+ </h3>
+ <p style={{ margin: 0, color: "#666", fontSize: "14px" }}>
+ Utilizing custom icons to distinguish teams in the legend for improved clarity.
+ </p>
+ </div>
+ <RadarChart {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "This chart demonstrates how to enhance the legend with custom icons. It's an effective way to visually associate data series with specific entities, like teams or products. The thicker stroke width also improves line visibility.",
+ },
+ },
+ },
+};
+
+export const BusinessMetrics: Story = {
+ name: "📈 Quarterly Business Metrics",
+ args: {
+ data: dataVariations.businessMetrics,
+ categoryKey: "department",
+ theme: "sunset",
+ variant: "area",
+ grid: true,
+ legend: true,
+ strokeWidth: 2,
+ areaOpacity: 0.4,
+ isAnimationActive: true,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "500px", height: "auto", padding: "24px" }}>
+ <div style={{ marginBottom: "16px" }}>
+ <h3 style={{ margin: "0 0 8px 0", fontSize: "18px", fontWeight: "600" }}>
+ Quarterly Performance Review
+ </h3>
+ <p style={{ margin: 0, color: "#666", fontSize: "14px" }}>
+ Tracking key business metrics across departments over four quarters.
+ </p>
+ </div>
+ <RadarChart {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "A comprehensive view of business performance, this example showcases how the 'area' variant can effectively display multiple overlapping datasets to reveal trends and patterns over time.",
+ },
+ },
+ },
+};
+
+export const InteractivePlayground: Story = {
+ name: "🧪 Interactive Playground",
+ args: {
+ theme: "ocean",
+ variant: "line",
+ grid: true,
+ legend: true,
+ strokeWidth: 2,
+ areaOpacity: 0.5,
+ isAnimationActive: true,
+ },
+ render: (args: any) => {
+ const [selectedDataType, setSelectedDataType] =
+ useState<keyof typeof dataVariations>("default");
+
+ const currentData = dataVariations[selectedDataType];
+ const currentCategoryKey = categoryKeys[selectedDataType];
+
+ const buttonStyle: React.CSSProperties = {
+ margin: "2px",
+ padding: "6px 12px",
+ fontSize: "12px",
+ border: "1px solid #ddd",
+ borderRadius: "4px",
+ cursor: "pointer",
+ background: "#fff",
+ color: "#333",
+ fontFamily: "monospace",
+ transition: "all 0.2s",
+ };
+
+ const activeButtonStyle: React.CSSProperties = {
+ ...buttonStyle,
+ background: "#3b82f6",
+ color: "white",
+ border: "1px solid #3b82f6",
+ fontWeight: 600,
+ };
+
+ return (
+ <div style={{ width: "700px" }}>
+ <Card style={{ padding: "20px", marginBottom: "20px" }}>
+ <h3 style={{ margin: "0 0 12px 0", fontSize: "16px", fontWeight: "600" }}>
+ 🕸️ Radar Chart Test Suite
+ </h3>
+ <div style={{ display: "flex", flexWrap: "wrap", gap: "6px" }}>
+ {(Object.keys(dataVariations) as Array<keyof typeof dataVariations>).map((key) => (
+ <button
+ key={key}
+ onClick={() => setSelectedDataType(key)}
+ style={selectedDataType === key ? activeButtonStyle : buttonStyle}
+ >
+ {key.replace(/([A-Z])/g, " $1").replace(/^./, (str) => str.toUpperCase())}
+ </button>
+ ))}
+ </div>
+ <div style={{ marginTop: "12px", fontSize: "12px", color: "#666" }}>
+ <strong>Current Dataset:</strong> {selectedDataType} | <strong>Axes:</strong>{" "}
+ {currentData.length} | <strong>Category Key:</strong> {currentCategoryKey}
+ </div>
+ </Card>
+ <Card
+ style={{
+ height: "400px",
+ padding: "24px",
+ resize: "both",
+ overflow: "hidden",
+ minWidth: "400px",
+ minHeight: "400px",
+ }}
+ >
+ <RadarChart {...args} data={currentData} categoryKey={currentCategoryKey} />
+ </Card>
+ </div>
+ );
+ },
+ parameters: {
+ docs: {
+ description: {
+ story: `
+Use the buttons to switch between different datasets and explore how the RadarChart adapts.
+You can also use the Storybook controls to change theme, variant, and other properties in real-time.
+This playground is designed for testing various configurations and edge cases.
+`,
+ },
+ },
+ },
+};
+
+export const ThemeShowcase: Story = {
+ name: "🎨 Theme Showcase",
+ args: {
+ data: dataVariations.productFeatures,
+ categoryKey: "feature",
+ variant: "area",
+ grid: true,
+ legend: true,
+ strokeWidth: 2,
+ areaOpacity: 0.6,
+ isAnimationActive: false,
+ },
+ render: (args: any) => (
+ <div
+ style={{
+ display: "grid",
+ gridTemplateColumns: "repeat(3, 1fr)",
+ gap: "24px",
+ width: "900px",
+ }}
+ >
+ {(["ocean", "orchid", "emerald", "sunset", "spectrum", "vivid"] as const).map((theme) => (
+ <div key={theme}>
+ <h4
+ style={{
+ textAlign: "center",
+ marginBottom: "12px",
+ textTransform: "capitalize",
+ fontSize: "14px",
+ fontWeight: 600,
+ }}
+ >
+ {theme}
+ </h4>
+ <Card style={{ height: "fit-content", padding: "12px" }}>
+ <RadarChart {...args} theme={theme} />
+ </Card>
+ </div>
+ ))}
+ </div>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "This story showcases all available color themes. Each theme provides a professionally curated palette suitable for different branding and data contexts. Animations are disabled for quicker comparison.",
+ },
+ },
+ },
+};
+
+/**
+ * ## Custom Palette
+ *
+ * This story demonstrates how to use the customPalette prop to provide your own color scheme
+ * for the chart. This is useful when you need to match your brand colors or create
+ * specific visual themes.
+ */
+export const CustomPaletteStory: Story = {
+ name: "🎨 Custom Palette",
+ args: {
+ data: dataVariations.productFeatures,
+ categoryKey: "metric",
+ customPalette: [
+ "#0A0E60",
+ "#14197B",
+ "#272DA6",
+ "#383FC9",
+ "#444CE7",
+ "#5F67F4",
+ "#7884FF",
+ "#97A9FF",
+ "#B4C6FF",
+ "#CBD7FF",
+ ],
+ theme: "ocean", // This will be overridden by customPalette
+ variant: "area",
+ grid: true,
+ legend: true,
+ strokeWidth: 3,
+ isAnimationActive: true,
+ },
+ render: (args: any) => (
+ <div>
+ <div
+ style={{
+ marginBottom: "16px",
+ padding: "12px",
+ background: "#f8f9fa",
+ borderRadius: "8px",
+ border: "1px solid #e9ecef",
+ }}
+ >
+ <h4 style={{ margin: "0 0 8px 0", color: "#333" }}>🎨 Custom Color Palette</h4>
+ <p style={{ margin: "0 0 12px 0", fontSize: "14px", color: "#666" }}>
+ This radar chart uses a custom color palette instead of the default theme colors.
+ </p>
+ <div style={{ display: "flex", gap: "8px", flexWrap: "wrap" }}>
+ {args.customPalette?.map((color: string, index: number) => (
+ <div
+ key={index}
+ style={{
+ display: "flex",
+ alignItems: "center",
+ gap: "4px",
+ padding: "4px 8px",
+ background: "white",
+ borderRadius: "4px",
+ border: "1px solid #ddd",
+ fontSize: "12px",
+ }}
+ >
+ <div
+ style={{
+ width: "12px",
+ height: "12px",
+ borderRadius: "2px",
+ backgroundColor: color,
+ border: "1px solid #ccc",
+ }}
+ />
+ <span style={{ fontFamily: "monospace" }}>{color}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ <Card style={{ width: "500px", height: "auto", padding: "24px" }}>
+ <div style={{ marginBottom: "16px" }}>
+ <h3 style={{ margin: "0 0 8px 0", fontSize: "18px", fontWeight: "600" }}>
+ Team Performance with Custom Colors
+ </h3>
+ <p style={{ margin: 0, color: "#666", fontSize: "14px" }}>
+ Using custom brand colors to match your application's design system.
+ </p>
+ </div>
+ <RadarChart {...args} />
+ </Card>
+ </div>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'Demonstrates how to use the `customPalette` prop to provide your own color scheme for the radar chart. When `customPalette` is provided, it overrides the `theme` prop and uses your specified colors instead of the predefined theme palettes.\n\n**Key Features:**\n- 🎨 **Custom Colors**: Override default theme colors with your own palette\n- 🔄 **Theme Override**: The `theme` prop is ignored when `customPalette` is provided\n- 📊 **Consistent Distribution**: Colors are distributed evenly across data series\n- 🎯 **Brand Matching**: Perfect for matching your application\'s brand colors\n\n**Usage:**\n```tsx\n<RadarChart\n data={data}\n categoryKey="metric"\n customPalette={["#FF6B6B", "#4ECDC4", "#45B7D1"]}\n // theme prop is ignored when customPalette is provided\n/>\n```',
+ },
+ },
+ },
+};
diff --git a/packages/react-ui/src/components/D3Charts/RadarChart/types.ts b/packages/react-ui/src/components/D3Charts/RadarChart/types.ts
new file mode 100644
index 000000000..4b4393fdb
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/RadarChart/types.ts
@@ -0,0 +1,41 @@
+import type { ChartData } from "../types";
+
+export type RadarChartData = ChartData;
+
+export interface RadarChartProps<T extends RadarChartData> {
+ data: T;
+ categoryKey: keyof T[number];
+ customPalette?: string[];
+ gridShape?: "circle" | "polygon";
+ gridLevels?: number;
+ grid?: boolean;
+ legend?: boolean;
+ icons?: Partial<Record<keyof T[number], React.ComponentType>>;
+ /**
+ * Play the entrance animation. Gates the entrance ONLY — any hover or
+ * data-update motion is independent of this flag, and printing always
+ * disables it.
+ * Default false (streaming-safe: marks mounted while data streams in don't
+ * replay staggered entrances).
+ */
+ isAnimationActive?: boolean;
+ /**
+ * `"line"` (default): series outlines only. `"area"`: outlines filled at
+ * `areaOpacity`. Matches react-ui's Recharts RadarChart.
+ */
+ variant?: "line" | "area";
+ /** Fill opacity of the `"area"` variant. Default 0.2. */
+ areaOpacity?: number;
+ /** Vertex dots on every series. Default false. */
+ showDots?: boolean;
+ dotRadius?: number;
+ /** Explicit fill opacity for every variant; overrides `variant` / `areaOpacity`. */
+ fillOpacity?: number;
+ maxChartSize?: number;
+ minChartSize?: number;
+ height?: number | string;
+ width?: number | string;
+ fitLegendInHeight?: boolean;
+ className?: string;
+ onClick?: (row: T[number], index: number) => void;
+}
diff --git a/packages/react-ui/src/components/D3Charts/RadialChart/RadialChart.tsx b/packages/react-ui/src/components/D3Charts/RadialChart/RadialChart.tsx
new file mode 100644
index 000000000..0724318c5
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/RadialChart/RadialChart.tsx
@@ -0,0 +1,181 @@
+import { useMemo } from "react";
+
+import {
+ useCategoricalChartOrchestrator,
+ useEffectiveAnimation,
+ useExportChartData,
+} from "../hooks";
+import { ChartShell } from "../shared/core/ChartShell";
+import { DefaultLegend } from "../shared/core/DefaultLegend/DefaultLegend";
+import { useResolvedLegendKey } from "../shared/core/legend/LegendStoreProvider";
+import { ChartTooltip } from "../shared/core/PortalTooltip/ChartTooltip";
+import { ChartWithStackedLegend } from "../shared/core/StackedLegend/ChartWithStackedLegend";
+import { CHART_CLASS_PREFIX } from "../utils/constants";
+import { RadialBars } from "./parts/RadialBars";
+import { RadialGrid } from "./parts/RadialGrid";
+import type { RadialChartData, RadialChartProps } from "./types";
+
+const BAR_GAP = 2;
+
+/**
+ * `legendVariant="stacked"` (the default, as in react-ui's Recharts RadialChart)
+ * lays the chart out with its built-in stacked legend. The inline legend is
+ * used for `"default"`, and none when the chart publishes to an external
+ * legend (`legendKey`, or a surrounding `LegendStoreProvider`'s key).
+ */
+export function RadialChart<T extends RadialChartData>(props: RadialChartProps<T>) {
+ const { legend = true, legendVariant = "stacked", legendKey, width, height, className } = props;
+ const externalLegendKey = useResolvedLegendKey(legendKey);
+
+ if (legend && legendVariant === "stacked" && externalLegendKey === undefined) {
+ return (
+ <ChartWithStackedLegend width={width} height={height} className={className}>
+ <RadialChartImpl {...props} width={undefined} height={undefined} className={undefined} />
+ </ChartWithStackedLegend>
+ );
+ }
+ return <RadialChartImpl {...props} />;
+}
+
+function RadialChartImpl<T extends RadialChartData>(props: RadialChartProps<T>) {
+ const {
+ data,
+ categoryKey,
+ dataKey,
+ customPalette,
+ variant = "circular",
+ format = "number",
+ legend: showLegend = true,
+ grid: showGrid = false,
+ isAnimationActive = false,
+ cornerRadius = 10,
+ maxChartSize = 500,
+ minChartSize = 150,
+ height,
+ width,
+ fitLegendInHeight,
+ className,
+ onClick,
+ legendKey,
+ } = props;
+
+ const isSemiCircular = variant === "semiCircular";
+
+ const orch = useCategoricalChartOrchestrator({
+ data,
+ categoryKey,
+ dataKey,
+ themePaletteName: "radialChartPalette",
+ customPalette,
+ format,
+ showLegend,
+ isSemiCircular,
+ maxChartSize,
+ minChartSize,
+ height,
+ width,
+ fitLegendInHeight,
+ legendKey,
+ });
+
+ const animate = useEffectiveAnimation(isAnimationActive);
+
+ // Radial-specific geometry
+ const maxRadius = orch.dimensions.chartSize * 0.45;
+ const minRadius = maxRadius * 0.25;
+ // semiCircular viewport shows the TOP half-plane (centerY sits at the bottom
+ // edge), so the sweep must run 9→12→3 o'clock (d3 angles: 0 = 12 o'clock,
+ // clockwise) — same convention as PieChart's semiCircular.
+ const startAngle = isSemiCircular ? -Math.PI / 2 : 0;
+ const endAngle = isSemiCircular ? Math.PI / 2 : 2 * Math.PI;
+
+ const maxValue = useMemo(
+ () => Math.max(...orch.data.visibleSlices.map((s) => s.value), 0),
+ [orch.data.visibleSlices],
+ );
+
+ // PPTX print-export JSON — mirrors react-ui's RadialChart call, which (like
+ // its PieChart) emits type:'pie' with a single series = [dataKey] and no
+ // extraOptions. Colors are the resolved slice palette in sorted-data order.
+ // Undefined off the print path.
+ const exportData = useExportChartData({
+ type: "pie",
+ data: orch.data.sortedData,
+ categoryKey: orch.data.catKey,
+ dataKeys: [orch.data.valKey],
+ colors: orch.data.slices.map((s) => s.color),
+ legend: showLegend,
+ });
+
+ return (
+ <ChartShell
+ containerRef={orch.refs.containerRef}
+ classPrefix={`${CHART_CLASS_PREFIX}-radial-chart`}
+ className={className}
+ style={orch.style.containerStyle}
+ isEmpty={orch.isEmpty}
+ exportData={exportData}
+ >
+ {() => (
+ <>
+ <div className={`${CHART_CLASS_PREFIX}-radial-chart-svg-wrapper`}>
+ <svg
+ width={orch.dimensions.svgWidth}
+ height={orch.dimensions.svgHeight}
+ viewBox={`0 0 ${orch.dimensions.svgWidth} ${orch.dimensions.svgHeight}`}
+ role="img"
+ aria-label="Radial chart"
+ >
+ <g transform={`translate(${orch.dimensions.centerX}, ${orch.dimensions.centerY})`}>
+ {showGrid && (
+ <RadialGrid
+ maxRadius={maxRadius}
+ minRadius={minRadius}
+ startAngle={startAngle}
+ endAngle={endAngle}
+ />
+ )}
+ <RadialBars
+ slices={orch.data.visibleSlices}
+ maxValue={maxValue}
+ maxRadius={maxRadius}
+ minRadius={minRadius}
+ startAngle={startAngle}
+ endAngle={endAngle}
+ cornerRadius={cornerRadius}
+ barGap={BAR_GAP}
+ hoveredIndex={orch.hover.hoveredIndex}
+ animate={animate}
+ data={orch.data.visibleRows}
+ onMouseMove={orch.hover.handleMouseMove}
+ onMouseLeave={orch.hover.handleMouseLeave}
+ onClick={onClick}
+ />
+ </g>
+ </svg>
+ </div>
+
+ {showLegend && !orch.usesRemoteLegend && (
+ <DefaultLegend
+ ref={orch.refs.legendRef}
+ items={orch.data.legendItems}
+ containerWidth={orch.dimensions.containerWidth}
+ isExpanded={orch.legend.isLegendExpanded}
+ setIsExpanded={orch.legend.setIsLegendExpanded}
+ onItemClick={orch.data.toggleSlice}
+ hiddenSeries={orch.data.hiddenSlices}
+ />
+ )}
+
+ {orch.tooltip.tooltipPayload && orch.hover.mousePos && (
+ <ChartTooltip
+ label={orch.tooltip.tooltipPayload.label}
+ items={orch.tooltip.tooltipPayload.items}
+ viewportPosition={orch.hover.mousePos}
+ />
+ )}
+ </>
+ )}
+ </ChartShell>
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/RadialChart/index.ts b/packages/react-ui/src/components/D3Charts/RadialChart/index.ts
new file mode 100644
index 000000000..d4da77b01
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/RadialChart/index.ts
@@ -0,0 +1,2 @@
+export { RadialChart } from "./RadialChart";
+export type { RadialChartData, RadialChartProps } from "./types";
diff --git a/packages/react-ui/src/components/D3Charts/RadialChart/parts/RadialBars.tsx b/packages/react-ui/src/components/D3Charts/RadialChart/parts/RadialBars.tsx
new file mode 100644
index 000000000..60f121361
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/RadialChart/parts/RadialBars.tsx
@@ -0,0 +1,99 @@
+import { arc } from "d3-shape";
+import React, { useMemo } from "react";
+import type { CategoricalSlice } from "../../hooks";
+import { useIndexedClickHandler } from "../../hooks/core/useIndexedClickHandler";
+import { CHART_CLASS_PREFIX } from "../../utils/constants";
+import { entranceProps } from "../../utils/entranceUtils";
+import { getSliceStyle, POLAR_HOVER_TRANSITION } from "../../utils/polarUtils";
+
+interface RadialBarsProps<T> {
+ slices: CategoricalSlice[];
+ maxValue: number;
+ maxRadius: number;
+ minRadius: number;
+ startAngle: number;
+ endAngle: number;
+ cornerRadius: number;
+ barGap: number;
+ hoveredIndex: number | null;
+ /** Pre-folded "animation on AND not printing" — computed at the chart entry via useEffectiveAnimation. */
+ animate: boolean;
+ data: T[];
+ onMouseMove: (event: React.MouseEvent, index: number) => void;
+ onMouseLeave: () => void;
+ onClick?: (row: T, index: number) => void;
+}
+
+export function RadialBars<T>({
+ slices,
+ maxValue,
+ maxRadius,
+ minRadius,
+ startAngle,
+ endAngle,
+ cornerRadius,
+ barGap,
+ hoveredIndex,
+ animate,
+ data,
+ onMouseMove,
+ onMouseLeave,
+ onClick,
+}: RadialBarsProps<T>) {
+ const handleClick = useIndexedClickHandler(data, onClick);
+
+ const totalSweep = endAngle - startAngle;
+ const barThickness = (maxRadius - minRadius) / slices.length;
+
+ const bars = useMemo(
+ () =>
+ slices.map((slice, i) => {
+ const barInner = minRadius + i * barThickness + barGap;
+ const barOuter = minRadius + (i + 1) * barThickness;
+ const sweepAngle = maxValue > 0 ? (slice.value / maxValue) * totalSweep : 0;
+
+ const arcGen = arc<null>()
+ .innerRadius(barInner)
+ .outerRadius(barOuter)
+ .startAngle(startAngle)
+ .endAngle(startAngle + sweepAngle)
+ .cornerRadius(cornerRadius);
+
+ return {
+ path: arcGen(null) as string,
+ color: slice.color,
+ label: slice.label,
+ };
+ }),
+ [slices, maxValue, minRadius, startAngle, totalSweep, cornerRadius, barGap, barThickness],
+ );
+
+ return (
+ <g>
+ {bars.map((bar, i) => {
+ const { className, animationDelay } = entranceProps(
+ animate,
+ `${CHART_CLASS_PREFIX}-radial-chart-bar--animated`,
+ i * 60,
+ );
+ return (
+ <path
+ key={bar.label}
+ d={bar.path}
+ fill={bar.color}
+ className={className || undefined}
+ style={{
+ ...getSliceStyle(i, hoveredIndex),
+ cursor: onClick ? "pointer" : undefined,
+ animationDelay,
+ transition: POLAR_HOVER_TRANSITION,
+ }}
+ onMouseMove={(e) => onMouseMove(e, i)}
+ onMouseLeave={onMouseLeave}
+ onClick={() => handleClick(i)}
+ />
+ );
+ })}
+ </g>
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/RadialChart/parts/RadialGrid.tsx b/packages/react-ui/src/components/D3Charts/RadialChart/parts/RadialGrid.tsx
new file mode 100644
index 000000000..ce8e0035e
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/RadialChart/parts/RadialGrid.tsx
@@ -0,0 +1,57 @@
+import { CHART_CLASS_PREFIX } from "../../utils/constants";
+
+interface RadialGridProps {
+ maxRadius: number;
+ minRadius: number;
+ gridLevels?: number;
+ startAngle: number;
+ endAngle: number;
+}
+
+export function RadialGrid({
+ maxRadius,
+ minRadius,
+ gridLevels = 5,
+ startAngle,
+ endAngle,
+}: RadialGridProps) {
+ const isSemiCircular = endAngle - startAngle < 2 * Math.PI;
+
+ return (
+ <g className={`${CHART_CLASS_PREFIX}-radial-chart-grid`}>
+ {Array.from({ length: gridLevels }, (_, i) => {
+ const fraction = (i + 1) / gridLevels;
+ const r = minRadius + (maxRadius - minRadius) * fraction;
+
+ if (isSemiCircular) {
+ const x1 = r * Math.cos(startAngle - Math.PI / 2);
+ const y1 = r * Math.sin(startAngle - Math.PI / 2);
+ const x2 = r * Math.cos(endAngle - Math.PI / 2);
+ const y2 = r * Math.sin(endAngle - Math.PI / 2);
+ // SVG arc large-arc-flag: use long arc when sweep > 180 degrees
+ const largeArcFlag = endAngle - startAngle > Math.PI ? 1 : 0;
+
+ return (
+ <path
+ key={i}
+ d={`M ${x1} ${y1} A ${r} ${r} 0 ${largeArcFlag} 1 ${x2} ${y2}`}
+ fill="none"
+ className={`${CHART_CLASS_PREFIX}-radial-chart-grid-circle`}
+ />
+ );
+ }
+
+ return (
+ <circle
+ key={i}
+ cx={0}
+ cy={0}
+ r={r}
+ fill="none"
+ className={`${CHART_CLASS_PREFIX}-radial-chart-grid-circle`}
+ />
+ );
+ })}
+ </g>
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/RadialChart/radialChart.scss b/packages/react-ui/src/components/D3Charts/RadialChart/radialChart.scss
new file mode 100644
index 000000000..29489faaf
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/RadialChart/radialChart.scss
@@ -0,0 +1,22 @@
+@use "../../../cssUtils" as cssUtils;
+@use "../shared/cartesian/chartBase" as base;
+@use "../prefix" as brand;
+
+@include base.centered-container("radial-chart");
+@include base.centered-svg-wrapper("radial-chart");
+
+.#{brand.$prefix}-radial-chart-grid-circle {
+ stroke: cssUtils.$border-default;
+ stroke-width: 1;
+ stroke-dasharray: 4 4;
+}
+
+// Entrances are decorative: gate the whole rule (pre-state included) behind
+// reduced-motion so users who opt out get the natural static state immediately
+// — gating only the animation would strand elements at the opacity: 0 start.
+@media (prefers-reduced-motion: no-preference) {
+ .#{brand.$prefix}-radial-chart-bar--animated {
+ opacity: 0;
+ animation: #{brand.$prefix}-fade-appear 0.5s ease-out forwards;
+ }
+}
diff --git a/packages/react-ui/src/components/D3Charts/RadialChart/stories/RadialChart.stories.tsx b/packages/react-ui/src/components/D3Charts/RadialChart/stories/RadialChart.stories.tsx
new file mode 100644
index 000000000..5a8086c82
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/RadialChart/stories/RadialChart.stories.tsx
@@ -0,0 +1,953 @@
+// Copy of Charts/RadialChart/stories/RadialChart.stories.tsx with only the chart import and the title changed:
+// the same args and renders, rendering the D3Charts chart via
+// ../../stories/rechartsStoryAdapters.
+import type { Meta, StoryObj } from "@storybook/react";
+import { useState } from "react";
+import { Card } from "../../../Card";
+import { RadialChart, RadialChartProps } from "../../stories/rechartsStoryAdapters";
+
+/**
+ * Sample data sets for demonstrating various RadialChart configurations
+ * These data structures represent common use cases in business applications
+ */
+
+// Basic monthly sales data - ideal for business dashboards
+const monthlyRevenueData = [
+ { month: "January", value: 1250 },
+ { month: "February", value: 980 },
+ { month: "March", value: 1450 },
+ { month: "April", value: 1320 },
+ { month: "May", value: 1680 },
+ { month: "June", value: 2100 },
+ { month: "July", value: 1950 },
+ { month: "August", value: 1820 },
+ { month: "September", value: 1650 },
+ { month: "October", value: 1480 },
+ { month: "November", value: 1350 },
+ { month: "December", value: 1200 },
+];
+
+// Extended dataset for demonstrating carousel functionality
+const comprehensiveFinancialData = [
+ { category: "Base Salary", amount: 75000 },
+ { category: "Q1 Bonus", amount: 8500 },
+ { category: "Q2 Bonus", amount: 9200 },
+ { category: "Q3 Bonus", amount: 7800 },
+ { category: "Q4 Bonus", amount: 11000 },
+ { category: "Holiday Pay", amount: 6500 },
+ { category: "Overtime", amount: 4200 },
+ { category: "Commission", amount: 8900 },
+ { category: "Performance Incentive", amount: 7200 },
+ { category: "Stock Options", amount: 12000 },
+ { category: "Healthcare Benefits", amount: 4800 },
+ { category: "Retirement Match", amount: 3600 },
+ { category: "Professional Development", amount: 2400 },
+ { category: "Transportation Allowance", amount: 1800 },
+ { category: "Meal Vouchers", amount: 1200 },
+];
+
+// Custom color palette for demonstration
+
+const customColorPalette = [
+ "#0A0E60",
+ "#14197B",
+ "#272DA6",
+ "#383FC9",
+ "#444CE7",
+ "#5F67F4",
+ "#7884FF",
+ "#97A9FF",
+ "#B4C6FF",
+ "#CBD7FF",
+];
+
+/**
+ * # RadialChart Component Documentation
+ *
+ * The RadialChart component is a powerful and flexible visualization tool for displaying
+ * categorical data in a circular format. It's particularly effective for showing:
+ *
+ * - **Proportional Relationships**: How different categories relate to each other
+ * - **Part-to-Whole Analysis**: Understanding individual contributions to a total
+ * - **Comparative Data**: Quickly comparing values across multiple categories
+ * - **Dashboard Metrics**: Essential KPIs in executive dashboards
+ *
+ * ## Key Features
+ *
+ * ### Visual Variants
+ * - **Circular**: Full 360-degree display for comprehensive data visualization
+ * - **Semicircle**: Half-circle display for space-efficient layouts
+ *
+ * ### Data Formatting
+ * - **Percentage Mode**: Automatically calculates and displays percentages
+ * - **Number Mode**: Shows raw values with customizable formatting
+ *
+ * ### Interactive Elements
+ * - **Responsive Legend**: Adapts to container size with carousel navigation
+ * - **Hover States**: Interactive feedback for enhanced user experience
+ * - **Animation Support**: Smooth transitions and loading animations
+ *
+ * ### Customization Options
+ * - **Theme System**: Pre-built color palettes (ocean, orchid, emerald, sunset, spectrum, vivid)
+
+ * - **Layout Flexibility**: Responsive design that adapts to container dimensions
+ */
+
+const meta: Meta<RadialChartProps<typeof monthlyRevenueData>> = {
+ title: "Components/D3Charts/RadialChart",
+ component: RadialChart,
+ parameters: {
+ layout: "centered",
+ docs: {
+ description: {
+ component: `
+## Installation and Basic Usage
+
+\`\`\`tsx
+import { RadialChart } from '@openuidev/react-ui/Charts/RadialChart';
+
+// Basic implementation
+<RadialChart
+ data={yourData}
+ categoryKey="category"
+ dataKey="value"
+ theme="ocean"
+ variant="circular"
+/>
+\`\`\`
+
+## Data Structure Requirements
+
+Your data should be an array of objects where each object contains:
+- A **category field** (string): Used for labels and legend items
+- A **value field** (number): Used to determine segment sizes
+
+\`\`\`tsx
+const exampleData = [
+ { category: "Sales", value: 45000 },
+ { category: "Marketing", value: 32000 },
+ { category: "Operations", value: 28000 },
+ { category: "Support", value: 15000 }
+];
+\`\`\`
+
+## Performance Considerations
+
+- **Data Size**: Optimized for 3-20 data points for best readability
+- **Responsive**: Automatically adjusts to container dimensions
+- **Animation**: Can be disabled for better performance with large datasets
+ `,
+ },
+ },
+ },
+ tags: ["dev", "autodocs"],
+ argTypes: {
+ data: {
+ description: `
+**Required.** An array of data objects representing your dataset. Each object should contain:
+- A category identifier (string)
+- One or more numeric values
+
+**Best Practices:**
+- Use 3-12 data points for optimal readability
+- Ensure consistent data structure across all objects
+- Use meaningful category names for better user experience
+ `,
+ control: false,
+ table: {
+ type: { summary: "Array<Record<string, string | number>>" },
+ defaultValue: { summary: "[]" },
+ category: "📊 Data Configuration",
+ },
+ },
+ categoryKey: {
+ description: `
+**Required.** Specifies which field in your data objects should be used as category labels.
+
+**Examples:**
+- "month" for time-series data
+- "department" for organizational data
+- "product" for sales data
+ `,
+ control: false,
+ table: {
+ type: { summary: "string" },
+ category: "📊 Data Configuration",
+ },
+ },
+ dataKey: {
+ description: `
+**Required.** Specifies which field contains the numeric values for visualization.
+
+**Examples:**
+- "value", "amount", "revenue", "count"
+- Values should be positive numbers
+- Supports both integers and decimals
+ `,
+ control: false,
+ table: {
+ type: { summary: "string" },
+ category: "📊 Data Configuration",
+ },
+ },
+ theme: {
+ description: `
+**Color Theme Selection.** Choose from professionally designed color palettes:
+
+- **ocean**: Cool blues and teals (professional, corporate)
+- **orchid**: Purple and pink tones (creative, modern)
+- **emerald**: Green variations (nature, growth, finance)
+- **sunset**: Warm oranges and reds (energy, attention-grabbing)
+- **spectrum**: Full color range (diverse, comprehensive)
+- **vivid**: High-contrast colors (accessibility, clarity)
+ `,
+ control: "select",
+ options: ["ocean", "orchid", "emerald", "sunset", "spectrum", "vivid"],
+ table: {
+ defaultValue: { summary: "ocean" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ customPalette: {
+ description: `
+**Custom Color Palette.** Override the theme colors with your own color array.
+
+**Usage:**
+- Provide an array of hex color strings
+- Colors will be applied in order to chart segments
+- Takes precedence over theme colors when provided
+- Useful for brand-specific color requirements
+
+**Example:**
+\`["#FF6B6B", "#4ECDC4", "#45B7D1", "#96CEB4"]\`
+ `,
+ control: false,
+ table: {
+ type: { summary: "string[]" },
+ defaultValue: { summary: "undefined" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ variant: {
+ description: `
+**Chart Layout Style:**
+
+- **circular**: Full 360° display - best for comprehensive data overview
+- **semicircle**: Half-circle display - space-efficient for dashboards
+ `,
+ control: "radio",
+ options: ["semicircle", "circular"],
+ table: {
+ defaultValue: { summary: "circular" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ format: {
+ description: `
+**Data Display Format:**
+
+- **percentage**: Automatically calculates percentages from your data
+- **number**: Shows raw numeric values with smart formatting
+ `,
+ control: "radio",
+ options: ["percentage", "number"],
+ table: {
+ defaultValue: { summary: "number" },
+ category: "📱 Display Options",
+ },
+ },
+ legend: {
+ description: `
+**Legend Visibility.** Controls whether the legend is displayed.
+
+**When to disable:**
+- Minimal dashboard widgets
+- When labels are embedded in the chart
+- Space-constrained layouts
+ `,
+ control: "boolean",
+ table: {
+ type: { summary: "boolean" },
+ defaultValue: { summary: "true" },
+ category: "📱 Display Options",
+ },
+ },
+ legendVariant: {
+ description: `
+**Legend Layout Style:**
+
+- **stacked**: Vertical layout with responsive behavior (recommended)
+- **default**: Horizontal layout at bottom (classic style)
+ `,
+ control: "radio",
+ options: ["default", "stacked"],
+ table: {
+ defaultValue: { summary: "stacked" },
+ category: "📱 Display Options",
+ },
+ },
+ grid: {
+ description: `
+**Polar Grid Lines.** Adds concentric circles for value reference.
+
+**Use cases:**
+- Data analysis and comparison
+- Scientific or technical presentations
+- When precise value reading is important
+ `,
+ control: "boolean",
+ table: {
+ type: { summary: "boolean" },
+ defaultValue: { summary: "false" },
+ category: "📱 Display Options",
+ },
+ },
+ isAnimationActive: {
+ description: `
+**Animation Control.** Enables smooth loading and transition animations.
+
+**Performance note:** Disable for large datasets or performance-critical applications.
+ `,
+ control: "boolean",
+ table: {
+ type: { summary: "boolean" },
+ defaultValue: { summary: "true" },
+ category: "🎬 Animation & Interaction",
+ },
+ },
+ cornerRadius: {
+ description: `
+**Corner Rounding.** Controls the roundness of radial bar ends.
+
+**Design impact:**
+- 0: Sharp, technical appearance
+- 5-10: Subtle modern look (recommended)
+- 15+: Highly rounded, friendly appearance
+ `,
+ control: { type: "number", min: 0, max: 20 },
+ table: {
+ type: { summary: "number" },
+ defaultValue: { summary: "10" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ height: {
+ description: "The height of the chart.",
+ control: "text",
+ table: {
+ type: { summary: "string | number" },
+ category: "📱 Display Options",
+ },
+ },
+ width: {
+ description: "The width of the chart.",
+ control: "text",
+ table: {
+ type: { summary: "string | number" },
+ category: "📱 Display Options",
+ },
+ },
+ },
+} satisfies Meta<typeof RadialChart>;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+/**
+ * ## Default Configuration
+ *
+ * This example demonstrates the RadialChart with its default settings - the most common
+ * configuration for business dashboards and data visualization applications.
+ *
+ * **Key Features Shown:**
+ * - Standard circular layout with full 360° display
+ * - Professional ocean color theme
+ * - Stacked legend for optimal space utilization
+ * - Smooth animations for polished user experience
+ * - Number format for clear value display
+ */
+export const DefaultConfiguration: Story = {
+ name: "📊 Default Configuration",
+ args: {
+ data: monthlyRevenueData,
+ categoryKey: "month",
+ dataKey: "value",
+ theme: "ocean",
+ variant: "circular",
+ format: "number",
+ legend: true,
+ legendVariant: "stacked",
+ grid: false,
+ isAnimationActive: true,
+ cornerRadius: 10,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "700px", height: "auto", padding: "24px" }}>
+ <div style={{ marginBottom: "16px" }}>
+ <h3 style={{ margin: "0 0 8px 0", fontSize: "18px", fontWeight: "600" }}>
+ Monthly Revenue Analysis
+ </h3>
+ <p style={{ margin: 0, color: "#666", fontSize: "14px" }}>
+ Comprehensive view of revenue distribution across 12 months
+ </p>
+ </div>
+ <RadialChart {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story: `
+This is the recommended starting configuration for most use cases. The chart displays data
+in a clear, professional manner with optimal default settings for readability and user experience.
+
+**Configuration Details:**
+- **Data**: 12 months of revenue data
+- **Layout**: Full circular display
+- **Colors**: Ocean theme (blues and teals)
+- **Legend**: Stacked layout for space efficiency
+- **Animations**: Enabled for smooth interactions
+ `,
+ },
+ },
+ },
+};
+
+/**
+ * ## Theme Showcase
+ *
+ * RadialChart includes six professionally designed color themes, each optimized
+ * for different contexts and brand requirements.
+ */
+export const ThemeShowcase: Story = {
+ name: "🎨 Theme Variations",
+ args: {
+ data: monthlyRevenueData.slice(0, 6),
+ categoryKey: "month",
+ dataKey: "value",
+ theme: "emerald",
+ variant: "circular",
+ format: "number",
+ legend: true,
+ legendVariant: "stacked",
+ grid: false,
+ isAnimationActive: true,
+ cornerRadius: 10,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "600px", height: "auto", padding: "24px" }}>
+ <div style={{ marginBottom: "20px" }}>
+ <h3 style={{ margin: "0 0 8px 0", fontSize: "18px", fontWeight: "600" }}>
+ Financial Growth Metrics
+ </h3>
+ <p style={{ margin: 0, color: "#666", fontSize: "14px" }}>
+ Using the emerald theme for finance-related data visualization
+ </p>
+ </div>
+ <RadialChart {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story: `
+**Theme Selection Guide:**
+
+- **Ocean** 🌊: Corporate, professional, trustworthy (recommended for business)
+- **Orchid** 🌸: Creative, modern, innovative (great for design/marketing)
+- **Emerald** 🍃: Growth, finance, nature (perfect for financial data)
+- **Sunset** 🌅: Energy, attention, warmth (ideal for alerts/important metrics)
+- **Spectrum** 🌈: Diverse, comprehensive (when you need many distinct colors)
+- **Vivid** ⚡: High contrast, accessible (optimized for accessibility requirements)
+
+**Best Practice:** Choose themes that align with your brand colors and data context.
+ `,
+ },
+ },
+ },
+};
+
+/**
+ * ## Advanced Visual Enhancement
+ *
+ * This example showcases percentage formatting to create visually striking and informative charts.
+ */
+export const VisualEnhancement: Story = {
+ name: "✨ Visual Enhancement",
+ args: {
+ data: monthlyRevenueData.slice(0, 6),
+ categoryKey: "month",
+ dataKey: "value",
+ theme: "sunset",
+ variant: "circular",
+ format: "percentage",
+ legend: true,
+ legendVariant: "stacked",
+ grid: false,
+ isAnimationActive: true,
+ cornerRadius: 15,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "500px", padding: "24px" }}>
+ <div style={{ marginBottom: "20px" }}>
+ <h3 style={{ margin: "0 0 8px 0", fontSize: "18px", fontWeight: "600" }}>
+ Revenue Distribution
+ </h3>
+ <p style={{ margin: 0, color: "#666", fontSize: "14px" }}>
+ Enhanced with percentage display
+ </p>
+ </div>
+ <RadialChart {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story: `
+**Visual Enhancement Features:**
+
+- **Percentage Display**: Shows data as percentages for better comparison
+- **Modern Aesthetic**: Aligns with contemporary design trends
+- **Theme Integration**: Uses theme colors for consistent visual design
+- **Performance Optimized**: Efficiently rendered for smooth interactions
+
+**When to Use Percentage Format:**
+- Executive dashboards and presentations
+- Marketing materials and public-facing reports
+- When relative comparisons are important
+- With 3-8 data points for optimal readability
+
+**Technical Note:** Percentages are automatically calculated from the data values,
+providing clear relative comparisons across all chart segments.
+ `,
+ },
+ },
+ },
+};
+
+/**
+ * ## Custom Color Palette
+ *
+ * This example demonstrates how to use a custom color palette to override
+ * the default theme colors with brand-specific or custom color schemes.
+ */
+export const CustomPalette: Story = {
+ name: "🎨 Custom Color Palette",
+ args: {
+ data: monthlyRevenueData.slice(0, 8),
+ categoryKey: "month",
+ dataKey: "value",
+ customPalette: customColorPalette,
+ variant: "circular",
+ format: "number",
+ legend: true,
+ legendVariant: "stacked",
+ grid: false,
+ isAnimationActive: true,
+ cornerRadius: 12,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "600px", padding: "24px" }}>
+ <div style={{ marginBottom: "20px" }}>
+ <h3 style={{ margin: "0 0 8px 0", fontSize: "18px", fontWeight: "600" }}>
+ Brand-Specific Color Scheme
+ </h3>
+ <p style={{ margin: 0, color: "#666", fontSize: "14px" }}>
+ Using custom colors that align with your brand identity
+ </p>
+ </div>
+ <RadialChart {...args} />
+ <div
+ style={{
+ marginTop: "16px",
+ padding: "12px",
+ backgroundColor: "#f8f9fa",
+ borderRadius: "6px",
+ fontSize: "12px",
+ color: "#666",
+ }}
+ >
+ <strong>🎨 Custom Palette:</strong>{" "}
+ {customColorPalette.slice(0, 8).map((color, index) => (
+ <span
+ key={index}
+ style={{
+ display: "inline-block",
+ width: "16px",
+ height: "16px",
+ backgroundColor: color,
+ borderRadius: "3px",
+ marginLeft: "4px",
+ marginRight: "4px",
+ border: "1px solid #ddd",
+ verticalAlign: "middle",
+ }}
+ />
+ ))}
+ </div>
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story: `
+**Custom Palette Features:**
+
+- **Brand Alignment**: Use your exact brand colors for consistent visual identity
+- **Override Themes**: Takes precedence over theme-based color selection
+- **Flexible Array**: Provide any number of colors - they'll cycle automatically for larger datasets
+- **Hex Color Support**: Standard hex color format (#RRGGBB)
+
+**Implementation Example:**
+\`\`\`tsx
+const brandColors = [
+ "#FF6B6B", // Primary brand color
+ "#4ECDC4", // Secondary brand color
+ "#45B7D1", // Accent color 1
+ "#96CEB4", // Accent color 2
+ // ... more colors as needed
+];
+
+<RadialChart
+ data={data}
+ categoryKey="category"
+ dataKey="value"
+ customPalette={brandColors}
+/>
+\`\`\`
+
+**Best Practices:**
+- Ensure sufficient contrast between adjacent colors
+- Test color accessibility for users with color vision differences
+- Provide at least as many colors as data points for optimal display
+- Consider color psychology and brand associations when selecting colors
+
+**Technical Notes:**
+- Colors are applied in array order to data segments
+- If fewer colors than data points, colors will cycle automatically
+ `,
+ },
+ },
+ },
+};
+
+/**
+ * ## Large Dataset Management
+ *
+ * When working with extensive datasets, RadialChart provides intelligent
+ * legend management with carousel navigation to maintain usability.
+ */
+export const LargeDatasetDemo: Story = {
+ name: "📈 Large Dataset with Carousel",
+ args: {
+ data: comprehensiveFinancialData,
+ categoryKey: "category",
+ dataKey: "amount",
+ theme: "spectrum",
+ variant: "circular",
+ format: "number",
+ legend: true,
+ legendVariant: "stacked",
+ grid: false,
+ isAnimationActive: true,
+ cornerRadius: 8,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "700px", height: "auto", padding: "24px" }}>
+ <div style={{ marginBottom: "20px" }}>
+ <h3 style={{ margin: "0 0 8px 0", fontSize: "18px", fontWeight: "600" }}>
+ Comprehensive Compensation Analysis
+ </h3>
+ <p style={{ margin: 0, color: "#666", fontSize: "14px" }}>
+ Complete breakdown of 15 compensation categories with carousel navigation
+ </p>
+ </div>
+ <RadialChart {...args} />
+ <div
+ style={{
+ marginTop: "16px",
+ padding: "12px",
+ backgroundColor: "#f8f9fa",
+ borderRadius: "6px",
+ fontSize: "12px",
+ color: "#666",
+ }}
+ >
+ <strong>💡 Carousel Feature:</strong> When legend items exceed available space, up/down
+ navigation arrows automatically appear. Use the arrows to scroll through all legend items
+ while maintaining chart visibility.
+ </div>
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story: `
+**Large Dataset Management:**
+
+**Automatic Carousel Detection:**
+- Activates when legend content exceeds container height
+- Provides smooth scrolling navigation
+- Maintains chart proportions and visibility
+
+**Navigation Features:**
+- **Up/Down Arrows**: Navigate through legend items
+- **Smooth Scrolling**: Polished user experience
+- **Visual Indicators**: Clear navigation state
+
+**Performance Optimizations:**
+- Virtual scrolling for datasets with 50+ items
+- Efficient rendering of visible legend items only
+- Optimized color cycling for unlimited data points
+
+**Best Practices for Large Datasets:**
+- Consider data aggregation for better readability
+- Use meaningful category names
+- Test carousel functionality in your target container sizes
+- Consider alternative visualizations for 25+ categories
+ `,
+ },
+ },
+ },
+};
+
+/**
+ * ## Interactive Responsiveness Demo
+ *
+ * This advanced example demonstrates RadialChart's responsive capabilities
+ * with a resizable container to show real-time adaptation.
+ */
+export const ResponsiveDemo: Story = {
+ name: "📱 Responsive Behavior Demo",
+ args: {
+ data: monthlyRevenueData,
+ categoryKey: "month",
+ dataKey: "value",
+ theme: "spectrum",
+ variant: "circular",
+ format: "number",
+ legend: true,
+ legendVariant: "stacked",
+ isAnimationActive: false,
+ cornerRadius: 8,
+ },
+ render: (args: any) => {
+ const [dimensions, setDimensions] = useState<{ width: number; height: number | string }>({
+ width: 650,
+ height: "auto",
+ });
+
+ const handleMouseDown = (e: React.MouseEvent<HTMLDivElement>, handle: string) => {
+ e.preventDefault();
+ e.stopPropagation();
+ const startX = e.clientX;
+ const startY = e.clientY;
+ const startWidth = dimensions.width;
+ const startHeight = (e.currentTarget.parentElement as HTMLElement).offsetHeight;
+
+ const doDrag = (e: MouseEvent) => {
+ const dx = e.clientX - startX;
+ const dy = e.clientY - startY;
+ let newWidth = startWidth;
+ let newHeight = startHeight;
+
+ if (handle.includes("e")) newWidth = startWidth + dx;
+ if (handle.includes("w")) newWidth = startWidth - dx;
+ if (handle.includes("s")) newHeight = startHeight + dy;
+ if (handle.includes("n")) newHeight = startHeight - dy;
+
+ setDimensions({
+ width: Math.max(300, newWidth),
+ height: "auto",
+ });
+ };
+
+ const stopDrag = () => {
+ document.removeEventListener("mousemove", doDrag);
+ document.removeEventListener("mouseup", stopDrag);
+ };
+
+ document.addEventListener("mousemove", doDrag);
+ document.addEventListener("mouseup", stopDrag);
+ };
+
+ const handleStyle: React.CSSProperties = {
+ position: "absolute",
+ background: "#3b82f6",
+ opacity: 0.6,
+ zIndex: 10,
+ transition: "opacity 0.2s ease",
+ };
+
+ return (
+ <div style={{ padding: "20px" }}>
+ <div style={{ marginBottom: "20px" }}>
+ <h3 style={{ margin: "0 0 8px 0", fontSize: "18px", fontWeight: "600" }}>
+ Responsive Behavior Demonstration
+ </h3>
+ <p style={{ margin: "0 0 12px 0", color: "#666", fontSize: "14px" }}>
+ Drag the edges or corners of the container below to see how the chart adapts
+ </p>
+ <div
+ style={{
+ padding: "12px",
+ backgroundColor: "#e3f2fd",
+ borderRadius: "6px",
+ fontSize: "12px",
+ color: "#1565c0",
+ }}
+ >
+ <strong>🎯 Try This:</strong> Resize the container to see automatic legend layout
+ changes, chart proportion adjustments, and responsive breakpoint behaviors.
+ </div>
+ </div>
+
+ <Card
+ style={{
+ position: "relative",
+ width: `${dimensions.width}px`,
+ height:
+ typeof dimensions.height === "number" ? `${dimensions.height}px` : dimensions.height,
+ border: "2px dashed #9ca3af",
+ padding: "20px",
+ boxSizing: "border-box",
+ overflow: "hidden",
+ cursor: "default",
+ }}
+ >
+ <RadialChart {...args} />
+
+ {/* Resize Handles */}
+ <div
+ style={{ ...handleStyle, top: -2, left: 0, right: 0, height: 12, cursor: "ns-resize" }}
+ onMouseDown={(e) => handleMouseDown(e, "n")}
+ />
+ <div
+ style={{
+ ...handleStyle,
+ bottom: -2,
+ left: 0,
+ right: 0,
+ height: 12,
+ cursor: "ns-resize",
+ }}
+ onMouseDown={(e) => handleMouseDown(e, "s")}
+ />
+ <div
+ style={{ ...handleStyle, top: 0, bottom: 0, left: -2, width: 12, cursor: "ew-resize" }}
+ onMouseDown={(e) => handleMouseDown(e, "w")}
+ />
+ <div
+ style={{ ...handleStyle, top: 0, bottom: 0, right: -2, width: 12, cursor: "ew-resize" }}
+ onMouseDown={(e) => handleMouseDown(e, "e")}
+ />
+
+ {/* Corner Handles */}
+ <div
+ style={{
+ ...handleStyle,
+ top: -2,
+ left: -2,
+ width: 20,
+ height: 20,
+ cursor: "nwse-resize",
+ borderRadius: "2px",
+ }}
+ onMouseDown={(e) => handleMouseDown(e, "nw")}
+ />
+ <div
+ style={{
+ ...handleStyle,
+ top: -2,
+ right: -2,
+ width: 20,
+ height: 20,
+ cursor: "nesw-resize",
+ borderRadius: "2px",
+ }}
+ onMouseDown={(e) => handleMouseDown(e, "ne")}
+ />
+ <div
+ style={{
+ ...handleStyle,
+ bottom: -2,
+ right: -2,
+ width: 20,
+ height: 20,
+ cursor: "nwse-resize",
+ borderRadius: "2px",
+ }}
+ onMouseDown={(e) => handleMouseDown(e, "se")}
+ />
+
+ {/* Dimension Display */}
+ <div
+ style={{
+ position: "absolute",
+ bottom: 8,
+ right: 8,
+ background: "rgba(0,0,0,0.8)",
+ color: "white",
+ padding: "4px 8px",
+ borderRadius: "4px",
+ fontSize: "11px",
+ fontFamily: "monospace",
+ fontWeight: "500",
+ }}
+ >
+ {dimensions.width}px ×{" "}
+ {typeof dimensions.height === "number" ? `${dimensions.height}px` : "auto"}
+ </div>
+ </Card>
+
+ <div
+ style={{
+ marginTop: "16px",
+ padding: "12px",
+ backgroundColor: "#f8f9fa",
+ borderRadius: "6px",
+ fontSize: "12px",
+ color: "#666",
+ }}
+ >
+ <strong>📊 Responsive Features Demonstrated:</strong>
+ <ul style={{ margin: "8px 0 0 0", paddingLeft: "16px" }}>
+ <li>Automatic chart scaling and proportion maintenance</li>
+ <li>Legend layout adaptation (stacked ↔ horizontal)</li>
+ <li>Text size and spacing adjustments</li>
+ <li>Optimal space utilization at any container size</li>
+ </ul>
+ </div>
+ </div>
+ );
+ },
+ parameters: {
+ docs: {
+ description: {
+ story: `
+**Responsive Design Philosophy:**
+
+**Automatic Adaptation:**
+- Chart dimensions automatically adjust to container size
+- Legend layout switches between horizontal and stacked based on available space
+- Text and spacing scale appropriately for readability
+
+**Breakpoint Behavior:**
+- **Large Containers (>600px)**: Side-by-side chart and legend layout
+- **Medium Containers (400-600px)**: Stacked layout with optimized proportions
+- **Small Containers (<400px)**: Compact layout with essential elements only
+
+**Performance Optimizations:**
+- Efficient re-rendering during resize operations
+- Debounced resize calculations to prevent performance issues
+- Optimized SVG scaling for crisp display at any size
+
+**Implementation Notes:**
+- Uses ResizeObserver API for precise container size detection
+- Maintains aspect ratios while maximizing space utilization
+- Supports both fixed and flexible container sizing strategies
+ `,
+ },
+ },
+ },
+};
diff --git a/packages/react-ui/src/components/D3Charts/RadialChart/types.ts b/packages/react-ui/src/components/D3Charts/RadialChart/types.ts
new file mode 100644
index 000000000..6b5c2eb0b
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/RadialChart/types.ts
@@ -0,0 +1,42 @@
+import type { ChartData } from "../types";
+
+export type RadialChartData = ChartData;
+
+export interface RadialChartProps<T extends RadialChartData> {
+ data: T;
+ categoryKey: keyof T[number];
+ dataKey: keyof T[number];
+ customPalette?: string[];
+ variant?: "circular" | "semiCircular";
+ format?: "percentage" | "number";
+ legend?: boolean;
+ /**
+ * `"stacked"` (default): the chart with a stacked legend listing each item's
+ * share — side by side from 400px wide, below the chart when narrower.
+ * `"default"`: the compact legend under the chart. Matches react-ui's
+ * Recharts RadialChart.
+ */
+ legendVariant?: "default" | "stacked";
+ grid?: boolean;
+ /** When set, this chart publishes its legend to the shared legend store under
+ * this key instead of rendering an inline legend. Place a
+ * `<StackedLegend legendKey="…" />` (under a `LegendStoreProvider`) anywhere to
+ * render + drive it. Keys must be unique per chart instance. */
+ legendKey?: string;
+ /**
+ * Play the entrance animation. Gates the entrance ONLY — any hover or
+ * data-update motion is independent of this flag, and printing always
+ * disables it.
+ * Default false (streaming-safe: marks mounted while data streams in don't
+ * replay staggered entrances).
+ */
+ isAnimationActive?: boolean;
+ cornerRadius?: number;
+ maxChartSize?: number;
+ minChartSize?: number;
+ height?: number | string;
+ width?: number | string;
+ fitLegendInHeight?: boolean;
+ className?: string;
+ onClick?: (row: T[number], index: number) => void;
+}
diff --git a/packages/react-ui/src/components/D3Charts/ScatterChart/ScatterChart.tsx b/packages/react-ui/src/components/D3Charts/ScatterChart/ScatterChart.tsx
new file mode 100644
index 000000000..facd06171
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/ScatterChart/ScatterChart.tsx
@@ -0,0 +1,165 @@
+import { useEffectiveAnimation, useScatterChartOrchestrator } from "../hooks";
+import { NumericXAxis } from "../shared/cartesian/axes/NumericXAxis";
+import { YAxis } from "../shared/cartesian/axes/YAxis";
+import { Grid } from "../shared/cartesian/Grid";
+import { VerticalGrid } from "../shared/cartesian/VerticalGrid";
+import { ChartShell } from "../shared/core/ChartShell";
+import { DefaultLegend } from "../shared/core/DefaultLegend/DefaultLegend";
+import { ChartTooltip } from "../shared/core/PortalTooltip/ChartTooltip";
+import { CHART_CLASS_PREFIX } from "../utils/constants";
+import { ScatterDots } from "./parts/ScatterDots";
+import type { ScatterChartProps } from "./types";
+
+export function ScatterChart(props: ScatterChartProps) {
+ const {
+ data,
+ customPalette,
+ grid: showGrid = true,
+ verticalGrid: showVerticalGrid = true,
+ legend: showLegend = true,
+ showYAxis = true,
+ xAxisLabel,
+ yAxisLabel,
+ isAnimationActive = false,
+ dotRadius = 4,
+ className,
+ height,
+ width,
+ fitLegendInHeight,
+ onClick,
+ } = props;
+
+ const orch = useScatterChartOrchestrator({
+ data,
+ themePaletteName: "defaultChartPalette",
+ customPalette,
+ showLegend,
+ showYAxis,
+ height,
+ width,
+ fitLegendInHeight,
+ xAxisLabel: typeof xAxisLabel === "string" ? xAxisLabel : undefined,
+ yAxisLabel: typeof yAxisLabel === "string" ? yAxisLabel : undefined,
+ onClick,
+ });
+
+ const animate = useEffectiveAnimation(isAnimationActive);
+
+ const {
+ dimensions: {
+ effectiveYAxisWidth,
+ chartAreaWidth,
+ chartInnerHeight,
+ totalSvgWidth,
+ totalSvgHeight,
+ xAxisHeight,
+ CHART_MARGIN_TOP: marginTop,
+ },
+ scales: { xScale, yScale },
+ } = orch;
+
+ return (
+ <ChartShell
+ containerRef={orch.refs.containerRef}
+ classPrefix={`${CHART_CLASS_PREFIX}-scatter-chart`}
+ className={className}
+ style={orch.style.containerStyle}
+ isEmpty={orch.isEmpty}
+ >
+ {() => (
+ <>
+ <svg
+ width={totalSvgWidth}
+ height={totalSvgHeight}
+ style={{ overflow: "visible" }}
+ role="img"
+ aria-label="Scatter chart"
+ >
+ {showYAxis && (
+ <g transform={`translate(0, ${marginTop})`}>
+ <YAxis
+ scale={yScale}
+ width={effectiveYAxisWidth}
+ chartHeight={chartInnerHeight}
+ className={`${CHART_CLASS_PREFIX}-scatter-chart-y-axis`}
+ tickClassName={`${CHART_CLASS_PREFIX}-scatter-chart-y-tick`}
+ />
+ </g>
+ )}
+
+ <g
+ transform={`translate(${effectiveYAxisWidth}, ${marginTop})`}
+ onMouseMove={orch.hover.handleMouseMove}
+ onMouseLeave={orch.hover.handleMouseLeave}
+ onTouchMove={orch.hover.handleTouchMove}
+ onTouchEnd={orch.hover.handleTouchEnd}
+ onClick={orch.hover.handleClick}
+ >
+ <rect width={chartAreaWidth} height={chartInnerHeight} fill="transparent" />
+
+ {showGrid && (
+ <Grid
+ yScale={yScale}
+ chartWidth={chartAreaWidth}
+ chartHeight={chartInnerHeight}
+ className={`${CHART_CLASS_PREFIX}-scatter-chart-grid`}
+ />
+ )}
+
+ {showVerticalGrid && (
+ <VerticalGrid
+ xScale={xScale}
+ chartWidth={chartAreaWidth}
+ chartHeight={chartInnerHeight}
+ className={`${CHART_CLASS_PREFIX}-scatter-chart-grid-vertical`}
+ />
+ )}
+
+ <ScatterDots
+ datasets={orch.data.visibleDatasets}
+ xScale={xScale}
+ yScale={yScale}
+ colorMap={orch.data.colorMap}
+ dotRadius={dotRadius}
+ hoveredPoint={orch.hover.hoveredPoint}
+ animate={animate}
+ />
+ </g>
+
+ <g transform={`translate(${effectiveYAxisWidth}, ${chartInnerHeight + marginTop})`}>
+ <NumericXAxis
+ scale={xScale}
+ chartWidth={chartAreaWidth}
+ height={xAxisHeight}
+ className={`${CHART_CLASS_PREFIX}-scatter-chart-x-axis`}
+ tickClassName={`${CHART_CLASS_PREFIX}-scatter-chart-x-tick`}
+ />
+ </g>
+ </svg>
+
+ {showLegend && (
+ <DefaultLegend
+ ref={orch.refs.legendRef}
+ items={orch.legend.legendItems}
+ containerWidth={orch.dimensions.containerWidth}
+ isExpanded={orch.legend.isLegendExpanded}
+ setIsExpanded={orch.legend.setIsLegendExpanded}
+ onItemClick={orch.legend.toggleSeries}
+ hiddenSeries={orch.legend.hiddenSeries}
+ xAxisLabel={xAxisLabel}
+ yAxisLabel={yAxisLabel}
+ />
+ )}
+
+ {orch.tooltip.tooltipPayload && orch.hover.mousePos && (
+ <ChartTooltip
+ label={orch.tooltip.tooltipPayload.label}
+ items={orch.tooltip.tooltipPayload.items}
+ viewportPosition={orch.hover.mousePos}
+ />
+ )}
+ </>
+ )}
+ </ChartShell>
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/ScatterChart/index.ts b/packages/react-ui/src/components/D3Charts/ScatterChart/index.ts
new file mode 100644
index 000000000..cc7932d85
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/ScatterChart/index.ts
@@ -0,0 +1,2 @@
+export { ScatterChart } from "./ScatterChart";
+export type { ScatterChartData, ScatterChartProps } from "./types";
diff --git a/packages/react-ui/src/components/D3Charts/ScatterChart/parts/ScatterDots.tsx b/packages/react-ui/src/components/D3Charts/ScatterChart/parts/ScatterDots.tsx
new file mode 100644
index 000000000..01a450a83
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/ScatterChart/parts/ScatterDots.tsx
@@ -0,0 +1,75 @@
+import type { ScaleLinear } from "d3-scale";
+import React from "react";
+
+import type { VisibleDataset } from "../../hooks/cartesian/useScatterChartOrchestrator";
+import { CHART_CLASS_PREFIX } from "../../utils/constants";
+import { entranceProps } from "../../utils/entranceUtils";
+import type { HoveredScatterPoint } from "../types";
+
+interface ScatterDotsProps {
+ datasets: VisibleDataset[];
+ xScale: ScaleLinear<number, number>;
+ yScale: ScaleLinear<number, number>;
+ colorMap: Record<string, string>;
+ dotRadius: number;
+ hoveredPoint: HoveredScatterPoint | null;
+ /** Pre-folded "animation on AND not printing" — computed at the chart entry via useEffectiveAnimation. */
+ animate: boolean;
+}
+
+export const ScatterDots: React.FC<ScatterDotsProps> = ({
+ datasets,
+ xScale,
+ yScale,
+ colorMap,
+ dotRadius,
+ hoveredPoint,
+ animate,
+}) => {
+ return (
+ <g className={`${CHART_CLASS_PREFIX}-scatter-chart-dots`}>
+ {datasets.map(({ dataset: ds, originalIndex }) => {
+ const color = colorMap[ds.name] ?? "#000";
+ const isHoveredDataset = hoveredPoint?.datasetName === ds.name;
+ const hasHover = hoveredPoint !== null;
+
+ return (
+ <g key={ds.name}>
+ {ds.data.map((pt, ptIdx) => {
+ const isHoveredDot = isHoveredDataset && hoveredPoint?.pointIndex === ptIdx;
+
+ const r = isHoveredDot ? dotRadius * 1.5 : dotRadius;
+ // fill/stroke-opacity, NOT opacity — the entrance's forwards
+ // fill holds opacity:1 (dead dim) AND an inline opacity:1 would
+ // defeat the --animated class's pre-delay opacity:0 (stagger
+ // flash). Both sub-properties together ≡ opacity for a dot.
+ const dim = hasHover && !isHoveredDataset ? 0.3 : 1;
+
+ const { className, animationDelay } = entranceProps(
+ animate,
+ `${CHART_CLASS_PREFIX}-scatter-chart-dot--animated`,
+ originalIndex * 80,
+ );
+
+ return (
+ <circle
+ key={ptIdx}
+ cx={xScale(pt.x)}
+ cy={yScale(pt.y)}
+ r={r}
+ fill={color}
+ className={`${CHART_CLASS_PREFIX}-scatter-chart-dot ${className}`}
+ style={{
+ fillOpacity: dim,
+ strokeOpacity: dim,
+ animationDelay,
+ }}
+ />
+ );
+ })}
+ </g>
+ );
+ })}
+ </g>
+ );
+};
diff --git a/packages/react-ui/src/components/D3Charts/ScatterChart/scatterChart.scss b/packages/react-ui/src/components/D3Charts/ScatterChart/scatterChart.scss
new file mode 100644
index 000000000..b4c959bc4
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/ScatterChart/scatterChart.scss
@@ -0,0 +1,56 @@
+@use "../../../cssUtils" as cssUtils;
+@use "../shared/cartesian/chartBase" as base;
+@use "../prefix" as brand;
+
+@include base.centered-container("scatter-chart");
+
+.#{brand.$prefix}-scatter-chart-grid line {
+ stroke: cssUtils.$border-default;
+ stroke-dasharray: 3 3;
+}
+
+.#{brand.$prefix}-scatter-chart-grid line.#{brand.$prefix}-grid-zero-line {
+ stroke-dasharray: none;
+}
+
+.#{brand.$prefix}-scatter-chart-grid-vertical line {
+ stroke: cssUtils.$border-default;
+ stroke-dasharray: 3 3;
+}
+
+.#{brand.$prefix}-scatter-chart-y-tick {
+ @include base.svg-tick-label;
+}
+
+.#{brand.$prefix}-scatter-chart-x-tick {
+ @include base.svg-tick-label;
+}
+
+.#{brand.$prefix}-scatter-chart-dot {
+ stroke: cssUtils.$foreground;
+ stroke-width: 1.5;
+ transition:
+ r 0.15s ease,
+ fill-opacity 0.15s ease,
+ stroke-opacity 0.15s ease;
+}
+
+// Entrances are decorative: gate the whole rule (pre-state included) behind
+// reduced-motion so users who opt out get the natural static state immediately
+// — gating only the animation would strand elements at the opacity: 0 start.
+@media (prefers-reduced-motion: no-preference) {
+ .#{brand.$prefix}-scatter-chart-dot--animated {
+ opacity: 0;
+ animation: #{brand.$prefix}-scatter-dot-appear 0.4s ease-out forwards;
+ }
+}
+
+@keyframes #{brand.$prefix}-scatter-dot-appear {
+ from {
+ opacity: 0;
+ r: 0;
+ }
+ to {
+ opacity: 1;
+ }
+}
diff --git a/packages/react-ui/src/components/D3Charts/ScatterChart/stories/ScatterChart.stories.tsx b/packages/react-ui/src/components/D3Charts/ScatterChart/stories/ScatterChart.stories.tsx
new file mode 100644
index 000000000..e6ed06ed5
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/ScatterChart/stories/ScatterChart.stories.tsx
@@ -0,0 +1,823 @@
+// Copy of Charts/ScatterChart/stories/ScatterChart.stories.tsx with only the chart import and the title changed:
+// the same args and renders, rendering the D3Charts chart via
+// ../../stories/rechartsStoryAdapters.
+import type { Meta, StoryObj } from "@storybook/react";
+import {
+ Calendar,
+ Globe,
+ Laptop,
+ Monitor,
+ Smartphone,
+ TabletSmartphone,
+ Tv,
+ Watch,
+} from "lucide-react";
+import { useState } from "react";
+import { Card } from "../../../Card";
+import { ScatterChart, ScatterChartProps } from "../../stories/rechartsStoryAdapters";
+
+const customColorPalette = [
+ "#0A0E60",
+ "#14197B",
+ "#272DA6",
+ "#383FC9",
+ "#444CE7",
+ "#5F67F4",
+ "#7884FF",
+ "#97A9FF",
+ "#B4C6FF",
+ "#CBD7FF",
+];
+
+// Sample scatter chart datasets
+const dataVariations = {
+ default: [
+ {
+ name: "A school",
+ data: [
+ { x: 100, y: 200, z: 200 },
+ { x: 120, y: 100, z: 260 },
+ { x: 170, y: 300, z: 400 },
+ { x: 140, y: 250, z: 280 },
+ { x: 150, y: 400, z: 500 },
+ { x: 110, y: 280, z: 200 },
+ ],
+ },
+ {
+ name: "B school",
+ data: [
+ { x: 200, y: 180, z: 240 },
+ { x: 180, y: 350, z: 220 },
+ { x: 160, y: 320, z: 250 },
+ { x: 190, y: 150, z: 210 },
+ ],
+ },
+ ],
+ correlation: [
+ {
+ name: "Revenue",
+ data: [
+ { x: 1000, y: 1200 },
+ { x: 1200, y: 1400 },
+ { x: 1700, y: 2100 },
+ { x: 1400, y: 1800 },
+ { x: 1500, y: 1950 },
+ { x: 1100, y: 1300 },
+ { x: 2000, y: 2500 },
+ { x: 1800, y: 2200 },
+ { x: 1600, y: 1850 },
+ { x: 1900, y: 2350 },
+ { x: 1300, y: 1600 },
+ { x: 2200, y: 2800 },
+ ],
+ },
+ {
+ name: "Profit",
+ data: [
+ { x: 1000, y: 200 },
+ { x: 1200, y: 280 },
+ { x: 1700, y: 420 },
+ { x: 1400, y: 350 },
+ { x: 1500, y: 380 },
+ { x: 1100, y: 240 },
+ { x: 2000, y: 500 },
+ { x: 1800, y: 450 },
+ { x: 1600, y: 390 },
+ { x: 1900, y: 470 },
+ { x: 1300, y: 320 },
+ { x: 2200, y: 580 },
+ ],
+ },
+ ],
+ multipleDatasets: [
+ {
+ name: "Desktop",
+ data: [
+ { x: 1, y: 4 },
+ { x: 2, y: 2 },
+ { x: 3, y: 7 },
+ { x: 4, y: 5 },
+ { x: 5, y: 8 },
+ { x: 6, y: 3 },
+ { x: 7, y: 9 },
+ { x: 8, y: 6 },
+ { x: 9, y: 10 },
+ { x: 10, y: 1 },
+ ],
+ },
+ {
+ name: "Mobile",
+ data: [
+ { x: 1, y: 3 },
+ { x: 2, y: 5 },
+ { x: 3, y: 4 },
+ { x: 4, y: 7 },
+ { x: 5, y: 6 },
+ { x: 6, y: 8 },
+ { x: 7, y: 5 },
+ { x: 8, y: 9 },
+ { x: 9, y: 7 },
+ { x: 10, y: 8 },
+ ],
+ },
+ {
+ name: "Tablet",
+ data: [
+ { x: 1, y: 2 },
+ { x: 2, y: 6 },
+ { x: 3, y: 3 },
+ { x: 4, y: 4 },
+ { x: 5, y: 7 },
+ { x: 6, y: 5 },
+ { x: 7, y: 6 },
+ { x: 8, y: 8 },
+ { x: 9, y: 4 },
+ { x: 10, y: 9 },
+ ],
+ },
+ ],
+ performance: [
+ {
+ name: "Performance",
+ data: [
+ { x: 30, y: 1200 },
+ { x: 35, y: 1500 },
+ { x: 40, y: 1800 },
+ { x: 45, y: 2100 },
+ { x: 50, y: 2400 },
+ { x: 55, y: 2700 },
+ { x: 60, y: 3000 },
+ { x: 25, y: 900 },
+ { x: 65, y: 3300 },
+ { x: 70, y: 3600 },
+ ],
+ },
+ {
+ name: "Efficiency",
+ data: [
+ { x: 30, y: 1100 },
+ { x: 35, y: 1350 },
+ { x: 40, y: 1650 },
+ { x: 45, y: 1950 },
+ { x: 50, y: 2200 },
+ { x: 55, y: 2500 },
+ { x: 60, y: 2850 },
+ { x: 25, y: 800 },
+ { x: 65, y: 3150 },
+ { x: 70, y: 3450 },
+ ],
+ },
+ ],
+ comprehensive: [
+ {
+ name: "North America Sales",
+ data: [
+ { x: 1200, y: 8500, z: 120 },
+ { x: 1350, y: 9200, z: 140 },
+ { x: 1100, y: 7800, z: 95 },
+ { x: 1450, y: 10200, z: 160 },
+ { x: 1250, y: 8900, z: 130 },
+ { x: 1600, y: 11500, z: 180 },
+ { x: 1050, y: 7600, z: 85 },
+ { x: 1700, y: 12800, z: 200 },
+ { x: 1300, y: 9100, z: 135 },
+ { x: 1500, y: 10800, z: 170 },
+ { x: 1150, y: 8200, z: 110 },
+ { x: 1750, y: 13200, z: 210 },
+ { x: 1400, y: 9800, z: 150 },
+ { x: 1650, y: 12100, z: 190 },
+ { x: 1220, y: 8700, z: 125 },
+ { x: 1800, y: 13800, z: 220 },
+ { x: 1180, y: 8100, z: 105 },
+ { x: 1550, y: 11100, z: 175 },
+ { x: 1280, y: 9000, z: 128 },
+ { x: 1620, y: 11800, z: 185 },
+ { x: 1120, y: 7900, z: 100 },
+ { x: 1720, y: 13000, z: 205 },
+ { x: 1380, y: 9500, z: 145 },
+ { x: 1680, y: 12500, z: 195 },
+ { x: 1240, y: 8800, z: 120 },
+ ],
+ },
+ {
+ name: "Europe Sales",
+ data: [
+ { x: 980, y: 7200, z: 88 },
+ { x: 1150, y: 8400, z: 115 },
+ { x: 1020, y: 7500, z: 95 },
+ { x: 1280, y: 9200, z: 140 },
+ { x: 1080, y: 7800, z: 105 },
+ { x: 1420, y: 10100, z: 165 },
+ { x: 950, y: 6900, z: 80 },
+ { x: 1520, y: 11200, z: 185 },
+ { x: 1120, y: 8200, z: 120 },
+ { x: 1380, y: 9800, z: 155 },
+ { x: 1050, y: 7600, z: 100 },
+ { x: 1580, y: 11800, z: 195 },
+ { x: 1180, y: 8600, z: 130 },
+ { x: 1480, y: 10700, z: 175 },
+ { x: 1000, y: 7300, z: 90 },
+ { x: 1620, y: 12200, z: 205 },
+ { x: 1060, y: 7700, z: 102 },
+ { x: 1320, y: 9400, z: 145 },
+ { x: 1100, y: 8000, z: 115 },
+ { x: 1450, y: 10400, z: 170 },
+ { x: 970, y: 7100, z: 85 },
+ { x: 1550, y: 11500, z: 190 },
+ { x: 1140, y: 8300, z: 125 },
+ { x: 1680, y: 12600, z: 200 },
+ { x: 1040, y: 7500, z: 98 },
+ ],
+ },
+ {
+ name: "Asia Pacific Sales",
+ data: [
+ { x: 1800, y: 15200, z: 280 },
+ { x: 1950, y: 16800, z: 320 },
+ { x: 1650, y: 13800, z: 240 },
+ { x: 2100, y: 18200, z: 360 },
+ { x: 1750, y: 14800, z: 260 },
+ { x: 2250, y: 19500, z: 400 },
+ { x: 1600, y: 13200, z: 220 },
+ { x: 2350, y: 20200, z: 420 },
+ { x: 1900, y: 16200, z: 300 },
+ { x: 2150, y: 18500, z: 380 },
+ { x: 1700, y: 14200, z: 250 },
+ { x: 2400, y: 20800, z: 440 },
+ { x: 2000, y: 17200, z: 340 },
+ { x: 2200, y: 18800, z: 390 },
+ { x: 1820, y: 15500, z: 290 },
+ { x: 2450, y: 21200, z: 460 },
+ { x: 1720, y: 14500, z: 255 },
+ { x: 2050, y: 17500, z: 350 },
+ { x: 1870, y: 15800, z: 295 },
+ { x: 2300, y: 19800, z: 410 },
+ { x: 1780, y: 15000, z: 275 },
+ { x: 2500, y: 21800, z: 480 },
+ { x: 1920, y: 16400, z: 310 },
+ { x: 2070, y: 17700, z: 355 },
+ { x: 1830, y: 15600, z: 285 },
+ ],
+ },
+ {
+ name: "Latin America Sales",
+ data: [
+ { x: 650, y: 4200, z: 55 },
+ { x: 780, y: 5100, z: 75 },
+ { x: 720, y: 4800, z: 65 },
+ { x: 850, y: 5800, z: 90 },
+ { x: 690, y: 4500, z: 60 },
+ { x: 920, y: 6300, z: 105 },
+ { x: 620, y: 4000, z: 50 },
+ { x: 980, y: 6800, z: 120 },
+ { x: 750, y: 5000, z: 70 },
+ { x: 880, y: 6000, z: 95 },
+ { x: 670, y: 4400, z: 58 },
+ { x: 1020, y: 7100, z: 130 },
+ { x: 730, y: 4900, z: 68 },
+ { x: 950, y: 6500, z: 110 },
+ { x: 640, y: 4100, z: 52 },
+ { x: 1100, y: 7500, z: 150 },
+ { x: 700, y: 4700, z: 62 },
+ { x: 860, y: 5900, z: 92 },
+ { x: 680, y: 4600, z: 56 },
+ { x: 930, y: 6400, z: 108 },
+ { x: 610, y: 3900, z: 48 },
+ { x: 1050, y: 7200, z: 140 },
+ { x: 740, y: 4950, z: 69 },
+ { x: 970, y: 6650, z: 118 },
+ { x: 660, y: 4300, z: 54 },
+ ],
+ },
+ {
+ name: "Middle East & Africa",
+ data: [
+ { x: 450, y: 2800, z: 35 },
+ { x: 580, y: 3700, z: 55 },
+ { x: 520, y: 3300, z: 45 },
+ { x: 680, y: 4400, z: 70 },
+ { x: 490, y: 3100, z: 40 },
+ { x: 750, y: 4900, z: 85 },
+ { x: 420, y: 2600, z: 30 },
+ { x: 820, y: 5500, z: 100 },
+ { x: 560, y: 3600, z: 52 },
+ { x: 710, y: 4700, z: 78 },
+ { x: 470, y: 2900, z: 38 },
+ { x: 880, y: 5900, z: 115 },
+ { x: 530, y: 3400, z: 48 },
+ { x: 780, y: 5200, z: 92 },
+ { x: 440, y: 2700, z: 32 },
+ { x: 920, y: 6200, z: 125 },
+ { x: 500, y: 3200, z: 42 },
+ { x: 650, y: 4100, z: 65 },
+ { x: 480, y: 3000, z: 39 },
+ { x: 730, y: 4800, z: 80 },
+ { x: 410, y: 2500, z: 28 },
+ { x: 850, y: 5700, z: 105 },
+ { x: 540, y: 3500, z: 50 },
+ { x: 800, y: 5400, z: 95 },
+ { x: 460, y: 2850, z: 36 },
+ ],
+ },
+ {
+ name: "Small Business",
+ data: [
+ { x: 200, y: 1200, z: 15 },
+ { x: 280, y: 1600, z: 22 },
+ { x: 240, y: 1400, z: 18 },
+ { x: 320, y: 1900, z: 28 },
+ { x: 220, y: 1300, z: 16 },
+ { x: 360, y: 2200, z: 35 },
+ { x: 180, y: 1100, z: 12 },
+ { x: 400, y: 2500, z: 45 },
+ { x: 260, y: 1500, z: 20 },
+ { x: 340, y: 2100, z: 32 },
+ { x: 210, y: 1250, z: 15 },
+ { x: 380, y: 2400, z: 40 },
+ { x: 250, y: 1450, z: 19 },
+ { x: 370, y: 2300, z: 38 },
+ { x: 190, y: 1150, z: 13 },
+ { x: 420, y: 2700, z: 50 },
+ { x: 230, y: 1350, z: 17 },
+ { x: 290, y: 1700, z: 24 },
+ { x: 205, y: 1220, z: 15 },
+ { x: 350, y: 2150, z: 34 },
+ { x: 170, y: 1050, z: 11 },
+ { x: 390, y: 2450, z: 42 },
+ { x: 245, y: 1420, z: 18 },
+ { x: 375, y: 2350, z: 39 },
+ { x: 195, y: 1180, z: 14 },
+ ],
+ },
+ {
+ name: "Enterprise Clients",
+ data: [
+ { x: 2500, y: 35000, z: 800 },
+ { x: 2800, y: 38000, z: 900 },
+ { x: 2200, y: 32000, z: 700 },
+ { x: 3100, y: 42000, z: 1000 },
+ { x: 2650, y: 36500, z: 850 },
+ { x: 3400, y: 46000, z: 1200 },
+ { x: 2100, y: 30000, z: 650 },
+ { x: 3600, y: 48000, z: 1300 },
+ { x: 2750, y: 37500, z: 875 },
+ { x: 2950, y: 40000, z: 950 },
+ { x: 2350, y: 33500, z: 750 },
+ { x: 3750, y: 50000, z: 1400 },
+ { x: 2900, y: 39500, z: 925 },
+ { x: 3250, y: 44000, z: 1100 },
+ { x: 2550, y: 35500, z: 825 },
+ { x: 3850, y: 52000, z: 1500 },
+ { x: 2400, y: 34000, z: 775 },
+ { x: 3050, y: 41000, z: 975 },
+ { x: 2700, y: 37000, z: 860 },
+ { x: 3300, y: 45000, z: 1150 },
+ { x: 2250, y: 31500, z: 675 },
+ { x: 3500, y: 47000, z: 1250 },
+ { x: 2850, y: 38500, z: 910 },
+ { x: 3200, y: 43000, z: 1050 },
+ { x: 2600, y: 36000, z: 835 },
+ ],
+ },
+ {
+ name: "Government Contracts",
+ data: [
+ { x: 1800, y: 25000, z: 600 },
+ { x: 2100, y: 28000, z: 700 },
+ { x: 1650, y: 23000, z: 550 },
+ { x: 2400, y: 32000, z: 800 },
+ { x: 1950, y: 26500, z: 650 },
+ { x: 2700, y: 36000, z: 900 },
+ { x: 1500, y: 21000, z: 500 },
+ { x: 2850, y: 38000, z: 950 },
+ { x: 2250, y: 30000, z: 750 },
+ { x: 2550, y: 34000, z: 850 },
+ { x: 1750, y: 24000, z: 575 },
+ { x: 3000, y: 40000, z: 1000 },
+ { x: 2150, y: 29000, z: 725 },
+ { x: 2600, y: 35000, z: 875 },
+ { x: 1850, y: 25500, z: 625 },
+ { x: 3100, y: 41000, z: 1025 },
+ { x: 1700, y: 23500, z: 525 },
+ { x: 2300, y: 30500, z: 775 },
+ { x: 2000, y: 27500, z: 675 },
+ { x: 2750, y: 37000, z: 925 },
+ { x: 1600, y: 22500, z: 525 },
+ { x: 2900, y: 39000, z: 975 },
+ { x: 2200, y: 29500, z: 740 },
+ { x: 2650, y: 35500, z: 890 },
+ { x: 1900, y: 26000, z: 640 },
+ ],
+ },
+ ],
+};
+
+const icons = {
+ desktop: Monitor,
+ mobile: TabletSmartphone,
+ tablet: Calendar,
+ series1: Globe,
+ series2: Smartphone,
+ revenue: Laptop,
+ profit: Tv,
+ performance: Watch,
+ efficiency: Monitor,
+} as const;
+
+/**
+ * # ScatterChart Component Documentation
+ *
+ * The ScatterChart component is designed for visualizing relationships between two continuous variables.
+ * It's ideal for:
+ *
+ * - **Correlation Analysis**: Identifying relationships between variables.
+ * - **Distribution Analysis**: Understanding data point clustering and outliers.
+ * - **Comparative Analysis**: Comparing multiple datasets on the same coordinate system.
+ *
+ * ## Key Features
+ *
+ * ### Interactive & Responsive
+ * - **Interactive Tooltips**: Hover over points to see detailed data values.
+ * - **Multiple Datasets**: Support for multiple data series with different colors.
+ * - **Responsive Design**: Adapts to any container size.
+ *
+ * ### Customization
+ * - **Theming**: Six pre-built color palettes or custom colors.
+ * - **Shape Options**: Multiple point shapes (circle, diamond, square, etc.).
+ * - **Axis Configuration**: Customizable axis labels, units, and domains.
+ */
+const meta: Meta<ScatterChartProps> = {
+ title: "Components/D3Charts/ScatterChart",
+ component: ScatterChart,
+ parameters: {
+ layout: "centered",
+ docs: {
+ description: {
+ component: `
+## Installation and Basic Usage
+
+\`\`\`tsx
+import { ScatterChart } from '@openuidev/react-ui/Charts/ScatterChart';
+
+const scatterData = [
+ { x: 100, y: 200, category: "A" },
+ { x: 120, y: 100, category: "B" },
+ { x: 170, y: 300, category: "A" },
+];
+
+// Basic implementation
+<ScatterChart
+ data={scatterData}
+ xAxisDataKey="x"
+ yAxisDataKey="y"
+ theme="ocean"
+/>
+
+// With custom labels and units
+<ScatterChart
+ data={scatterData}
+ xAxisDataKey="x"
+ yAxisDataKey="y"
+ xAxisLabel="Temperature (°C)"
+ yAxisLabel="Sales ($)"
+ xAxisUnit="°C"
+ yAxisUnit="$"
+/>
+\`\`\`
+
+## Data Structure Requirements
+
+Your data should be an array of objects. Each object must contain:
+- **x coordinate** (number): The X-axis value for the point.
+- **y coordinate** (number): The Y-axis value for the point.
+- One or more **series fields**: Additional fields that define different datasets/series.
+
+\`\`\`tsx
+const scatterData = [
+ { x: 10, y: 20, dataset1: 1, dataset2: 1 },
+ { x: 15, y: 25, dataset1: 1, dataset2: 1 },
+ { x: 20, y: 30, dataset1: 1, dataset2: 1 },
+];
+\`\`\`
+`,
+ },
+ },
+ },
+ tags: ["!dev", "autodocs"],
+ argTypes: {
+ data: {
+ description: `
+**Required.** An array of data objects for the scatter chart. Each object should contain:
+- x coordinate (number) for the X-axis.
+- y coordinate (number) for the Y-axis.
+- One or more series identifiers.
+`,
+ control: false,
+ table: {
+ type: { summary: "Array<Record<string, string | number>>" },
+ category: "📊 Data Configuration",
+ },
+ },
+ xAxisDataKey: {
+ description: "The key in your data object that represents the X-axis values.",
+ control: "text",
+ table: {
+ defaultValue: { summary: "x" },
+ category: "📊 Data Configuration",
+ },
+ },
+ yAxisDataKey: {
+ description: "The key in your data object that represents the Y-axis values.",
+ control: "text",
+ table: {
+ defaultValue: { summary: "y" },
+ category: "📊 Data Configuration",
+ },
+ },
+ theme: {
+ description: "Specifies the color palette for the chart points and legend.",
+ control: "select",
+ options: ["ocean", "orchid", "emerald", "sunset", "spectrum", "vivid"],
+ table: {
+ defaultValue: { summary: "ocean" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ customPalette: {
+ description: "Custom array of colors to use instead of the theme palette.",
+ control: "object",
+ table: {
+ type: { summary: "string[]" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ shape: {
+ description: "The shape of the scatter points.",
+ control: "select",
+ options: ["circle", "square"],
+ table: {
+ defaultValue: { summary: "circle" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ grid: {
+ description: "Toggles the visibility of the background grid lines.",
+ control: "boolean",
+ table: {
+ defaultValue: { summary: "true" },
+ category: "📱 Display Options",
+ },
+ },
+ legend: {
+ description: "Toggles the visibility of the chart legend.",
+ control: "boolean",
+ table: {
+ defaultValue: { summary: "true" },
+ category: "📱 Display Options",
+ },
+ },
+ isAnimationActive: {
+ description: "Enables or disables the initial loading animation.",
+ control: "boolean",
+ table: {
+ defaultValue: { summary: "false" },
+ category: "🎬 Animation & Interaction",
+ },
+ },
+ xAxisLabel: {
+ description: "A label to display below the X-axis.",
+ control: "text",
+ table: {
+ type: { summary: "React.ReactNode" },
+ category: "📱 Display Options",
+ },
+ },
+ yAxisLabel: {
+ description: "A label to display beside the Y-axis.",
+ control: "text",
+ table: {
+ type: { summary: "React.ReactNode" },
+ category: "📱 Display Options",
+ },
+ },
+ className: {
+ description: "Custom CSS class to apply to the chart's container.",
+ control: "text",
+ table: {
+ type: { summary: "string" },
+ category: "Layout & Sizing",
+ },
+ },
+ height: {
+ description: "Sets the height of the chart container.",
+ control: "number",
+ table: {
+ type: { summary: "number" },
+ category: "Layout & Sizing",
+ },
+ },
+ width: {
+ description: "Sets the width of the chart container.",
+ control: "number",
+ table: {
+ type: { summary: "number" },
+ category: "Layout & Sizing",
+ },
+ },
+ },
+} satisfies Meta<typeof ScatterChart>;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+/**
+ * ## Basic Scatter Chart
+ *
+ * This demonstrates a basic scatter chart with default settings.
+ * Perfect for showing simple correlations between two variables.
+ */
+export const BasicScatter: Story = {
+ name: "📈 Basic Scatter Chart",
+ args: {
+ data: dataVariations.default,
+ xAxisDataKey: "x",
+ yAxisDataKey: "y",
+ theme: "ocean",
+ grid: true,
+ legend: true,
+ isAnimationActive: true,
+ showYAxis: true,
+ showXAxis: true,
+ shape: "circle",
+ width: 700,
+ height: 400,
+ },
+ render: (args: any) => <ScatterChart {...args} />,
+};
+
+/**
+ * ## Correlation Analysis
+ *
+ * This example shows how to use the scatter chart for correlation analysis.
+ * Notice how the points follow a general upward trend, indicating positive correlation.
+ */
+export const CorrelationAnalysis: Story = {
+ name: "📊 Correlation Analysis",
+ args: {
+ data: dataVariations.correlation,
+ xAxisDataKey: "x",
+ yAxisDataKey: "y",
+ theme: "emerald",
+ grid: true,
+ legend: true,
+ isAnimationActive: true,
+ xAxisLabel: "Marketing Spend",
+ yAxisLabel: "Sales Revenue",
+ shape: "circle",
+ },
+ render: (args: any) => (
+ <Card style={{ width: "700px" }}>
+ <ScatterChart {...args} />
+ </Card>
+ ),
+};
+
+/**
+ * ## Shape Comparison
+ *
+ * Compare different point shapes available in the scatter chart.
+ * Each shape provides a different visual style for your data points.
+ */
+export const ShapeComparison: Story = {
+ name: "🔷 Shape Comparison",
+ args: {
+ data: dataVariations.default as never,
+ xAxisDataKey: "x",
+ yAxisDataKey: "y",
+ theme: "sunset",
+ grid: true,
+ legend: true,
+ isAnimationActive: false,
+ },
+ render: (args: any) => {
+ const shapes = ["circle", "square"] as const;
+
+ return (
+ <div style={{ display: "flex", flexDirection: "column", gap: "20px" }}>
+ {shapes.map((shape) => (
+ <div key={shape}>
+ <h4
+ style={{
+ margin: "0 0 8px 0",
+ fontSize: "14px",
+ fontWeight: "600",
+ textTransform: "capitalize",
+ }}
+ >
+ {shape} Shape
+ </h4>
+ <Card style={{ width: "500px", height: "600px" }}>
+ <ScatterChart {...args} shape={shape} height={"100%"} />
+ </Card>
+ </div>
+ ))}
+ </div>
+ );
+ },
+};
+
+/**
+ * ## Data Explorer
+ *
+ * Interactive tool for exploring different scatter chart datasets.
+ * Use the buttons to switch between various data scenarios.
+ */
+export const DataExplorer: Story = {
+ name: "🎛️ Data Explorer",
+ args: {
+ data: dataVariations.default as never,
+ xAxisDataKey: "x",
+ yAxisDataKey: "y",
+ theme: "ocean",
+ grid: true,
+ legend: true,
+ isAnimationActive: true,
+ shape: "circle",
+ },
+ render: (args: any) => {
+ const [selectedDataType, setSelectedDataType] =
+ useState<keyof typeof dataVariations>("default");
+
+ const currentData = dataVariations[selectedDataType];
+
+ const buttonStyle = {
+ margin: "2px",
+ padding: "6px 12px",
+ fontSize: "12px",
+ border: "1px solid #ddd",
+ borderRadius: "4px",
+ cursor: "pointer",
+ background: "#fff",
+ fontFamily: "monospace",
+ };
+
+ const activeButtonStyle = {
+ ...buttonStyle,
+ background: "#007acc",
+ color: "white",
+ border: "1px solid #007acc",
+ };
+
+ return (
+ <div>
+ <div
+ style={{
+ marginBottom: "16px",
+ padding: "12px",
+ background: "#f8f9fa",
+ borderRadius: "8px",
+ border: "1px solid #e9ecef",
+ width: "600px",
+ }}
+ >
+ <strong>📈 Scatter Chart Test Suite:</strong>
+ <div style={{ marginTop: "8px", display: "flex", flexWrap: "wrap", gap: "4px" }}>
+ <button
+ onClick={() => setSelectedDataType("default")}
+ style={selectedDataType === "default" ? activeButtonStyle : buttonStyle}
+ >
+ 📊 Default
+ </button>
+ <button
+ onClick={() => setSelectedDataType("correlation")}
+ style={selectedDataType === "correlation" ? activeButtonStyle : buttonStyle}
+ >
+ 📈 Correlation
+ </button>
+ <button
+ onClick={() => setSelectedDataType("multipleDatasets")}
+ style={selectedDataType === "multipleDatasets" ? activeButtonStyle : buttonStyle}
+ >
+ 🎯 Multiple Datasets
+ </button>
+ <button
+ onClick={() => setSelectedDataType("performance")}
+ style={selectedDataType === "performance" ? activeButtonStyle : buttonStyle}
+ >
+ ⚡ Performance
+ </button>
+ <button
+ onClick={() => setSelectedDataType("comprehensive")}
+ style={selectedDataType === "comprehensive" ? activeButtonStyle : buttonStyle}
+ >
+ 🌍 Comprehensive
+ </button>
+ </div>
+ </div>
+ <Card style={{ width: "600px" }}>
+ <ScatterChart {...args} data={currentData} height={"600px"} />
+ </Card>
+ </div>
+ );
+ },
+};
diff --git a/packages/react-ui/src/components/D3Charts/ScatterChart/types.ts b/packages/react-ui/src/components/D3Charts/ScatterChart/types.ts
new file mode 100644
index 000000000..80ddbfc3a
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/ScatterChart/types.ts
@@ -0,0 +1,53 @@
+export interface ScatterPoint {
+ x: number;
+ y: number;
+ [key: string]: string | number | undefined;
+}
+
+export interface ScatterDataset {
+ name: string;
+ data: ScatterPoint[];
+}
+
+export type ScatterChartData = ScatterDataset[];
+
+export interface HoveredScatterPoint {
+ datasetIndex: number;
+ pointIndex: number;
+ point: ScatterPoint;
+ datasetName: string;
+}
+
+export interface ScatterChartProps {
+ data: ScatterChartData;
+ customPalette?: string[];
+ grid?: boolean;
+ verticalGrid?: boolean;
+ /**
+ * Show the legend. NOTE: `xAxisLabel`/`yAxisLabel` render inside the legend
+ * strip, so `legend={false}` hides them too.
+ */
+ legend?: boolean;
+ showYAxis?: boolean;
+ xAxisLabel?: React.ReactNode;
+ yAxisLabel?: React.ReactNode;
+ /**
+ * Play the entrance animation. Gates the entrance ONLY — any hover or
+ * data-update motion is independent of this flag, and printing always
+ * disables it.
+ * Default false (streaming-safe: marks mounted while data streams in don't
+ * replay staggered entrances).
+ */
+ isAnimationActive?: boolean;
+ dotRadius?: number;
+ className?: string;
+ height?: number | string;
+ width?: number | string;
+ fitLegendInHeight?: boolean;
+ onClick?: (
+ point: ScatterPoint,
+ datasetName: string,
+ datasetIndex: number,
+ pointIndex: number,
+ ) => void;
+}
diff --git a/packages/react-ui/src/components/D3Charts/SegmentedBar/SegmentedBar.tsx b/packages/react-ui/src/components/D3Charts/SegmentedBar/SegmentedBar.tsx
new file mode 100644
index 000000000..63e49b7e7
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/SegmentedBar/SegmentedBar.tsx
@@ -0,0 +1,253 @@
+import clsx from "clsx";
+import React, { useCallback, useMemo, useRef, useState } from "react";
+import { Separator } from "../../Separator";
+import { useTheme } from "../../ThemeProvider";
+
+import { useChartShell } from "../hooks/core/useChartShell";
+import { ChartShell } from "../shared/core/ChartShell";
+import { DefaultLegend } from "../shared/core/DefaultLegend/DefaultLegend";
+import type { StackedLegendItem } from "../shared/core/legend";
+import { ChartTooltip } from "../shared/core/PortalTooltip/ChartTooltip";
+import { StackedLegend } from "../shared/core/StackedLegend";
+import type { LegendItem } from "../types";
+import { CHART_CLASS_PREFIX } from "../utils/constants";
+import { resolvePalette } from "../utils/paletteUtils";
+import { numberTickFormatter } from "../utils/styleUtils";
+import { segmentShare, segmentValue } from "./parts/segmentedBarGeometry";
+import type { SegmentedBarData, SegmentedBarProps } from "./types";
+
+const CLASS_PREFIX = `${CHART_CLASS_PREFIX}-segmented-bar`;
+
+/**
+ * A thin div-based stacked progress bar — a faithful visual port of react-ui's
+ * `SingleStackedBar`. One horizontal track split into segments sized by SHARE
+ * OF TOTAL (value / Σ), the compact `DefaultLegend` by default. Hovering a segment (or a
+ * legend row) highlights it, dims the rest, and shows a value/percentage
+ * tooltip. Adapted to viz conventions: no named-palette `theme` prop (colors
+ * come from the react-ui `ThemeProvider` via `resolvePalette`), no in-track
+ * labels, no legend visibility toggle (openui only hover-highlights).
+ */
+export function SegmentedBar<T extends SegmentedBarData>({
+ data,
+ categoryKey,
+ dataKey,
+ customPalette,
+ legend = true,
+ legendVariant = "default",
+ isAnimationActive = false,
+ className,
+ style,
+}: SegmentedBarProps<T>) {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const legendRef = useRef<HTMLDivElement>(null);
+
+ const [activeIndex, setActiveIndex] = useState<number | null>(null);
+ const [hoveredKey, setHoveredKey] = useState<string | null>(null);
+ const [tooltipPosition, setTooltipPosition] = useState<{
+ x: number;
+ y: number;
+ } | null>(null);
+ const [isLegendExpanded, setIsLegendExpanded] = useState(false);
+
+ const { isPrinting, isEmpty, containerWidth } = useChartShell({
+ data,
+ showLegend: legend,
+ containerRef,
+ legendRef,
+ });
+
+ // Entrance/width tween gate: printing always snaps to the settled frame.
+ const animate = isAnimationActive && !isPrinting;
+
+ const { theme } = useTheme();
+
+ // Ordered ramp, one hue per segment by INPUT order — matches openui's
+ // `themePaletteName: 'barChartPalette'`.
+ const ramp = useMemo(
+ () => resolvePalette(theme, "barChartPalette", customPalette),
+ [theme, customPalette],
+ );
+
+ // Segments sized by share of the total (value / Σ), computed inline like
+ // openui. Keys disambiguate duplicate categories (LLMs re-emit them).
+ const segments = useMemo(() => {
+ if (!data || data.length === 0) return [];
+ const catKey = String(categoryKey);
+ const valKey = String(dataKey);
+ const values = data.map((row) => segmentValue(row[valKey]));
+ const total = values.reduce((sum, v) => sum + v, 0);
+ return data.map((row, index) => {
+ const share = segmentShare(values[index] ?? 0, total);
+ return {
+ key: `${String(row[catKey])}-${index}`,
+ label: String(row[catKey]),
+ value: values[index] ?? 0,
+ share,
+ percentage: share * 100,
+ color: ramp[index % ramp.length] ?? "#000000",
+ };
+ });
+ }, [data, categoryKey, dataKey, ramp]);
+
+ const stackedLegendItems = useMemo<StackedLegendItem[]>(
+ () =>
+ segments.map((s) => ({
+ key: s.key,
+ label: s.label,
+ color: s.color,
+ value: s.value,
+ })),
+ [segments],
+ );
+
+ const legendItems = useMemo<LegendItem[]>(
+ () =>
+ segments.map((s) => ({
+ key: s.key,
+ label: s.label,
+ color: s.color,
+ percentage: s.percentage,
+ })),
+ [segments],
+ );
+
+ // Position the tooltip at the top-center of a segment, in VIEWPORT coords
+ // (viz's ChartTooltip positions a virtual element by raw client rect).
+ const positionTooltipOver = useCallback((index: number) => {
+ const segmentEl = containerRef.current?.querySelectorAll(`.${CLASS_PREFIX}-segment`)?.[
+ index
+ ] as HTMLElement | undefined;
+ if (!segmentEl) return;
+ const rect = segmentEl.getBoundingClientRect();
+ setTooltipPosition({ x: rect.left + rect.width / 2, y: rect.top });
+ }, []);
+
+ const handleSegmentEnter = useCallback(
+ (index: number, e: React.MouseEvent<HTMLDivElement>) => {
+ const segment = segments[index];
+ if (!segment) return;
+ setActiveIndex(index);
+ setHoveredKey(segment.key);
+ const rect = e.currentTarget.getBoundingClientRect();
+ setTooltipPosition({ x: rect.left + rect.width / 2, y: rect.top });
+ },
+ [segments],
+ );
+
+ const clearHover = useCallback(() => {
+ setActiveIndex(null);
+ setHoveredKey(null);
+ setTooltipPosition(null);
+ }, []);
+
+ // Legend-row hover ↔ segment: highlight the matching segment (dim the rest)
+ // and float the tooltip over it — the key↔index map.
+ const handleLegendHover = useCallback(
+ (key: string | null) => {
+ if (key === null) {
+ clearHover();
+ return;
+ }
+ const index = segments.findIndex((s) => s.key === key);
+ if (index < 0) return;
+ setActiveIndex(index);
+ setHoveredKey(key);
+ positionTooltipOver(index);
+ },
+ [segments, clearHover, positionTooltipOver],
+ );
+
+ const activeSegment = activeIndex !== null ? segments[activeIndex] : undefined;
+
+ return (
+ <ChartShell
+ containerRef={containerRef}
+ classPrefix={CLASS_PREFIX}
+ className={clsx(className, {
+ [`${CLASS_PREFIX}-container--gap`]: legend && legendVariant === "default",
+ })}
+ style={style ?? {}}
+ isEmpty={isEmpty}
+ >
+ {() => (
+ <>
+ <div className={CLASS_PREFIX} role="img" aria-label="Segmented bar">
+ {segments.map((segment, index) => {
+ const isActive = activeIndex === null || activeIndex === index;
+ return (
+ <div
+ key={segment.key}
+ className={clsx(`${CLASS_PREFIX}-segment`, {
+ [`${CLASS_PREFIX}-segment--animated`]: animate,
+ })}
+ style={{
+ width: `${segment.percentage}%`,
+ backgroundColor: segment.color,
+ opacity: isActive ? 1 : 0.5,
+ }}
+ onMouseEnter={(e) => handleSegmentEnter(index, e)}
+ onMouseLeave={clearHover}
+ >
+ <div className={`${CLASS_PREFIX}-segment-line`} />
+ </div>
+ );
+ })}
+ </div>
+
+ {activeSegment && tooltipPosition && (
+ <ChartTooltip
+ label={activeSegment.label}
+ items={[
+ {
+ name: "Value",
+ value: numberTickFormatter(activeSegment.value),
+ color: activeSegment.color,
+ },
+ {
+ name: "Percentage",
+ value: `${activeSegment.percentage.toFixed(1)}%`,
+ color: activeSegment.color,
+ },
+ ]}
+ viewportPosition={tooltipPosition}
+ placement="top"
+ />
+ )}
+
+ {legend && legendVariant === "default" && (
+ <>
+ <Separator />
+ <DefaultLegend
+ ref={legendRef}
+ items={legendItems}
+ isExpanded={isLegendExpanded}
+ setIsExpanded={setIsLegendExpanded}
+ containerWidth={containerWidth}
+ style={{ paddingTop: 0 }}
+ />
+ </>
+ )}
+
+ {legend && legendVariant === "stacked" && (
+ // Wrapper carries `legendRef` so `useChartShell`'s (required) legend
+ // measurement is attached in this mode too — the `default` variant
+ // attaches it via `DefaultLegend`. `StackedLegend` keeps its own
+ // class (and its `margin-top`), so the layout is unchanged.
+ <div ref={legendRef}>
+ <StackedLegend
+ items={stackedLegendItems}
+ activeKey={hoveredKey}
+ onItemHover={handleLegendHover}
+ layout="showMore"
+ separator
+ showTitle={false}
+ containerWidth={containerWidth}
+ className={`${CLASS_PREFIX}-stacked-legend`}
+ />
+ </div>
+ )}
+ </>
+ )}
+ </ChartShell>
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/SegmentedBar/index.ts b/packages/react-ui/src/components/D3Charts/SegmentedBar/index.ts
new file mode 100644
index 000000000..e831545de
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/SegmentedBar/index.ts
@@ -0,0 +1,2 @@
+export { SegmentedBar } from "./SegmentedBar";
+export type { SegmentedBarData, SegmentedBarProps } from "./types";
diff --git a/packages/react-ui/src/components/D3Charts/SegmentedBar/parts/segmentedBarGeometry.test.ts b/packages/react-ui/src/components/D3Charts/SegmentedBar/parts/segmentedBarGeometry.test.ts
new file mode 100644
index 000000000..86e91a765
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/SegmentedBar/parts/segmentedBarGeometry.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, it } from "vitest";
+import { segmentShare, segmentValue } from "./segmentedBarGeometry";
+
+describe("segmentValue (clamp neg / NaN / non-numeric → 0)", () => {
+ it("keeps a positive number", () => {
+ expect(segmentValue(42)).toBe(42);
+ });
+ it("parses a numeric string", () => {
+ expect(segmentValue("17.5")).toBe(17.5);
+ });
+ it("clamps a negative to 0", () => {
+ expect(segmentValue(-3)).toBe(0);
+ });
+ it("clamps NaN / non-numeric / undefined to 0", () => {
+ expect(segmentValue(Number.NaN)).toBe(0);
+ expect(segmentValue("abc")).toBe(0);
+ expect(segmentValue(undefined)).toBe(0);
+ });
+});
+
+describe("segmentShare (share of TOTAL, not retention)", () => {
+ it("share is value / total", () => {
+ expect(segmentShare(25, 100)).toBe(0.25);
+ });
+ it("shares over a set sum to 1", () => {
+ const values = [30, 24, 7, 39];
+ const total = values.reduce((a, b) => a + b, 0);
+ const sum = values.reduce((acc, v) => acc + segmentShare(v, total), 0);
+ expect(sum).toBeCloseTo(1, 10);
+ });
+ it("guards divide-by-zero (total <= 0) → 0, never NaN/Infinity", () => {
+ expect(segmentShare(5, 0)).toBe(0);
+ expect(segmentShare(5, -10)).toBe(0);
+ expect(Number.isFinite(segmentShare(5, 0))).toBe(true);
+ });
+ it("clamps a negative value to a 0 share", () => {
+ expect(segmentShare(-5, 100)).toBe(0);
+ });
+});
diff --git a/packages/react-ui/src/components/D3Charts/SegmentedBar/parts/segmentedBarGeometry.ts b/packages/react-ui/src/components/D3Charts/SegmentedBar/parts/segmentedBarGeometry.ts
new file mode 100644
index 000000000..54e468f0a
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/SegmentedBar/parts/segmentedBarGeometry.ts
@@ -0,0 +1,28 @@
+// Pure share math for the SegmentedBar: value clamp + SHARE-OF-TOTAL. Kept out
+// of the component so the clamp and the divide-by-zero guard are unit-testable
+// in isolation.
+//
+// NOTE: this is share-of-TOTAL (value / Σ visible), NOT the funnel's
+// retention-relative-to-first-stage (see funnelGeometry.ts:funnelPercentage).
+
+/**
+ * A segment's numeric value. Non-numeric / NaN / negative collapses to 0 — a
+ * negative share has no geometry, and a NaN would poison the total. Adapts
+ * funnelStageValue (useFunnelChartOrchestrator.ts:31), tightened to also clamp
+ * negatives (the funnel allows them; the segmented bar does not).
+ */
+export function segmentValue(raw: string | number | undefined): number {
+ const value = Number(raw);
+ return Number.isFinite(value) ? Math.max(0, value) : 0;
+}
+
+/**
+ * Share of the TOTAL: value / Σ, clamped to [0, 1]. Divide-by-zero guard:
+ * total <= 0 → 0, so an all-zero (or empty) set renders zero-width segments,
+ * never NaN / Infinity. The div-based bar multiplies this by 100 for its
+ * `width: %` — the same width that encodes the segment's share.
+ */
+export function segmentShare(value: number, total: number): number {
+ if (!(total > 0)) return 0;
+ return Math.max(0, value) / total;
+}
diff --git a/packages/react-ui/src/components/D3Charts/SegmentedBar/segmentedBar.scss b/packages/react-ui/src/components/D3Charts/SegmentedBar/segmentedBar.scss
new file mode 100644
index 000000000..7a91b7b61
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/SegmentedBar/segmentedBar.scss
@@ -0,0 +1,83 @@
+// Faithful port of react-ui's `singleStackedBarChart.scss`, re-prefixed
+// `#{brand.$prefix}-segmented-bar*` and pulling the same design tokens from
+// `@openuidev/react-ui/scssUtils`. A thin div-based stacked progress bar: 20px
+// track, rounded + soft-shadowed, per-segment shadow + rounded outer corners +
+// a centered 1px accent line, with an optional width tween.
+
+@use "../../../cssUtils" as cssUtils;
+@use "../shared/cartesian/chartBase" as base;
+@use "../prefix" as brand;
+
+// The persistent container (rendered by ChartShell): the centered column shared
+// by the non-cartesian charts, plus openui's justify-center + the legend gap.
+@include base.centered-container("segmented-bar");
+
+.#{brand.$prefix}-segmented-bar-container {
+ justify-content: center;
+
+ // Gap between the bar and the DefaultLegend (default variant only) — openui's
+ // `-container-gap`. The StackedLegend spaces itself with margin-top below.
+ &--gap {
+ gap: cssUtils.$space-m;
+ }
+}
+
+// The thin bar track.
+.#{brand.$prefix}-segmented-bar {
+ width: 100%;
+ height: 20px;
+ font-family: inherit;
+ background-color: cssUtils.$background;
+ border-radius: cssUtils.$radius-s;
+ overflow: hidden;
+ box-shadow: cssUtils.$shadow-s;
+ display: flex;
+ padding: cssUtils.$space-2xs;
+ gap: cssUtils.$space-3xs;
+}
+
+.#{brand.$prefix}-segmented-bar-segment {
+ height: 100%;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ min-width: 2px;
+ box-shadow: cssUtils.$shadow-s;
+ position: relative;
+ overflow: hidden;
+ transition:
+ box-shadow 0.2s ease,
+ filter 0.2s ease,
+ opacity 0.2s ease;
+
+ &:first-child {
+ border-radius: cssUtils.$radius-xs 0 0 cssUtils.$radius-xs;
+ }
+
+ &:last-child {
+ border-radius: 0 cssUtils.$radius-xs cssUtils.$radius-xs 0;
+ }
+
+ // The centered 1px accent line inside each segment.
+ &-line {
+ position: absolute;
+ transform: translateY(-50%);
+ background-color: cssUtils.$border-accent-emphasis;
+ top: 50%;
+ left: 5px;
+ width: calc(100% - 10px);
+ height: 1px;
+ z-index: 1;
+ min-width: 2px;
+ }
+
+ // The width tween (each segment grows/shrinks as its share shifts). Openui's
+ // `-animated`; gated in JS so printing snaps to the settled frame.
+ &--animated {
+ transition: width 0.6s cubic-bezier(0.4, 0, 0.2, 1);
+ }
+}
+
+.#{brand.$prefix}-segmented-bar-stacked-legend {
+ margin-top: cssUtils.$space-s;
+}
diff --git a/packages/react-ui/src/components/D3Charts/SegmentedBar/stories/SingleStackedBarChart.stories.tsx b/packages/react-ui/src/components/D3Charts/SegmentedBar/stories/SingleStackedBarChart.stories.tsx
new file mode 100644
index 000000000..5dcf79af1
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/SegmentedBar/stories/SingleStackedBarChart.stories.tsx
@@ -0,0 +1,426 @@
+// Copy of Charts/SingleStackedBarChart/stories/SingleStackedBarChart.stories.tsx with only the chart import and the title changed:
+// the same args and renders, rendering the D3Charts chart via
+// ../../stories/rechartsStoryAdapters.
+import type { Meta, StoryObj } from "@storybook/react";
+import { Card } from "../../../Card";
+import { SingleStackedBar, SingleStackedBarProps } from "../../stories/rechartsStoryAdapters";
+
+const meta: Meta<SingleStackedBarProps<any>> = {
+ title: "Components/D3Charts/SingleStackedBar",
+ component: SingleStackedBar,
+ parameters: {
+ layout: "centered",
+ docs: {
+ description: {
+ component: `
+// Note: While the component is named 'ProgressBar', it's presented here as a 'SingleStackedBar'
+// to emphasize its use for showing proportional data, much like a pie chart.
+## Installation and Basic Usage
+
+\`\`\`tsx
+import { SingleStackedBar } from '@openuidev/react-ui/Charts/SingleStackedBar';
+
+// Basic implementation
+<SingleStackedBar
+ data={[
+ { category: 'A', value: 25 },
+ { category: 'B', value: 30 },
+ { category: 'C', value: 20 }
+ ]}
+ categoryKey="category"
+ dataKey="value"
+ theme="ocean"
+ legend={true}
+/>
+\`\`\`
+
+## Data Structure Requirements
+
+The data should be an array of objects with consistent property names. Use \`categoryKey\` to specify which property contains the segment labels, and \`dataKey\` to specify which property contains the numeric values.
+
+\`\`\`tsx
+// Example data structure
+const data = [
+ { category: 'Desktop', value: 45 },
+ { category: 'Mobile', value: 35 },
+ { category: 'Tablet', value: 20 }
+];
+
+// Component usage
+<SingleStackedBar
+ data={data}
+ categoryKey="category"
+ dataKey="value"
+/>
+\`\`\`
+
+## Key Features
+
+- **Segmented Display**: Visualize the composition of a whole.
+- **Theming**: Six built-in color palettes.
+- **Animation**: Smoothly animates the bar segments.
+- **Legend Support**: Optional legend with category names and colors.
+- **Responsive**: Adapts to the width of its container.
+`,
+ },
+ },
+ },
+ tags: ["dev", "autodocs"],
+ argTypes: {
+ data: {
+ description: `
+**Required.** An array of objects where each object contains category and value information.
+The component extracts values using the specified \`dataKey\` and calculates proportional widths.
+
+**Example:** \`[{ category: 'A', value: 20 }, { category: 'B', value: 30 }, { category: 'C', value: 15 }]\`
+`,
+ control: false,
+ table: {
+ type: { summary: "Array<Record<string, string | number>>" },
+ defaultValue: { summary: "[]" },
+ category: "📊 Data Configuration",
+ },
+ },
+ categoryKey: {
+ description: `
+**Required.** The property name in each data object that contains the segment labels/categories.
+This value will be displayed in tooltips and used for accessibility.
+
+**Example:** \`'category'\` or \`'name'\`
+`,
+ control: "text",
+ table: {
+ type: { summary: "string" },
+ category: "📊 Data Configuration",
+ },
+ },
+ dataKey: {
+ description: `
+**Required.** The property name in each data object that contains the numeric values.
+These values determine the proportional width of each segment.
+
+**Example:** \`'value'\` or \`'count'\` or \`'percentage'\`
+`,
+ control: "text",
+ table: {
+ type: { summary: "string" },
+ category: "📊 Data Configuration",
+ },
+ },
+ theme: {
+ description: `
+**Color Theme Selection.** Choose from professionally designed color palettes:
+
+- **ocean**: Cool blues and teals
+- **orchid**: Purple and pink tones
+- **emerald**: Green variations
+- **sunset**: Warm oranges and reds
+- **spectrum**: Full color range
+- **vivid**: High-contrast colors
+`,
+ control: "select",
+ options: ["ocean", "orchid", "emerald", "sunset", "spectrum", "vivid"],
+ table: {
+ defaultValue: { summary: "ocean" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ animated: {
+ description: `
+**Animation Control.** Enables or disables the fill animation on load.
+`,
+ control: "boolean",
+ table: {
+ type: { summary: "boolean" },
+ defaultValue: { summary: "true" },
+ category: "🎬 Animation & Interaction",
+ },
+ },
+ legend: {
+ description: `
+**Legend Display.** Shows or hides the legend below the single stacked bar chart.
+The legend displays category names with their corresponding colors.
+`,
+ control: "boolean",
+ table: {
+ type: { summary: "boolean" },
+ defaultValue: { summary: "false" },
+ category: "📊 Data Configuration",
+ },
+ },
+ legendVariant: {
+ description: `
+**Legend Variant.** Choose between default (inline) and stacked (vertical) legend.
+Stacked legend appears at the bottom and shows values as percentages.
+`,
+ control: "radio",
+ options: ["default", "stacked"],
+ table: {
+ type: { summary: '"default" | "stacked"' },
+ defaultValue: { summary: "default" },
+ category: "📱 Display Options",
+ },
+ },
+ },
+} satisfies Meta<typeof SingleStackedBar>;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+const sampleData = {
+ default: [
+ { category: "A", value: 25 },
+ { category: "B", value: 30 },
+ { category: "C", value: 20 },
+ ],
+ many: [
+ { category: "Item 1", value: 10 },
+ { category: "Item 2", value: 8 },
+ { category: "Item 3", value: 12 },
+ { category: "Item 4", value: 5 },
+ { category: "Item 5", value: 15 },
+ { category: "Item 6", value: 7 },
+ { category: "Item 7", value: 13 },
+ { category: "Item 8", value: 10 },
+ ],
+ full: [
+ { category: "Q1", value: 25 },
+ { category: "Q2", value: 25 },
+ { category: "Q3", value: 25 },
+ { category: "Q4", value: 25 },
+ ],
+};
+
+export const DefaultConfiguration: Story = {
+ name: "📊 Default Configuration",
+ args: {
+ data: sampleData.default,
+ categoryKey: "category",
+ dataKey: "value",
+ theme: "ocean",
+ animated: true,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "400px", padding: "24px" }}>
+ <div style={{ marginBottom: "16px" }}>
+ <h3 style={{ margin: "0 0 8px 0", fontSize: "16px", fontWeight: "600" }}>
+ Category Breakdown
+ </h3>
+ <p style={{ margin: 0, color: "#666", fontSize: "14px" }}>
+ Visualizing the breakdown of a dataset into its constituent parts.
+ </p>
+ </div>
+ <SingleStackedBar {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "This is the standard appearance of the Single Stacked Bar. It shows multiple segments, each with a color from the selected theme, representing the proportional breakdown of a whole.",
+ },
+ },
+ },
+};
+
+export const ThemeShowcase: Story = {
+ name: "🎨 Theme Showcase",
+ args: {
+ data: [
+ { category: "Segment 1", value: 15 },
+ { category: "Segment 2", value: 20 },
+ { category: "Segment 3", value: 25 },
+ { category: "Segment 4", value: 15 },
+ ],
+ categoryKey: "category",
+ dataKey: "value",
+ animated: true,
+ },
+ render: (args: any) => (
+ <div style={{ width: "400px", display: "flex", flexDirection: "column", gap: "24px" }}>
+ {(["ocean", "orchid", "emerald", "sunset", "spectrum", "vivid"] as const).map((theme) => (
+ <div key={theme}>
+ <h4
+ style={{
+ marginBottom: "12px",
+ textTransform: "capitalize",
+ fontSize: "14px",
+ fontWeight: 600,
+ }}
+ >
+ {theme}
+ </h4>
+ <SingleStackedBar {...args} theme={theme} />
+ </div>
+ ))}
+ </div>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "The Single Stacked Bar supports six different color themes. This allows it to fit seamlessly into various application designs and visual identities.",
+ },
+ },
+ },
+};
+
+export const ManySegments: Story = {
+ name: "🧩 Many Segments",
+ args: {
+ data: sampleData.many,
+ categoryKey: "category",
+ dataKey: "value",
+ theme: "vivid",
+ animated: true,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "500px", padding: "24px" }}>
+ <div style={{ marginBottom: "16px" }}>
+ <h3 style={{ margin: "0 0 8px 0", fontSize: "16px", fontWeight: "600" }}>
+ Resource Distribution
+ </h3>
+ <p style={{ margin: 0, color: "#666", fontSize: "14px" }}>
+ The component gracefully handles numerous small segments.
+ </p>
+ </div>
+ <SingleStackedBar {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "The Single Stacked Bar can display many segments. The colors will cycle through the selected theme palette if the number of segments exceeds the number of available colors.",
+ },
+ },
+ },
+};
+
+export const FullComposition: Story = {
+ name: "✅ Full Composition",
+ args: {
+ data: sampleData.full,
+ categoryKey: "category",
+ dataKey: "value",
+ theme: "spectrum",
+ animated: false,
+ },
+ render: (args: any) => (
+ <Card style={{ width: "400px", padding: "24px" }}>
+ <div style={{ marginBottom: "16px" }}>
+ <h3 style={{ margin: "0 0 8px 0", fontSize: "16px", fontWeight: "600" }}>
+ Complete Data Set
+ </h3>
+ <p style={{ margin: 0, color: "#666", fontSize: "14px" }}>
+ Displaying a bar where segments add up to 100%.
+ </p>
+ </div>
+ <SingleStackedBar {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "This example shows a bar where the segments add up to 100%. The segments collectively fill the entire width of the container, representing the full composition of the data.",
+ },
+ },
+ },
+};
+
+export const WithLegend: Story = {
+ name: "📊 With Legend",
+ args: {
+ data: sampleData.default,
+ categoryKey: "category",
+ dataKey: "value",
+ theme: "ocean",
+ animated: true,
+ legend: true,
+ legendVariant: "default",
+ },
+ render: (args: any) => (
+ <Card style={{ width: "500px", padding: "24px" }}>
+ <div style={{ marginBottom: "16px" }}>
+ <h3 style={{ margin: "0 0 8px 0", fontSize: "16px", fontWeight: "600" }}>
+ Category Breakdown with Legend
+ </h3>
+ <p style={{ margin: 0, color: "#666", fontSize: "14px" }}>
+ Visualizing the breakdown with a legend that shows category names and colors. The legend
+ automatically expands when there are many items.
+ </p>
+ </div>
+ <SingleStackedBar {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "This example demonstrates the SingleStackedBar with legend enabled. The legend displays below the chart and shows the category names with their corresponding colors. For larger datasets, the legend will show a 'Show More' button to expand and see all items.",
+ },
+ },
+ },
+};
+
+export const LegendWithManyItems: Story = {
+ name: "🧩 Legend with Many Items",
+ args: {
+ data: sampleData.many,
+ categoryKey: "category",
+ dataKey: "value",
+ theme: "vivid",
+ animated: true,
+ legend: true,
+ legendVariant: "default",
+ },
+ render: (args: any) => (
+ <Card style={{ width: "600px", padding: "24px" }}>
+ <div style={{ marginBottom: "16px" }}>
+ <h3 style={{ margin: "0 0 8px 0", fontSize: "16px", fontWeight: "600" }}>
+ Resource Distribution with Legend
+ </h3>
+ <p style={{ margin: 0, color: "#666", fontSize: "14px" }}>
+ The component handles many segments gracefully with the legend showing category names and
+ values. The legend automatically manages overflow with expand/collapse functionality.
+ </p>
+ </div>
+ <SingleStackedBar {...args} />
+ </Card>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "This example shows how the SingleStackedBar handles many segments with legend enabled. The legend automatically shows a 'Show More' button when items don't fit in the available space, providing a clean way to manage large datasets.",
+ },
+ },
+ },
+};
+
+export const StackedLegendVariant: Story = {
+ name: "📚 Stacked Legend (Bottom)",
+ args: {
+ data: sampleData.many,
+ categoryKey: "category",
+ dataKey: "value",
+ theme: "ocean",
+ animated: true,
+ legend: true,
+ legendVariant: "stacked",
+ },
+ render: (args: any) => (
+ <Card style={{ width: "650px", padding: "24px" }}>
+ <div style={{ marginBottom: "16px" }}>
+ <h3 style={{ margin: "0 0 8px 0", fontSize: "16px", fontWeight: "600" }}>
+ Stacked Legend at Bottom
+ </h3>
+ <p style={{ margin: 0, color: "#666", fontSize: "14px" }}>
+ Displays a vertical legend beneath the bar with percentage values and overflow handling.
+ </p>
+ </div>
+ <SingleStackedBar {...args} />
+ </Card>
+ ),
+};
diff --git a/packages/react-ui/src/components/D3Charts/SegmentedBar/types.ts b/packages/react-ui/src/components/D3Charts/SegmentedBar/types.ts
new file mode 100644
index 000000000..24d071b12
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/SegmentedBar/types.ts
@@ -0,0 +1,35 @@
+import type { CSSProperties } from "react";
+import type { ChartData } from "../types";
+
+export type SegmentedBarData = ChartData;
+
+export interface SegmentedBarProps<T extends SegmentedBarData> {
+ /**
+ * Row-shaped data, same contract as Pie/Radial/Funnel: one row per segment,
+ * in display order. `categoryKey` names the segment-label field; `dataKey`
+ * names the numeric value field. Each segment is sized by its SHARE OF THE
+ * TOTAL (value / Σ of all values).
+ */
+ data: T;
+ categoryKey: keyof T[number];
+ dataKey: keyof T[number];
+ /** Ordered colors for the segments (by input order); overrides the theme palette. */
+ customPalette?: string[];
+ /** Show the legend (one row per segment). Default true. */
+ legend?: boolean;
+ /**
+ * `'default'` (default, as in react-ui's `SingleStackedBar`) → a `Separator`
+ * plus the compact swatch `DefaultLegend`. `'stacked'` → a `StackedLegend`
+ * under the bar (label + value per row, hovering a row highlights its
+ * segment).
+ */
+ legendVariant?: "default" | "stacked";
+ /**
+ * Animate the bar's width transitions (each segment tweens as its share
+ * shifts — e.g. as data streams in). Printing always disables it. Default
+ * false (streaming-safe).
+ */
+ isAnimationActive?: boolean;
+ className?: string;
+ style?: CSSProperties;
+}
diff --git a/packages/react-ui/src/components/D3Charts/_prefix.scss b/packages/react-ui/src/components/D3Charts/_prefix.scss
new file mode 100644
index 000000000..6e2bcbc6f
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/_prefix.scss
@@ -0,0 +1,5 @@
+// Brand prefix for every chart class selector and @keyframes name — the SCSS
+// mirror of `CHART_CLASS_PREFIX` in `utils/constants.ts` (SCSS can't read
+// TS constants). Change BOTH or the stylesheets stop matching the DOM.
+// Usage: `@use '<rel>/prefix' as brand;` then `.#{brand.$prefix}-bar-chart`.
+$prefix: openui-d3;
diff --git a/packages/react-ui/src/components/D3Charts/classPrefix.test.ts b/packages/react-ui/src/components/D3Charts/classPrefix.test.ts
new file mode 100644
index 000000000..1d34301fe
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/classPrefix.test.ts
@@ -0,0 +1,154 @@
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { describe, expect, it } from "vitest";
+import { CHART_CLASS_PREFIX } from "./utils/constants";
+
+/**
+ * Self-audit: every chart class, keyframe, and CSS custom property D3Charts
+ * emits must be composed from CHART_CLASS_PREFIX (TS) / brand.$prefix (SCSS) —
+ * never hardcoded — so the prefix stays a one-line rename. The only sanctioned
+ * literal is the print/PPTX exporter data attribute (`data-openui-chart` — see
+ * utils/constants.ts).
+ */
+
+const THIS_DIR = path.dirname(fileURLToPath(import.meta.url));
+const SRC_DIR = THIS_DIR;
+
+const walkFiles = (startDir: string): string[] => {
+ const entries = fs.readdirSync(startDir, { withFileTypes: true });
+ const files: string[] = [];
+ for (const entry of entries) {
+ const absolutePath = path.join(startDir, entry.name);
+ if (entry.isDirectory()) {
+ files.push(...walkFiles(absolutePath));
+ continue;
+ }
+ files.push(absolutePath);
+ }
+ return files;
+};
+
+interface PrefixSource {
+ relativePath: string;
+ content: string;
+}
+
+const ALL_SOURCES: PrefixSource[] = walkFiles(SRC_DIR)
+ .filter(
+ (absolutePath) =>
+ [".ts", ".tsx", ".scss"].includes(path.extname(absolutePath)) &&
+ !/\.test\.tsx?$/.test(absolutePath),
+ )
+ .map((absolutePath) => ({
+ relativePath: path.relative(SRC_DIR, absolutePath).split(path.sep).join("/"),
+ content: fs.readFileSync(absolutePath, "utf8"),
+ }));
+
+const SCSS_SOURCES = ALL_SOURCES.filter(({ relativePath }) => relativePath.endsWith(".scss"));
+const TS_SOURCES = ALL_SOURCES.filter(({ relativePath }) => !relativePath.endsWith(".scss"));
+
+const stripSourceComments = (content: string): string =>
+ content
+ .replace(/\/\*[\s\S]*?\*\//g, (comment) => comment.replace(/[^\n]/g, " "))
+ .replace(/\/\/[^\n]*/g, (comment) => " ".repeat(comment.length));
+
+// The exporter contract attribute is the ONLY sanctioned brand literal; blank
+// it (preserving offsets) before scanning. Word boundary on the right so
+// `data-openui-chart-extra` still flags.
+const EXPORT_ATTRIBUTE_RE = /\bdata-openui-chart(?![a-z0-9-])/g;
+const blankExportAttributes = (content: string): string =>
+ content.replace(EXPORT_ATTRIBUTE_RE, (token) => " ".repeat(token.length));
+
+const BRANDS = CHART_CLASS_PREFIX.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+const PREFIX_LITERAL_RE = new RegExp(`\\b${BRANDS}-[a-z0-9-]+\\b`, "g");
+const SCSS_LITERAL_SELECTOR_RE = new RegExp(`\\.${BRANDS}-[a-z0-9-]+`, "g");
+const SCSS_LITERAL_CUSTOM_PROP_RE = new RegExp(`--${BRANDS}-[a-z0-9-]+`, "g");
+const SCSS_LITERAL_KEYFRAMES_RE = new RegExp(`@keyframes\\s+${BRANDS}[-_][a-z0-9_-]+`, "g");
+const SCSS_LITERAL_ANIMATION_REF_RE = new RegExp(
+ `animation(?:-name)?\\s*:[^;]*\\b${BRANDS}[-_][a-z0-9_-]+`,
+ "g",
+);
+
+const lineNumberAt = (content: string, index: number): number =>
+ content.slice(0, index).split("\n").length;
+
+const collectViolations = (sources: PrefixSource[], patterns: RegExp[]): string[] => {
+ const violations: string[] = [];
+ for (const { relativePath, content } of sources) {
+ const stripped = blankExportAttributes(stripSourceComments(content));
+ for (const pattern of patterns) {
+ pattern.lastIndex = 0;
+ for (const match of stripped.matchAll(pattern)) {
+ violations.push(
+ `${relativePath}:${lineNumberAt(stripped, match.index)}:${match[0].trim()}`,
+ );
+ }
+ }
+ }
+ return violations;
+};
+
+describe("D3Charts class prefix self-audit", () => {
+ it("keeps the TS and SCSS prefix declarations mirrored", () => {
+ const scss = fs.readFileSync(path.join(SRC_DIR, "_prefix.scss"), "utf8");
+ const match = scss.match(/\$prefix:\s*([a-zA-Z0-9_-]+)\s*;/);
+ expect(match?.[1]).toBe(CHART_CLASS_PREFIX);
+ expect(CHART_CLASS_PREFIX).toBe("openui-d3");
+ });
+
+ it("bans hardcoded brand literals in TS/TSX sources", () => {
+ const violations = collectViolations(TS_SOURCES, [PREFIX_LITERAL_RE]);
+ expect(
+ violations,
+ [
+ "Hardcoded chart brand literals found — compose from CHART_CLASS_PREFIX.",
+ ...violations,
+ ].join("\n"),
+ ).toEqual([]);
+ });
+
+ it("bans literal brand selectors, custom properties, and keyframes in SCSS", () => {
+ const violations = collectViolations(SCSS_SOURCES, [
+ SCSS_LITERAL_SELECTOR_RE,
+ SCSS_LITERAL_CUSTOM_PROP_RE,
+ SCSS_LITERAL_KEYFRAMES_RE,
+ SCSS_LITERAL_ANIMATION_REF_RE,
+ ]);
+ expect(
+ violations,
+ ["Hardcoded brand usage in SCSS — compose via #{brand.$prefix}.", ...violations].join("\n"),
+ ).toEqual([]);
+ });
+
+ it("requires every non-barrel stylesheet to compose from the prefix partial", () => {
+ const failures: string[] = [];
+ for (const { relativePath, content } of SCSS_SOURCES) {
+ if (relativePath === "_prefix.scss" || relativePath === "d3Charts.scss") {
+ continue;
+ }
+ const stripped = stripSourceComments(content);
+ const usesPartial = /@use\s+['"][^'"]*prefix['"]\s+as\s+brand/.test(stripped);
+ const referencesPrefix = stripped.includes("#{brand.$prefix}");
+ if (!usesPartial || !referencesPrefix) {
+ failures.push(
+ `${relativePath}: ${usesPartial ? "" : "missing @use of the prefix partial as brand; "}${referencesPrefix ? "" : "never references #{brand.$prefix}"}`,
+ );
+ }
+ }
+ expect(
+ failures,
+ ["Stylesheets not composed from _prefix.scss:", ...failures].join("\n"),
+ ).toEqual([]);
+ });
+
+ it("pins the exporter attribute contract", () => {
+ for (const file of [
+ "shared/core/ChartShell.tsx",
+ "shared/cartesian/layouts/CartesianChartLayout.tsx",
+ ]) {
+ const stripped = stripSourceComments(fs.readFileSync(path.join(SRC_DIR, file), "utf8"));
+ expect(stripped, `${file} must keep the exporter attribute`).toMatch(/data-openui-chart=/);
+ }
+ });
+});
diff --git a/packages/react-ui/src/components/D3Charts/d3Charts.scss b/packages/react-ui/src/components/D3Charts/d3Charts.scss
new file mode 100644
index 000000000..e2d074910
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/d3Charts.scss
@@ -0,0 +1,18 @@
+@forward "./AreaChart/areaChart";
+@forward "./LineChart/lineChart";
+@forward "./BarChart/barChart";
+@forward "./BarChart/horizontalBarChart";
+@forward "./PieChart/pieChart";
+@forward "./RadialChart/radialChart";
+@forward "./RadarChart/radarChart";
+@forward "./ScatterChart/scatterChart";
+@forward "./HeatmapChart/heatmapChart";
+@forward "./FunnelChart/funnelChart";
+@forward "./CalendarHeatmap/calendarHeatmap";
+@forward "./SegmentedBar/segmentedBar";
+@forward "./shared/mini/miniChart";
+@forward "./shared/core/PortalTooltip/portalTooltip";
+@forward "./shared/core/DefaultLegend/defaultLegend";
+@forward "./shared/core/StackedLegend/stackedLegend";
+@forward "./shared/cartesian/ScrollButtonsHorizontal/scrollButtonsHorizontal";
+@forward "./shared/cartesian/ScrollButtonsVertical/scrollButtonsVertical";
diff --git a/packages/react-ui/src/components/D3Charts/hooks/cartesian/index.ts b/packages/react-ui/src/components/D3Charts/hooks/cartesian/index.ts
new file mode 100644
index 000000000..d4981b02f
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/cartesian/index.ts
@@ -0,0 +1,14 @@
+export * from "./orchestratorTypes";
+export * from "./useAutoAngleCalculation";
+export * from "./useCartesianChartOrchestrator";
+export * from "./useChartDimensions";
+export * from "./useChartScroll";
+export * from "./useMaxLabelWidth";
+export * from "./useScatterChartOrchestrator";
+export * from "./useStackedData";
+export * from "./useXAxisHeight";
+export * from "./useXAxisLabelLayout";
+export * from "./useXBandScale";
+export * from "./useXScale";
+export * from "./useYAxisWidth";
+export * from "./useYScale";
diff --git a/packages/react-ui/src/components/D3Charts/hooks/cartesian/orchestratorTypes.ts b/packages/react-ui/src/components/D3Charts/hooks/cartesian/orchestratorTypes.ts
new file mode 100644
index 000000000..90b45f0ea
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/cartesian/orchestratorTypes.ts
@@ -0,0 +1,111 @@
+import type { Dispatch, RefObject, SetStateAction } from "react";
+
+import type { buildContainerStyle } from "../../utils/buildContainerStyle";
+import type { useChartData } from "../core/useChartData";
+import type { useChartHover } from "../core/useChartHover";
+import type { TooltipPayload } from "../core/useTooltipPayload";
+import type { useChartDimensions } from "./useChartDimensions";
+import type { useChartScroll } from "./useChartScroll";
+
+/**
+ * The closed contract for the unified cartesian orchestrator return.
+ *
+ * `useCartesianChartOrchestrator` annotates its return with
+ * `CartesianChartOrchestrator`, and `CartesianChartLayout` depends on this
+ * interface instead of `ReturnType<typeof useCartesianChartOrchestrator>` (an
+ * inferred shape). The payoff is two-fold:
+ * - adding a field to the orchestrator no longer *silently* widens the
+ * layout's accepted props — the layout only sees what the interface declares;
+ * - the closed return annotation makes tsc flag any drift between the
+ * orchestrator and its contract (missing or stray fields).
+ *
+ * One orchestrator serves both cartesian modes; `layout` is the discriminant.
+ * Every slice is always present (scroll fields are inert in fit mode and vice
+ * versa) so the layout reads a single flat shape. Field types are pulled from
+ * the source hooks via indexed access where they originate there, so the
+ * contract stays exact without re-declaring shapes. (The whole return is
+ * non-generic: `useChartData` normalizes the category key to a `string`, so
+ * nothing here depends on the chart's data type.)
+ */
+
+type DataModel = ReturnType<typeof useChartData>;
+type HoverModel = ReturnType<typeof useChartHover>;
+type ScrollModel = ReturnType<typeof useChartScroll>;
+type DimensionsModel = ReturnType<typeof useChartDimensions>;
+type ContainerStyle = ReturnType<typeof buildContainerStyle>;
+
+// ── slices ──────────────────────────────────────────────────────────────────
+
+export interface CartesianChartRefs {
+ containerRef: RefObject<HTMLDivElement | null>;
+ /** Scroll mode's horizontally-scrolling viewport; unused (but inert) in fit. */
+ mainContainerRef: RefObject<HTMLDivElement | null>;
+ legendRef: RefObject<HTMLDivElement | null>;
+}
+
+export interface ChartIdentity {
+ chartId: string;
+}
+
+export interface CartesianChartData {
+ catKey: DataModel["catKey"];
+ allDataKeys: DataModel["allDataKeys"];
+ dataKeys: DataModel["dataKeys"];
+ colors: DataModel["colors"];
+ transformedKeys: DataModel["transformedKeys"];
+ chartConfig: DataModel["chartConfig"];
+ colorMap: DataModel["colorMap"];
+}
+
+/** Geometry, minus the x-axis slice which `CartesianChartOrchestrator` lifts out. */
+export type CartesianChartDimensions = Omit<DimensionsModel, "xAxis">;
+
+/** The x-axis label layout: angle, band height, label width and line cap. */
+export type ChartXAxis = DimensionsModel["xAxis"];
+
+export interface ChartScroll {
+ canScrollLeft: ScrollModel["canScrollLeft"];
+ canScrollRight: ScrollModel["canScrollRight"];
+ handleScroll: ScrollModel["handleScroll"];
+ scrollTo: ScrollModel["scrollTo"];
+}
+
+export interface ChartHover {
+ hoveredIndex: HoverModel["hoveredIndex"];
+ mousePos: HoverModel["mousePos"];
+ createMouseHandlers: HoverModel["createMouseHandlers"];
+}
+
+export interface ChartLegend {
+ legendItems: DataModel["legendItems"];
+ hiddenSeries: DataModel["hiddenSeries"];
+ toggleSeries: DataModel["toggleSeries"];
+ isLegendExpanded: boolean;
+ setIsLegendExpanded: Dispatch<SetStateAction<boolean>>;
+}
+
+export interface ChartTooltip {
+ tooltipPayload: TooltipPayload | null;
+}
+
+export interface CartesianChartStyle {
+ containerStyle: ContainerStyle;
+ chartStyle: DataModel["chartStyle"];
+}
+
+// ── orchestrator ──────────────────────────────────────────────────────────────
+
+export interface CartesianChartOrchestrator {
+ /** "scroll" = fixed y-axis svg + scrolling main svg; "fit" = single svg. */
+ layout: "scroll" | "fit";
+ refs: CartesianChartRefs;
+ identity: ChartIdentity;
+ data: CartesianChartData;
+ dimensions: CartesianChartDimensions;
+ xAxis: ChartXAxis;
+ scroll: ChartScroll;
+ hover: ChartHover;
+ legend: ChartLegend;
+ tooltip: ChartTooltip;
+ style: CartesianChartStyle;
+}
diff --git a/packages/react-ui/src/components/D3Charts/hooks/cartesian/useAutoAngleCalculation.ts b/packages/react-ui/src/components/D3Charts/hooks/cartesian/useAutoAngleCalculation.ts
new file mode 100644
index 000000000..7812a0d2c
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/cartesian/useAutoAngleCalculation.ts
@@ -0,0 +1,67 @@
+import { useMemo } from "react";
+
+const DEFAULT_X_AXIS_HEIGHT = 30;
+const MIN_ROTATION_ANGLE = 0;
+const X_AXIS_PADDING = 20;
+
+interface AngleCalculationResult {
+ angle: number;
+ height: number;
+}
+
+/**
+ * Calculates the optimal rotation angle and height for X-axis labels using trigonometry.
+ *
+ * Uses the Pythagorean theorem:
+ * - Hypotenuse = maxLabelWidth (the label length)
+ * - Base = widthOfData or X_AXIS_PADDING (available horizontal space)
+ * - Height = sqrt(hypotenuse^2 - base^2)
+ * - Angle = atan(height / base) converted to degrees
+ */
+export const useAutoAngleCalculation = (
+ maxLabelWidth: number,
+ enabled: boolean,
+ widthOfData?: number,
+): AngleCalculationResult => {
+ return useMemo(() => {
+ if (!enabled) {
+ return {
+ angle: 0,
+ height: DEFAULT_X_AXIS_HEIGHT,
+ };
+ }
+
+ const base = widthOfData ?? X_AXIS_PADDING;
+ const hypotenuse = maxLabelWidth;
+
+ // Labels fit horizontally — apply minimum rotation
+ if (base >= hypotenuse) {
+ const angleRadians = (MIN_ROTATION_ANGLE * Math.PI) / 180;
+ const height = Math.ceil(hypotenuse * Math.sin(angleRadians));
+
+ return {
+ angle: -MIN_ROTATION_ANGLE,
+ height: Math.max(height, DEFAULT_X_AXIS_HEIGHT),
+ };
+ }
+
+ // Calculate height using Pythagorean theorem
+ const heightSquared = hypotenuse * hypotenuse - base * base;
+ const height = Math.sqrt(Math.max(0, heightSquared));
+
+ const angleRadians = Math.atan(height / base);
+ const angleDegrees = (angleRadians * 180) / Math.PI;
+
+ const finalAngle = Math.max(angleDegrees, MIN_ROTATION_ANGLE);
+
+ const finalHeight =
+ finalAngle > angleDegrees
+ ? Math.ceil(hypotenuse * Math.sin((finalAngle * Math.PI) / 180))
+ : Math.ceil(height);
+
+ return {
+ angle: -finalAngle,
+ height: Math.max(finalHeight + 16, DEFAULT_X_AXIS_HEIGHT),
+ };
+ }, [maxLabelWidth, enabled, widthOfData]);
+};
diff --git a/packages/react-ui/src/components/D3Charts/hooks/cartesian/useCalendarHeatmapOrchestrator.ts b/packages/react-ui/src/components/D3Charts/hooks/cartesian/useCalendarHeatmapOrchestrator.ts
new file mode 100644
index 000000000..45ab0f80d
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/cartesian/useCalendarHeatmapOrchestrator.ts
@@ -0,0 +1,337 @@
+import { type CSSProperties, useMemo, useRef, useState } from "react";
+
+import type { ChartColorPalette } from "../../../ThemeProvider";
+import { useTheme } from "../../../ThemeProvider";
+import {
+ buildCalendarGrid,
+ type CalendarCell,
+ type CalendarRange,
+ formatCalendarTooltipDate,
+ monthLabelColumns,
+} from "../../CalendarHeatmap/parts/calendarMath";
+import { contributionLevel } from "../../CalendarHeatmap/parts/levelScale";
+import {
+ resolveCalendarSeparators,
+ type ResolvedCalendarSeparators,
+} from "../../CalendarHeatmap/parts/separatorLayout";
+import type { CalendarColumnSeparators, CalendarLevelStyle } from "../../CalendarHeatmap/types";
+import { buildContainerStyle } from "../../utils/buildContainerStyle";
+import { CHART_CLASS_PREFIX, DEFAULT_CHART_HEIGHT } from "../../utils/constants";
+import { parseLineHeight } from "../../utils/labelWrap";
+import { resolvePalette } from "../../utils/paletteUtils";
+import { sampleRampStops } from "../../utils/rampUtils";
+import { useCanvasContextForLabelSize } from "../core/useCanvasContextForLabelSize";
+import { useChartShell } from "../core/useChartShell";
+import { usePerElementHover } from "../core/usePerElementHover";
+
+// Level-scale size — GitHub's 5 contribution buckets (empty + four intensities).
+const LEVEL_COUNT = 5;
+// Never let a measuring/streaming frame collapse a cell to 0/negative px.
+const MIN_CELL = 2;
+const ROW_COUNT = 7;
+// Gap between the weekday labels and the grid; also the breathing room on the
+// label's far side (so the reserved gutter is `label + 2·gap`).
+const WEEKDAY_LABEL_GAP = 6;
+// Minimum weekday gutter — holds space through the SSR/hydration frame where the
+// canvas measurer reports zero-width text.
+const WEEKDAY_GUTTER_MIN = 24;
+// Gap between the month labels and the top of the grid.
+const MONTH_LABEL_BOTTOM_GAP = 4;
+// Right padding after the last week column (0 = grid fills the width).
+const GUTTER_RIGHT = 0;
+
+// A local Sunday (getDay() === 0) to name weekday rows off a fixed reference
+// week — no dependency on today's weekday.
+const WEEKDAY_REFERENCE_SUNDAY = new Date(1970, 0, 4);
+const WEEKDAY_SHORT_FMT = new Intl.DateTimeFormat("en-US", { weekday: "short" });
+const WEEKDAY_INITIAL_FMT = new Intl.DateTimeFormat("en-US", {
+ weekday: "narrow",
+});
+
+/** The weekday name for grid row `row` under `weekStartDay`. */
+function weekdayLabel(weekStartDay: number, row: number, format: "full" | "initial"): string {
+ const date = new Date(WEEKDAY_REFERENCE_SUNDAY);
+ date.setDate(date.getDate() + ((weekStartDay + row) % ROW_COUNT));
+ return (format === "initial" ? WEEKDAY_INITIAL_FMT : WEEKDAY_SHORT_FMT).format(date);
+}
+
+/** The rows that get a left-hand weekday label, with their formatted text. */
+function buildWeekdayTicks(
+ weekStartDay: number,
+ filter: "all" | "odd" | "even",
+ format: "full" | "initial",
+): Array<{ row: number; label: string }> {
+ const ticks: Array<{ row: number; label: string }> = [];
+ for (let row = 0; row < ROW_COUNT; row++) {
+ if (filter === "odd" && row % 2 === 0) continue;
+ if (filter === "even" && row % 2 === 1) continue;
+ ticks.push({ row, label: weekdayLabel(weekStartDay, row, format) });
+ }
+ return ticks;
+}
+
+/** A grid cell tagged with its resolved contribution level 0..4. */
+export interface CalendarLeveledCell extends CalendarCell {
+ level: 0 | 1 | 2 | 3 | 4;
+}
+
+export interface UseCalendarHeatmapOrchestratorParams {
+ data: ReadonlyArray<{ date: string | Date; value: number }>;
+ themePaletteName: keyof ChartColorPalette;
+ customPalette?: string[];
+ levelColors?: [string, string, string, string, string];
+ levelStyles?: Array<CalendarLevelStyle | null>;
+ thresholds?: [number, number, number, number];
+ range?: CalendarRange;
+ layout: "fluid" | "fill";
+ binSize?: number;
+ gap: number;
+ weekStartDay: number;
+ hideGhostCells: boolean;
+ weekdayTickFilter: "all" | "odd" | "even";
+ weekdayLabelFormat: "full" | "initial";
+ showMonthLabels: boolean;
+ columnSeparators?: CalendarColumnSeparators;
+ showLegend: boolean;
+ formatTooltipLabel?: (value: number, date: Date) => string;
+ width?: number | string;
+ height?: number | string;
+}
+
+/** Normalize the sparse `levelStyles` prop to a fixed length-5 array. */
+function normalizeLevelStyles(
+ levelStyles: Array<CalendarLevelStyle | null> | undefined,
+): Array<CalendarLevelStyle | null> {
+ return Array.from({ length: LEVEL_COUNT }, (_, level) => levelStyles?.[level] ?? null);
+}
+
+/**
+ * Orchestrator for the CalendarHeatmap: a 7-row week-column grid where the VALUE
+ * axis is a discrete 0..4 contribution level (GitHub-contributions style).
+ * Follows the funnel/heatmap standalone fit-only shape — the calendar-grid math
+ * comes from the pure `parts/` modules, the level ramp is five stops sampled
+ * from `resolvePalette` (the low→high ordering HeatmapChart's quantize ramp
+ * uses), and hover is per-cell (each cell owns its mouse handlers; mouse-only,
+ * like heatmap/funnel).
+ */
+export function useCalendarHeatmapOrchestrator({
+ data,
+ themePaletteName,
+ customPalette,
+ levelColors: levelColorsProp,
+ levelStyles: levelStylesProp,
+ thresholds,
+ range,
+ layout,
+ binSize,
+ gap,
+ weekStartDay,
+ hideGhostCells,
+ weekdayTickFilter,
+ weekdayLabelFormat,
+ showMonthLabels,
+ columnSeparators,
+ showLegend,
+ formatTooltipLabel,
+ width,
+ height,
+}: UseCalendarHeatmapOrchestratorParams) {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const legendRef = useRef<HTMLDivElement>(null);
+ const {
+ hovered: hoveredCell,
+ mousePos,
+ handleMouseMove: handleCellMouseMove,
+ handleMouseLeave,
+ } = usePerElementHover<CalendarLeveledCell>();
+ // Legend-driven level highlight; combined below with the hovered cell's level
+ // so the link runs both ways (bklit parity).
+ const [hoveredLevel, setHoveredLevel] = useState<number | null>(null);
+
+ const { isPrinting, containerWidth, containerHeight, isEmpty, legendHeight } = useChartShell({
+ data,
+ showLegend,
+ containerRef,
+ legendRef,
+ width,
+ height,
+ });
+ const context = useCanvasContextForLabelSize();
+ const { theme } = useTheme();
+
+ const levelStyles = useMemo(() => normalizeLevelStyles(levelStylesProp), [levelStylesProp]);
+
+ // --- Level colors: five stops, either explicit or sampled from the ramp. The
+ // sampled ramp keeps HeatmapChart's low→high ordering, so stop 0 is the faint
+ // "empty" shade and stop 4 the most active. A per-level `levelStyles[i].color`
+ // then supersedes the resolved stop. ---
+ const levelColors = useMemo<string[]>(() => {
+ const base = levelColorsProp
+ ? [...levelColorsProp]
+ : sampleRampStops(resolvePalette(theme, themePaletteName, customPalette), LEVEL_COUNT);
+ return base.map((color, level) => levelStyles[level]?.color ?? color);
+ }, [levelColorsProp, theme, themePaletteName, customPalette, levelStyles]);
+
+ // --- Grid + per-cell level ---
+ const grid = useMemo(
+ () => buildCalendarGrid(data, { range, weekStartDay, hideGhostCells }),
+ [data, range, weekStartDay, hideGhostCells],
+ );
+
+ const cells = useMemo<CalendarLeveledCell[]>(
+ () =>
+ grid.cells.map((cell) => ({
+ ...cell,
+ level: contributionLevel(cell.value, thresholds),
+ })),
+ [grid, thresholds],
+ );
+
+ // --- Axis annotations ---
+ const monthLabels = useMemo(
+ () => (showMonthLabels ? monthLabelColumns(grid) : []),
+ [showMonthLabels, grid],
+ );
+ const weekdayTicks = useMemo(
+ () => buildWeekdayTicks(weekStartDay, weekdayTickFilter, weekdayLabelFormat),
+ [weekStartDay, weekdayTickFilter, weekdayLabelFormat],
+ );
+
+ // --- Column separators: resolve the config into rule columns, per-column
+ // gutter offsets, and (quarter mode) labels. Absent → no rules, zero offsets. ---
+ const separators = useMemo<ResolvedCalendarSeparators>(
+ () =>
+ columnSeparators
+ ? resolveCalendarSeparators(grid, columnSeparators)
+ : { columns: [], offsets: [], spacing: 0, labels: [] },
+ [columnSeparators, grid],
+ );
+ const totalGutter = separators.columns.length * separators.spacing;
+
+ // --- Reserved gutters (measured, like the heatmap's y-axis width) ---
+ const gutterLeft = useMemo(() => {
+ let max = 0;
+ for (const tick of weekdayTicks) {
+ max = Math.max(max, context.measureText(tick.label).width);
+ }
+ return Math.max(WEEKDAY_GUTTER_MIN, Math.ceil(max) + WEEKDAY_LABEL_GAP * 2);
+ }, [weekdayTicks, context]);
+
+ const gutterTop = showMonthLabels
+ ? Math.ceil(parseLineHeight(context.font)) + MONTH_LABEL_BOTTOM_GAP
+ : 0;
+
+ // --- Cell geometry ---
+ const weeks = grid.weeks;
+ // Separator gutters are carved out of the available width (auto-size modes) so
+ // the grid + rules still fit the container; a fixed binSize instead lets the
+ // plot grow by the gutters.
+ const innerWidth = Math.max(0, (containerWidth || 0) - gutterLeft - GUTTER_RIGHT - totalGutter);
+ const effectiveHeight = containerHeight || (typeof height === "number" ? height : 0);
+ const totalHeight = effectiveHeight || DEFAULT_CHART_HEIGHT;
+
+ let pitchX: number;
+ let pitchY: number;
+ if (binSize && binSize > 0) {
+ pitchX = binSize;
+ pitchY = binSize;
+ } else if (layout === "fill") {
+ const availableHeight = Math.max(0, totalHeight - gutterTop - legendHeight);
+ pitchX = innerWidth / weeks;
+ pitchY = availableHeight / ROW_COUNT;
+ } else {
+ // fluid — square cells sized from the width; height hugs the seven rows.
+ const cell = innerWidth / weeks;
+ pitchX = cell;
+ pitchY = cell;
+ }
+ // Clamp so a zero/negative measuring frame can never emit NaN or sub-2px cells.
+ pitchX = Math.max(pitchX, gap + MIN_CELL);
+ pitchY = Math.max(pitchY, gap + MIN_CELL);
+ const cellW = pitchX - gap;
+ const cellH = pitchY - gap;
+
+ const plotWidth = weeks * pitchX + totalGutter;
+ const plotHeight = ROW_COUNT * pitchY;
+ const svgWidth = gutterLeft + plotWidth + GUTTER_RIGHT;
+ const svgHeight = gutterTop + plotHeight;
+
+ // --- Tooltip (mouse-only, per-cell). The header is the ordinal-date line; the
+ // single item is the day's contribution total, `formatTooltipLabel`-formatted
+ // when provided. ---
+ const tooltipPayload = useMemo(() => {
+ if (!hoveredCell) return null;
+ return {
+ label: formatCalendarTooltipDate(hoveredCell.date),
+ items: [
+ {
+ name: "contributions",
+ value: formatTooltipLabel
+ ? formatTooltipLabel(hoveredCell.value, hoveredCell.date)
+ : hoveredCell.value,
+ color: levelColors[hoveredCell.level] ?? levelColors[0] ?? "#000000",
+ },
+ ],
+ };
+ }, [hoveredCell, levelColors, formatTooltipLabel]);
+
+ // --- Bidirectional level highlight, in two scopes (bklit parity):
+ // `hoveredLevel` (legend hover only) drives the GRID dim — hovering a cell
+ // must never re-shade the grid. The combined `highlightedLevel` (legend hover,
+ // else the hovered cell's level) drives the LEGEND swatch highlight, so a
+ // hovered cell still lights up its swatch. ---
+ const highlightedLevel = hoveredLevel ?? hoveredCell?.level ?? null;
+
+ // --- Container style: the five level colors as CSS vars so a later task's
+ // per-level styles can override a level's fill without touching the painter,
+ // plus any fixed width/height. ---
+ const containerStyle = useMemo<CSSProperties>(() => {
+ const vars: Record<string, string> = {};
+ for (let level = 0; level < LEVEL_COUNT; level++) {
+ vars[`--${CHART_CLASS_PREFIX}-calendar-heatmap-level-${level}`] =
+ levelColors[level] ?? "#000000";
+ }
+ return {
+ ...buildContainerStyle({}, width, height),
+ ...vars,
+ } as CSSProperties;
+ }, [levelColors, width, height]);
+
+ return {
+ refs: { containerRef, legendRef },
+ isPrinting,
+ isEmpty,
+ cells,
+ levelColors,
+ levelStyles,
+ monthLabels,
+ weekdayTicks,
+ separators,
+ dimensions: {
+ containerWidth,
+ svgWidth,
+ svgHeight,
+ gutterLeft,
+ gutterTop,
+ pitchX,
+ pitchY,
+ cellW,
+ cellH,
+ gap,
+ plotHeight,
+ monthLabelY: gutterTop - MONTH_LABEL_BOTTOM_GAP,
+ weekdayLabelX: gutterLeft - WEEKDAY_LABEL_GAP,
+ },
+ hover: {
+ hoveredCell,
+ mousePos,
+ handleCellMouseMove,
+ handleMouseLeave,
+ hoveredLevel,
+ highlightedLevel,
+ setHoveredLevel,
+ },
+ tooltip: { tooltipPayload },
+ style: { containerStyle },
+ };
+}
diff --git a/packages/react-ui/src/components/D3Charts/hooks/cartesian/useCartesianChartOrchestrator.ts b/packages/react-ui/src/components/D3Charts/hooks/cartesian/useCartesianChartOrchestrator.ts
new file mode 100644
index 000000000..63f272f69
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/cartesian/useCartesianChartOrchestrator.ts
@@ -0,0 +1,184 @@
+import React, { useId, useMemo, useRef, useState } from "react";
+
+import { buildContainerStyle } from "../../utils/buildContainerStyle";
+import { useChartData } from "../core/useChartData";
+import { useChartHover } from "../core/useChartHover";
+import { useTooltipPayload } from "../core/useTooltipPayload";
+import { useChartDimensions } from "./useChartDimensions";
+import { useChartScroll } from "./useChartScroll";
+
+import type { ChartColorPalette } from "../../../ThemeProvider";
+import type { ChartData, XAxisTickVariant } from "../../types";
+import type { ChartDensity } from "../../utils/scrollUtils";
+import type { StackOffset } from "../../utils/yDomain";
+import type { CartesianChartOrchestrator } from "./orchestratorTypes";
+
+export interface UseCartesianChartOrchestratorParams<T extends ChartData> {
+ /** "scroll" (default chart) or "fit" (the condensed, scroll-free variant). */
+ layout: "scroll" | "fit";
+ data: T;
+ categoryKey: keyof T[number];
+ themePaletteName: keyof ChartColorPalette;
+ customPalette?: string[];
+ showLegend: boolean;
+ showYAxis: boolean;
+ height?: number | string;
+ fixedWidth?: number | string;
+ fitLegendInHeight?: boolean;
+ tickVariantProp: XAxisTickVariant;
+ chartIdPrefix: string;
+ icons?: Partial<Record<keyof T[number], React.ComponentType>>;
+ onClick?: (row: T[number], index: number) => void;
+ density?: ChartDensity;
+ /** Series are stacked — y domain/axis width size to per-row sums. */
+ stacked?: boolean;
+ /** How stacked series combine (see `StackOffset`). */
+ stackOffset?: StackOffset;
+ /**
+ * Y-tick-count hint. The chart also passes it to CartesianChartLayout for
+ * YAxis/Grid rendering; here it makes the y-axis WIDTH measurement size the
+ * same tick strings the axis will draw.
+ */
+ yTickCount?: number;
+}
+
+/**
+ * Composes the data / geometry / hover / scroll / tooltip hooks behind one
+ * cartesian contract. `layout` flows into `useChartDimensions` (which owns the
+ * scroll-vs-fit value branching); the slices below are mode-agnostic. Every hook
+ * is called unconditionally so the orchestrator obeys the Rules of Hooks across
+ * a `layout` change.
+ */
+export function useCartesianChartOrchestrator<T extends ChartData>({
+ layout,
+ data,
+ categoryKey,
+ themePaletteName,
+ customPalette,
+ showLegend,
+ showYAxis,
+ height,
+ fixedWidth,
+ fitLegendInHeight,
+ tickVariantProp,
+ chartIdPrefix,
+ icons,
+ onClick,
+ density,
+ stacked,
+ stackOffset,
+ yTickCount,
+}: UseCartesianChartOrchestratorParams<T>): CartesianChartOrchestrator {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const mainContainerRef = useRef<HTMLDivElement>(null);
+ const legendRef = useRef<HTMLDivElement>(null);
+ const chartId = `${chartIdPrefix}-${useId()}`;
+
+ // Data: keys, colors, hidden series, config
+ const chartData = useChartData({
+ data,
+ categoryKey,
+ themePaletteName,
+ customPalette,
+ icons,
+ });
+
+ // Dimensions: sizing, layout, axis measurements (mode-aware)
+ const dimensions = useChartDimensions({
+ layout,
+ containerRef,
+ legendRef,
+ data,
+ catKey: chartData.catKey,
+ dataKeys: chartData.dataKeys,
+ showYAxis,
+ showLegend,
+ height,
+ fixedWidth,
+ fitLegendInHeight,
+ tickVariantProp,
+ density,
+ stacked,
+ stackOffset,
+ yTickCount,
+ });
+
+ // Hover: index, mouse position, handler factory
+ const hover = useChartHover({ data, onClick });
+
+ // Scroll: buttons, snap navigation (inert in fit — needsScroll is false there)
+ const scroll = useChartScroll({
+ mainContainerRef,
+ data,
+ needsScroll: dimensions.needsScroll,
+ density,
+ });
+
+ // Legend expand/collapse
+ const [isLegendExpanded, setIsLegendExpanded] = useState(false);
+
+ // Tooltip
+ const tooltipPayload = useTooltipPayload(
+ hover.hoveredIndex,
+ data,
+ chartData.dataKeys,
+ chartData.catKey,
+ chartData.chartConfig,
+ );
+
+ // Container style
+ const containerStyle = useMemo(
+ () => buildContainerStyle(chartData.chartStyle, fixedWidth, height),
+ [chartData.chartStyle, fixedWidth, height],
+ );
+
+ return {
+ layout,
+ refs: { containerRef, mainContainerRef, legendRef },
+ identity: { chartId },
+ data: {
+ catKey: chartData.catKey,
+ allDataKeys: chartData.allDataKeys,
+ dataKeys: chartData.dataKeys,
+ colors: chartData.colors,
+ transformedKeys: chartData.transformedKeys,
+ chartConfig: chartData.chartConfig,
+ colorMap: chartData.colorMap,
+ },
+ dimensions: {
+ containerWidth: dimensions.containerWidth,
+ effectiveYAxisWidth: dimensions.effectiveYAxisWidth,
+ chartAreaWidth: dimensions.chartAreaWidth,
+ widthOfGroup: dimensions.widthOfGroup,
+ chartInnerHeight: dimensions.chartInnerHeight,
+ totalHeight: dimensions.totalHeight,
+ totalSvgWidth: dimensions.totalSvgWidth,
+ dataWidth: dimensions.dataWidth,
+ needsScroll: dimensions.needsScroll,
+ tickVariant: dimensions.tickVariant,
+ labelInterval: dimensions.labelInterval,
+ marginTop: dimensions.marginTop,
+ },
+ xAxis: dimensions.xAxis,
+ scroll: {
+ canScrollLeft: scroll.canScrollLeft,
+ canScrollRight: scroll.canScrollRight,
+ handleScroll: scroll.handleScroll,
+ scrollTo: scroll.scrollTo,
+ },
+ hover: {
+ hoveredIndex: hover.hoveredIndex,
+ mousePos: hover.mousePos,
+ createMouseHandlers: hover.createMouseHandlers,
+ },
+ legend: {
+ legendItems: chartData.legendItems,
+ hiddenSeries: chartData.hiddenSeries,
+ isLegendExpanded,
+ setIsLegendExpanded,
+ toggleSeries: chartData.toggleSeries,
+ },
+ tooltip: { tooltipPayload },
+ style: { containerStyle, chartStyle: chartData.chartStyle },
+ };
+}
diff --git a/packages/react-ui/src/components/D3Charts/hooks/cartesian/useChartDimensions.ts b/packages/react-ui/src/components/D3Charts/hooks/cartesian/useChartDimensions.ts
new file mode 100644
index 000000000..6ae649f8f
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/cartesian/useChartDimensions.ts
@@ -0,0 +1,171 @@
+import React, { useMemo } from "react";
+
+import {
+ CHART_MARGIN_TOP,
+ DEFAULT_CHART_HEIGHT,
+ SINGLE_LINE_BREAKPOINT,
+} from "../../utils/constants";
+import { resolveShouldFitLegend } from "../../utils/resolveShouldFitLegend";
+import { getWidthOfData, getWidthOfGroup } from "../../utils/scrollUtils";
+import { MAX_X_AXIS_HEIGHT_SHARE } from "../../utils/xAxisLabelLayout";
+import type { StackOffset } from "../../utils/yDomain";
+import { useContainerSize } from "../core/useContainerSize";
+import { useLegendHeight } from "../core/useLegendHeight";
+import { useXAxisLabelLayout } from "./useXAxisLabelLayout";
+import { useYAxisWidth } from "./useYAxisWidth";
+
+import type { ChartData, XAxisTickVariant } from "../../types";
+import type { ChartDensity } from "../../utils/scrollUtils";
+
+export interface UseChartDimensionsParams<T extends ChartData> {
+ /**
+ * "scroll" sizes the chart to its data (overflowing into a horizontal scroll
+ * when wider than the container). "fit" packs all points into the available
+ * width.
+ */
+ layout: "scroll" | "fit";
+ containerRef: React.RefObject<HTMLDivElement | null>;
+ legendRef: React.RefObject<HTMLDivElement | null>;
+ data: T;
+ catKey: string;
+ dataKeys: string[];
+ showYAxis: boolean;
+ showLegend: boolean;
+ height?: number | string;
+ fixedWidth?: number | string;
+ fitLegendInHeight?: boolean;
+ tickVariantProp: XAxisTickVariant;
+ density?: ChartDensity;
+ /** Series are stacked — the y domain/axis-width use per-row sums. */
+ stacked?: boolean;
+ /** How stacked series combine (see `StackOffset`). */
+ stackOffset?: StackOffset;
+ /**
+ * Y-tick-count hint (the chart's `yTickCount` prop). Threaded into the
+ * y-axis width measurement so the measured tick strings are the RENDERED
+ * ones when the consumer pins the count (YAxis/Grid receive the same hint).
+ */
+ yTickCount?: number;
+}
+
+/**
+ * The single geometry source for the two cartesian modes. Every sub-hook is
+ * called unconditionally (Rules of Hooks — `layout` is a prop that can change
+ * between renders); only derived *values* branch on the mode. The two x-axis
+ * sub-hooks both run every render and the live one is selected by `layout`.
+ */
+export function useChartDimensions<T extends ChartData>({
+ layout,
+ containerRef,
+ legendRef,
+ data,
+ catKey,
+ dataKeys,
+ showYAxis,
+ showLegend,
+ height,
+ fixedWidth,
+ fitLegendInHeight,
+ tickVariantProp,
+ density,
+ stacked = false,
+ stackOffset,
+ yTickCount,
+}: UseChartDimensionsParams<T>) {
+ const isFit = layout === "fit";
+
+ const legendHeight = useLegendHeight(legendRef, showLegend);
+
+ const { width: containerWidth, height: containerHeight } = useContainerSize(
+ containerRef,
+ fixedWidth,
+ height,
+ );
+
+ const { yAxisWidth } = useYAxisWidth(data, dataKeys, stacked, {
+ tickCount: yTickCount,
+ scopeRef: containerRef,
+ stackOffset,
+ });
+ const effectiveYAxisWidth = showYAxis ? yAxisWidth : 0;
+ // Clamped: before the container is measured (SSR + first client render)
+ // containerWidth is 0, and 0 − yAxisWidth would propagate a negative width
+ // into the fit-mode hit rect / svg attributes (invalid SVG, console errors
+ // on every fit-mode deep link).
+ const availableWidth = Math.max(0, containerWidth - effectiveYAxisWidth);
+
+ // Per-point group width: fit divides the available width across all points;
+ // scroll uses a fixed density-derived width (which is what lets it overflow).
+ const widthOfGroup = isFit
+ ? data.length > 0
+ ? availableWidth / data.length
+ : 0
+ : getWidthOfGroup(density);
+
+ const dataWidth = useMemo(
+ () => (isFit ? availableWidth : getWidthOfData(data, availableWidth, density)),
+ [isFit, data, availableWidth, density],
+ );
+ const needsScroll = isFit ? false : dataWidth > availableWidth;
+
+ // The drawable chart width. Scroll overflows to `dataWidth` when it needs to
+ // scroll; otherwise (and always in fit, where needsScroll is false) it is the
+ // available width. Collapses the old scroll `svgWidth` and fit `chartAreaWidth`.
+ const chartAreaWidth = needsScroll ? dataWidth : availableWidth;
+
+ const resolvedHeight =
+ typeof height === "number"
+ ? height
+ : containerHeight > 0
+ ? containerHeight
+ : DEFAULT_CHART_HEIGHT;
+ const shouldFitLegend = resolveShouldFitLegend(fitLegendInHeight, height);
+ const svgAvailableHeight = shouldFitLegend ? resolvedHeight - legendHeight : resolvedHeight;
+
+ // "angled" is fit-only; the scrolling axis also drops to one line in narrow containers.
+ const tickVariant: XAxisTickVariant =
+ isFit || (tickVariantProp !== "angled" && containerWidth >= SINGLE_LINE_BREAKPOINT)
+ ? tickVariantProp
+ : "singleLine";
+
+ // The label band is capped at half the drawable height so the plot keeps
+ // the rest; labels that don't fit are truncated rather than growing the band.
+ const labelLayout = useXAxisLabelLayout(
+ data,
+ catKey,
+ {
+ variant: tickVariant,
+ slotWidth: widthOfGroup,
+ maxHeight: (svgAvailableHeight - CHART_MARGIN_TOP) * MAX_X_AXIS_HEIGHT_SHARE,
+ condensed: isFit,
+ },
+ containerRef,
+ );
+ const labelInterval = labelLayout.interval;
+ const xAxis = {
+ angle: labelLayout.angle,
+ xAxisHeight: labelLayout.height,
+ labelWidth: labelLayout.labelWidth,
+ maxLines: labelLayout.maxLines,
+ };
+
+ const chartInnerHeight = Math.max(0, svgAvailableHeight - CHART_MARGIN_TOP - xAxis.xAxisHeight);
+ const totalHeight = svgAvailableHeight;
+ const totalSvgWidth = effectiveYAxisWidth + chartAreaWidth;
+
+ return {
+ containerWidth,
+ effectiveYAxisWidth,
+ chartAreaWidth,
+ widthOfGroup,
+ chartInnerHeight,
+ totalHeight,
+ totalSvgWidth,
+ dataWidth,
+ needsScroll,
+ tickVariant,
+ labelInterval,
+ marginTop: CHART_MARGIN_TOP,
+ xAxis,
+ };
+}
diff --git a/packages/react-ui/src/components/D3Charts/hooks/cartesian/useChartScroll.ts b/packages/react-ui/src/components/D3Charts/hooks/cartesian/useChartScroll.ts
new file mode 100644
index 000000000..abe430952
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/cartesian/useChartScroll.ts
@@ -0,0 +1,64 @@
+import React, { useCallback, useEffect, useState } from "react";
+
+import { findNearestSnapPosition, getSnapPositions } from "../../utils/scrollUtils";
+
+import type { ChartData } from "../../types";
+import type { ChartDensity } from "../../utils/scrollUtils";
+
+export interface UseChartScrollParams<T extends ChartData> {
+ mainContainerRef: React.RefObject<HTMLDivElement | null>;
+ data: T;
+ needsScroll: boolean;
+ density?: ChartDensity;
+}
+
+export function useChartScroll<T extends ChartData>({
+ mainContainerRef,
+ data,
+ needsScroll,
+ density,
+}: UseChartScrollParams<T>) {
+ const [canScrollLeft, setCanScrollLeft] = useState(false);
+ const [canScrollRight, setCanScrollRight] = useState(needsScroll);
+
+ useEffect(() => {
+ if (!needsScroll) {
+ setCanScrollLeft(false);
+ setCanScrollRight(false);
+ return;
+ }
+ const el = mainContainerRef.current;
+ if (el) {
+ setCanScrollLeft(el.scrollLeft > 1);
+ setCanScrollRight(el.scrollLeft < el.scrollWidth - el.clientWidth - 1);
+ } else {
+ setCanScrollRight(true);
+ }
+ }, [needsScroll, mainContainerRef]);
+
+ const handleScroll = useCallback(() => {
+ const el = mainContainerRef.current;
+ if (!el) return;
+ setCanScrollLeft(el.scrollLeft > 1);
+ setCanScrollRight(el.scrollLeft < el.scrollWidth - el.clientWidth - 1);
+ }, [mainContainerRef]);
+
+ const scrollTo = useCallback(
+ (direction: "left" | "right") => {
+ const el = mainContainerRef.current;
+ if (!el) return;
+ const snaps = getSnapPositions(data, density);
+ const idx = findNearestSnapPosition(snaps, el.scrollLeft, direction);
+ const target = snaps[idx] ?? 0;
+ el.scrollTo({ left: target, behavior: "smooth" });
+ },
+ [data, mainContainerRef, density],
+ );
+
+ return {
+ canScrollLeft,
+ canScrollRight,
+ handleScroll,
+ scrollTo,
+ };
+}
diff --git a/packages/react-ui/src/components/D3Charts/hooks/cartesian/useFunnelChartOrchestrator.ts b/packages/react-ui/src/components/D3Charts/hooks/cartesian/useFunnelChartOrchestrator.ts
new file mode 100644
index 000000000..45f9827c2
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/cartesian/useFunnelChartOrchestrator.ts
@@ -0,0 +1,284 @@
+import { useMemo, useRef } from "react";
+import type { ChartColorPalette } from "../../../ThemeProvider";
+import { useTheme } from "../../../ThemeProvider";
+
+import type { FunnelOrientation } from "../../FunnelChart/parts/funnelGeometry";
+import { funnelPercentage } from "../../FunnelChart/parts/funnelGeometry";
+import type { TooltipItem } from "../../shared/core/PortalTooltip/ChartTooltip";
+import type { ChartData, LegendItem } from "../../types";
+import { buildContainerStyle } from "../../utils/buildContainerStyle";
+import { DEFAULT_CHART_HEIGHT } from "../../utils/constants";
+import { buildColumnKeys } from "../../utils/heatmapUtils";
+import { parseLineHeight } from "../../utils/labelWrap";
+import { resolvePalette } from "../../utils/paletteUtils";
+import { useCanvasContextForLabelSize } from "../core/useCanvasContextForLabelSize";
+import { useChartShell } from "../core/useChartShell";
+import { usePerElementHover } from "../core/usePerElementHover";
+import { useSeriesVisibility } from "../core/useSeriesVisibility";
+import { useAutoAngleCalculation } from "./useAutoAngleCalculation";
+import { useMaxLabelWidth } from "./useMaxLabelWidth";
+
+// Gap between the funnel plot and its label band/column.
+const LABEL_GAP = 6;
+// The vertical label column is at most this fraction of the container width…
+const MAX_LABEL_COL_RATIO = 0.34;
+// …but the cap never drops below this floor (so a tiny container still leaves a
+// usable column). NOTE: this floors the CAP, not the column — short labels
+// produce a narrower content-fit column.
+const MAX_LABEL_COL_FLOOR = 64;
+
+/** A stage's numeric value; non-numeric / missing collapses to 0 (no taper). */
+const funnelStageValue = (raw: string | number | undefined): number => {
+ const value = Number(raw);
+ return Number.isFinite(value) ? value : 0;
+};
+
+export interface FunnelStage {
+ /** Unique React key (duplicate labels disambiguated); NOT for display. */
+ key: string;
+ label: string;
+ value: number;
+ color: string;
+ /** value / geometry-max, clamped to [0, 1] — the cell's leading-edge ratio. */
+ norm: number;
+ /** The NEXT visible stage's norm — the cell's trailing-edge ratio (taper). */
+ normEnd: number;
+ /** Percentage relative to the FIRST visible stage (retention). */
+ pct: number;
+}
+
+export interface UseFunnelChartOrchestratorParams<T extends ChartData> {
+ data: T;
+ categoryKey: keyof T[number];
+ dataKey: keyof T[number];
+ themePaletteName: keyof ChartColorPalette;
+ customPalette?: string[];
+ orientation: FunnelOrientation;
+ /** Gap between stage cells (px) — matches the painter so the label-angle
+ * threshold uses the painter's true cell width. */
+ gap: number;
+ /** Whether labels render — gates the reserved label band/column. */
+ showLabels: boolean;
+ showLegend: boolean;
+ height?: number | string;
+ width?: number | string;
+ fitLegendInHeight?: boolean;
+}
+
+/**
+ * Orchestrator for the funnel: a single-series chart of stacked tapering
+ * stages. Standalone fit-only layout (heatmap/scatter precedent) — no axes, so
+ * the plot is simply the container minus the legend. The palette is consumed
+ * as an ORDERED ramp via resolvePalette (one hue per stage, by INPUT order —
+ * never getDistributedColors, which value-sorts + center-out picks). Stage
+ * colors are keyed to the ORIGINAL data index so toggling a stage in the
+ * legend never recolors the others. Hover is per-stage (the painter owns the
+ * mouse handlers; mouse-only, like pie/heatmap).
+ */
+export function useFunnelChartOrchestrator<T extends ChartData>({
+ data,
+ categoryKey,
+ dataKey,
+ themePaletteName,
+ customPalette,
+ orientation,
+ gap,
+ showLabels,
+ showLegend,
+ height,
+ width,
+ fitLegendInHeight,
+}: UseFunnelChartOrchestratorParams<T>) {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const legendRef = useRef<HTMLDivElement>(null);
+ const {
+ hovered: hoveredIndex,
+ mousePos,
+ handleMouseMove,
+ handleMouseLeave,
+ } = usePerElementHover();
+
+ const {
+ isPrinting,
+ containerWidth,
+ containerHeight,
+ isEmpty,
+ legendHeight,
+ shouldFitLegend,
+ isLegendExpanded,
+ setIsLegendExpanded,
+ } = useChartShell({
+ data,
+ showLegend,
+ containerRef,
+ legendRef,
+ width,
+ height,
+ fitLegendInHeight,
+ });
+ // For the label line-height (sizing the reserved band). Hydration-safe (SSR
+ // stub through the hydration render), so no server/client mismatch.
+ const context = useCanvasContextForLabelSize(containerRef);
+ const { theme } = useTheme();
+ const catKey = String(categoryKey);
+ const valKey = String(dataKey);
+
+ // Ordered ramp, one hue per stage by INPUT order.
+ const ramp = useMemo(
+ () => resolvePalette(theme, themePaletteName, customPalette),
+ [theme, themePaletteName, customPalette],
+ );
+
+ // Every stage with its stable color (keyed to original index so a legend
+ // toggle never recolors the rest).
+ const allStages = useMemo(
+ () =>
+ data.map((row, i) => ({
+ label: String(row[catKey]),
+ value: funnelStageValue(row[valKey]),
+ color: ramp[i % ramp.length] ?? "#000000",
+ })),
+ [data, catKey, valKey, ramp],
+ );
+
+ const stageLabels = useMemo(() => allStages.map((s) => s.label), [allStages]);
+ const { hiddenSeries: hiddenStages, toggleSeries: toggleStage } =
+ useSeriesVisibility(stageLabels);
+
+ // Visible stages (input order preserved) + the parallel original rows for
+ // onClick. norms are computed over the VISIBLE sequence: the geometry-max is
+ // the largest visible value (guarantees rings fit, even for non-monotonic
+ // edge data) while the percentage reference is the FIRST visible stage.
+ const { visibleStages, visibleRows } = useMemo(() => {
+ const rows: T[number][] = [];
+ const kept = allStages.filter((s, i) => {
+ if (hiddenStages.has(s.label)) return false;
+ rows.push(data[i]!);
+ return true;
+ });
+ const geomMax = Math.max(1, ...kept.map((s) => Math.max(0, s.value)));
+ // `||`, NOT `??`: a first-stage value of 0 (e.g. a partial streamed row
+ // whose value field hasn't parsed yet) must fall back to the geometry-max
+ // — `??` only catches null/undefined, so a real 0 would make every
+ // percentage read 0%. Falsy-0 is exactly the case to catch here.
+ const pctRef = kept[0]?.value || geomMax;
+ // Unique React keys for duplicate stage labels (LLMs re-emit categories) —
+ // a NUL-suffixed occurrence counter, like the heatmap's columns. Stable
+ // across streamed appends so existing stages never re-key (no entrance
+ // replay). `label` stays the display string.
+ const renderKeys = buildColumnKeys(kept.map((s) => s.label));
+ const stages: FunnelStage[] = kept.map((s, i) => {
+ // The trailing edge tapers toward the next stage; the last stage is a
+ // flat rect (its "next" is itself, so normEnd === norm).
+ const nextIdx = Math.min(i + 1, kept.length - 1);
+ return {
+ key: renderKeys[i]!,
+ label: s.label,
+ value: s.value,
+ color: s.color,
+ norm: Math.max(0, s.value) / geomMax,
+ normEnd: Math.max(0, kept[nextIdx]!.value) / geomMax,
+ pct: funnelPercentage(s.value, pctRef),
+ };
+ });
+ return { visibleStages: stages, visibleRows: rows };
+ }, [allStages, hiddenStages, data]);
+
+ // --- Tooltip: value + retention for the hovered stage ---
+ const tooltipPayload = useMemo(() => {
+ if (hoveredIndex === null) return null;
+ const stage = visibleStages[hoveredIndex];
+ if (!stage) return null;
+ const items: TooltipItem[] = [
+ { name: "Value", value: stage.value, color: stage.color },
+ {
+ name: "of first stage",
+ value: `${Math.round(stage.pct)}%`,
+ color: stage.color,
+ },
+ ];
+ return { label: stage.label, items };
+ }, [hoveredIndex, visibleStages]);
+
+ // --- Legend: one item per stage (all stages, so hidden ones can return) ---
+ const legendItems: LegendItem[] = useMemo(
+ () => allStages.map((s) => ({ key: s.label, label: s.label, color: s.color })),
+ [allStages],
+ );
+
+ // --- Dimensions (the stage labels are a reserved axis: a bottom band for
+ // horizontal, a right column for vertical — like the heatmap's X/Y axes) ---
+ const effectiveHeight = containerHeight || (typeof height === "number" ? height : 0);
+ const totalHeight = effectiveHeight || DEFAULT_CHART_HEIGHT;
+ const legendDeduction = showLegend && shouldFitLegend ? legendHeight : 0;
+ const W = containerWidth || 0;
+ const H = Math.max(0, totalHeight - legendDeduction);
+
+ const horizontal = orientation === "horizontal";
+ // Max label width over ALL stages (not just visible) so toggling a stage in
+ // the legend never reflows the axis band.
+ const maxLabelWidth = useMaxLabelWidth(data, catKey);
+ const visibleCount = Math.max(1, visibleStages.length);
+ // Each horizontal label gets one cell's width before it must angle — the
+ // SAME width the painter tiles to (gap-subtracted), or the angle threshold
+ // and the painter's truncation disagree.
+ const perStageWidth =
+ horizontal && W > 0 ? Math.max(0, (W - gap * (visibleCount - 1)) / visibleCount) : 0;
+ const { angle: labelAngle, height: angledHeight } = useAutoAngleCalculation(
+ maxLabelWidth,
+ showLabels && horizontal && maxLabelWidth > perStageWidth,
+ perStageWidth,
+ );
+
+ // Single-line band height from the theme's label line-height (not a magic
+ // number) so a larger label font doesn't clip the bottom of the labels.
+ const singleLineLabelHeight = Math.ceil(parseLineHeight(context.font));
+
+ // Reserved label band (horizontal: bottom) / column (vertical: right). No
+ // reservation when labels are hidden — the funnel reclaims the full area.
+ const labelBandHeight =
+ !showLabels || !horizontal
+ ? 0
+ : (labelAngle !== 0 ? Math.max(angledHeight, singleLineLabelHeight) : singleLineLabelHeight) +
+ LABEL_GAP;
+ const labelColWidth =
+ !showLabels || horizontal
+ ? 0
+ : Math.min(
+ Math.ceil(maxLabelWidth) + LABEL_GAP * 2,
+ Math.max(MAX_LABEL_COL_FLOOR, Math.round(W * MAX_LABEL_COL_RATIO)),
+ );
+
+ // The funnel plot (rings + value + pct) lives in the area the labels don't.
+ const ringW = horizontal ? W : Math.max(0, W - labelColWidth);
+ const ringH = horizontal ? Math.max(0, H - labelBandHeight) : H;
+
+ const containerStyle = useMemo(() => buildContainerStyle({}, width, height), [width, height]);
+
+ return {
+ refs: { containerRef, legendRef },
+ isPrinting,
+ isEmpty,
+ data: {
+ visibleStages,
+ visibleRows,
+ hiddenStages,
+ toggleStage,
+ legendItems,
+ },
+ dimensions: {
+ containerWidth,
+ W,
+ H,
+ ringW,
+ ringH,
+ labelBandHeight,
+ labelColWidth,
+ labelAngle,
+ },
+ hover: { hoveredIndex, mousePos, handleMouseMove, handleMouseLeave },
+ legend: { isLegendExpanded, setIsLegendExpanded },
+ tooltip: { tooltipPayload },
+ style: { containerStyle },
+ };
+}
diff --git a/packages/react-ui/src/components/D3Charts/hooks/cartesian/useHeatmapChartOrchestrator.test.ts b/packages/react-ui/src/components/D3Charts/hooks/cartesian/useHeatmapChartOrchestrator.test.ts
new file mode 100644
index 000000000..42488e7a4
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/cartesian/useHeatmapChartOrchestrator.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from "vitest";
+import { heatmapCellValue } from "./useHeatmapChartOrchestrator";
+
+describe('heatmapCellValue (the single source of "is this cell empty")', () => {
+ it("passes finite numbers through, including 0 and negatives", () => {
+ expect(heatmapCellValue(42)).toBe(42);
+ expect(heatmapCellValue(0)).toBe(0);
+ expect(heatmapCellValue(-5)).toBe(-5);
+ expect(heatmapCellValue("42")).toBe(42);
+ expect(heatmapCellValue("3.5")).toBe(3.5);
+ });
+
+ it('treats empty/whitespace strings as missing (Number("") is 0 — the trap)', () => {
+ expect(heatmapCellValue("")).toBeNull();
+ expect(heatmapCellValue(" ")).toBeNull();
+ });
+
+ it("treats absent keys and non-numeric strings as missing", () => {
+ expect(heatmapCellValue(undefined)).toBeNull();
+ expect(heatmapCellValue("abc")).toBeNull();
+ expect(heatmapCellValue("NaN")).toBeNull();
+ expect(heatmapCellValue("Infinity")).toBeNull();
+ });
+});
diff --git a/packages/react-ui/src/components/D3Charts/hooks/cartesian/useHeatmapChartOrchestrator.ts b/packages/react-ui/src/components/D3Charts/hooks/cartesian/useHeatmapChartOrchestrator.ts
new file mode 100644
index 000000000..7ab5d1b31
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/cartesian/useHeatmapChartOrchestrator.ts
@@ -0,0 +1,386 @@
+import { scaleBand, scaleQuantize } from "d3-scale";
+import { useMemo, useRef } from "react";
+
+import type { ChartColorPalette } from "../../../ThemeProvider";
+import { useTheme } from "../../../ThemeProvider";
+import type { LegendItem } from "../../types";
+import { buildContainerStyle } from "../../utils/buildContainerStyle";
+import { CHART_MARGIN_TOP, DEFAULT_CHART_HEIGHT } from "../../utils/constants";
+import { getDataKeys } from "../../utils/dataUtils";
+import type { HeatmapRampMode } from "../../utils/heatmapUtils";
+import {
+ buildColumnKeys,
+ computeHeatmapColorDomain,
+ computeLabelInterval,
+} from "../../utils/heatmapUtils";
+import {
+ DIVERGING_DEFAULT_DARK,
+ DIVERGING_DEFAULT_LIGHT,
+ resolvePalette,
+} from "../../utils/paletteUtils";
+import { useCanvasContextForLabelSize } from "../core/useCanvasContextForLabelSize";
+import { useChartShell } from "../core/useChartShell";
+import { useLegendHeight } from "../core/useLegendHeight";
+import { usePerElementHover } from "../core/usePerElementHover";
+import { useSeriesVisibility } from "../core/useSeriesVisibility";
+import { useXAxisHeight } from "./useXAxisHeight";
+
+// Mirror measureYAxisWidth's clamp (its constants are private and its
+// formatting is numeric-tick-only — heatmap row labels are category strings).
+const MIN_Y_AXIS_WIDTH = 20;
+const MAX_Y_AXIS_WIDTH = 200;
+const Y_AXIS_PADDING = 10;
+
+// Below this band width, x labels thin out (every n-th) instead of rendering
+// an ellipsis + tooltip wrapper per column. ~3 characters of the tick font.
+const MIN_X_LABEL_PX = 28;
+
+export interface HoveredHeatmapCell {
+ rowKey: string;
+ columnIndex: number;
+ columnLabel: string;
+ /** null = the cell has no numeric value. */
+ value: number | null;
+}
+
+/**
+ * A cell's numeric value, or null for "no value". Empty/whitespace-only
+ * strings are treated as missing — `Number('')` is 0, which would otherwise
+ * paint blank cells as value-0 AND drag the quantize domain's min to 0,
+ * recoloring every other cell. Single source of truth for the extent scan,
+ * the cell renderer, and the legend row means — they must agree or the color
+ * domain and the painted cells drift apart.
+ */
+export const heatmapCellValue = (raw: string | number | undefined): number | null => {
+ if (raw === undefined || (typeof raw === "string" && raw.trim() === "")) {
+ return null;
+ }
+ const value = Number(raw);
+ return Number.isFinite(value) ? value : null;
+};
+
+/** Tooltip context rows show means at one decimal — enough to compare by. */
+const roundMean = (mean: number): number => Math.round(mean * 10) / 10;
+
+export interface UseHeatmapChartOrchestratorParams<
+ T extends Array<Record<string, string | number>>,
+> {
+ data: T;
+ categoryKey: keyof T[number];
+ themePaletteName: keyof ChartColorPalette;
+ customPalette?: string[];
+ rampMode: HeatmapRampMode;
+ showLegend: boolean;
+ showColorScale: boolean;
+ showYAxis: boolean;
+ height?: number | string;
+ width?: number | string;
+ fitLegendInHeight?: boolean;
+}
+
+/**
+ * Orchestrator for the heatmap: a band×band grid where the VALUE axis is
+ * color. Follows useScatterChartOrchestrator's standalone fit-only shape, with
+ * three deliberate differences: the y axis is categorical (row labels measured
+ * as text, not numeric ticks), the palette is consumed as an ORDERED ramp via
+ * resolvePalette (never getDistributedColors — a heatmap wants the gradient,
+ * not center-out series picks), and hover is per-cell (the chart's cells own
+ * their mouse handlers; there is no plot-level hit search). Per-cell hover is
+ * the pie/radial regime and, like those charts, is mouse-only for now — touch
+ * support belongs to a unified pass over the per-element-handler charts, not
+ * a heatmap one-off.
+ */
+export function useHeatmapChartOrchestrator<T extends Array<Record<string, string | number>>>({
+ data,
+ categoryKey,
+ themePaletteName,
+ customPalette,
+ rampMode,
+ showLegend,
+ showColorScale,
+ showYAxis,
+ height,
+ width,
+ fitLegendInHeight,
+}: UseHeatmapChartOrchestratorParams<T>) {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const legendRef = useRef<HTMLDivElement>(null);
+ const colorScaleRef = useRef<HTMLDivElement>(null);
+ const {
+ hovered: hoveredCell,
+ mousePos,
+ handleMouseMove: handleCellMouseMove,
+ handleMouseLeave,
+ } = usePerElementHover<HoveredHeatmapCell>();
+
+ const {
+ isPrinting,
+ containerWidth,
+ containerHeight,
+ isEmpty,
+ legendHeight,
+ shouldFitLegend,
+ isLegendExpanded,
+ setIsLegendExpanded,
+ } = useChartShell({
+ data,
+ showLegend,
+ containerRef,
+ legendRef,
+ width,
+ height,
+ fitLegendInHeight,
+ // Heatmap is ALSO empty when row 0 carries no series keys — nothing to
+ // draw even with rows present, which a bare row count can't see.
+ isEmptyOverride:
+ !data || data.length === 0 || getDataKeys(data, String(categoryKey)).length === 0,
+ });
+ // Same measured-deduction mechanism as the legend: the color-scale strip is
+ // HTML below the svg, so its real height (typography-dependent) comes from
+ // observation, not a constant. Shares the shell's isEmpty so the strip
+ // remounts/re-observes in lockstep with the legend.
+ const colorScaleHeight = useLegendHeight(colorScaleRef, showColorScale && !isEmpty);
+ const context = useCanvasContextForLabelSize(containerRef);
+ const { theme, mode } = useTheme();
+
+ const catKey = String(categoryKey);
+
+ // --- Data shape: columns from the category field, rows from the series keys ---
+ const columns = useMemo(() => data.map((row) => String(row[catKey])), [data, catKey]);
+ const rowKeys = useMemo(() => getDataKeys(data, catKey), [data, catKey]);
+
+ const { hiddenSeries: hiddenRows, toggleSeries: toggleRow } = useSeriesVisibility(rowKeys);
+
+ const visibleRowKeys = useMemo(
+ () => rowKeys.filter((key) => !hiddenRows.has(key)),
+ [rowKeys, hiddenRows],
+ );
+
+ // --- Color: ordered ramp quantized over the visible value extent ---
+ // Diverging mode without a customPalette uses the built-in two-hue ramps:
+ // the theme's sequential ramp can't express "neutral at zero" (mirroring it
+ // would give both signs the same hue). A customPalette always wins — in
+ // diverging mode it's read as the full low→neutral→high ramp.
+ const ramp = useMemo(() => {
+ if (rampMode === "diverging" && !customPalette) {
+ return mode === "dark" ? DIVERGING_DEFAULT_DARK : DIVERGING_DEFAULT_LIGHT;
+ }
+ return resolvePalette(theme, themePaletteName, customPalette);
+ }, [rampMode, customPalette, mode, theme, themePaletteName]);
+
+ const [minValue, maxValue] = useMemo(() => {
+ let min = Infinity;
+ let max = -Infinity;
+ for (const row of data) {
+ for (const key of visibleRowKeys) {
+ const value = heatmapCellValue(row[key]);
+ if (value !== null) {
+ min = Math.min(min, value);
+ max = Math.max(max, value);
+ }
+ }
+ }
+ if (!Number.isFinite(min)) return [0, 1];
+ return [min, max];
+ }, [data, visibleRowKeys]);
+
+ const colorScale = useMemo(() => {
+ // Domain rules (collapsed-extent widening; diverging = symmetric about
+ // zero) live in computeHeatmapColorDomain — unit-tested there.
+ const [domainMin, domainMax] = computeHeatmapColorDomain(minValue, maxValue, rampMode);
+ return scaleQuantize<string>().domain([domainMin, domainMax]).range(ramp);
+ }, [minValue, maxValue, rampMode, ramp]);
+
+ // The color-scale legend strip: one swatch per ramp bucket, each with the
+ // exact value range the quantize scale assigns it — honest by construction.
+ // Extents come from thresholds() BY INDEX, not invertExtent(color):
+ // invertExtent looks colors up with indexOf, so a customPalette that
+ // repeats a color would hand every repeat the FIRST occurrence's range.
+ const colorScaleBuckets = useMemo(() => {
+ const [domainMin, domainMax] = colorScale.domain();
+ const thresholds = colorScale.thresholds();
+ return ramp.map((color, index) => ({
+ color,
+ lo: index === 0 ? domainMin : thresholds[index - 1]!,
+ hi: index === ramp.length - 1 ? domainMax : thresholds[index]!,
+ }));
+ }, [ramp, colorScale]);
+
+ // --- Dimensions (scatter's standalone fit math) ---
+ // Width measured over ALL rows (not just visible) so toggling a row in the
+ // legend doesn't shift the whole plot horizontally.
+ const yAxisWidth = useMemo(() => {
+ if (!showYAxis) return 0;
+ let max = 0;
+ for (const key of rowKeys) {
+ max = Math.max(max, context.measureText(key).width);
+ }
+ return Math.max(MIN_Y_AXIS_WIDTH, Math.min(MAX_Y_AXIS_WIDTH, Math.ceil(max) + Y_AXIS_PADDING));
+ }, [showYAxis, rowKeys, context]);
+
+ const xAxisHeight = useXAxisHeight(data, catKey, "singleLine");
+
+ const effectiveHeight = containerHeight || (typeof height === "number" ? height : 0);
+ const totalHeight = effectiveHeight || DEFAULT_CHART_HEIGHT;
+ const legendDeduction = showLegend && shouldFitLegend ? legendHeight : 0;
+ const colorScaleDeduction = showColorScale && shouldFitLegend ? colorScaleHeight : 0;
+ const chartInnerHeight =
+ totalHeight - CHART_MARGIN_TOP - xAxisHeight - legendDeduction - colorScaleDeduction;
+ const chartAreaWidth = Math.max(0, (containerWidth || 0) - yAxisWidth);
+
+ const totalSvgWidth = containerWidth || 0;
+ const totalSvgHeight = CHART_MARGIN_TOP + Math.max(0, chartInnerHeight) + xAxisHeight;
+
+ // --- Scales (band × band; cell gap is applied at render time so it stays
+ // an exact pixel inset instead of a proportional band padding) ---
+ const xScale = useMemo(
+ () => scaleBand<string>().domain(columns).range([0, chartAreaWidth]),
+ [columns, chartAreaWidth],
+ );
+
+ // React keys for the cell columns — duplicate labels disambiguated (the
+ // x scale interns duplicates into one band, but React keys must be unique).
+ const columnKeys = useMemo(() => buildColumnKeys(columns), [columns]);
+
+ // Thin the x labels once bands get narrower than a readable tick. The
+ // bandwidth comes from the SCALE: its domain interns duplicate labels, and
+ // XAxis thins over those unique bands — columns.length would over-count
+ // (and over-thin) whenever an LLM re-emits a category.
+ const labelInterval = computeLabelInterval(xScale.bandwidth(), MIN_X_LABEL_PX);
+ const yScale = useMemo(
+ () =>
+ scaleBand<string>()
+ .domain(visibleRowKeys)
+ .range([0, Math.max(0, chartInnerHeight)]),
+ [visibleRowKeys, chartInnerHeight],
+ );
+
+ // --- Row/column means: tooltip context + the row-legend swatch colors.
+ // Row means scan ALL columns (a hidden row's swatch should still summarize
+ // its own data); column means scan only VISIBLE rows (they contextualize
+ // what's on screen).
+ const rowMeans = useMemo(() => {
+ const means = new Map<string, number>();
+ for (const key of rowKeys) {
+ let sum = 0;
+ let count = 0;
+ for (const row of data) {
+ const value = heatmapCellValue(row[key]);
+ if (value !== null) {
+ sum += value;
+ count++;
+ }
+ }
+ if (count > 0) means.set(key, sum / count);
+ }
+ return means;
+ }, [rowKeys, data]);
+
+ const columnMeans = useMemo(
+ () =>
+ data.map((row) => {
+ let sum = 0;
+ let count = 0;
+ for (const key of visibleRowKeys) {
+ const value = heatmapCellValue(row[key]);
+ if (value !== null) {
+ sum += value;
+ count++;
+ }
+ }
+ return count > 0 ? sum / count : null;
+ }),
+ [data, visibleRowKeys],
+ );
+
+ // --- Tooltip ---
+ const tooltipPayload = useMemo(() => {
+ if (!hoveredCell) return null;
+ const { rowKey, columnIndex, columnLabel, value } = hoveredCell;
+ if (value === null) {
+ // An empty cell is still a place on the grid — name it instead of
+ // leaving a tooltip-less dead zone indistinguishable from a miss.
+ return {
+ label: columnLabel,
+ items: [{ name: rowKey, value: "No value", color: "transparent" }],
+ };
+ }
+ const items: { name: string; value: number | string; color: string }[] = [
+ { name: rowKey, value, color: colorScale(value) },
+ ];
+ // Context rows: where this cell sits against its row and column. The
+ // swatches are the means' own quantize colors — a ramp readout for free.
+ const rowMean = rowMeans.get(rowKey);
+ if (data.length > 1 && rowMean !== undefined) {
+ items.push({
+ name: "row avg",
+ value: roundMean(rowMean),
+ color: colorScale(rowMean),
+ });
+ }
+ const columnMean = columnMeans[columnIndex];
+ if (visibleRowKeys.length > 1 && columnMean != null) {
+ items.push({
+ name: "column avg",
+ value: roundMean(columnMean),
+ color: colorScale(columnMean),
+ });
+ }
+ return { label: columnLabel, items };
+ }, [hoveredCell, colorScale, rowMeans, columnMeans, data, visibleRowKeys]);
+
+ // --- Legend: one item per row. A row has no single color under a value
+ // ramp, so the swatch shows the quantize color of the row's MEAN value —
+ // a row-level summary that keeps swatches distinguishable. ---
+ const legendItems: LegendItem[] = useMemo(
+ () =>
+ rowKeys.map((key) => {
+ const mean = rowMeans.get(key);
+ const midColor = ramp[Math.floor(ramp.length / 2)] ?? "#000000";
+ return {
+ key,
+ label: key,
+ color: mean !== undefined ? colorScale(mean) : midColor,
+ };
+ }),
+ [rowKeys, rowMeans, colorScale, ramp],
+ );
+
+ const containerStyle = useMemo(() => buildContainerStyle({}, width, height), [width, height]);
+
+ return {
+ refs: { containerRef, legendRef, colorScaleRef },
+ isPrinting,
+ isEmpty,
+ data: {
+ catKey,
+ columns,
+ columnKeys,
+ rowKeys,
+ visibleRowKeys,
+ hiddenRows,
+ toggleRow,
+ },
+ dimensions: {
+ containerWidth,
+ effectiveYAxisWidth: yAxisWidth,
+ chartAreaWidth,
+ chartInnerHeight: Math.max(0, chartInnerHeight),
+ totalSvgWidth,
+ totalSvgHeight,
+ xAxisHeight,
+ labelInterval,
+ CHART_MARGIN_TOP,
+ },
+ scales: { xScale, yScale, colorScale },
+ colorScaleLegend: {
+ buckets: colorScaleBuckets,
+ domainMin: colorScale.domain()[0],
+ domainMax: colorScale.domain()[1],
+ },
+ hover: { hoveredCell, mousePos, handleCellMouseMove, handleMouseLeave },
+ legend: { legendItems, isLegendExpanded, setIsLegendExpanded },
+ tooltip: { tooltipPayload },
+ style: { containerStyle },
+ };
+}
diff --git a/packages/react-ui/src/components/D3Charts/hooks/cartesian/useHorizontalBarChartOrchestrator.ts b/packages/react-ui/src/components/D3Charts/hooks/cartesian/useHorizontalBarChartOrchestrator.ts
new file mode 100644
index 000000000..7034ca257
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/cartesian/useHorizontalBarChartOrchestrator.ts
@@ -0,0 +1,506 @@
+import type { ScaleLinear } from "d3-scale";
+import { scaleLinear } from "d3-scale";
+import { pointer } from "d3-selection";
+import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
+
+import {
+ BAR_GAP,
+ BAR_HEIGHT,
+ BAR_RADIUS,
+ barValue,
+ contentHeight as computeContentHeight,
+ groupHeight as computeGroupHeight,
+ rowOffsets as computeRowOffsets,
+ snapPositions as computeSnapPositions,
+ nearestSnap,
+ radiusArray,
+ showInternalLine,
+ stackSegments,
+ valueDomain,
+ verticalPadding,
+ X_AXIS_HEIGHT,
+} from "../../BarChart/parts/horizontalBarGeometry";
+import type { BarChartData, BarChartProps } from "../../BarChart/types";
+import type { TooltipItem } from "../../shared/core/PortalTooltip/ChartTooltip";
+import type { LegendItem } from "../../types";
+import { buildContainerStyle } from "../../utils/buildContainerStyle";
+import { DEFAULT_CHART_HEIGHT } from "../../utils/constants";
+import { getDataKeys } from "../../utils/dataUtils";
+import { buildColumnKeys } from "../../utils/heatmapUtils";
+import { parseLineHeight } from "../../utils/labelWrap";
+import { useChartPalette } from "../../utils/paletteUtils";
+import { numberTickFormatter } from "../../utils/styleUtils";
+import { useCanvasContextForLabelSize } from "../core/useCanvasContextForLabelSize";
+import { useChartShell } from "../core/useChartShell";
+import { useSeriesVisibility } from "../core/useSeriesVisibility";
+
+/**
+ * Small left margin (px) so the value-zero line / leftmost bar isn't flush
+ * against the container edge. Kept SMALL — smaller than the category label's
+ * left padding — so the leftmost gridline sits in the label's PADDING, never
+ * through its text (the bug a bigger inset caused). Edge tick-label clipping is
+ * handled by `NumericXAxis edgeAlign`, NOT by insetting the scale.
+ */
+const AXIS_PAD = 2;
+/** Minimum px between value ticks — matched to `NumericXAxis`/`VerticalGrid` so
+ * the shared scale produces the same ticks in the grid and the bottom axis. */
+const TICK_MIN_SPACING = 60;
+
+/** One rendered bar (a whole grouped bar, or one segment of a stacked bar). */
+export interface HorizontalBar {
+ /** React key within the row (grouped: the series key; stacked: the segment
+ * key). */
+ key: string;
+ /** The series this bar/segment belongs to (drives color + tooltip). */
+ seriesKey: string;
+ /** Left edge (px) in the row SVG's coordinate space; negatives extend left of
+ * `valueScale(0)`, so `x` is already the LEFT edge for either sign. */
+ x: number;
+ /** Top edge (px) in the row SVG's coordinate space. */
+ y: number;
+ /** Bar extent along the value axis (px), always `>= 0`. */
+ width: number;
+ /** Cross-axis thickness (px) — always `BAR_HEIGHT`. */
+ height: number;
+ /** Series color (distributed palette, keyed to input order — matches the
+ * vertical BarChart). */
+ color: string;
+ /** Per-corner radii `[tl, tr, br, bl]` for `roundedBarPath`. */
+ radii: [number, number, number, number];
+ /** Value is `< 0` — the bar draws left of the zero line. */
+ isNegative: boolean;
+ /** Bar is wide enough to carry its internal decorative line. */
+ showLine: boolean;
+ /** The finite, signed value this bar represents. */
+ value: number;
+}
+
+/** One category row: its label band plus every bar drawn under it. */
+export interface HorizontalBarRow {
+ /** Stable React key (duplicate categories disambiguated); NOT for display. */
+ key: string;
+ /** The category label (display string). */
+ category: string;
+ /** Top edge (px) of the whole group (label + bars) in the row SVG. */
+ rowTop: number;
+ /** Height (px) of the whole group — uniform across rows. */
+ groupHeight: number;
+ /** Bars under this row: grouped → one per visible series; stacked → the
+ * sign-diverging segments (positives then negatives). */
+ bars: HorizontalBar[];
+}
+
+/**
+ * Private orchestrator for the HORIZONTAL BarChart — the integration layer that
+ * turns `BarChartProps` into a render-ready structure for the row renderer
+ * (`HorizontalBarSeries`) and the shell (`HorizontalBarChartImpl`). Mirrors the
+ * `ScatterChart`/`FunnelChart` precedent: renders through `ChartShell` WITHOUT
+ * `CartesianChartLayout`, so it touches none of the shared vertical Line/Area
+ * machinery.
+ *
+ * All orientation math is delegated to the pure `horizontalBarGeometry` module
+ * (group/content heights, row offsets, snap targets, value domain, stack split,
+ * corner radii, internal-line threshold); this hook is glue — measurement,
+ * scales, per-row bar geometry, hover hit-testing, tooltip payload, and the
+ * vertical snap-scroll state.
+ *
+ * @param props The BarChart props (already on the horizontal path).
+ * @param containerRef Attached by the shell to the measured container (feeds
+ * `useChartShell`'s size + emptiness).
+ * @param scrollBodyRef Attached by the shell to the `overflow-y:auto` scroll
+ * body; read for `scrollTop`/`scrollHeight`/`clientHeight`
+ * to drive the snap-scroll buttons.
+ *
+ * Returned shape (consumed by Task 5/6):
+ * - `isEmpty`, `isPrinting` — from the shell.
+ * - `legendRef`, `containerStyle` — wire the legend + container.
+ * - `dataKeys` (visible series), `colors` (parallel to `dataKeys`),
+ * `legendItems` (ALL series), `labelHeight` (measured band height).
+ * - `valueScale` (zero-anchored, `.nice()`), `ticks`, `formatTick`.
+ * - `rows` (one `HorizontalBarRow` per category, data order), `rowOffsets`,
+ * `groupHeight` (uniform row height, for the hover crosshair band),
+ * `snapPositions`, `contentHeight` (raw), `svgHeight` (drawn, incl. pad),
+ * `topPad`, `bodyHeight`, `chartWidth`, `chartHeight`.
+ * - `hover` { hoveredIndex, hoveredCategory, onMouseMove, onMouseLeave }.
+ * - `tooltip` { payload, position }.
+ * - `legend` { hiddenSeries, toggleSeries, isLegendExpanded, setIsLegendExpanded }.
+ * - `scroll` { canUp, canDown, needsScroll, onScrollUp, onScrollDown, onScroll }.
+ */
+export function useHorizontalBarChartOrchestrator<T extends BarChartData>(
+ props: BarChartProps<T>,
+ containerRef: React.RefObject<HTMLDivElement | null>,
+ scrollBodyRef: React.RefObject<HTMLDivElement | null>,
+) {
+ const {
+ data,
+ categoryKey,
+ variant = "grouped",
+ customPalette,
+ barRadius = BAR_RADIUS,
+ legend: showLegend = true,
+ height,
+ width,
+ fitLegendInHeight,
+ } = props;
+
+ const catKey = String(categoryKey);
+ const legendRef = useRef<HTMLDivElement>(null);
+ const context = useCanvasContextForLabelSize(containerRef);
+
+ const {
+ isPrinting,
+ containerWidth,
+ containerHeight,
+ isEmpty,
+ legendHeight,
+ shouldFitLegend,
+ isLegendExpanded,
+ setIsLegendExpanded,
+ } = useChartShell({
+ data,
+ showLegend,
+ containerRef,
+ legendRef,
+ width,
+ height,
+ fitLegendInHeight,
+ });
+
+ // --- Series keys + visibility (legend toggle hides a series, matching the
+ // vertical BarChart's useChartData path) ---
+ const allDataKeys = useMemo(() => getDataKeys(data, catKey), [data, catKey]);
+ const { hiddenSeries, toggleSeries } = useSeriesVisibility(allDataKeys);
+ const dataKeys = useMemo(
+ () => allDataKeys.filter((k) => !hiddenSeries.has(k)),
+ [allDataKeys, hiddenSeries],
+ );
+
+ // --- Colors: DISTRIBUTED (middle-out) across the series, keyed to the
+ // ORIGINAL index so a legend toggle never recolors the rest. This is the
+ // SAME resolution the vertical BarChart uses — useChartData →
+ // useChartPalette → getDistributedColors(resolvePalette(theme,
+ // 'barChartPalette', customPalette), allDataKeys.length) — so a horizontal
+ // and a vertical BarChart on the same data color identically (and match
+ // openui, which also distributes rather than reading the raw ordered ramp).
+ // ---
+ const ramp = useChartPalette({
+ customPalette,
+ themePaletteName: "barChartPalette",
+ dataLength: allDataKeys.length,
+ });
+ const colorMap = useMemo(() => {
+ const map: Record<string, string> = {};
+ allDataKeys.forEach((key, i) => {
+ map[key] = ramp[i] ?? "#000000";
+ });
+ return map;
+ }, [allDataKeys, ramp]);
+ const colors = useMemo(
+ () => dataKeys.map((key) => colorMap[key] ?? "#000000"),
+ [dataKeys, colorMap],
+ );
+
+ const legendItems: LegendItem[] = useMemo(
+ () =>
+ allDataKeys.map((key) => ({
+ key,
+ label: key,
+ color: colorMap[key] ?? "#000000",
+ })),
+ [allDataKeys, colorMap],
+ );
+
+ // --- Category-label band height: single line-height (from the theme font)
+ // padded, floored at 24 (openui's `max(measured + 8, 24)`). ---
+ const labelHeight = useMemo(
+ () => Math.max(Math.ceil(parseLineHeight(context.font)) + 8, 24),
+ [context],
+ );
+
+ // --- Dimensions (shell measurement → chart / body sizes) ---
+ const effectiveHeight = containerHeight || (typeof height === "number" ? height : 0);
+ const totalHeight = effectiveHeight || DEFAULT_CHART_HEIGHT;
+ const legendDeduction = showLegend && shouldFitLegend ? legendHeight : 0;
+ const chartHeight = Math.max(0, totalHeight - legendDeduction);
+ const chartWidth = containerWidth || 0;
+ const bodyHeight = Math.max(0, chartHeight - X_AXIS_HEIGHT);
+
+ // --- Value scale: zero-anchored domain (0 always inside), niced, mapped to
+ // the drawable width. One scale drives the bars, the grid, and the bottom
+ // axis (pixel-exact vs openui's two-chart hack). ---
+ const rightEdge = Math.max(AXIS_PAD, chartWidth - AXIS_PAD);
+ const [domainMin, domainMax] = useMemo(
+ () => valueDomain(data, dataKeys, variant),
+ [data, dataKeys, variant],
+ );
+ const valueScale: ScaleLinear<number, number> = useMemo(
+ () => scaleLinear().domain([domainMin, domainMax]).nice().range([AXIS_PAD, rightEdge]),
+ [domainMin, domainMax, rightEdge],
+ );
+ const ticks = useMemo(() => {
+ const tickCount = Math.max(2, Math.floor(chartWidth / TICK_MIN_SPACING));
+ return valueScale.ticks(tickCount);
+ }, [valueScale, chartWidth]);
+
+ // --- Per-row layout (all delegated to the geometry module) ---
+ const rowCount = data.length;
+ const seriesCount = dataKeys.length;
+ const groupHeight = useMemo(
+ () => computeGroupHeight(seriesCount, variant, labelHeight),
+ [seriesCount, variant, labelHeight],
+ );
+ const contentHeight = useMemo(
+ () => computeContentHeight(rowCount, groupHeight),
+ [rowCount, groupHeight],
+ );
+ const pad = useMemo(
+ () => verticalPadding(contentHeight, bodyHeight),
+ [contentHeight, bodyHeight],
+ );
+ const rowOffsets = useMemo(
+ () => computeRowOffsets(rowCount, groupHeight, pad.top),
+ [rowCount, groupHeight, pad.top],
+ );
+ const snapPositions = useMemo(
+ () => computeSnapPositions(rowCount, groupHeight),
+ [rowCount, groupHeight],
+ );
+ const svgHeight = pad.top + contentHeight + pad.bottom;
+ const needsScroll = contentHeight > bodyHeight;
+
+ // Stable React keys per row (LLMs re-emit duplicate categories).
+ const rowKeys = useMemo(
+ () => buildColumnKeys(data.map((row) => String(row[catKey]))),
+ [data, catKey],
+ );
+
+ // --- Bars per row: grouped → one bar per visible series offset down the
+ // group; stacked → sign-diverging segments laid from the zero line. ---
+ const rows: HorizontalBarRow[] = useMemo(() => {
+ const zeroX = valueScale(0);
+ return data.map((row, i) => {
+ const rowTop = rowOffsets[i] ?? 0;
+ const barsTop = rowTop + labelHeight;
+ const bars: HorizontalBar[] = [];
+
+ if (variant === "stacked") {
+ const { positives, negatives } = stackSegments(row, dataKeys);
+ // Positives stack rightward from 0; negatives stack leftward from 0.
+ let cumulative = 0;
+ for (const seg of positives) {
+ const start = valueScale(cumulative);
+ cumulative += seg.value;
+ const end = valueScale(cumulative);
+ const width = Math.abs(end - start);
+ bars.push({
+ key: seg.key,
+ seriesKey: seg.key,
+ x: Math.min(start, end),
+ y: barsTop,
+ width,
+ height: BAR_HEIGHT,
+ color: colorMap[seg.key] ?? "#000000",
+ radii: radiusArray("stacked", barRadius, seg.isFirst, seg.isLast, false),
+ isNegative: false,
+ showLine: showInternalLine(width),
+ value: seg.value,
+ });
+ }
+ cumulative = 0;
+ for (const seg of negatives) {
+ const start = valueScale(cumulative);
+ cumulative += seg.value;
+ const end = valueScale(cumulative);
+ const width = Math.abs(end - start);
+ bars.push({
+ key: seg.key,
+ seriesKey: seg.key,
+ x: Math.min(start, end),
+ y: barsTop,
+ width,
+ height: BAR_HEIGHT,
+ color: colorMap[seg.key] ?? "#000000",
+ radii: radiusArray("stacked", barRadius, seg.isFirst, seg.isLast, true),
+ isNegative: true,
+ showLine: showInternalLine(width),
+ value: seg.value,
+ });
+ }
+ } else {
+ dataKeys.forEach((key, j) => {
+ const value = barValue(row[key]);
+ const valueX = valueScale(value);
+ const width = Math.abs(valueX - zeroX);
+ const isNegative = value < 0;
+ bars.push({
+ key,
+ seriesKey: key,
+ x: Math.min(zeroX, valueX),
+ y: barsTop + j * (BAR_HEIGHT + BAR_GAP),
+ width,
+ height: BAR_HEIGHT,
+ color: colorMap[key] ?? "#000000",
+ radii: radiusArray("grouped", barRadius, false, false, isNegative),
+ isNegative,
+ showLine: showInternalLine(width),
+ value,
+ });
+ });
+ }
+
+ return {
+ key: rowKeys[i] ?? String(row[catKey]),
+ category: String(row[catKey]),
+ rowTop,
+ groupHeight,
+ bars,
+ };
+ });
+ }, [
+ data,
+ catKey,
+ dataKeys,
+ variant,
+ valueScale,
+ rowOffsets,
+ labelHeight,
+ groupHeight,
+ colorMap,
+ barRadius,
+ rowKeys,
+ ]);
+
+ // --- Hover: hit-test the pointer's SVG-local y against the row offsets
+ // (whole group — label band + bars — highlights the category). ---
+ const [hoveredIndex, setHoveredIndex] = useState<number | null>(null);
+ const [mousePos, setMousePos] = useState<{ x: number; y: number } | null>(null);
+
+ const handleMouseMove = useCallback(
+ (event: React.MouseEvent<SVGSVGElement>) => {
+ const [, my] = pointer(event.nativeEvent, event.currentTarget);
+ let found: number | null = null;
+ for (let i = 0; i < rowOffsets.length; i++) {
+ const top = rowOffsets[i] ?? 0;
+ if (my >= top && my < top + groupHeight) {
+ found = i;
+ break;
+ }
+ }
+ setHoveredIndex(found);
+ setMousePos({ x: event.clientX, y: event.clientY });
+ },
+ [rowOffsets, groupHeight],
+ );
+
+ const handleMouseLeave = useCallback(() => {
+ setHoveredIndex(null);
+ setMousePos(null);
+ }, []);
+
+ const hoveredCategory = hoveredIndex !== null ? (rows[hoveredIndex]?.category ?? null) : null;
+
+ // --- Tooltip: category label + one row per visible series ---
+ const tooltipPayload = useMemo(() => {
+ if (hoveredIndex === null) return null;
+ const row = data[hoveredIndex];
+ if (!row) return null;
+ const items: TooltipItem[] = dataKeys.map((key) => ({
+ name: key,
+ value: barValue(row[key]),
+ color: colorMap[key] ?? "#000000",
+ }));
+ return { label: String(row[catKey]), items };
+ }, [hoveredIndex, data, dataKeys, colorMap, catKey]);
+
+ // --- Vertical snap-scroll (mirrors useChartScroll's boundary math on the Y
+ // axis). Buttons render only when the content overflows the body. ---
+ const [canScrollUp, setCanScrollUp] = useState(false);
+ const [canScrollDown, setCanScrollDown] = useState(needsScroll);
+
+ useEffect(() => {
+ if (!needsScroll) {
+ setCanScrollUp(false);
+ setCanScrollDown(false);
+ return;
+ }
+ const el = scrollBodyRef.current;
+ if (el) {
+ setCanScrollUp(el.scrollTop > 0);
+ setCanScrollDown(el.scrollTop < el.scrollHeight - el.clientHeight - 1);
+ } else {
+ setCanScrollDown(true);
+ }
+ }, [needsScroll, scrollBodyRef, contentHeight, bodyHeight]);
+
+ const onScroll = useCallback(() => {
+ const el = scrollBodyRef.current;
+ if (!el) return;
+ setCanScrollUp(el.scrollTop > 0);
+ setCanScrollDown(el.scrollTop < el.scrollHeight - el.clientHeight - 1);
+ }, [scrollBodyRef]);
+
+ const onScrollUp = useCallback(() => {
+ const el = scrollBodyRef.current;
+ if (!el) return;
+ const idx = nearestSnap(snapPositions, el.scrollTop, "up");
+ el.scrollTo({ top: snapPositions[idx] ?? 0, behavior: "smooth" });
+ }, [scrollBodyRef, snapPositions]);
+
+ const onScrollDown = useCallback(() => {
+ const el = scrollBodyRef.current;
+ if (!el) return;
+ const idx = nearestSnap(snapPositions, el.scrollTop, "down");
+ el.scrollTo({ top: snapPositions[idx] ?? 0, behavior: "smooth" });
+ }, [scrollBodyRef, snapPositions]);
+
+ const containerStyle = useMemo(() => buildContainerStyle({}, width, height), [width, height]);
+
+ return {
+ isEmpty,
+ isPrinting,
+ legendRef,
+ containerStyle,
+
+ dataKeys,
+ colors,
+ legendItems,
+ labelHeight,
+
+ valueScale,
+ ticks,
+ formatTick: numberTickFormatter,
+
+ rows,
+ rowOffsets,
+ groupHeight,
+ snapPositions,
+ contentHeight,
+ svgHeight,
+ topPad: pad.top,
+ bodyHeight,
+ chartWidth,
+ chartHeight,
+
+ hover: {
+ hoveredIndex,
+ hoveredCategory,
+ onMouseMove: handleMouseMove,
+ onMouseLeave: handleMouseLeave,
+ },
+ tooltip: { payload: tooltipPayload, position: mousePos },
+ legend: {
+ hiddenSeries,
+ toggleSeries,
+ isLegendExpanded,
+ setIsLegendExpanded,
+ },
+ scroll: {
+ canUp: canScrollUp,
+ canDown: canScrollDown,
+ needsScroll,
+ onScrollUp,
+ onScrollDown,
+ onScroll,
+ },
+ };
+}
diff --git a/packages/react-ui/src/components/D3Charts/hooks/cartesian/useMaxLabelWidth.ts b/packages/react-ui/src/components/D3Charts/hooks/cartesian/useMaxLabelWidth.ts
new file mode 100644
index 000000000..14e5d7a90
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/cartesian/useMaxLabelWidth.ts
@@ -0,0 +1,36 @@
+import React, { useMemo } from "react";
+
+import { useCanvasContextForLabelSize } from "../core/useCanvasContextForLabelSize";
+
+/**
+ * Measures the pixel width of each category label and returns the maximum width found.
+ * Uses a canvas context to accurately measure text dimensions based on the
+ * render-scope font (`scopeRef` — see measureFontScope.ts).
+ */
+export const useMaxLabelWidth = <T extends Record<string, any>>(
+ data: T[],
+ categoryKey: keyof T,
+ scopeRef?: React.RefObject<HTMLElement | null>,
+): number => {
+ const context = useCanvasContextForLabelSize(scopeRef);
+
+ return useMemo(() => {
+ if (!data || data.length === 0) {
+ return 0;
+ }
+
+ let maxWidth = 0;
+
+ for (const item of data) {
+ const labelValue = String(item[categoryKey] ?? "");
+ const metrics = context.measureText(labelValue);
+ const width = metrics.width;
+
+ if (width > maxWidth) {
+ maxWidth = width;
+ }
+ }
+
+ return maxWidth;
+ }, [data, categoryKey, context]);
+};
diff --git a/packages/react-ui/src/components/D3Charts/hooks/cartesian/useScatterChartOrchestrator.ts b/packages/react-ui/src/components/D3Charts/hooks/cartesian/useScatterChartOrchestrator.ts
new file mode 100644
index 000000000..8b660f1ff
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/cartesian/useScatterChartOrchestrator.ts
@@ -0,0 +1,299 @@
+import { scaleLinear } from "d3-scale";
+import { pointer } from "d3-selection";
+import React, { useCallback, useMemo, useRef, useState } from "react";
+
+import type { ChartColorPalette } from "../../../ThemeProvider";
+import type { HoveredScatterPoint, ScatterChartData, ScatterPoint } from "../../ScatterChart/types";
+import type { LegendItem } from "../../types";
+import { buildContainerStyle } from "../../utils/buildContainerStyle";
+import { CHART_MARGIN_TOP, DEFAULT_CHART_HEIGHT } from "../../utils/constants";
+import { useChartPalette } from "../../utils/paletteUtils";
+import { measureYAxisWidth } from "../../utils/styleUtils";
+import { useCanvasContextForLabelSize } from "../core/useCanvasContextForLabelSize";
+import { useChartShell } from "../core/useChartShell";
+import { useSeriesVisibility } from "../core/useSeriesVisibility";
+
+const SNAP_RADIUS = 30;
+const X_AXIS_HEIGHT = 28;
+
+export interface VisibleDataset {
+ dataset: ScatterChartData[number];
+ originalIndex: number;
+}
+
+export interface UseScatterChartOrchestratorParams {
+ data: ScatterChartData;
+ themePaletteName: keyof ChartColorPalette;
+ customPalette?: string[];
+ showLegend: boolean;
+ showYAxis: boolean;
+ height?: number | string;
+ width?: number | string;
+ fitLegendInHeight?: boolean;
+ xAxisLabel?: string;
+ yAxisLabel?: string;
+ onClick?: (
+ point: ScatterPoint,
+ datasetName: string,
+ datasetIndex: number,
+ pointIndex: number,
+ ) => void;
+}
+
+export function useScatterChartOrchestrator({
+ data,
+ themePaletteName,
+ customPalette,
+ showLegend,
+ showYAxis,
+ height,
+ width,
+ fitLegendInHeight,
+ xAxisLabel,
+ yAxisLabel,
+ onClick,
+}: UseScatterChartOrchestratorParams) {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const legendRef = useRef<HTMLDivElement>(null);
+ const [hoveredPoint, setHoveredPoint] = useState<HoveredScatterPoint | null>(null);
+ const [mousePos, setMousePos] = useState<{ x: number; y: number } | null>(null);
+
+ const {
+ isPrinting,
+ containerWidth,
+ containerHeight,
+ isEmpty,
+ legendHeight,
+ shouldFitLegend,
+ isLegendExpanded,
+ setIsLegendExpanded,
+ } = useChartShell({
+ data,
+ showLegend,
+ containerRef,
+ legendRef,
+ width,
+ height,
+ fitLegendInHeight,
+ });
+ const context = useCanvasContextForLabelSize(containerRef);
+
+ // --- Colors (via shared useChartPalette — respects ThemeProvider overrides) ---
+ const datasetNames = useMemo(() => data.map((ds) => ds.name), [data]);
+
+ const distributedColors = useChartPalette({
+ customPalette,
+ themePaletteName,
+ dataLength: datasetNames.length,
+ });
+
+ const colorMap = useMemo(() => {
+ const map: Record<string, string> = {};
+ datasetNames.forEach((name, i) => {
+ map[name] = distributedColors[i] ?? "#000";
+ });
+ return map;
+ }, [datasetNames, distributedColors]);
+
+ // --- Hidden series (via shared useSeriesVisibility) ---
+ const { hiddenSeries, toggleSeries } = useSeriesVisibility(datasetNames);
+
+ const visibleDatasets: VisibleDataset[] = useMemo(
+ () =>
+ data
+ .map((dataset, originalIndex) => ({ dataset, originalIndex }))
+ .filter(({ dataset }) => !hiddenSeries.has(dataset.name)),
+ [data, hiddenSeries],
+ );
+
+ // --- Scales (domain from ALL datasets for stability) ---
+ const { xMin, xMax, yMin, yMax } = useMemo(() => {
+ let xMin = Infinity;
+ let xMax = -Infinity;
+ let yMin = Infinity;
+ let yMax = -Infinity;
+ for (const ds of data) {
+ for (const pt of ds.data) {
+ if (pt.x < xMin) xMin = pt.x;
+ if (pt.x > xMax) xMax = pt.x;
+ if (pt.y < yMin) yMin = pt.y;
+ if (pt.y > yMax) yMax = pt.y;
+ }
+ }
+ if (!isFinite(xMin)) {
+ xMin = 0;
+ xMax = 100;
+ yMin = 0;
+ yMax = 100;
+ }
+ return { xMin, xMax, yMin, yMax };
+ }, [data]);
+
+ // --- Y-axis width (via shared measureYAxisWidth utility) ---
+ const yAxisWidth = useMemo(() => {
+ if (!showYAxis) return 0;
+ const tempScale = scaleLinear().domain([yMin, yMax]).nice();
+ const ticks = tempScale.ticks();
+ return measureYAxisWidth(ticks, context);
+ }, [showYAxis, yMin, yMax, context]);
+
+ // --- Dimensions ---
+ const effectiveHeight = containerHeight || (typeof height === "number" ? height : 0);
+ const totalHeight = effectiveHeight || DEFAULT_CHART_HEIGHT;
+ const legendDeduction = showLegend && shouldFitLegend ? legendHeight : 0;
+ const chartInnerHeight = totalHeight - CHART_MARGIN_TOP - X_AXIS_HEIGHT - legendDeduction;
+ const chartAreaWidth = Math.max(0, (containerWidth || 0) - yAxisWidth);
+
+ const totalSvgWidth = containerWidth || 0;
+ const totalSvgHeight = CHART_MARGIN_TOP + Math.max(0, chartInnerHeight) + X_AXIS_HEIGHT;
+
+ // --- Scales ---
+ const xScale = useMemo(
+ () => scaleLinear().domain([xMin, xMax]).range([0, chartAreaWidth]).nice(),
+ [xMin, xMax, chartAreaWidth],
+ );
+
+ const yScale = useMemo(
+ () => scaleLinear().domain([yMin, yMax]).range([chartInnerHeight, 0]).nice(),
+ [yMin, yMax, chartInnerHeight],
+ );
+
+ // --- Hover (2D nearest-point) ---
+ const findNearestPoint = useCallback(
+ (clientX: number, clientY: number, currentTarget: SVGGElement) => {
+ const [mx, my] = pointer({ clientX, clientY }, currentTarget);
+ let minDist = Infinity;
+ let closest: HoveredScatterPoint | null = null;
+
+ for (const { dataset: ds, originalIndex } of visibleDatasets) {
+ for (let ptIdx = 0; ptIdx < ds.data.length; ptIdx++) {
+ const pt = ds.data[ptIdx]!;
+ const px = xScale(pt.x);
+ const py = yScale(pt.y);
+ const dist = Math.sqrt((mx - px) ** 2 + (my - py) ** 2);
+ if (dist < minDist) {
+ minDist = dist;
+ closest = {
+ datasetIndex: originalIndex,
+ pointIndex: ptIdx,
+ point: pt,
+ datasetName: ds.name,
+ };
+ }
+ }
+ }
+
+ if (closest && minDist <= SNAP_RADIUS) {
+ setHoveredPoint(closest);
+ } else {
+ setHoveredPoint(null);
+ }
+
+ setMousePos({ x: clientX, y: clientY });
+ },
+ [visibleDatasets, xScale, yScale],
+ );
+
+ const handleMouseMove = useCallback(
+ (event: React.MouseEvent<SVGGElement>) => {
+ findNearestPoint(event.clientX, event.clientY, event.currentTarget);
+ },
+ [findNearestPoint],
+ );
+
+ const handleMouseLeave = useCallback(() => {
+ setHoveredPoint(null);
+ setMousePos(null);
+ }, []);
+
+ const handleTouchMove = useCallback(
+ (event: React.TouchEvent<SVGGElement>) => {
+ const touch = event.touches[0];
+ if (!touch) return;
+ findNearestPoint(touch.clientX, touch.clientY, event.currentTarget);
+ },
+ [findNearestPoint],
+ );
+
+ const handleTouchEnd = useCallback(() => {
+ setHoveredPoint(null);
+ setMousePos(null);
+ }, []);
+
+ const handleClick = useCallback(
+ (event: React.MouseEvent<SVGGElement>) => {
+ if (!onClick || !hoveredPoint) return;
+ event.stopPropagation();
+ onClick(
+ hoveredPoint.point,
+ hoveredPoint.datasetName,
+ hoveredPoint.datasetIndex,
+ hoveredPoint.pointIndex,
+ );
+ },
+ [onClick, hoveredPoint],
+ );
+
+ // --- Tooltip (uses xAxisLabel/yAxisLabel for item names) ---
+ const tooltipPayload = useMemo(() => {
+ if (!hoveredPoint) return null;
+ const color = colorMap[hoveredPoint.datasetName] ?? "#000";
+ return {
+ label: hoveredPoint.datasetName,
+ items: [
+ { name: xAxisLabel ?? "X", value: hoveredPoint.point.x, color },
+ { name: yAxisLabel ?? "Y", value: hoveredPoint.point.y, color },
+ ],
+ };
+ }, [hoveredPoint, colorMap, xAxisLabel, yAxisLabel]);
+
+ // --- Legend ---
+ const legendItems: LegendItem[] = useMemo(
+ () =>
+ datasetNames.map((name) => ({
+ key: name,
+ label: name,
+ color: colorMap[name] ?? "#000",
+ })),
+ [datasetNames, colorMap],
+ );
+
+ // --- Container style ---
+ const containerStyle = useMemo(() => buildContainerStyle({}, width, height), [width, height]);
+
+ return {
+ refs: { containerRef, legendRef },
+ isPrinting,
+ isEmpty,
+ data: { visibleDatasets, datasetNames, colorMap },
+ dimensions: {
+ containerWidth,
+ effectiveYAxisWidth: yAxisWidth,
+ chartAreaWidth,
+ chartInnerHeight: Math.max(0, chartInnerHeight),
+ totalSvgWidth,
+ totalSvgHeight,
+ xAxisHeight: X_AXIS_HEIGHT,
+ CHART_MARGIN_TOP,
+ },
+ scales: { xScale, yScale },
+ hover: {
+ hoveredPoint,
+ mousePos,
+ handleMouseMove,
+ handleMouseLeave,
+ handleTouchMove,
+ handleTouchEnd,
+ handleClick,
+ },
+ legend: {
+ legendItems,
+ hiddenSeries,
+ toggleSeries,
+ isLegendExpanded,
+ setIsLegendExpanded,
+ },
+ tooltip: { tooltipPayload },
+ style: { containerStyle },
+ };
+}
diff --git a/packages/react-ui/src/components/D3Charts/hooks/cartesian/useStackedData.ts b/packages/react-ui/src/components/D3Charts/hooks/cartesian/useStackedData.ts
new file mode 100644
index 000000000..c6a03a665
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/cartesian/useStackedData.ts
@@ -0,0 +1,64 @@
+import type { Series } from "d3-shape";
+import { stack, stackOffsetNone, stackOrderNone } from "d3-shape";
+import { useMemo } from "react";
+import type { ChartData } from "../../types";
+import type { StackOffset } from "../../utils/yDomain";
+
+export type StackedData = Series<Record<string, string | number>, string>[];
+
+/**
+ * d3's stackOffsetDiverging with ONE change: zero-value segments ride the
+ * positive running total instead of being re-based to [0, 0]. d3's zero branch
+ * (`d[0] = 0, d[1] = dy`) pins zeros to the baseline, which visibly drops a
+ * stacked AREA series' band/line to the floor wherever a value is exactly 0 —
+ * stackOffsetNone (the previous offset) kept zeros at the running cumulative.
+ * With this branch, all-non-negative data produces output identical to
+ * stackOffsetNone (pixel-compat), while mixed signs still diverge: positives
+ * stack up from zero, negatives stack down.
+ */
+export const stackOffsetDivergingZeroPreserving = (
+ series: Series<Record<string, string | number>, string>[],
+ order: Iterable<number>,
+): void => {
+ const orderArr = Array.from(order);
+ const n = series.length;
+ if (n === 0) return;
+ const m = series[orderArr[0]!]!.length;
+ for (let j = 0; j < m; ++j) {
+ let positiveSum = 0;
+ let negativeSum = 0;
+ for (let i = 0; i < n; ++i) {
+ const d = series[orderArr[i]!]![j]!;
+ const dy = d[1] - d[0];
+ if (dy > 0) {
+ d[0] = positiveSum;
+ d[1] = positiveSum += dy;
+ } else if (dy < 0) {
+ d[1] = negativeSum;
+ d[0] = negativeSum += dy;
+ } else {
+ // Zero: ride the positive running total (d3 re-bases to [0, dy]).
+ d[0] = positiveSum;
+ d[1] = positiveSum;
+ }
+ }
+ }
+};
+
+export const useStackedData = (
+ data: ChartData,
+ dataKeys: string[],
+ stacked: boolean,
+ stackOffset: StackOffset = "sign",
+): StackedData | null => {
+ return useMemo(() => {
+ if (!stacked || dataKeys.length === 0) return null;
+
+ const stackGenerator = stack<Record<string, string | number>>()
+ .keys(dataKeys)
+ .order(stackOrderNone)
+ .offset(stackOffset === "none" ? stackOffsetNone : stackOffsetDivergingZeroPreserving);
+
+ return stackGenerator(data as Iterable<{ [key: string]: number }>);
+ }, [data, dataKeys, stacked, stackOffset]);
+};
diff --git a/packages/react-ui/src/components/D3Charts/hooks/cartesian/useXAxisHeight.ts b/packages/react-ui/src/components/D3Charts/hooks/cartesian/useXAxisHeight.ts
new file mode 100644
index 000000000..3952e8f65
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/cartesian/useXAxisHeight.ts
@@ -0,0 +1,49 @@
+import React, { useMemo } from "react";
+
+import { XAxisTickVariant } from "../../types";
+import { MAX_LABEL_LINES, parseLineHeight, wrapLabelLines } from "../../utils/labelWrap";
+import { useCanvasContextForLabelSize } from "../core/useCanvasContextForLabelSize";
+
+const MIN_HEIGHT = 30;
+const X_AXIS_LABEL_PADDING = 13;
+
+/**
+ * Height (px) to reserve for the x-axis label band.
+ *
+ * Single-line: one line + padding. Multi-line: the tallest wrapped label ×
+ * line-height + padding. Uses the SAME `wrapLabelLines` the renderer (`XAxis`)
+ * uses, so the reserved height always matches what gets drawn — replacing the
+ * old `MAX_LABEL_LINES`↔`-webkit-line-clamp: 3` magic-number contract.
+ *
+ * (canvas measureText ignores letter-spacing — a pre-existing limitation shared
+ * with useYAxisWidth and useMaxLabelWidth.)
+ */
+export const useXAxisHeight = (
+ data: Record<string, string | number>[],
+ categoryKey: string,
+ tickVariant: XAxisTickVariant,
+ widthOfGroup = 70,
+ scopeRef?: React.RefObject<HTMLElement | null>,
+) => {
+ const context = useCanvasContextForLabelSize(scopeRef);
+
+ return useMemo(() => {
+ const lineHeight = parseLineHeight(context.font);
+ // Single-line: 1 line of text + padding, floored at MIN_HEIGHT. Font-aware.
+ const singleLineHeight = Math.max(lineHeight + X_AXIS_LABEL_PADDING, MIN_HEIGHT);
+
+ if (tickVariant !== "multiLine") return singleLineHeight;
+ if (!data || data.length === 0) return singleLineHeight;
+ if (widthOfGroup <= 0) return singleLineHeight;
+
+ let maxLines = 1;
+ for (const item of data) {
+ const label = String(item[categoryKey]);
+ const lines = wrapLabelLines(context, label, widthOfGroup, MAX_LABEL_LINES).length;
+ if (lines > maxLines) maxLines = lines;
+ }
+
+ const labelHeight = maxLines * lineHeight;
+ return Math.max(labelHeight + X_AXIS_LABEL_PADDING, MIN_HEIGHT);
+ }, [data, categoryKey, tickVariant, widthOfGroup, context]);
+};
diff --git a/packages/react-ui/src/components/D3Charts/hooks/cartesian/useXAxisLabelLayout.ts b/packages/react-ui/src/components/D3Charts/hooks/cartesian/useXAxisLabelLayout.ts
new file mode 100644
index 000000000..0cd4ac854
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/cartesian/useXAxisLabelLayout.ts
@@ -0,0 +1,34 @@
+import React, { useMemo } from "react";
+
+import type { ChartData } from "../../types";
+import { parseLineHeight } from "../../utils/labelWrap";
+import {
+ layoutXAxisLabels,
+ type XAxisLabelLayout,
+ type XAxisLabelLayoutOptions,
+} from "../../utils/xAxisLabelLayout";
+import { useCanvasContextForLabelSize } from "../core/useCanvasContextForLabelSize";
+
+/**
+ * The x-axis label layout (`layoutXAxisLabels`) measured with the render-scope
+ * tick font (`scopeRef` — see measureFontScope.ts).
+ */
+export const useXAxisLabelLayout = (
+ data: ChartData,
+ categoryKey: string,
+ options: Omit<XAxisLabelLayoutOptions, "lineHeight">,
+ scopeRef?: React.RefObject<HTMLElement | null>,
+): XAxisLabelLayout => {
+ const context = useCanvasContextForLabelSize(scopeRef);
+ const { variant, slotWidth, maxHeight, condensed } = options;
+
+ return useMemo(
+ () =>
+ layoutXAxisLabels(
+ context,
+ data.map((d) => String(d[categoryKey])),
+ { variant, slotWidth, maxHeight, condensed, lineHeight: parseLineHeight(context.font) },
+ ),
+ [context, data, categoryKey, variant, slotWidth, maxHeight, condensed],
+ );
+};
diff --git a/packages/react-ui/src/components/D3Charts/hooks/cartesian/useXBandScale.ts b/packages/react-ui/src/components/D3Charts/hooks/cartesian/useXBandScale.ts
new file mode 100644
index 000000000..0bef4f4b5
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/cartesian/useXBandScale.ts
@@ -0,0 +1,20 @@
+import type { ScaleBand } from "d3-scale";
+import { scaleBand } from "d3-scale";
+import { useMemo } from "react";
+import type { ChartData } from "../../types";
+
+export const useXBandScale = (
+ data: ChartData,
+ categoryKey: string,
+ svgWidth: number,
+ paddingInner?: number,
+ paddingOuter?: number,
+): ScaleBand<string> => {
+ return useMemo(() => {
+ return scaleBand<string>()
+ .domain(data.map((d) => String(d[categoryKey])))
+ .range([0, svgWidth])
+ .paddingInner(paddingInner ?? 0.2)
+ .paddingOuter(paddingOuter ?? 0.1);
+ }, [data, categoryKey, svgWidth, paddingInner, paddingOuter]);
+};
diff --git a/packages/react-ui/src/components/D3Charts/hooks/cartesian/useXScale.ts b/packages/react-ui/src/components/D3Charts/hooks/cartesian/useXScale.ts
new file mode 100644
index 000000000..2dbc47f8a
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/cartesian/useXScale.ts
@@ -0,0 +1,18 @@
+import type { ScalePoint } from "d3-scale";
+import { scalePoint } from "d3-scale";
+import { useMemo } from "react";
+import type { ChartData } from "../../types";
+
+export const useXScale = (
+ data: ChartData,
+ categoryKey: string,
+ svgWidth: number,
+ widthOfGroup: number,
+): ScalePoint<string> => {
+ return useMemo(() => {
+ return scalePoint<string>()
+ .domain(data.map((d) => String(d[categoryKey])))
+ .range([widthOfGroup / 2, svgWidth - widthOfGroup / 2])
+ .padding(0);
+ }, [data, categoryKey, svgWidth, widthOfGroup]);
+};
diff --git a/packages/react-ui/src/components/D3Charts/hooks/cartesian/useYAxisWidth.ts b/packages/react-ui/src/components/D3Charts/hooks/cartesian/useYAxisWidth.ts
new file mode 100644
index 000000000..bf42a72e6
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/cartesian/useYAxisWidth.ts
@@ -0,0 +1,76 @@
+import { scaleLinear } from "d3-scale";
+import React, { useMemo } from "react";
+import { measureYAxisWidth } from "../../utils/styleUtils";
+import { computeYDomain, type StackOffset } from "../../utils/yDomain";
+import { useCanvasContextForLabelSize } from "../core/useCanvasContextForLabelSize";
+import { useHydrated } from "../core/useHydrated";
+
+const DEFAULT_Y_AXIS_WIDTH = 40;
+
+/**
+ * Width reserved for the y-axis labels.
+ *
+ * The axis only ever renders the scale's `.ticks()` — a handful of "nice" round
+ * numbers — so we size against exactly those, via the shared `measureYAxisWidth`
+ * helper (the scatter chart already sizes this way). Measuring every raw data
+ * value instead, as this hook used to, is both wasteful (O(rows × series)
+ * `measureText` calls) and wrong:
+ * - `.nice()` lifts the domain, so a data max of 950 yields a top tick of
+ * "1.0K" (4 chars) — wider than the raw "950" the old code measured, so the
+ * real tick label clipped.
+ * - fractional data (e.g. 47.38) formats to a string the axis never shows.
+ *
+ * The domain comes from the same `computeYDomain` the rendered scale uses —
+ * stacked totals and negative extents included — so the measured labels are
+ * the rendered ones by construction.
+ */
+export const useYAxisWidth = (
+ data: Array<Record<string, string | number>>,
+ dataKeys: string[],
+ stacked: boolean,
+ options?: {
+ /**
+ * The consumer's y-tick-count hint (the same `yTickCount` YAxis receives).
+ * When present, YAxis renders `scale.ticks(clamped(hint))` — so measure
+ * exactly that set. When absent, YAxis derives the count from the chart
+ * height, which isn't known at measure time (height depends on the x-axis
+ * band, which depends on THIS width via `availableWidth` — circular), so
+ * we keep measuring d3's default tick set; the value strings differ only
+ * marginally across counts for a nice'd domain.
+ */
+ tickCount?: number;
+ /** The chart container — the measurement font's theme scope. */
+ scopeRef?: React.RefObject<HTMLElement | null>;
+ /** How stacked series combine — must match the rendered scale's. */
+ stackOffset?: StackOffset;
+ },
+) => {
+ const { tickCount, scopeRef, stackOffset = "sign" } = options ?? {};
+ const context = useCanvasContextForLabelSize(scopeRef);
+ // Hydration gate (not a window check): the server renders the default
+ // width, so the hydration render must too — measuring real text here
+ // mismatched the SSR'd svg width/tick positions, and React leaves
+ // mismatched attributes permanently stale.
+ const hydrated = useHydrated();
+
+ const yAxisWidth = useMemo(() => {
+ if (!hydrated || !data || data.length === 0 || !dataKeys.length || !context) {
+ return DEFAULT_Y_AXIS_WIDTH;
+ }
+
+ // Mirror useYScale's domain + .nice() so we measure exactly the ticks the
+ // axis will render. The range (height) doesn't affect tick *values*, so we
+ // can size before chart height is known (same trick the scatter chart uses).
+ // The count mirrors resolveTickCount's override clamp (constants.ts).
+ const scale = scaleLinear()
+ .domain(computeYDomain(data, dataKeys, stacked, stackOffset))
+ .nice();
+ const ticks =
+ tickCount != null && Number.isFinite(tickCount)
+ ? scale.ticks(Math.max(2, Math.floor(tickCount)))
+ : scale.ticks();
+ return measureYAxisWidth(ticks, context);
+ }, [hydrated, data, dataKeys, stacked, stackOffset, tickCount, context]);
+
+ return { yAxisWidth };
+};
diff --git a/packages/react-ui/src/components/D3Charts/hooks/cartesian/useYScale.ts b/packages/react-ui/src/components/D3Charts/hooks/cartesian/useYScale.ts
new file mode 100644
index 000000000..22d92cce6
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/cartesian/useYScale.ts
@@ -0,0 +1,20 @@
+import type { ScaleLinear } from "d3-scale";
+import { scaleLinear } from "d3-scale";
+import { useMemo } from "react";
+import type { ChartData } from "../../types";
+import { computeYDomain, type StackOffset } from "../../utils/yDomain";
+
+export const useYScale = (
+ data: ChartData,
+ dataKeys: string[],
+ chartInnerHeight: number,
+ stacked: boolean,
+ stackOffset: StackOffset = "sign",
+): ScaleLinear<number, number> => {
+ return useMemo(() => {
+ return scaleLinear()
+ .domain(computeYDomain(data, dataKeys, stacked, stackOffset))
+ .range([chartInnerHeight, 0])
+ .nice();
+ }, [data, dataKeys, stacked, stackOffset, chartInnerHeight]);
+};
diff --git a/packages/react-ui/src/components/D3Charts/hooks/core/index.ts b/packages/react-ui/src/components/D3Charts/hooks/core/index.ts
new file mode 100644
index 000000000..b508e3bc7
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/core/index.ts
@@ -0,0 +1,15 @@
+export * from "./useCanvasContextForLabelSize";
+export * from "./useCategoricalChartData";
+export * from "./useChartData";
+export * from "./useChartHover";
+export * from "./useChartShell";
+export * from "./useContainerSize";
+export * from "./useEffectiveAnimation";
+export * from "./useExportChartData";
+export * from "./useHydrated";
+export * from "./useLegendHeight";
+export * from "./usePerElementHover";
+export * from "./usePrintContext";
+export * from "./useSeriesVisibility";
+export * from "./useTooltipPayload";
+export * from "./useTransformedKeys";
diff --git a/packages/react-ui/src/components/D3Charts/hooks/core/measureFontScope.test.ts b/packages/react-ui/src/components/D3Charts/hooks/core/measureFontScope.test.ts
new file mode 100644
index 000000000..6dd9b1456
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/core/measureFontScope.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from "vitest";
+import { resolveMeasureFont } from "./measureFontScope";
+
+describe("resolveMeasureFont", () => {
+ it("prefers the CSS-var font (the render channel) over the theme token", () => {
+ expect(
+ resolveMeasureFont('400 20px/1.2 "Inter", system-ui, sans-serif', "400 12px/1.25 Inter"),
+ ).toBe('400 20px/1.2 "Inter", system-ui, sans-serif');
+ });
+
+ it("trims whitespace from computed custom-property values", () => {
+ // getComputedStyle().getPropertyValue preserves the declaration's leading
+ // whitespace — ' 400 20px…' must not defeat the css-var branch.
+ expect(resolveMeasureFont(" 400 20px/1.2 Inter ", "400 12px/1.25 Inter")).toBe(
+ "400 20px/1.2 Inter",
+ );
+ });
+
+ it("falls back to the theme token when no scope element resolved the var", () => {
+ expect(resolveMeasureFont("", "400 14px/1.3 Inter")).toBe("400 14px/1.3 Inter");
+ expect(resolveMeasureFont(null, "400 14px/1.3 Inter")).toBe("400 14px/1.3 Inter");
+ expect(resolveMeasureFont(undefined, "400 14px/1.3 Inter")).toBe("400 14px/1.3 Inter");
+ });
+
+ it("falls back to the react-ui default when both channels are empty", () => {
+ expect(resolveMeasureFont("", "")).toBe("400 12px/1.25 Inter");
+ expect(resolveMeasureFont(null, undefined)).toBe("400 12px/1.25 Inter");
+ expect(resolveMeasureFont(" ", " ")).toBe("400 12px/1.25 Inter");
+ });
+});
diff --git a/packages/react-ui/src/components/D3Charts/hooks/core/measureFontScope.ts b/packages/react-ui/src/components/D3Charts/hooks/core/measureFontScope.ts
new file mode 100644
index 000000000..08c0dc53b
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/core/measureFontScope.ts
@@ -0,0 +1,46 @@
+import { createContext } from "react";
+
+/**
+ * The CSS custom properties that style every native-SVG tick/axis label — the
+ * `svg-tick-label` mixin (shared/cartesian/chartBase.scss) compiles to
+ * `font: var(--openui-text-label-xs); letter-spacing: var(--openui-text-label-xs-letter-spacing)`.
+ * Text measurement MUST read the same channel: resolving the font from the JS
+ * theme context instead once clipped every axis label inside presentation
+ * slides, because a duplicated @openuidev/react-ui module gave the charts a
+ * different ThemeContext instance (12px default) than the one the slide's
+ * ThemeProvider wrote its 20px tokens to — while the CSS cascade, immune to JS
+ * module identity, rendered the 20px var. Same-channel measurement makes the
+ * budgets immune to that entire failure class (context splits, portals,
+ * out-of-scope rendering).
+ */
+export const TICK_FONT_CSS_VAR = "--openui-text-label-xs";
+export const TICK_LETTER_SPACING_CSS_VAR = "--openui-text-label-xs-letter-spacing";
+
+/**
+ * The element whose computed styles carry the theme scope the chart renders
+ * under. Provided by the chart containers (ChartShell, CartesianChartLayout)
+ * with their persistent container ref, so any measuring component rendered
+ * inside them — XAxis, RadarAxisLabels, HeatmapCells, the legend — picks up
+ * the render-scope font with no prop threading. Orchestrator-level hooks run
+ * ABOVE the provider and pass their own container ref explicitly instead.
+ */
+export const MeasureFontScopeContext = createContext<React.RefObject<HTMLElement | null> | null>(
+ null,
+);
+
+/**
+ * Measurement-font precedence: the CSS var actually styling the ticks wins;
+ * the JS theme token is the fallback (no DOM scope yet — e.g. the render
+ * before refs attach); the react-ui default is the floor. Pure — unit-tested
+ * without a DOM.
+ */
+export function resolveMeasureFont(
+ cssVarFont: string | null | undefined,
+ themeFont: string | null | undefined,
+): string {
+ const fromCss = cssVarFont?.trim();
+ if (fromCss) return fromCss;
+ const fromTheme = themeFont?.trim();
+ if (fromTheme) return fromTheme;
+ return "400 12px/1.25 Inter";
+}
diff --git a/packages/react-ui/src/components/D3Charts/hooks/core/useCanvasContextForLabelSize.ts b/packages/react-ui/src/components/D3Charts/hooks/core/useCanvasContextForLabelSize.ts
new file mode 100644
index 000000000..fe2cd0574
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/core/useCanvasContextForLabelSize.ts
@@ -0,0 +1,112 @@
+import { useContext, useMemo, useState, useSyncExternalStore } from "react";
+import { useTheme } from "../../../ThemeProvider";
+import {
+ MeasureFontScopeContext,
+ TICK_FONT_CSS_VAR,
+ TICK_LETTER_SPACING_CSS_VAR,
+ resolveMeasureFont,
+} from "./measureFontScope";
+import { useHydrated } from "./useHydrated";
+import { useIsomorphicLayoutEffect } from "./useIsomorphicLayoutEffect";
+
+// document.fonts one-shot store: canvas measureText before the webfont loads
+// uses fallback-font metrics, so every budget must re-measure once real
+// metrics exist. Module-level so the subscribe identity is stable.
+const subscribeFontsReady = (onStoreChange: () => void) => {
+ if (typeof document === "undefined" || document.fonts?.status === "loaded") {
+ return () => {};
+ }
+ let active = true;
+ document.fonts?.ready.then(() => {
+ if (active) onStoreChange();
+ });
+ return () => {
+ active = false;
+ };
+};
+const getFontsReady = () => typeof document !== "undefined" && document.fonts?.status === "loaded";
+const getServerFontsReady = () => false;
+
+export const useCanvasContextForLabelSize = (scopeRef?: React.RefObject<HTMLElement | null>) => {
+ const { theme: userTheme } = useTheme();
+ const hydrated = useHydrated();
+ const contextScope = useContext(MeasureFontScopeContext);
+ const fontsReady = useSyncExternalStore(subscribeFontsReady, getFontsReady, getServerFontsReady);
+ // Orchestrator hooks pass their container ref explicitly (they run above
+ // the providers); components inside ChartShell/CartesianChartLayout inherit
+ // the shell's scope via context.
+ const scope = scopeRef ?? contextScope;
+
+ // Refs attach at COMMIT, after the render that computes the memo below. On
+ // an SSR page the hydrated flip re-renders post-commit so the ref is
+ // dereferenceable in time — but on a chart mounted into an ALREADY-hydrated
+ // page (a streamed chat response, a slide mounted on deck navigation)
+ // hydrated and fontsReady are both true from the first render and nothing
+ // would ever re-key the memo: the scope element would stay null and the
+ // render-channel font would silently never be read (the theme fallback
+ // would stick for the component's lifetime). Read the ref after every
+ // commit into state — the bail-out keeps it a no-op except when the element
+ // actually appears/changes — so the memo always re-keys once the scope is
+ // real. Layout-effect timing re-measures before paint (no fallback-font
+ // frame).
+ const [scopeEl, setScopeEl] = useState<HTMLElement | null>(null);
+ useIsomorphicLayoutEffect(() => {
+ setScopeEl((prev) => {
+ const el = scope?.current ?? null;
+ return prev === el ? prev : el;
+ });
+ });
+
+ return useMemo(() => {
+ const themeFont = userTheme.textLabelXs;
+
+ // Stub on the server AND during the hydration render, so every canvas
+ // measurement produces the same geometry the server HTML carries — a
+ // `typeof document` branch alone made the hydration render measure REAL
+ // text, mismatching the server's zero-width measurements (and React never
+ // patches mismatched attributes: the DOM kept the stale server values).
+ // Returns zero-width measurements but preserves the font string so
+ // parseLineHeight can derive correct line-height on both sides.
+ // Note: only measureText and font are implemented — other
+ // CanvasRenderingContext2D methods are not available on this stub.
+ // (!hydrated alone covers SSR; the document check additionally guards
+ // document-less client-style renderers, e.g. react-test-renderer.)
+ if (!hydrated || typeof document === "undefined") {
+ return {
+ measureText: () => ({ width: 0 }),
+ font: resolveMeasureFont(null, themeFont),
+ } as unknown as CanvasRenderingContext2D;
+ }
+
+ // Measure with the font the ticks RENDER with: the same CSS custom
+ // property the svg-tick-label mixin applies, read from the chart's own
+ // scope element so theme-provider class scoping (e.g. a presentation
+ // slide's 20px tokens) is honored. The JS theme token is only the
+ // fallback — see measureFontScope.ts for why the CSS channel must win.
+ const scopeStyle = scopeEl ? getComputedStyle(scopeEl) : null;
+ const font = resolveMeasureFont(scopeStyle?.getPropertyValue(TICK_FONT_CSS_VAR), themeFont);
+ const letterSpacing = scopeStyle?.getPropertyValue(TICK_LETTER_SPACING_CSS_VAR).trim();
+
+ const canvas = document.createElement("canvas");
+ const context = canvas.getContext("2d")!;
+ context.font = font;
+ // Rendered ticks also carry the theme's letter-spacing; canvas measureText
+ // ignores it unless set explicitly. Supported in all evergreen browsers;
+ // invalid/empty values are safely ignored by the setter's CSS parsing.
+ if (letterSpacing && "letterSpacing" in context) {
+ (context as CanvasRenderingContext2D & { letterSpacing: string }).letterSpacing =
+ letterSpacing;
+ }
+ // Same shape as the stub: measureText delegating to the real context,
+ // plus the ORIGINAL font string. The canvas spec strips line-height in
+ // the font getter (setting '400 12px/1.25 Inter' reads back without
+ // '/1.25'), so consumers calling parseLineHeight(ctx.font) on the raw
+ // context silently fell to the 1.2× fallback and the theme line-height
+ // was never honored client-side.
+ return {
+ measureText: (text: string) => context.measureText(text),
+ font,
+ } as unknown as CanvasRenderingContext2D;
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- `fontsReady` is a deliberate re-key trigger: its value isn't read in the body, but flipping false→true must rebuild the context so budgets re-measure with real webfont metrics
+ }, [userTheme.textLabelXs, hydrated, scopeEl, fontsReady]);
+};
diff --git a/packages/react-ui/src/components/D3Charts/hooks/core/useCategoricalChartData.ts b/packages/react-ui/src/components/D3Charts/hooks/core/useCategoricalChartData.ts
new file mode 100644
index 000000000..463af6d9b
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/core/useCategoricalChartData.ts
@@ -0,0 +1,108 @@
+import { useMemo } from "react";
+
+import type { ChartColorPalette } from "../../../ThemeProvider";
+import type { ChartData, LegendItem } from "../../types";
+import { useChartPalette } from "../../utils/paletteUtils";
+import { sortByValueDescending } from "../../utils/polarUtils";
+import { useSeriesVisibility } from "./useSeriesVisibility";
+
+export interface CategoricalSlice {
+ label: string;
+ value: number;
+ color: string;
+ percentage: number;
+}
+
+export interface UseCategoricalChartDataParams<T extends ChartData> {
+ data: T;
+ categoryKey: keyof T[number];
+ dataKey: keyof T[number];
+ themePaletteName: keyof ChartColorPalette;
+ customPalette?: string[];
+ format?: "number" | "percentage";
+}
+
+export function useCategoricalChartData<T extends ChartData>({
+ data,
+ categoryKey,
+ dataKey,
+ themePaletteName,
+ customPalette,
+ format = "number",
+}: UseCategoricalChartDataParams<T>) {
+ const catKey = String(categoryKey);
+ const valKey = String(dataKey);
+
+ const sortedData = useMemo(() => sortByValueDescending(data, valKey), [data, valKey]);
+
+ // Slices toggle by LABEL through the same machinery series use — one
+ // last-visible guard implementation instead of two drifting copies.
+ const sliceLabels = useMemo(
+ () => sortedData.map((row) => String(row[catKey])),
+ [sortedData, catKey],
+ );
+ const { hiddenSeries: hiddenSlices, toggleSeries: toggleSlice } =
+ useSeriesVisibility(sliceLabels);
+
+ const colors = useChartPalette({
+ customPalette,
+ themePaletteName,
+ dataLength: sortedData.length,
+ });
+
+ const total = useMemo(
+ () =>
+ sortedData.reduce((sum, row) => {
+ if (hiddenSlices.has(String(row[catKey]))) return sum;
+ return sum + (Number(row[valKey]) || 0);
+ }, 0),
+ [sortedData, catKey, valKey, hiddenSlices],
+ );
+
+ const slices: CategoricalSlice[] = useMemo(
+ () =>
+ sortedData.map((row, i) => {
+ const value = Number(row[valKey]) || 0;
+ return {
+ label: String(row[catKey]),
+ value,
+ color: colors[i] ?? "#000",
+ percentage: total > 0 ? (value / total) * 100 : 0,
+ };
+ }),
+ [sortedData, catKey, valKey, colors, total],
+ );
+
+ const legendItems: LegendItem[] = useMemo(
+ () =>
+ slices.map((s) => ({
+ key: s.label,
+ label: s.label,
+ color: s.color,
+ percentage: format === "percentage" ? s.percentage : undefined,
+ })),
+ [slices, format],
+ );
+
+ const chartStyle = useMemo(() => {
+ return slices.reduce(
+ (styles, s, i) => ({
+ ...styles,
+ [`--slice-color-${i}`]: s.color,
+ }),
+ {} as Record<string, string>,
+ );
+ }, [slices]);
+
+ return {
+ catKey,
+ valKey,
+ sortedData,
+ slices,
+ total,
+ hiddenSlices,
+ toggleSlice,
+ legendItems,
+ chartStyle,
+ };
+}
diff --git a/packages/react-ui/src/components/D3Charts/hooks/core/useChartData.ts b/packages/react-ui/src/components/D3Charts/hooks/core/useChartData.ts
new file mode 100644
index 000000000..5ec89856c
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/core/useChartData.ts
@@ -0,0 +1,90 @@
+import React, { useMemo } from "react";
+
+import { get2dChartConfig, getDataKeys, getLegendItems } from "../../utils/dataUtils";
+import { useChartPalette } from "../../utils/paletteUtils";
+import { useSeriesVisibility } from "./useSeriesVisibility";
+import { useTransformedKeys } from "./useTransformedKeys";
+
+import type { ChartColorPalette } from "../../../ThemeProvider";
+import type { ChartData } from "../../types";
+
+export interface UseChartDataParams<T extends ChartData> {
+ data: T;
+ categoryKey: keyof T[number];
+ themePaletteName: keyof ChartColorPalette;
+ customPalette?: string[];
+ icons?: Partial<Record<keyof T[number], React.ComponentType>>;
+}
+
+export function useChartData<T extends ChartData>({
+ data,
+ categoryKey,
+ themePaletteName,
+ customPalette,
+ icons,
+}: UseChartDataParams<T>) {
+ const catKey = String(categoryKey);
+ const allDataKeys = useMemo(() => getDataKeys(data, catKey), [data, catKey]);
+
+ const { hiddenSeries, toggleSeries } = useSeriesVisibility(allDataKeys);
+ const dataKeys = useMemo(
+ () => allDataKeys.filter((k) => !hiddenSeries.has(k)),
+ [allDataKeys, hiddenSeries],
+ );
+
+ const colors = useChartPalette({
+ customPalette,
+ themePaletteName,
+ dataLength: allDataKeys.length,
+ });
+
+ const transformedKeys = useTransformedKeys(allDataKeys);
+
+ const chartConfig = useMemo(
+ () => get2dChartConfig(allDataKeys, colors, transformedKeys, icons),
+ [allDataKeys, colors, transformedKeys, icons],
+ );
+
+ const colorMap = useMemo(() => {
+ return allDataKeys.reduce(
+ (map, key) => {
+ map[key] = chartConfig[key]?.color ?? "#000";
+ return map;
+ },
+ {} as Record<string, string>,
+ );
+ }, [allDataKeys, chartConfig]);
+
+ const chartStyle = useMemo(() => {
+ return allDataKeys.reduce(
+ (styles, key) => {
+ const transformedKey = transformedKeys[key];
+ const color = chartConfig[key]?.color;
+ return {
+ ...styles,
+ [`--color-${transformedKey}`]: color,
+ };
+ },
+ {} as Record<string, string | undefined>,
+ );
+ }, [allDataKeys, transformedKeys, chartConfig]);
+
+ const legendItems = useMemo(
+ () => getLegendItems(allDataKeys, colors, icons),
+ [allDataKeys, colors, icons],
+ );
+
+ return {
+ catKey,
+ allDataKeys,
+ dataKeys,
+ hiddenSeries,
+ toggleSeries,
+ colors,
+ transformedKeys,
+ chartConfig,
+ colorMap,
+ chartStyle,
+ legendItems,
+ };
+}
diff --git a/packages/react-ui/src/components/D3Charts/hooks/core/useChartHover.ts b/packages/react-ui/src/components/D3Charts/hooks/core/useChartHover.ts
new file mode 100644
index 000000000..879ba6fe3
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/core/useChartHover.ts
@@ -0,0 +1,72 @@
+import { pointer } from "d3-selection";
+import React, { useCallback, useState } from "react";
+
+import type { ChartData } from "../../types";
+
+export interface UseChartHoverParams<T extends ChartData> {
+ data: T;
+ onClick?: (row: T[number], index: number) => void;
+}
+
+export function useChartHover<T extends ChartData>({ data, onClick }: UseChartHoverParams<T>) {
+ const [hoveredIndex, setHoveredIndex] = useState<number | null>(null);
+ const [mousePos, setMousePos] = useState<{ x: number; y: number } | null>(null);
+
+ const createMouseHandlers = useCallback(
+ // 2D on purpose: radar's angular hit-test needs (x, y); cartesian callers
+ // pass 1-arg findIndex functions, which are assignable (TS arity
+ // contravariance) — this replaced a 95%-verbatim useRadarHover fork.
+ (findIndex: (mouseX: number, mouseY: number) => number) => {
+ const handleMouseMove = (event: React.MouseEvent<SVGElement>) => {
+ const [mouseX, mouseY] = pointer(event.nativeEvent, event.currentTarget);
+ setHoveredIndex(findIndex(mouseX, mouseY));
+ setMousePos({ x: event.clientX, y: event.clientY });
+ };
+
+ const handleMouseLeave = () => {
+ setHoveredIndex(null);
+ setMousePos(null);
+ };
+
+ const handleTouchMove = (event: React.TouchEvent<SVGElement>) => {
+ const touch = event.touches[0];
+ if (!touch) return;
+ const svgRect = event.currentTarget.getBoundingClientRect();
+ const mouseX = touch.clientX - svgRect.left;
+ const mouseY = touch.clientY - svgRect.top;
+ setHoveredIndex(findIndex(mouseX, mouseY));
+ setMousePos({ x: touch.clientX, y: touch.clientY });
+ };
+
+ const handleTouchEnd = () => {
+ setHoveredIndex(null);
+ setMousePos(null);
+ };
+
+ const handleClick = onClick
+ ? (event: React.MouseEvent<SVGElement>) => {
+ const [mouseX, mouseY] = pointer(event.nativeEvent, event.currentTarget);
+ const idx = findIndex(mouseX, mouseY);
+ if (idx >= 0 && idx < data.length) {
+ onClick(data[idx]!, idx);
+ }
+ }
+ : undefined;
+
+ return {
+ handleMouseMove,
+ handleMouseLeave,
+ handleTouchMove,
+ handleTouchEnd,
+ handleClick,
+ };
+ },
+ [onClick, data],
+ );
+
+ return {
+ hoveredIndex,
+ mousePos,
+ createMouseHandlers,
+ };
+}
diff --git a/packages/react-ui/src/components/D3Charts/hooks/core/useChartShell.ts b/packages/react-ui/src/components/D3Charts/hooks/core/useChartShell.ts
new file mode 100644
index 000000000..a4bcfbec4
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/core/useChartShell.ts
@@ -0,0 +1,75 @@
+import React, { useState } from "react";
+
+import { resolveShouldFitLegend } from "../../utils/resolveShouldFitLegend";
+import { useContainerSize } from "./useContainerSize";
+import { useLegendHeight } from "./useLegendHeight";
+import { usePrintContext } from "./usePrintContext";
+
+interface UseChartShellParams {
+ /** Row data; the default emptiness test is `!data || data.length === 0`. */
+ data: readonly unknown[] | null | undefined;
+ showLegend: boolean;
+ /** Created by the orchestrator (it may own extra refs) and passed in. */
+ containerRef: React.RefObject<HTMLDivElement | null>;
+ legendRef: React.RefObject<HTMLDivElement | null>;
+ width?: number | string;
+ height?: number | string;
+ fitLegendInHeight?: boolean;
+ /**
+ * Override the default emptiness test. Heatmap is also empty when row 0 has
+ * no series keys (`getDataKeys(...).length === 0`), which a row count alone
+ * cannot see.
+ */
+ isEmptyOverride?: boolean;
+}
+
+/**
+ * The measurement + emptiness + legend preamble shared by the five
+ * non-cartesian orchestrators (funnel / scatter / heatmap / the categorical
+ * pie & radial / radar). Owns the persistent container's measured size, the
+ * empty-state flag, the legend-height deduction, and the legend-expanded
+ * toggle.
+ *
+ * The container/legend refs are created BY the orchestrator and passed in — an
+ * orchestrator may own extra refs (heatmap's color-scale strip) and must keep
+ * them adjacent. `useCanvasContextForLabelSize` is deliberately NOT folded in:
+ * only the three cartesian-geometry charts (funnel/scatter/heatmap) need it,
+ * and the polar charts (categorical/radar) do not call it at all.
+ */
+export function useChartShell({
+ data,
+ showLegend,
+ containerRef,
+ legendRef,
+ width,
+ height,
+ fitLegendInHeight,
+ isEmptyOverride,
+}: UseChartShellParams) {
+ const [isLegendExpanded, setIsLegendExpanded] = useState(false);
+ const isPrinting = usePrintContext();
+ const { width: containerWidth, height: containerHeight } = useContainerSize(
+ containerRef,
+ width,
+ height,
+ );
+ // Empty = placeholder instead of the chart. The measured container stays
+ // mounted through this state (a stream's first frame is empty; unmounting the
+ // observed node freezes ResizeObserver-fed sizes at 0 for the component's
+ // life), but the legend DOES unmount — flipping its measurement toggle with
+ // emptiness re-runs the observer effect against the remounted node.
+ const isEmpty = isEmptyOverride ?? (!data || data.length === 0);
+ const legendHeight = useLegendHeight(legendRef, showLegend && !isEmpty);
+ const shouldFitLegend = resolveShouldFitLegend(fitLegendInHeight, height);
+
+ return {
+ isPrinting,
+ containerWidth,
+ containerHeight,
+ isEmpty,
+ legendHeight,
+ shouldFitLegend,
+ isLegendExpanded,
+ setIsLegendExpanded,
+ };
+}
diff --git a/packages/react-ui/src/components/D3Charts/hooks/core/useContainerSize.ts b/packages/react-ui/src/components/D3Charts/hooks/core/useContainerSize.ts
new file mode 100644
index 000000000..f5ad3bfd0
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/core/useContainerSize.ts
@@ -0,0 +1,45 @@
+import { useEffect, useState } from "react";
+
+export function useContainerSize(
+ ref: React.RefObject<HTMLElement | null>,
+ fixedWidth?: number | string,
+ fixedHeight?: number | string,
+): { width: number; height: number } {
+ const [size, setSize] = useState({ width: 0, height: 0 });
+
+ const numericWidth = typeof fixedWidth === "number" ? fixedWidth : undefined;
+ const numericHeight = typeof fixedHeight === "number" ? fixedHeight : undefined;
+
+ useEffect(() => {
+ if ((numericWidth && numericHeight) || !ref.current) return;
+
+ const observer = new ResizeObserver((entries) => {
+ for (const entry of entries) {
+ setSize({
+ width: entry.contentRect.width,
+ height: entry.contentRect.height,
+ });
+ }
+ });
+
+ observer.observe(ref.current);
+ // Seed with LAYOUT px (clientWidth/clientHeight), not getBoundingClientRect
+ // (VISUAL px). Under a CSS `transform: scale(...)` on an ancestor — e.g. the
+ // slide canvas — getBoundingClientRect returns the scaled size, so the chart
+ // would seed at the wrong (scaled) size for the frame before the observer
+ // fires. clientWidth/clientHeight are transform-invariant and exclude
+ // borders, matching the observer's contentRect for these borderless
+ // containers, so the seed and steady-state size agree.
+ setSize({
+ width: ref.current.clientWidth,
+ height: ref.current.clientHeight,
+ });
+
+ return () => observer.disconnect();
+ }, [numericWidth, numericHeight, ref]);
+
+ return {
+ width: numericWidth ?? size.width,
+ height: numericHeight ?? (typeof fixedHeight === "string" ? size.height : 0),
+ };
+}
diff --git a/packages/react-ui/src/components/D3Charts/hooks/core/useEffectiveAnimation.ts b/packages/react-ui/src/components/D3Charts/hooks/core/useEffectiveAnimation.ts
new file mode 100644
index 000000000..986d09d03
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/core/useEffectiveAnimation.ts
@@ -0,0 +1,13 @@
+import { usePrintContext } from "./usePrintContext";
+
+/**
+ * The single source of "should entrance animations run":
+ * `isAnimationActive ∧ ¬printing`. Every chart entry folds its public prop
+ * through this once and hands parts ONE pre-folded boolean — parts never see
+ * isPrinting. This is also the seam where a future global entrance policy
+ * (e.g. a reduced-motion gate, decision D-3) would live.
+ */
+export function useEffectiveAnimation(isAnimationActive: boolean): boolean {
+ const isPrinting = usePrintContext();
+ return isAnimationActive && !isPrinting;
+}
diff --git a/packages/react-ui/src/components/D3Charts/hooks/core/useExportChartData.test.ts b/packages/react-ui/src/components/D3Charts/hooks/core/useExportChartData.test.ts
new file mode 100644
index 000000000..f7b41b683
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/core/useExportChartData.test.ts
@@ -0,0 +1,209 @@
+import { createElement } from "react";
+import { describe, expect, it } from "vitest";
+
+import { buildExportChartData } from "./useExportChartData";
+
+// Unit tests for the PURE builder only (node env, no DOM). The gated hook
+// (`useExportChartData`) needs a react-ui <PrintContextProvider> to return a
+// string and is exercised at runtime, not here — see the report's behavior
+// guard for how the "undefined outside the provider" contract is verified.
+
+const twoSeriesData = [
+ { month: "Jan", sales: 10, profit: 4 },
+ { month: "Feb", sales: 20, profit: 8 },
+ { month: "Mar", sales: 15, profit: 6 },
+];
+
+describe("buildExportChartData — 2D (cartesian) shape", () => {
+ it("emits one series per dataKey with per-row labels and numeric values", () => {
+ const result = buildExportChartData({
+ type: "bar",
+ data: twoSeriesData,
+ categoryKey: "month",
+ dataKeys: ["sales", "profit"],
+ colors: ["#111", "#222"],
+ legend: true,
+ });
+
+ expect(result.type).toBe("bar");
+ expect(result.data).toEqual([
+ {
+ name: "sales",
+ labels: ["Jan", "Feb", "Mar"],
+ values: [10, 20, 15],
+ },
+ {
+ name: "profit",
+ labels: ["Jan", "Feb", "Mar"],
+ values: [4, 8, 6],
+ },
+ ]);
+ });
+
+ it("coerces label values to strings and cell values to numbers", () => {
+ const result = buildExportChartData({
+ type: "line",
+ data: [
+ { year: 2024, value: "100" },
+ { year: 2025, value: "200" },
+ ],
+ categoryKey: "year",
+ dataKeys: ["value"],
+ colors: ["#abc"],
+ });
+
+ // Category 2024 (a number) becomes the string "2024"; the string "100"
+ // becomes the number 100 — mirroring react-ui's String()/Number() coercion.
+ expect(result.data[0]?.labels).toEqual(["2024", "2025"]);
+ expect(result.data[0]?.values).toEqual([100, 200]);
+ });
+
+ it("emits empty-string labels when no categoryKey is supplied", () => {
+ const result = buildExportChartData({
+ type: "bar",
+ data: twoSeriesData,
+ dataKeys: ["sales"],
+ colors: ["#111"],
+ });
+
+ expect(result.data[0]?.labels).toEqual(["", "", ""]);
+ expect(result.data[0]?.values).toEqual([10, 20, 15]);
+ });
+
+ it("emits an empty data array when dataKeys is omitted", () => {
+ const result = buildExportChartData({
+ type: "area",
+ data: twoSeriesData,
+ categoryKey: "month",
+ colors: [],
+ });
+
+ expect(result.data).toEqual([]);
+ });
+});
+
+describe("buildExportChartData — 1D (pie/radial) shape", () => {
+ it("emits a single series keyed by the value dataKey", () => {
+ const pieData = [
+ { region: "North", revenue: 300 },
+ { region: "South", revenue: 150 },
+ { region: "East", revenue: 50 },
+ ];
+
+ const result = buildExportChartData({
+ type: "pie",
+ data: pieData,
+ categoryKey: "region",
+ dataKeys: ["revenue"],
+ colors: ["#a", "#b", "#c"],
+ legend: true,
+ });
+
+ expect(result.type).toBe("pie");
+ expect(result.data).toEqual([
+ {
+ name: "revenue",
+ labels: ["North", "South", "East"],
+ values: [300, 150, 50],
+ },
+ ]);
+ });
+});
+
+describe("buildExportChartData — axis titles (string vs non-string)", () => {
+ it("populates cat/val titles and their show-flags when labels are strings", () => {
+ const result = buildExportChartData({
+ type: "bar",
+ data: twoSeriesData,
+ categoryKey: "month",
+ dataKeys: ["sales"],
+ colors: ["#111"],
+ xAxisLabel: "Month",
+ yAxisLabel: "Sales ($)",
+ });
+
+ expect(result.options?.catAxisTitle).toBe("Month");
+ expect(result.options?.showCatAxisTitle).toBe(true);
+ expect(result.options?.valAxisTitle).toBe("Sales ($)");
+ expect(result.options?.showValAxisTitle).toBe(true);
+ });
+
+ it("omits titles and sets show-flags false when labels are non-string nodes", () => {
+ const result = buildExportChartData({
+ type: "bar",
+ data: twoSeriesData,
+ categoryKey: "month",
+ dataKeys: ["sales"],
+ colors: ["#111"],
+ // A React element is not a string → title undefined, flag false.
+ xAxisLabel: createElement("span", null, "Month"),
+ yAxisLabel: undefined,
+ });
+
+ expect(result.options?.catAxisTitle).toBeUndefined();
+ expect(result.options?.showCatAxisTitle).toBe(false);
+ expect(result.options?.valAxisTitle).toBeUndefined();
+ expect(result.options?.showValAxisTitle).toBe(false);
+ });
+});
+
+describe("buildExportChartData — options passthrough", () => {
+ it("carries chartColors and showLegend straight through", () => {
+ const result = buildExportChartData({
+ type: "line",
+ data: twoSeriesData,
+ categoryKey: "month",
+ dataKeys: ["sales"],
+ colors: ["#f00", "#0f0", "#00f"],
+ legend: false,
+ });
+
+ expect(result.options?.chartColors).toEqual(["#f00", "#0f0", "#00f"]);
+ expect(result.options?.showLegend).toBe(false);
+ });
+
+ it("merges extraOptions (barDir) after the base options", () => {
+ const result = buildExportChartData({
+ type: "bar",
+ data: twoSeriesData,
+ categoryKey: "month",
+ dataKeys: ["sales"],
+ colors: ["#111"],
+ extraOptions: { barDir: "bar" },
+ });
+
+ expect(result.options?.barDir).toBe("bar");
+ // Base options survive alongside the merged extras.
+ expect(result.options?.chartColors).toEqual(["#111"]);
+ });
+
+ it("supports both barDir and barGrouping via extraOptions", () => {
+ const result = buildExportChartData({
+ type: "bar",
+ data: twoSeriesData,
+ categoryKey: "month",
+ dataKeys: ["sales"],
+ colors: ["#111"],
+ extraOptions: { barDir: "bar", barGrouping: "stacked" },
+ });
+
+ expect(result.options?.barDir).toBe("bar");
+ expect(result.options?.barGrouping).toBe("stacked");
+ });
+});
+
+describe("buildExportChartData — customDataTransform", () => {
+ it("uses the custom transform in place of the default dataKeys mapping", () => {
+ const custom = [{ name: "series", x: [1, 2], y: [3, 4] }];
+
+ const result = buildExportChartData({
+ type: "scatter",
+ data: twoSeriesData,
+ dataKeys: ["sales"], // ignored when customDataTransform is provided
+ colors: ["#111"],
+ customDataTransform: () => custom,
+ });
+
+ expect(result.data).toBe(custom);
+ });
+});
diff --git a/packages/react-ui/src/components/D3Charts/hooks/core/useExportChartData.ts b/packages/react-ui/src/components/D3Charts/hooks/core/useExportChartData.ts
new file mode 100644
index 000000000..7dac676e0
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/core/useExportChartData.ts
@@ -0,0 +1,140 @@
+import { useMemo } from "react";
+
+import type { ExportChartData } from "../../../Charts/Charts";
+// react-ui's PRINT CONTEXT (a React context; falsy outside
+// <PrintContextProvider>). Deliberately NOT the D3Charts-local
+// `usePrintContext` (hooks/core/usePrintContext.ts) — that one is a
+// media-query hook returning a boolean for `@media print`, a different
+// concern. The PPTX export emitter must gate on the SAME provider react-ui's
+// charts do, so the c1 print pipeline drives both identically.
+import { usePrintContext as useReactUiPrintContext } from "../../../../context/PrintContext";
+
+/**
+ * Props for the print-export emitter — a 1:1 mirror of react-ui's
+ * `useExportChartData` (packages/react-ui/src/components/Charts/hooks/
+ * useExportChartData.ts) so viz charts, once they replace react-ui's in the c1
+ * artifacts, keep emitting byte-identical `data-openui-chart` JSON.
+ */
+export interface UseExportChartDataProps {
+ type: ExportChartData["type"];
+ data: Array<Record<string, unknown>>;
+ categoryKey?: string;
+ dataKeys?: string[];
+ colors: string[];
+ legend?: boolean;
+ xAxisLabel?: React.ReactNode;
+ yAxisLabel?: React.ReactNode;
+ extraOptions?: Omit<
+ NonNullable<ExportChartData["options"]>,
+ "chartColors" | "showLegend" | "catAxisTitle" | "valAxisTitle"
+ >;
+ /** For specialized charts (e.g. scatter) that shape their series manually. */
+ customDataTransform?: () => ExportChartData["data"];
+}
+
+/**
+ * PURE transform: props → the `ExportChartData` object. Extracted from the
+ * hook so it can be unit-tested without a React/DOM environment (the hook
+ * itself needs a provider and is exercised at runtime). Mirrors react-ui's
+ * in-hook `useMemo` body exactly:
+ * • 2D charts → one series per `dataKeys` entry, `labels` = the category
+ * value of every row, `values` = `Number(row[key])` of every row.
+ * • options → `chartColors`, `showLegend`, the cat/val axis-title pair
+ * (present only when the label is a string), then `...extraOptions`.
+ */
+export function buildExportChartData({
+ type,
+ data,
+ categoryKey,
+ dataKeys,
+ colors,
+ legend,
+ xAxisLabel,
+ yAxisLabel,
+ extraOptions,
+ customDataTransform,
+}: UseExportChartDataProps): ExportChartData {
+ const chartData: ExportChartData["data"] = customDataTransform
+ ? customDataTransform()
+ : (dataKeys || []).map((key) => ({
+ name: key,
+ labels: data.map((item) => (categoryKey ? String(item[categoryKey]) : "")),
+ values: data.map((item) => Number(item[key])),
+ }));
+
+ return {
+ type,
+ data: chartData,
+ options: {
+ chartColors: colors,
+ showLegend: legend,
+ catAxisTitle: typeof xAxisLabel === "string" ? xAxisLabel : undefined,
+ showCatAxisTitle: typeof xAxisLabel === "string",
+ valAxisTitle: typeof yAxisLabel === "string" ? yAxisLabel : undefined,
+ showValAxisTitle: typeof yAxisLabel === "string",
+ ...extraOptions,
+ },
+ };
+}
+
+/**
+ * Emits the `data-openui-chart` payload for PPTX export — the viz-side twin of
+ * react-ui's `useExportChartData`. Returns the JSON string ONLY inside a
+ * react-ui `<PrintContextProvider>` (the export path); `undefined` otherwise,
+ * so a chart binding `data-openui-chart={exportData}` drops the attribute
+ * entirely off the print path (React omits `undefined` attributes). Charts that
+ * pass the result to a container which sets its own `data-openui-chart` (the
+ * cartesian layout does) let this value take precedence when defined.
+ */
+export const useExportChartData = (props: UseExportChartDataProps): string | undefined => {
+ const printContext = useReactUiPrintContext();
+
+ const {
+ type,
+ data,
+ categoryKey,
+ dataKeys,
+ colors,
+ legend,
+ xAxisLabel,
+ yAxisLabel,
+ extraOptions,
+ customDataTransform,
+ } = props;
+
+ // Mirror react-ui's dependency list exactly (the destructured fields + the
+ // print context). The memo body reads only these locals, so the dep array is
+ // honest — no exhaustive-deps suppression needed (and that rule is not enabled
+ // in this package's eslint config anyway).
+ return useMemo(() => {
+ if (!printContext) {
+ return undefined;
+ }
+ return JSON.stringify(
+ buildExportChartData({
+ type,
+ data,
+ categoryKey,
+ dataKeys,
+ colors,
+ legend,
+ xAxisLabel,
+ yAxisLabel,
+ extraOptions,
+ customDataTransform,
+ }),
+ );
+ }, [
+ type,
+ data,
+ dataKeys,
+ categoryKey,
+ colors,
+ legend,
+ xAxisLabel,
+ yAxisLabel,
+ extraOptions,
+ customDataTransform,
+ printContext,
+ ]);
+};
diff --git a/packages/react-ui/src/components/D3Charts/hooks/core/useHydrated.ts b/packages/react-ui/src/components/D3Charts/hooks/core/useHydrated.ts
new file mode 100644
index 000000000..8b88dbd70
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/core/useHydrated.ts
@@ -0,0 +1,24 @@
+import { useSyncExternalStore } from "react";
+
+const emptySubscribe = () => () => {};
+
+/**
+ * False during SSR AND during the hydration render — so server HTML and the
+ * first client render agree — then true immediately after hydration (React
+ * re-renders subscribers when the server snapshot differs). On pure client
+ * mounts (no SSR) it is true from the very first render, so client-only
+ * consumers pay nothing.
+ *
+ * Use this instead of `typeof window` checks for anything that affects
+ * RENDERED OUTPUT (measured widths, label geometry): a `typeof window` branch
+ * flips between the server render and the hydration render, which is exactly
+ * the hydration-mismatch React warns about — and mismatched attributes are
+ * never patched, so the DOM keeps the stale server value forever.
+ */
+export function useHydrated(): boolean {
+ return useSyncExternalStore(
+ emptySubscribe,
+ () => true,
+ () => false,
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/hooks/core/useIndexedClickHandler.ts b/packages/react-ui/src/components/D3Charts/hooks/core/useIndexedClickHandler.ts
new file mode 100644
index 000000000..1d339964c
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/core/useIndexedClickHandler.ts
@@ -0,0 +1,14 @@
+import { useCallback } from "react";
+
+/**
+ * The click handler shared by the single-element painters (pie / radial /
+ * funnel): map a clicked element's index back to its data item and forward it.
+ * No-ops when `onClick` is absent. (The heatmap's handler is 3-arg —
+ * row/column/key — and stays bespoke.)
+ */
+export function useIndexedClickHandler<T>(
+ items: T[],
+ onClick?: (item: T, index: number) => void,
+): (index: number) => void {
+ return useCallback((index: number) => onClick?.(items[index]!, index), [onClick, items]);
+}
diff --git a/packages/react-ui/src/components/D3Charts/hooks/core/useIsomorphicLayoutEffect.ts b/packages/react-ui/src/components/D3Charts/hooks/core/useIsomorphicLayoutEffect.ts
new file mode 100644
index 000000000..a8f29a42d
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/core/useIsomorphicLayoutEffect.ts
@@ -0,0 +1,10 @@
+import { useEffect, useLayoutEffect } from "react";
+
+// useLayoutEffect on the client, useEffect on the server (avoids React's SSR
+// dev warning; the server never fires effects either way). The ONE shared
+// SSR-safe layout effect for the package — do not re-alias this locally.
+// Used by the spring followers (seed/aim a position before paint so a newly
+// shown follower never flashes from the origin) and by measurement hooks that
+// must read the DOM after commit but before paint.
+export const useIsomorphicLayoutEffect =
+ typeof window !== "undefined" ? useLayoutEffect : useEffect;
diff --git a/packages/react-ui/src/components/D3Charts/hooks/core/useLegendHeight.ts b/packages/react-ui/src/components/D3Charts/hooks/core/useLegendHeight.ts
new file mode 100644
index 000000000..5ce0aca66
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/core/useLegendHeight.ts
@@ -0,0 +1,37 @@
+import React, { useEffect, useState } from "react";
+
+/**
+ * Observed height of a legend-like element below the chart.
+ *
+ * `showLegend` is the ONLY live dependency — `legendRef` is a stable useRef
+ * object, so the effect cannot see the element being swapped for a new node.
+ * Consumers that conditionally UNMOUNT the measured element (e.g. charts
+ * hiding their legend while data is empty) must therefore flip `showLegend`
+ * in lockstep (`show && !isEmpty`): the flip re-runs the effect, which
+ * re-observes whatever node is mounted by then. Without the flip, the
+ * observer would stay on the detached node and the height would go stale.
+ */
+export function useLegendHeight(
+ legendRef: React.RefObject<HTMLDivElement | null>,
+ showLegend: boolean,
+): number {
+ const [legendHeight, setLegendHeight] = useState(0);
+
+ useEffect(() => {
+ const el = legendRef.current;
+ if (!el) {
+ setLegendHeight(0);
+ return;
+ }
+ const observer = new ResizeObserver((entries) => {
+ for (const entry of entries) {
+ setLegendHeight(entry.contentRect.height);
+ }
+ });
+ observer.observe(el);
+ setLegendHeight(el.getBoundingClientRect().height);
+ return () => observer.disconnect();
+ }, [showLegend, legendRef]);
+
+ return legendHeight;
+}
diff --git a/packages/react-ui/src/components/D3Charts/hooks/core/usePerElementHover.ts b/packages/react-ui/src/components/D3Charts/hooks/core/usePerElementHover.ts
new file mode 100644
index 000000000..65d2ee92b
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/core/usePerElementHover.ts
@@ -0,0 +1,31 @@
+import React, { useCallback, useState } from "react";
+
+/**
+ * Per-element hover state for the charts where each element reports its own
+ * identity on mouseover — funnel stages, pie/radial slices, heatmap cells. The
+ * painter passes the hovered item straight in (`handleMouseMove(event, item)`),
+ * so there's no hit-testing here.
+ *
+ * This is the counterpart to {@link useChartHover}, the position-based regime
+ * where an SVG-level `findIndex(x, y)` resolves the index from the pointer
+ * (radar, scatter, the cartesian line charts) — do not conflate the two.
+ *
+ * `T` defaults to `number` (the element index, used by funnel and the
+ * categorical pie/radial); heatmap passes its richer `HoveredHeatmapCell`.
+ */
+export function usePerElementHover<T = number>() {
+ const [hovered, setHovered] = useState<T | null>(null);
+ const [mousePos, setMousePos] = useState<{ x: number; y: number } | null>(null);
+
+ const handleMouseMove = useCallback((event: React.MouseEvent, item: T) => {
+ setHovered(item);
+ setMousePos({ x: event.clientX, y: event.clientY });
+ }, []);
+
+ const handleMouseLeave = useCallback(() => {
+ setHovered(null);
+ setMousePos(null);
+ }, []);
+
+ return { hovered, mousePos, handleMouseMove, handleMouseLeave };
+}
diff --git a/packages/react-ui/src/components/D3Charts/hooks/core/usePrintContext.ts b/packages/react-ui/src/components/D3Charts/hooks/core/usePrintContext.ts
new file mode 100644
index 000000000..40915abad
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/core/usePrintContext.ts
@@ -0,0 +1,27 @@
+import { useEffect, useState } from "react";
+
+/**
+ * Detects when the browser is in print mode (Ctrl+P / Cmd+P).
+ * Useful for disabling animations and ensuring the chart renders
+ * its final state for print output.
+ */
+export const usePrintContext = (): boolean => {
+ const [isPrinting, setIsPrinting] = useState(false);
+
+ useEffect(() => {
+ if (typeof window === "undefined") return;
+
+ const mediaQuery = window.matchMedia("print");
+
+ const handleChange = (e: MediaQueryListEvent) => {
+ setIsPrinting(e.matches);
+ };
+
+ setIsPrinting(mediaQuery.matches);
+
+ mediaQuery.addEventListener("change", handleChange);
+ return () => mediaQuery.removeEventListener("change", handleChange);
+ }, []);
+
+ return isPrinting;
+};
diff --git a/packages/react-ui/src/components/D3Charts/hooks/core/useSeriesVisibility.ts b/packages/react-ui/src/components/D3Charts/hooks/core/useSeriesVisibility.ts
new file mode 100644
index 000000000..34217398c
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/core/useSeriesVisibility.ts
@@ -0,0 +1,28 @@
+import { useCallback, useState } from "react";
+
+export function useSeriesVisibility(seriesKeys: string[]) {
+ const [hiddenSeries, setHiddenSeries] = useState<Set<string>>(new Set());
+
+ const toggleSeries = useCallback(
+ (key: string) => {
+ setHiddenSeries((prev) => {
+ const next = new Set(prev);
+ if (next.has(key)) {
+ next.delete(key);
+ } else {
+ // At least one series stays visible. Count only hidden keys that
+ // still exist in the CURRENT series — the set is never pruned on
+ // data swaps, and counting stale keys could block hiding a series
+ // that is visibly present.
+ const hiddenCurrent = seriesKeys.filter((k) => next.has(k)).length;
+ if (hiddenCurrent >= seriesKeys.length - 1) return prev;
+ next.add(key);
+ }
+ return next;
+ });
+ },
+ [seriesKeys],
+ );
+
+ return { hiddenSeries, toggleSeries };
+}
diff --git a/packages/react-ui/src/components/D3Charts/hooks/core/useTooltipPayload.test.ts b/packages/react-ui/src/components/D3Charts/hooks/core/useTooltipPayload.test.ts
new file mode 100644
index 000000000..23aa7410e
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/core/useTooltipPayload.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it } from "vitest";
+import { tooltipPayloadEqual, type TooltipPayload } from "./useTooltipPayload";
+
+const payload = (over: Partial<TooltipPayload> = {}): TooltipPayload => ({
+ label: "Jan",
+ items: [
+ { name: "alpha", value: 10, color: "#111" },
+ { name: "beta", value: 20, color: "#222" },
+ ],
+ ...over,
+});
+
+describe("tooltipPayloadEqual (the identity-stability key under streaming)", () => {
+ it("equal content → equal (fresh objects, fresh items arrays)", () => {
+ expect(tooltipPayloadEqual(payload(), payload())).toBe(true);
+ });
+
+ it("null handling: both null equal, one null not", () => {
+ expect(tooltipPayloadEqual(null, null)).toBe(true);
+ expect(tooltipPayloadEqual(payload(), null)).toBe(false);
+ expect(tooltipPayloadEqual(null, payload())).toBe(false);
+ });
+
+ it("any changed field breaks equality", () => {
+ expect(tooltipPayloadEqual(payload(), payload({ label: "Feb" }))).toBe(false);
+ const changedValue = payload();
+ changedValue.items[1] = { ...changedValue.items[1]!, value: 21 };
+ expect(tooltipPayloadEqual(payload(), changedValue)).toBe(false);
+ const changedColor = payload();
+ changedColor.items[0] = { ...changedColor.items[0]!, color: "#333" };
+ expect(tooltipPayloadEqual(payload(), changedColor)).toBe(false);
+ const changedName = payload();
+ changedName.items[0] = { ...changedName.items[0]!, name: "gamma" };
+ expect(tooltipPayloadEqual(payload(), changedName)).toBe(false);
+ });
+
+ it("item count changes break equality", () => {
+ const fewer = payload();
+ fewer.items = fewer.items.slice(0, 1);
+ expect(tooltipPayloadEqual(payload(), fewer)).toBe(false);
+ });
+
+ it('string values (heatmap "No value") compare by value', () => {
+ const a = payload({
+ items: [{ name: "a", value: "No value", color: "#1" }],
+ });
+ const b = payload({
+ items: [{ name: "a", value: "No value", color: "#1" }],
+ });
+ expect(tooltipPayloadEqual(a, b)).toBe(true);
+ });
+});
diff --git a/packages/react-ui/src/components/D3Charts/hooks/core/useTooltipPayload.ts b/packages/react-ui/src/components/D3Charts/hooks/core/useTooltipPayload.ts
new file mode 100644
index 000000000..caf4dcb25
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/core/useTooltipPayload.ts
@@ -0,0 +1,56 @@
+import { useMemo, useRef } from "react";
+import type { TooltipItem } from "../../shared/core/PortalTooltip/ChartTooltip";
+import type { ChartData } from "../../types";
+
+export interface TooltipPayload {
+ label: string;
+ items: TooltipItem[];
+}
+
+/**
+ * Content equality for tooltip payloads — the memo key `useTooltipPayload`
+ * uses to keep a stable object identity across data ticks. Pure; unit-tested.
+ */
+export function tooltipPayloadEqual(a: TooltipPayload | null, b: TooltipPayload | null): boolean {
+ if (a === b) return true;
+ if (a === null || b === null) return false;
+ if (a.label !== b.label || a.items.length !== b.items.length) return false;
+ for (let i = 0; i < a.items.length; i++) {
+ const x = a.items[i]!;
+ const y = b.items[i]!;
+ if (x.name !== y.name || x.value !== y.value || x.color !== y.color) {
+ return false;
+ }
+ }
+ return true;
+}
+
+export function useTooltipPayload<T extends ChartData>(
+ hoveredIndex: number | null,
+ data: T,
+ dataKeys: string[],
+ catKey: string,
+ chartConfig: Record<string, { color?: string } | undefined>,
+): TooltipPayload | null {
+ // Content-keyed identity: under streaming, `data` identity changes every
+ // tick, which used to rebuild the payload (new `items` array) even when the
+ // hovered row's values hadn't changed — defeating ChartTooltip's memo and
+ // re-rendering the portal + re-running floating-ui layout reads per frame.
+ // Reuse the previous object whenever the CONTENT is unchanged.
+ const lastRef = useRef<TooltipPayload | null>(null);
+ return useMemo(() => {
+ if (hoveredIndex === null || hoveredIndex >= data.length) return null;
+ const row = data[hoveredIndex]!;
+ const next: TooltipPayload = {
+ label: String(row[catKey]),
+ items: dataKeys.map((key) => ({
+ name: key,
+ value: Number(row[key]) || 0,
+ color: chartConfig[key]?.color ?? "#000",
+ })),
+ };
+ if (tooltipPayloadEqual(lastRef.current, next)) return lastRef.current;
+ lastRef.current = next;
+ return next;
+ }, [hoveredIndex, data, dataKeys, catKey, chartConfig]);
+}
diff --git a/packages/react-ui/src/components/D3Charts/hooks/core/useTransformedKeys.ts b/packages/react-ui/src/components/D3Charts/hooks/core/useTransformedKeys.ts
new file mode 100644
index 000000000..b124a8cb4
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/core/useTransformedKeys.ts
@@ -0,0 +1,19 @@
+import { useMemo, useRef } from "react";
+
+export const useTransformedKeys = (keys: string[]) => {
+ const nextIdRef = useRef(0);
+ const cacheRef = useRef<Record<string, string>>({});
+
+ return useMemo(() => {
+ return keys.reduce(
+ (acc, key) => {
+ if (!cacheRef.current[key]) {
+ cacheRef.current[key] = `tk-${nextIdRef.current++}`;
+ }
+ acc[key] = cacheRef.current[key];
+ return acc;
+ },
+ {} as Record<string, string>,
+ );
+ }, [keys]);
+};
diff --git a/packages/react-ui/src/components/D3Charts/hooks/index.ts b/packages/react-ui/src/components/D3Charts/hooks/index.ts
new file mode 100644
index 000000000..bd686f96d
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/index.ts
@@ -0,0 +1,3 @@
+export * from "./cartesian";
+export * from "./core";
+export * from "./polar";
diff --git a/packages/react-ui/src/components/D3Charts/hooks/polar/index.ts b/packages/react-ui/src/components/D3Charts/hooks/polar/index.ts
new file mode 100644
index 000000000..c5098141f
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/polar/index.ts
@@ -0,0 +1,2 @@
+export * from "./useCategoricalChartOrchestrator";
+export * from "./useRadarChartOrchestrator";
diff --git a/packages/react-ui/src/components/D3Charts/hooks/polar/useCategoricalChartOrchestrator.ts b/packages/react-ui/src/components/D3Charts/hooks/polar/useCategoricalChartOrchestrator.ts
new file mode 100644
index 000000000..904a9b6ce
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/polar/useCategoricalChartOrchestrator.ts
@@ -0,0 +1,237 @@
+import { useEffect, useMemo, useRef } from "react";
+
+import type { ChartColorPalette } from "../../../ThemeProvider";
+import {
+ indexToKey,
+ keyToIndex,
+ stackedItemsFromSlices,
+ useLegendBridge,
+ useLegendPublisher,
+ useResolvedLegendKey,
+} from "../../shared/core/legend";
+import type { TooltipItem } from "../../shared/core/PortalTooltip/ChartTooltip";
+import type { ChartData } from "../../types";
+import { buildContainerStyle } from "../../utils/buildContainerStyle";
+import { formatPercentage } from "../../utils/polarUtils";
+import { useCategoricalChartData } from "../core/useCategoricalChartData";
+import { useChartShell } from "../core/useChartShell";
+import { usePerElementHover } from "../core/usePerElementHover";
+
+export interface UseCategoricalChartOrchestratorParams<T extends ChartData> {
+ data: T;
+ categoryKey: keyof T[number];
+ dataKey: keyof T[number];
+ themePaletteName: keyof ChartColorPalette;
+ customPalette?: string[];
+ format?: "number" | "percentage";
+ showLegend: boolean;
+ isSemiCircular: boolean;
+ maxChartSize: number;
+ minChartSize: number;
+ height?: number | string;
+ width?: number | string;
+ fitLegendInHeight?: boolean;
+ legendKey?: string;
+}
+
+export function useCategoricalChartOrchestrator<T extends ChartData>({
+ data,
+ categoryKey,
+ dataKey,
+ themePaletteName,
+ customPalette,
+ format = "number",
+ showLegend,
+ isSemiCircular,
+ maxChartSize,
+ minChartSize,
+ height,
+ width,
+ fitLegendInHeight,
+ legendKey,
+}: UseCategoricalChartOrchestratorParams<T>) {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const legendRef = useRef<HTMLDivElement>(null);
+ const {
+ isPrinting,
+ containerWidth,
+ containerHeight,
+ isEmpty,
+ legendHeight,
+ shouldFitLegend,
+ isLegendExpanded,
+ setIsLegendExpanded,
+ } = useChartShell({
+ data,
+ showLegend,
+ containerRef,
+ legendRef,
+ width,
+ height,
+ fitLegendInHeight,
+ });
+
+ const { slices, total, hiddenSlices, toggleSlice, legendItems, chartStyle, sortedData } =
+ useCategoricalChartData({
+ data,
+ categoryKey,
+ dataKey,
+ themePaletteName,
+ customPalette,
+ format,
+ });
+
+ // Dimensions
+ const legendDeduction = showLegend && shouldFitLegend ? legendHeight : 0;
+ const availableHeight = (containerHeight || 300) - legendDeduction;
+ const availableWidth = containerWidth || 300;
+
+ const chartSize = Math.max(
+ minChartSize,
+ Math.min(maxChartSize, availableWidth, isSemiCircular ? availableHeight * 2 : availableHeight),
+ );
+
+ const svgWidth = chartSize;
+ const svgHeight = isSemiCircular ? chartSize / 2 + 10 : chartSize;
+ const centerX = svgWidth / 2;
+ const centerY = isSemiCircular ? svgHeight - 10 : svgHeight / 2;
+
+ // Hover
+ const {
+ hovered: hoveredIndex,
+ mousePos,
+ handleMouseMove,
+ handleMouseLeave,
+ } = usePerElementHover();
+
+ // ---- Legend store bridge (only active when a key resolves + a provider exists) ----
+ // The effective key is the explicit `legendKey` prop, else the nearest
+ // provider's `legendKey` default. Resolved once here so the hover-sync
+ // effect below can depend on the key that is actually in force.
+ const resolvedLegendKey = useResolvedLegendKey(legendKey);
+ const bridge = useLegendBridge(resolvedLegendKey);
+
+ // Effective hidden set: store-backed when keyed, else local hiddenSlices.
+ const effectiveHidden = bridge ? bridge.hiddenKeys : hiddenSlices;
+
+ // Publish legend items (memoized by slices so the publish effect doesn't loop).
+ // Carry `format` so a detached legend inherits the chart's value format.
+ const stackedItems = useMemo(() => stackedItemsFromSlices(slices), [slices]);
+ useLegendPublisher(legendKey, stackedItems, format);
+
+ // Visible slices
+ const visibleSlices = useMemo(
+ () => slices.filter((s) => !effectiveHidden.has(s.label)),
+ [slices, effectiveHidden],
+ );
+
+ // Keep the latest visibleSlices in a ref so the slice-hover → legend sync
+ // effect can read it without depending on its identity (see effect below).
+ const visibleSlicesRef = useRef(visibleSlices);
+ visibleSlicesRef.current = visibleSlices;
+
+ // Percentages must re-normalize over the VISIBLE set so the tooltip matches
+ // the (d3.pie-renormalized) wedge. In local mode this equals `total`; in
+ // remote mode `total` stays the grand total (toggles route to the store, not
+ // the local hiddenSlices set), so we recompute from visibleSlices here.
+ const visibleTotal = useMemo(
+ () => visibleSlices.reduce((sum, s) => sum + s.value, 0),
+ [visibleSlices],
+ );
+
+ // The original rows aligned 1:1 with visibleSlices — the parts map slices
+ // and onClick(row, index) through this parallel-arrays contract, so the
+ // filter lives HERE next to its invariant (the charts used to re-derive it
+ // inline, unmemoized, far from where visibleSlices is built).
+ const catKey = String(categoryKey);
+ const visibleRows = useMemo(
+ () => sortedData.filter((row) => !effectiveHidden.has(String(row[catKey]))),
+ [sortedData, effectiveHidden, catKey],
+ );
+
+ // Slice hover → store activeKey (so a remote legend row highlights in sync).
+ // This must fire ONLY on a LOCAL hover change — never on a `visibleSlices`
+ // identity change. A routine data re-render produces a fresh visibleSlices
+ // while hoveredIndex stays null; if that re-ran the effect it would call
+ // setActive(null) and wipe a highlight the detached legend just set. So we
+ // read visibleSlices through a ref and depend only on
+ // [hoveredIndex, resolvedLegendKey]. Deps intentionally exclude `bridge` (a
+ // fresh object each render — listing it would re-run this effect every
+ // render); `resolvedLegendKey` is the stable proxy for "the active bridge
+ // changed".
+ useEffect(() => {
+ if (!bridge) return;
+ bridge.setActive(
+ hoveredIndex != null ? indexToKey(visibleSlicesRef.current, hoveredIndex) : null,
+ );
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- `bridge` excluded on purpose, see comment above
+ }, [hoveredIndex, resolvedLegendKey]);
+
+ // Effective highlight index: local mouse hover wins; else legend-driven activeKey.
+ const effectiveHoveredIndex =
+ hoveredIndex ?? (bridge ? keyToIndex(visibleSlices, bridge.activeKey) : null);
+
+ // Tooltip
+ const tooltipPayload = useMemo(() => {
+ if (hoveredIndex === null) return null;
+ const slice = visibleSlices[hoveredIndex];
+ if (!slice) return null;
+
+ const items: TooltipItem[] = [
+ {
+ name: slice.label,
+ value:
+ format === "percentage"
+ ? parseFloat(formatPercentage(slice.value, visibleTotal))
+ : slice.value,
+ color: slice.color,
+ },
+ ];
+
+ return { label: slice.label, items };
+ }, [hoveredIndex, visibleSlices, format, visibleTotal]);
+
+ // Container style
+ const containerStyle = useMemo(
+ () => buildContainerStyle(chartStyle, width, height),
+ [chartStyle, width, height],
+ );
+
+ return {
+ refs: { containerRef, legendRef },
+ isEmpty,
+ data: {
+ slices,
+ visibleSlices,
+ visibleRows,
+ total,
+ hiddenSlices,
+ toggleSlice,
+ sortedData,
+ catKey,
+ valKey: String(dataKey),
+ legendItems,
+ },
+ dimensions: {
+ containerWidth,
+ availableWidth,
+ availableHeight,
+ chartSize,
+ svgWidth,
+ svgHeight,
+ centerX,
+ centerY,
+ },
+ isPrinting,
+ hover: {
+ hoveredIndex: effectiveHoveredIndex,
+ mousePos,
+ handleMouseMove,
+ handleMouseLeave,
+ },
+ usesRemoteLegend: bridge != null,
+ legend: { isLegendExpanded, setIsLegendExpanded },
+ tooltip: { tooltipPayload },
+ style: { containerStyle },
+ };
+}
diff --git a/packages/react-ui/src/components/D3Charts/hooks/polar/useRadarChartOrchestrator.ts b/packages/react-ui/src/components/D3Charts/hooks/polar/useRadarChartOrchestrator.ts
new file mode 100644
index 000000000..4227165ce
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/hooks/polar/useRadarChartOrchestrator.ts
@@ -0,0 +1,155 @@
+import { scaleLinear } from "d3-scale";
+import { useMemo, useRef } from "react";
+
+import type { ChartColorPalette } from "../../../ThemeProvider";
+import type { ChartData } from "../../types";
+import { buildContainerStyle } from "../../utils/buildContainerStyle";
+import { useChartData } from "../core/useChartData";
+import { useChartHover } from "../core/useChartHover";
+import { useChartShell } from "../core/useChartShell";
+import { useTooltipPayload } from "../core/useTooltipPayload";
+
+export interface UseRadarChartOrchestratorParams<T extends ChartData> {
+ data: T;
+ categoryKey: keyof T[number];
+ themePaletteName: keyof ChartColorPalette;
+ customPalette?: string[];
+ icons?: Partial<Record<keyof T[number], React.ComponentType>>;
+ showLegend: boolean;
+ maxChartSize: number;
+ minChartSize: number;
+ height?: number | string;
+ width?: number | string;
+ fitLegendInHeight?: boolean;
+ onClick?: (row: T[number], index: number) => void;
+}
+
+export function useRadarChartOrchestrator<T extends ChartData>({
+ data,
+ categoryKey,
+ themePaletteName,
+ customPalette,
+ icons,
+ showLegend,
+ maxChartSize,
+ minChartSize,
+ height,
+ width,
+ fitLegendInHeight,
+ onClick,
+}: UseRadarChartOrchestratorParams<T>) {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const legendRef = useRef<HTMLDivElement>(null);
+ const {
+ isPrinting,
+ containerWidth,
+ containerHeight,
+ isEmpty,
+ legendHeight,
+ shouldFitLegend,
+ isLegendExpanded,
+ setIsLegendExpanded,
+ } = useChartShell({
+ data,
+ showLegend,
+ containerRef,
+ legendRef,
+ width,
+ height,
+ fitLegendInHeight,
+ });
+
+ const {
+ catKey,
+ allDataKeys,
+ dataKeys,
+ hiddenSeries,
+ toggleSeries,
+ chartConfig,
+ colorMap,
+ chartStyle,
+ legendItems,
+ } = useChartData({
+ data,
+ categoryKey,
+ themePaletteName,
+ customPalette,
+ icons,
+ });
+
+ // Dimensions
+ const legendDeduction = showLegend && shouldFitLegend ? legendHeight : 0;
+ const availableHeight = (containerHeight || 300) - legendDeduction;
+ const availableWidth = containerWidth || 300;
+
+ const chartSize = Math.max(minChartSize, Math.min(maxChartSize, availableWidth, availableHeight));
+
+ const svgWidth = chartSize;
+ const svgHeight = chartSize;
+ const centerX = chartSize / 2;
+ const centerY = chartSize / 2;
+ const maxRadius = chartSize * 0.35;
+
+ // Radial scale
+ const maxValue = useMemo(() => {
+ let max = 0;
+ for (const row of data) {
+ for (const key of dataKeys) {
+ const val = Number(row[key]) || 0;
+ if (val > max) max = val;
+ }
+ }
+ return max;
+ }, [data, dataKeys]);
+
+ const radialScale = useMemo(
+ () =>
+ scaleLinear()
+ .domain([0, maxValue || 1])
+ .range([0, maxRadius]),
+ [maxValue, maxRadius],
+ );
+
+ // Hover
+ const hover = useChartHover({ data, onClick });
+
+ // Tooltip
+ const tooltipPayload = useTooltipPayload(hover.hoveredIndex, data, dataKeys, catKey, chartConfig);
+
+ // Container style
+ const containerStyle = useMemo(
+ () => buildContainerStyle(chartStyle, width, height),
+ [chartStyle, width, height],
+ );
+
+ return {
+ refs: { containerRef, legendRef },
+ isEmpty,
+ data: { catKey, allDataKeys, dataKeys, colorMap, chartConfig },
+ dimensions: {
+ containerWidth,
+ chartSize,
+ svgWidth,
+ svgHeight,
+ centerX,
+ centerY,
+ maxRadius,
+ radialScale,
+ },
+ isPrinting,
+ hover: {
+ hoveredIndex: hover.hoveredIndex,
+ mousePos: hover.mousePos,
+ createMouseHandlers: hover.createMouseHandlers,
+ },
+ legend: {
+ legendItems,
+ hiddenSeries,
+ isLegendExpanded,
+ setIsLegendExpanded,
+ toggleSeries,
+ },
+ tooltip: { tooltipPayload },
+ style: { containerStyle },
+ };
+}
diff --git a/packages/react-ui/src/components/D3Charts/index.ts b/packages/react-ui/src/components/D3Charts/index.ts
new file mode 100644
index 000000000..afbfd8bce
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/index.ts
@@ -0,0 +1,65 @@
+export { AreaChart } from "./AreaChart";
+export type { AreaChartData, AreaChartProps, AreaChartVariant } from "./AreaChart/types";
+
+export { LineChart } from "./LineChart";
+export type { LineChartData, LineChartProps, LineChartVariant } from "./LineChart/types";
+
+export { BarChart } from "./BarChart";
+export type {
+ BarChartData,
+ BarChartOrientation,
+ BarChartProps,
+ BarChartVariant,
+} from "./BarChart/types";
+
+export { PieChart } from "./PieChart";
+export type { PieChartData, PieChartProps } from "./PieChart/types";
+
+export { RadialChart } from "./RadialChart";
+export type { RadialChartData, RadialChartProps } from "./RadialChart/types";
+
+export { RadarChart } from "./RadarChart";
+export type { RadarChartData, RadarChartProps } from "./RadarChart/types";
+
+export { ScatterChart } from "./ScatterChart";
+export type {
+ ScatterChartData,
+ ScatterChartProps,
+ ScatterDataset,
+ ScatterPoint,
+} from "./ScatterChart/types";
+
+export { HeatmapChart } from "./HeatmapChart";
+export type { HeatmapChartData, HeatmapChartProps } from "./HeatmapChart/types";
+
+export { FunnelChart } from "./FunnelChart";
+export type {
+ FunnelChartData,
+ FunnelChartProps,
+ FunnelEdges,
+ FunnelOrientation,
+} from "./FunnelChart/types";
+
+export { SegmentedBar } from "./SegmentedBar";
+export type { SegmentedBarData, SegmentedBarProps } from "./SegmentedBar/types";
+
+export { CalendarHeatmap } from "./CalendarHeatmap";
+export type { CalendarHeatmapDatum, CalendarHeatmapProps } from "./CalendarHeatmap/types";
+
+export { MiniAreaChart } from "./MiniAreaChart";
+export type { MiniAreaChartData, MiniAreaChartProps } from "./MiniAreaChart/types";
+
+export { MiniBarChart } from "./MiniBarChart";
+export type { MiniBarChartData, MiniBarChartProps } from "./MiniBarChart/types";
+
+export { MiniLineChart } from "./MiniLineChart";
+export type { MiniLineChartData, MiniLineChartProps } from "./MiniLineChart/types";
+
+export { LegendStoreProvider, useLegendEntry } from "./shared/core/legend";
+export type { LegendEntry, StackedLegendItem } from "./shared/core/legend";
+export { StackedLegend } from "./shared/core/StackedLegend";
+export type { StackedLegendProps } from "./shared/core/StackedLegend";
+
+export type { BaseChartProps, ChartData, LegendItem, XAxisTickVariant } from "./types";
+
+export { CHART_CLASS_PREFIX } from "./utils/constants";
diff --git a/packages/react-ui/src/components/D3Charts/shared/cartesian/AnimatedPath.tsx b/packages/react-ui/src/components/D3Charts/shared/cartesian/AnimatedPath.tsx
new file mode 100644
index 000000000..4efdd7822
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/cartesian/AnimatedPath.tsx
@@ -0,0 +1,54 @@
+import { useRef } from "react";
+
+import { useIsomorphicLayoutEffect } from "../core/spring";
+
+interface AnimatedPathProps {
+ d: string;
+ color: string;
+ /** Base element class; the `--animated` modifier is appended when animating. */
+ className: string;
+ isAnimationActive?: boolean;
+ /**
+ * External ref so the owning series can write `d` imperatively (the spring
+ * data morph regenerates path data per ticker tick). Optional — without it
+ * the component measures through its own ref as before.
+ */
+ pathRef?: React.RefObject<SVGPathElement | null>;
+}
+
+/**
+ * A series line that can draw itself on. The stroke-dash draw-on keyframe
+ * (`${CHART_CLASS_PREFIX}-draw-line`, chartBase.scss) needs the path's length in the
+ * `--path-length` CSS var; it is measured in a LAYOUT effect — a plain
+ * useEffect ran after paint, so `stroke-dasharray: var(--path-length)` was
+ * invalid-at-computed-value-time for one frame, fell back to `none`, and the
+ * fully-drawn line flashed before the draw-on started.
+ */
+export function AnimatedPath({
+ d,
+ color,
+ className,
+ isAnimationActive,
+ pathRef,
+}: AnimatedPathProps) {
+ const internalRef = useRef<SVGPathElement>(null);
+ const ref = pathRef ?? internalRef;
+
+ useIsomorphicLayoutEffect(() => {
+ if (isAnimationActive && ref.current) {
+ const length = ref.current.getTotalLength();
+ ref.current.style.setProperty("--path-length", String(length));
+ }
+ }, [d, isAnimationActive]);
+
+ return (
+ <path
+ ref={ref}
+ className={`${className}${isAnimationActive ? ` ${className}--animated` : ""}`}
+ d={d}
+ fill="none"
+ stroke={color}
+ strokeWidth={2}
+ />
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/shared/cartesian/ClipDefs.tsx b/packages/react-ui/src/components/D3Charts/shared/cartesian/ClipDefs.tsx
new file mode 100644
index 000000000..3a48baf60
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/cartesian/ClipDefs.tsx
@@ -0,0 +1,24 @@
+import React from "react";
+
+const CLIP_OVERFLOW = 6;
+
+interface ClipDefsProps {
+ chartId: string;
+ chartWidth: number;
+ chartHeight: number;
+}
+
+export const ClipDefs: React.FC<ClipDefsProps> = ({ chartId, chartWidth, chartHeight }) => {
+ return (
+ <clipPath id={`clip-${chartId}`}>
+ <rect
+ y={-CLIP_OVERFLOW}
+ // Fit-mode SSR renders before the container is measured, so
+ // chartWidth can be negative (0 − yAxisWidth) — an invalid SVG
+ // attribute that logs a console error on every fit-mode deep link.
+ width={Math.max(0, chartWidth)}
+ height={chartHeight + CLIP_OVERFLOW}
+ />
+ </clipPath>
+ );
+};
diff --git a/packages/react-ui/src/components/D3Charts/shared/cartesian/Grid.tsx b/packages/react-ui/src/components/D3Charts/shared/cartesian/Grid.tsx
new file mode 100644
index 000000000..1df6818c0
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/cartesian/Grid.tsx
@@ -0,0 +1,49 @@
+import type { ScaleLinear } from "d3-scale";
+import React from "react";
+
+import { CHART_CLASS_PREFIX, resolveTickCount } from "../../utils/constants";
+
+interface GridProps {
+ yScale: ScaleLinear<number, number>;
+ chartWidth: number;
+ chartHeight: number;
+ className?: string;
+ /**
+ * Optional y-tick-count hint. When provided it wins (floored at 2) over the
+ * height-derived default. MUST match the value passed to the sibling `YAxis`
+ * so gridlines and labels stay aligned.
+ */
+ tickCount?: number;
+}
+
+export const Grid: React.FC<GridProps> = ({
+ yScale,
+ chartWidth,
+ chartHeight,
+ className,
+ tickCount: tickCountOverride,
+}) => {
+ const tickCount = resolveTickCount(chartHeight, tickCountOverride);
+ const ticks = yScale.ticks(tickCount);
+ // Emphasize the zero baseline only when the domain actually spans negatives —
+ // for all-positive charts tick 0 sits at the chart bottom and must stay a
+ // regular (dashed) gridline, pixel-identical to before negative support.
+ const spansNegative = (yScale.domain()[0] ?? 0) < 0;
+
+ return (
+ <g className={className}>
+ {ticks.map((tick) => (
+ <line
+ key={tick}
+ className={
+ spansNegative && tick === 0 ? `${CHART_CLASS_PREFIX}-grid-zero-line` : undefined
+ }
+ x1={0}
+ x2={chartWidth}
+ y1={yScale(tick)}
+ y2={yScale(tick)}
+ />
+ ))}
+ </g>
+ );
+};
diff --git a/packages/react-ui/src/components/D3Charts/shared/cartesian/LineDotCrosshair.tsx b/packages/react-ui/src/components/D3Charts/shared/cartesian/LineDotCrosshair.tsx
new file mode 100644
index 000000000..305811e6b
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/cartesian/LineDotCrosshair.tsx
@@ -0,0 +1,277 @@
+import type { ScaleLinear, ScalePoint } from "d3-scale";
+import React, { useCallback, useId, useRef } from "react";
+import { FadeFollower, springPresets, useSeededAim, useSpring } from "../core/spring";
+
+// Crosshair line + dots share springPresets.crosshair so they move as one;
+// the highlight band uses springPresets.highlight (trails a touch behind).
+
+interface LineDotCrosshairProps {
+ hoveredIndex: number | null;
+ xScale: ScalePoint<string>;
+ yScale: ScaleLinear<number, number>;
+ data: Array<Record<string, string | number>>;
+ dataKeys: string[];
+ categoryKey: string;
+ colors: Record<string, string>;
+ chartHeight: number;
+ getYValue: (row: Record<string, string | number>, key: string, seriesIndex: number) => number;
+ classPrefix: string;
+ /** Render the vertical crosshair line. Default true. */
+ crosshair?: boolean;
+ /** Render the traveling highlight segment. Default true. */
+ highlight?: boolean;
+ /** Render the active dots that ride the curve. Default true. */
+ activeDots?: boolean;
+}
+
+/**
+ * The hover crosshair + active dots. Kept mounted (the parent always renders it
+ * with a possibly-null `hoveredIndex`), so the followers' springs persist and the
+ * crosshair/dots GLIDE to the hovered point instead of snapping. The crosshair
+ * line slides in x; the dots travel ALONG the series' line path (sampled with
+ * `getPointAtLength`) so they ride the real curve — natural, step, etc. — instead
+ * of cutting a straight chord between points.
+ */
+export const LineDotCrosshair: React.FC<LineDotCrosshairProps> = ({
+ hoveredIndex,
+ xScale,
+ yScale,
+ data,
+ dataKeys,
+ categoryKey,
+ colors,
+ chartHeight,
+ getYValue,
+ classPrefix,
+ crosshair = true,
+ highlight = true,
+ activeDots = true,
+}) => {
+ const groupRef = useRef<SVGGElement>(null);
+
+ // Find the i-th rendered series line path (the real curve) within this chart's
+ // SVG. LineSeries draws `${classPrefix}-line`; AreaSeries draws
+ // `${classPrefix}-area-line`. They render in dataKeys order, so index lines up.
+ const getLinePath = useCallback(
+ (seriesIndex: number): SVGPathElement | null => {
+ const svg = groupRef.current?.ownerSVGElement;
+ if (!svg) return null;
+ const paths = svg.querySelectorAll<SVGPathElement>(
+ `.${classPrefix}-line, .${classPrefix}-area-line`,
+ );
+ return paths[seriesIndex] ?? null;
+ },
+ [classPrefix],
+ );
+
+ const visible = hoveredIndex !== null && hoveredIndex >= 0 && hoveredIndex < data.length;
+ const row = visible ? data[hoveredIndex]! : undefined;
+ const x = row ? (xScale(String(row[categoryKey])) ?? 0) : 0;
+
+ return (
+ <g ref={groupRef} className={`${classPrefix}-crosshair`}>
+ {/* Rendered first → sits under the crosshair line + dots. */}
+ {highlight && (
+ <HighlightLayer
+ hoveredIndex={hoveredIndex}
+ visible={visible}
+ data={data}
+ xScale={xScale}
+ categoryKey={categoryKey}
+ dataKeys={dataKeys}
+ colors={colors}
+ chartHeight={chartHeight}
+ getPath={getLinePath}
+ />
+ )}
+ {crosshair && (
+ <FadeFollower x={x} visible={visible}>
+ <line className={`${classPrefix}-crosshair-line`} x1={0} x2={0} y1={0} y2={chartHeight} />
+ </FadeFollower>
+ )}
+ {activeDots &&
+ dataKeys.map((key, seriesIndex) => (
+ <ActiveDot
+ key={key}
+ targetX={x}
+ fallbackY={row ? yScale(getYValue(row, key, seriesIndex)) : 0}
+ visible={visible}
+ color={colors[key] ?? "#000"}
+ classPrefix={classPrefix}
+ getPath={() => getLinePath(seriesIndex)}
+ />
+ ))}
+ </g>
+ );
+};
+
+// ── active dot: springs its position ALONG the series line path ───────────────
+
+// lengthAtX runs on every aim, and under streaming an aim lands every data
+// tick (the hovered row's y changes) — so its getPointAtLength cost is a
+// per-frame cost while hovering a live chart. Two containments:
+// • the bisection stops at half a pixel of arc-length precision (was a fixed
+// 22 iterations ≈ micro-pixel precision — ~2× the needed work);
+// • a per-path memo skips the search entirely when neither the geometry nor
+// the target x changed since the last aim (re-renders without data change).
+const lengthAtXCache = new WeakMap<SVGPathElement, { d: string | null; x: number; len: number }>();
+
+/** Arc-length on a (left-to-right monotonic-x) path where the path reaches `x`. */
+function lengthAtX(path: SVGPathElement, x: number): number {
+ const d = path.getAttribute("d");
+ const cached = lengthAtXCache.get(path);
+ if (cached && cached.d === d && cached.x === x) return cached.len;
+ const total = path.getTotalLength();
+ if (total === 0) return 0;
+ let lo = 0;
+ let hi = total;
+ while (hi - lo > 0.5) {
+ const mid = (lo + hi) / 2;
+ if (path.getPointAtLength(mid).x < x) lo = mid;
+ else hi = mid;
+ }
+ const len = (lo + hi) / 2;
+ lengthAtXCache.set(path, { d, x, len });
+ return len;
+}
+
+function ActiveDot({
+ targetX,
+ fallbackY,
+ visible,
+ color,
+ classPrefix,
+ getPath,
+}: {
+ targetX: number;
+ fallbackY: number;
+ visible: boolean;
+ color: string;
+ classPrefix: string;
+ getPath: () => SVGPathElement | null;
+}) {
+ const gRef = useRef<SVGGElement>(null);
+ const pathRef = useRef<SVGPathElement | null>(null);
+
+ const write = (px: number, py: number) => {
+ if (gRef.current) {
+ gRef.current.style.transform = `translate(${px}px, ${py}px)`;
+ }
+ };
+
+ // The spring's value is the arc-length along the line path; mapping it through
+ // getPointAtLength each frame makes the dot ride the curve.
+ const spring = useSpring(springPresets.crosshair, (len) => {
+ const p = pathRef.current?.getPointAtLength(len);
+ if (p) write(p.x, p.y);
+ });
+ useSeededAim(visible, [targetX, fallbackY], (first) => {
+ pathRef.current = getPath();
+ const path = pathRef.current;
+ if (!path) {
+ // No path found (shouldn't happen for line/area) — sit at the point. The
+ // false return skips seeding, so if this happens on FIRST show the
+ // eventual first real aim still jumps (mid-session it glides, as before).
+ write(targetX, fallbackY);
+ return false;
+ }
+ const targetLen = lengthAtX(path, targetX);
+ if (first) spring.jump(targetLen);
+ else spring.set(targetLen);
+ return true;
+ });
+
+ return (
+ <g ref={gRef} style={{ opacity: visible ? 1 : 0, transition: "opacity 0.12s ease" }}>
+ <circle cx={0} cy={0} r={4} className={`${classPrefix}-active-dot-outer`} />
+ <circle cx={0} cy={0} r={2} fill={color} className={`${classPrefix}-active-dot-inner`} />
+ </g>
+ );
+}
+
+// ── highlight segment: a brighter re-stroke of each line, clipped to a band ────
+// On hover, the slice of the line spanning ONE data point either side of the
+// hovered point (`[idx-1, idx+1]`) lights up and travels along the real curve.
+// One shared clip band (x + width spring); each series re-strokes its own real
+// `d` (read from the rendered path), so the glow traces the actual curve.
+
+function HighlightLayer({
+ hoveredIndex,
+ visible,
+ data,
+ xScale,
+ categoryKey,
+ dataKeys,
+ colors,
+ chartHeight,
+ getPath,
+}: {
+ hoveredIndex: number | null;
+ visible: boolean;
+ data: Array<Record<string, string | number>>;
+ xScale: ScalePoint<string>;
+ categoryKey: string;
+ dataKeys: string[];
+ colors: Record<string, string>;
+ chartHeight: number;
+ getPath: (seriesIndex: number) => SVGPathElement | null;
+}) {
+ const clipId = useId();
+ const rectRef = useRef<SVGRectElement>(null);
+ const pathRefs = useRef<(SVGPathElement | null)[]>([]);
+
+ // One band for every series: x = left edge, width = span — both spring.
+ const xSpring = useSpring(springPresets.highlight, (v) => {
+ rectRef.current?.setAttribute("x", String(v));
+ });
+ const wSpring = useSpring(springPresets.highlight, (v) => {
+ rectRef.current?.setAttribute("width", String(v));
+ });
+ useSeededAim(visible && hoveredIndex !== null, [hoveredIndex], (first) => {
+ const startIdx = Math.max(0, hoveredIndex! - 1);
+ const endIdx = Math.min(data.length - 1, hoveredIndex! + 1);
+ const startX = xScale(String(data[startIdx]?.[categoryKey])) ?? 0;
+ const endX = xScale(String(data[endIdx]?.[categoryKey])) ?? 0;
+ const bandX = startX;
+ const bandW = Math.max(0, endX - startX);
+ // Re-stroke each series with its real line `d`, clipped to the band.
+ dataKeys.forEach((_, i) => {
+ const real = getPath(i);
+ const hp = pathRefs.current[i];
+ if (real && hp) hp.setAttribute("d", real.getAttribute("d") ?? "");
+ });
+ if (first) {
+ xSpring.jump(bandX);
+ wSpring.jump(bandW);
+ } else {
+ xSpring.set(bandX);
+ wSpring.set(bandW);
+ }
+ });
+
+ return (
+ <g aria-hidden="true" style={{ opacity: visible ? 1 : 0, transition: "opacity 0.15s ease" }}>
+ <defs>
+ <clipPath id={clipId}>
+ {/* x + width set imperatively by the springs; width 0 until active. */}
+ <rect ref={rectRef} y={0} height={chartHeight} />
+ </clipPath>
+ </defs>
+ {dataKeys.map((key, i) => (
+ <path
+ key={key}
+ // d set imperatively from the real line; no React `d` prop to fight it.
+ ref={(el) => {
+ pathRefs.current[i] = el;
+ }}
+ clipPath={`url(#${clipId})`}
+ fill="none"
+ stroke={colors[key] ?? "#000"}
+ strokeWidth={3.5}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ ))}
+ </g>
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/shared/cartesian/ScrollButtonsHorizontal/ScrollButtonsHorizontal.tsx b/packages/react-ui/src/components/D3Charts/shared/cartesian/ScrollButtonsHorizontal/ScrollButtonsHorizontal.tsx
new file mode 100644
index 000000000..80db15a58
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/cartesian/ScrollButtonsHorizontal/ScrollButtonsHorizontal.tsx
@@ -0,0 +1,63 @@
+import clsx from "clsx";
+import { ChevronLeft, ChevronRight } from "lucide-react";
+import React from "react";
+import { IconButton } from "../../../../IconButton";
+import { CHART_CLASS_PREFIX } from "../../../utils/constants";
+
+interface ScrollButtonsHorizontalProps {
+ dataWidth: number;
+ effectiveWidth: number;
+ canScrollLeft: boolean;
+ canScrollRight: boolean;
+ onScrollLeft: () => void;
+ onScrollRight: () => void;
+}
+
+export const ScrollButtonsHorizontal = React.memo(
+ ({
+ dataWidth,
+ effectiveWidth,
+ canScrollLeft,
+ canScrollRight,
+ onScrollLeft,
+ onScrollRight,
+ }: ScrollButtonsHorizontalProps) => {
+ if (dataWidth <= effectiveWidth) {
+ return null;
+ }
+
+ return (
+ <div className={`${CHART_CLASS_PREFIX}-chart-horizontal-scroll-buttons-container`}>
+ <IconButton
+ className={clsx(
+ `${CHART_CLASS_PREFIX}-chart-horizontal-scroll-button ${CHART_CLASS_PREFIX}-chart-horizontal-scroll-button--left`,
+ {
+ [`${CHART_CLASS_PREFIX}-chart-horizontal-scroll-button--disabled`]: !canScrollLeft,
+ },
+ )}
+ icon={<ChevronLeft />}
+ variant="secondary"
+ onClick={onScrollLeft}
+ size="2-extra-small"
+ disabled={!canScrollLeft}
+ />
+
+ <IconButton
+ className={clsx(
+ `${CHART_CLASS_PREFIX}-chart-horizontal-scroll-button ${CHART_CLASS_PREFIX}-chart-horizontal-scroll-button--right`,
+ {
+ [`${CHART_CLASS_PREFIX}-chart-horizontal-scroll-button--disabled`]: !canScrollRight,
+ },
+ )}
+ icon={<ChevronRight />}
+ variant="secondary"
+ size="2-extra-small"
+ onClick={onScrollRight}
+ disabled={!canScrollRight}
+ />
+ </div>
+ );
+ },
+);
+
+ScrollButtonsHorizontal.displayName = "ScrollButtonsHorizontal";
diff --git a/packages/react-ui/src/components/D3Charts/shared/cartesian/ScrollButtonsHorizontal/scrollButtonsHorizontal.scss b/packages/react-ui/src/components/D3Charts/shared/cartesian/ScrollButtonsHorizontal/scrollButtonsHorizontal.scss
new file mode 100644
index 000000000..0436fa6bf
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/cartesian/ScrollButtonsHorizontal/scrollButtonsHorizontal.scss
@@ -0,0 +1,41 @@
+@use "../../../../../cssUtils" as cssUtils;
+@use "../../../prefix" as brand;
+
+.#{brand.$prefix}-chart-horizontal-scroll {
+ &-buttons-container {
+ position: relative;
+
+ // Nested under the container (specificity 0,2,0) so these beat react-ui's
+ // single-class IconButton rules — the `-secondary` transparent background
+ // and the base `transition` — whatever order the stylesheets load in
+ // (react-ui's generated components index forwards D3Charts before
+ // IconButton). IconButton's own `:hover` / `:active` / `:disabled` states
+ // still win on specificity.
+ .#{brand.$prefix}-chart-horizontal-scroll-button {
+ position: absolute;
+ background-color: cssUtils.$foreground;
+
+ &--left {
+ top: -23px;
+ transform: translateY(-50%);
+ left: 20px;
+ }
+
+ &--right {
+ top: -23px;
+ transform: translateY(-50%);
+ right: 0px;
+ }
+
+ &--disabled {
+ visibility: hidden;
+ cursor: not-allowed;
+ // Looks inert but isn't: visible→hidden under a transition holds
+ // `visible` until it completes (the brief linger on disable), and this
+ // declaration overrides react-ui's base `transition: all 0.12s ease`
+ // on the same element.
+ transition: visibility 0.1s linear;
+ }
+ }
+ }
+}
diff --git a/packages/react-ui/src/components/D3Charts/shared/cartesian/ScrollButtonsVertical/ScrollButtonsVertical.tsx b/packages/react-ui/src/components/D3Charts/shared/cartesian/ScrollButtonsVertical/ScrollButtonsVertical.tsx
new file mode 100644
index 000000000..e2a9883fc
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/cartesian/ScrollButtonsVertical/ScrollButtonsVertical.tsx
@@ -0,0 +1,56 @@
+import clsx from "clsx";
+import { ChevronDown, ChevronUp } from "lucide-react";
+import React from "react";
+import { IconButton } from "../../../../IconButton";
+import { CHART_CLASS_PREFIX } from "../../../utils/constants";
+
+interface ScrollButtonsVerticalProps {
+ canScrollUp: boolean;
+ canScrollDown: boolean;
+ onScrollUp: () => void;
+ onScrollDown: () => void;
+}
+
+export const ScrollButtonsVertical = React.memo(
+ ({ canScrollUp, canScrollDown, onScrollUp, onScrollDown }: ScrollButtonsVerticalProps) => {
+ if (!canScrollUp && !canScrollDown) {
+ return null;
+ }
+
+ return (
+ <div className={`${CHART_CLASS_PREFIX}-chart-vertical-scroll-buttons-container`}>
+ <IconButton
+ className={clsx(
+ `${CHART_CLASS_PREFIX}-chart-vertical-scroll-button ${CHART_CLASS_PREFIX}-chart-vertical-scroll-button--up`,
+ {
+ [`${CHART_CLASS_PREFIX}-chart-vertical-scroll-button--disabled`]: !canScrollUp,
+ },
+ )}
+ icon={<ChevronUp />}
+ variant="secondary"
+ onClick={onScrollUp}
+ size="extra-small"
+ disabled={!canScrollUp}
+ aria-label="Scroll up"
+ />
+
+ <IconButton
+ className={clsx(
+ `${CHART_CLASS_PREFIX}-chart-vertical-scroll-button ${CHART_CLASS_PREFIX}-chart-vertical-scroll-button--down`,
+ {
+ [`${CHART_CLASS_PREFIX}-chart-vertical-scroll-button--disabled`]: !canScrollDown,
+ },
+ )}
+ icon={<ChevronDown />}
+ variant="secondary"
+ size="extra-small"
+ onClick={onScrollDown}
+ disabled={!canScrollDown}
+ aria-label="Scroll down"
+ />
+ </div>
+ );
+ },
+);
+
+ScrollButtonsVertical.displayName = "ScrollButtonsVertical";
diff --git a/packages/react-ui/src/components/D3Charts/shared/cartesian/ScrollButtonsVertical/scrollButtonsVertical.scss b/packages/react-ui/src/components/D3Charts/shared/cartesian/ScrollButtonsVertical/scrollButtonsVertical.scss
new file mode 100644
index 000000000..3a93316dd
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/cartesian/ScrollButtonsVertical/scrollButtonsVertical.scss
@@ -0,0 +1,39 @@
+@use "../../../../../cssUtils" as cssUtils;
+@use "../../../prefix" as brand;
+
+.#{brand.$prefix}-chart-vertical-scroll {
+ &-buttons-container {
+ display: flex;
+ flex-direction: column;
+ justify-content: space-between;
+ align-items: center;
+ // Wide enough for the react-ui extra-small IconButton (~28px) + the left
+ // pad, so the button doesn't overflow the column and get clipped by the
+ // chart wrapper's `overflow: hidden`.
+ width: 36px;
+ height: calc(100% - 44px);
+ flex-shrink: 0;
+ padding-left: cssUtils.$space-2xs;
+
+ // Nested under the container (specificity 0,2,0) so these beat react-ui's
+ // single-class IconButton rules — the `-secondary` transparent background
+ // and the base `transition` — whatever order the stylesheets load in
+ // (react-ui's generated components index forwards D3Charts before
+ // IconButton). IconButton's own `:hover` / `:active` / `:disabled` states
+ // still win on specificity.
+ .#{brand.$prefix}-chart-vertical-scroll-button {
+ background-color: cssUtils.$foreground;
+ pointer-events: auto;
+
+ &--disabled {
+ visibility: hidden;
+ cursor: not-allowed;
+ // Looks inert but isn't: visible→hidden under a transition holds
+ // `visible` until it completes (the brief linger on disable), and this
+ // declaration overrides react-ui's base `transition: all 0.12s ease`
+ // on the same element.
+ transition: visibility 0.1s linear;
+ }
+ }
+ }
+}
diff --git a/packages/react-ui/src/components/D3Charts/shared/cartesian/VerticalGrid.tsx b/packages/react-ui/src/components/D3Charts/shared/cartesian/VerticalGrid.tsx
new file mode 100644
index 000000000..e30c0421e
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/cartesian/VerticalGrid.tsx
@@ -0,0 +1,31 @@
+import type { ScaleLinear } from "d3-scale";
+import React from "react";
+
+const DEFAULT_MIN_TICK_SPACING = 60;
+
+interface VerticalGridProps {
+ xScale: ScaleLinear<number, number>;
+ chartWidth: number;
+ chartHeight: number;
+ className?: string;
+ minTickSpacing?: number;
+}
+
+export const VerticalGrid: React.FC<VerticalGridProps> = ({
+ xScale,
+ chartWidth,
+ chartHeight,
+ className,
+ minTickSpacing = DEFAULT_MIN_TICK_SPACING,
+}) => {
+ const tickCount = Math.max(2, Math.floor(chartWidth / minTickSpacing));
+ const ticks = xScale.ticks(tickCount);
+
+ return (
+ <g className={className}>
+ {ticks.map((t) => (
+ <line key={t} x1={xScale(t)} x2={xScale(t)} y1={0} y2={chartHeight} />
+ ))}
+ </g>
+ );
+};
diff --git a/packages/react-ui/src/components/D3Charts/shared/cartesian/axes/CartesianXAxis.tsx b/packages/react-ui/src/components/D3Charts/shared/cartesian/axes/CartesianXAxis.tsx
new file mode 100644
index 000000000..6023c9908
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/cartesian/axes/CartesianXAxis.tsx
@@ -0,0 +1,79 @@
+import type { ScaleBand, ScalePoint } from "d3-scale";
+import React from "react";
+
+import type { XAxisTickVariant } from "../../../types";
+import { CondensedXAxis } from "./CondensedXAxis";
+import { XAxis } from "./XAxis";
+
+type CartesianXAxisScale = ScalePoint<string> | ScaleBand<string>;
+
+interface CartesianXAxisProps {
+ /** 'scroll' → the full multi-line <XAxis>; 'fit' → the <CondensedXAxis>. */
+ mode: "scroll" | "fit";
+ scale: CartesianXAxisScale;
+ classPrefix: string;
+ tickVariant: XAxisTickVariant;
+ /**
+ * Width of one category group, for point-scale charts (area/line). Band-scale
+ * charts (bar) omit it — <XAxis> derives the width from `bandwidth()` and
+ * ignores this entirely, so leaving it undefined is a no-op there.
+ */
+ widthOfGroup?: number;
+ labelHeight: number;
+ labelInterval?: number;
+ /** Fit mode: the width (horizontal) or text length (rotated) each label truncates to. */
+ labelWidth: number;
+ /** Line cap for wrapped labels. */
+ maxLines: number;
+ angle: number;
+ /** Fit mode: the plot width the axis spans. */
+ chartWidth: number;
+ /** Fit mode: the y-axis width, as far left as rotated labels may reach. */
+ yAxisWidth: number;
+}
+
+/**
+ * The scroll-vs-fit x-axis switch shared by the cartesian line charts
+ * (area / line / bar). `scroll` mode renders the full <XAxis> (multi-line
+ * ticks, group width, label interval); `fit` mode renders the
+ * <CondensedXAxis>. Area and line were byte-identical here; bar differs only by
+ * omitting `widthOfGroup`. Heatmap's x-axis is deliberately different (its own
+ * single-line variant, no angled branch) and is NOT routed through this.
+ */
+export const CartesianXAxis: React.FC<CartesianXAxisProps> = ({
+ mode,
+ scale,
+ classPrefix,
+ tickVariant,
+ widthOfGroup,
+ labelHeight,
+ labelInterval = 1,
+ labelWidth,
+ maxLines,
+ angle,
+ chartWidth,
+ yAxisWidth,
+}) =>
+ mode === "scroll" ? (
+ <XAxis
+ scale={scale}
+ tickVariant={tickVariant}
+ widthOfGroup={widthOfGroup}
+ labelHeight={labelHeight}
+ labelInterval={labelInterval}
+ maxLines={maxLines}
+ classPrefix={classPrefix}
+ />
+ ) : (
+ <CondensedXAxis
+ scale={scale}
+ angle={angle}
+ labelInterval={labelInterval}
+ labelWidth={labelWidth}
+ maxLines={maxLines}
+ labelHeight={labelHeight}
+ chartWidth={chartWidth}
+ yAxisWidth={yAxisWidth}
+ classPrefix={classPrefix}
+ />
+ );
diff --git a/packages/react-ui/src/components/D3Charts/shared/cartesian/axes/CondensedXAxis.tsx b/packages/react-ui/src/components/D3Charts/shared/cartesian/axes/CondensedXAxis.tsx
new file mode 100644
index 000000000..8abf98fe9
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/cartesian/axes/CondensedXAxis.tsx
@@ -0,0 +1,137 @@
+import type { ScaleBand, ScalePoint } from "d3-scale";
+import React from "react";
+
+import { useCanvasContextForLabelSize } from "../../../hooks/core/useCanvasContextForLabelSize";
+import { parseLineHeight, truncateToWidth, wrapLabelLines } from "../../../utils/labelWrap";
+import { X_AXIS_TOP_GAP } from "../../../utils/xAxisLabelLayout";
+import { LabelTooltip } from "../../core/LabelTooltip/LabelTooltip";
+
+type CondensedXAxisScale = ScaleBand<string> | ScalePoint<string>;
+
+function isBandScale(scale: CondensedXAxisScale): scale is ScaleBand<string> {
+ return typeof (scale as ScaleBand<string>).paddingInner === "function";
+}
+
+interface CondensedXAxisProps {
+ scale: CondensedXAxisScale;
+ /** 0 draws horizontal labels; anything else rotates them by that many degrees. */
+ angle: number;
+ /** Draw every `labelInterval`-th label. */
+ labelInterval: number;
+ /** Horizontal: the box each label wraps/truncates to. Rotated: the longest text kept. */
+ labelWidth: number;
+ /** Line cap for wrapped horizontal labels (1 = single line). */
+ maxLines: number;
+ labelHeight: number;
+ /** Width of the plot the axis spans. */
+ chartWidth: number;
+ /** Width of the y-axis to the axis' left — as far as rotated labels may reach. */
+ yAxisWidth: number;
+ classPrefix: string;
+}
+
+/**
+ * The condensed (fit) x-axis. Labels are laid out by `layoutXAxisLabels`:
+ * horizontal by default, rotated when `angle` is set, thinned to every n-th
+ * label when categories are too narrow, and truncated with an ellipsis when
+ * they don't fit — the full text shows on hover.
+ */
+export const CondensedXAxis: React.FC<CondensedXAxisProps> = ({
+ scale,
+ angle,
+ labelInterval,
+ labelWidth,
+ maxLines,
+ labelHeight,
+ chartWidth,
+ yAxisWidth,
+ classPrefix,
+}) => {
+ const ctx = useCanvasContextForLabelSize();
+ const lineHeight = parseLineHeight(ctx.font);
+ const domain = scale.domain();
+ const centerOf = (category: string) =>
+ (scale(category) ?? 0) + (isBandScale(scale) ? scale.bandwidth() / 2 : 0);
+ const isAngled = angle !== 0;
+
+ return (
+ <g className={`${classPrefix}-x-axis`}>
+ {domain.map((category, i) => {
+ if (i % labelInterval !== 0) return null;
+ const label = String(category);
+ const cx = centerOf(category);
+ const y = X_AXIS_TOP_GAP;
+
+ if (isAngled) {
+ // A rotated label reaches `width · cos(angle)` left of its tick; near
+ // the start of the axis it is truncated so it stays inside the chart.
+ const reach = (cx + yAxisWidth) / Math.cos((angle * Math.PI) / 180);
+ const text = truncateToWidth(ctx, label, Math.min(labelWidth, reach));
+ const textWidth = ctx.measureText(text).width;
+ const transform = `rotate(${angle}, ${cx}, ${y})`;
+ return (
+ <LabelTooltip key={category} content={label} disabled={text === label}>
+ <g>
+ {text !== label && (
+ <rect
+ x={cx - textWidth}
+ y={y}
+ width={textWidth}
+ height={lineHeight}
+ transform={transform}
+ fill="transparent"
+ />
+ )}
+ <text
+ x={cx}
+ y={y}
+ textAnchor="end"
+ dominantBaseline="hanging"
+ className={`${classPrefix}-x-tick-angled`}
+ transform={transform}
+ >
+ {text}
+ </text>
+ </g>
+ </LabelTooltip>
+ );
+ }
+
+ // Horizontal labels stay inside the plot's width: on a thinned axis a
+ // label's box is wider than its category, so the first and last boxes
+ // are cut at the ends (never shifted into their neighbours).
+ const left = Math.max(0, cx - labelWidth / 2);
+ const right = Math.min(chartWidth, cx + labelWidth / 2);
+ const lines =
+ maxLines > 1
+ ? wrapLabelLines(ctx, label, right - left, maxLines)
+ : [truncateToWidth(ctx, label, right - left)];
+ const truncated = lines.some((line) => line.endsWith("…"));
+ const half = Math.max(...lines.map((line) => ctx.measureText(line).width)) / 2;
+ const x = Math.min(Math.max(cx, left + half), right - half);
+ return (
+ <LabelTooltip key={category} content={label} disabled={!truncated}>
+ <g>
+ {truncated && (
+ <rect x={left} y={0} width={right - left} height={labelHeight} fill="transparent" />
+ )}
+ <text
+ x={x}
+ y={y}
+ textAnchor="middle"
+ dominantBaseline="hanging"
+ className={`${classPrefix}-x-tick`}
+ >
+ {lines.map((line, li) => (
+ <tspan key={li} x={x} dy={li === 0 ? 0 : lineHeight}>
+ {line}
+ </tspan>
+ ))}
+ </text>
+ </g>
+ </LabelTooltip>
+ );
+ })}
+ </g>
+ );
+};
diff --git a/packages/react-ui/src/components/D3Charts/shared/cartesian/axes/NumericXAxis.tsx b/packages/react-ui/src/components/D3Charts/shared/cartesian/axes/NumericXAxis.tsx
new file mode 100644
index 000000000..59cf3a532
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/cartesian/axes/NumericXAxis.tsx
@@ -0,0 +1,58 @@
+import type { ScaleLinear } from "d3-scale";
+import React from "react";
+import { numberTickFormatter } from "../../../utils/styleUtils";
+
+interface NumericXAxisProps {
+ scale: ScaleLinear<number, number>;
+ chartWidth: number;
+ height: number;
+ className?: string;
+ tickClassName?: string;
+ /**
+ * When true, the FIRST tick label is `text-anchor: start` and the LAST is
+ * `end` (rest stay centred) so the edge labels don't clip off the chart
+ * without insetting the scale (which would push the edge gridline into the
+ * category labels). Default false — keeps existing callers byte-identical.
+ */
+ edgeAlign?: boolean;
+}
+
+const MIN_TICK_SPACING = 60;
+
+export const NumericXAxis: React.FC<NumericXAxisProps> = ({
+ scale,
+ chartWidth,
+ height,
+ className,
+ tickClassName,
+ edgeAlign = false,
+}) => {
+ const tickCount = Math.max(2, Math.floor(chartWidth / MIN_TICK_SPACING));
+ const ticks = scale.ticks(tickCount);
+
+ return (
+ <g className={className}>
+ {ticks.map((tick, i) => {
+ const anchor = edgeAlign
+ ? i === 0
+ ? "start"
+ : i === ticks.length - 1
+ ? "end"
+ : "middle"
+ : "middle";
+ return (
+ <text
+ key={tick}
+ className={tickClassName}
+ x={scale(tick)}
+ y={height / 2}
+ textAnchor={anchor}
+ dominantBaseline="middle"
+ >
+ {numberTickFormatter(tick)}
+ </text>
+ );
+ })}
+ </g>
+ );
+};
diff --git a/packages/react-ui/src/components/D3Charts/shared/cartesian/axes/XAxis.tsx b/packages/react-ui/src/components/D3Charts/shared/cartesian/axes/XAxis.tsx
new file mode 100644
index 000000000..7a8ff00d1
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/cartesian/axes/XAxis.tsx
@@ -0,0 +1,106 @@
+import type { ScaleBand, ScalePoint } from "d3-scale";
+import React from "react";
+
+import { useCanvasContextForLabelSize } from "../../../hooks/core/useCanvasContextForLabelSize";
+import type { XAxisTickVariant } from "../../../types";
+import {
+ MAX_LABEL_LINES,
+ parseLineHeight,
+ truncateToWidth,
+ wrapLabelLines,
+} from "../../../utils/labelWrap";
+import { LabelTooltip } from "../../core/LabelTooltip/LabelTooltip";
+
+const X_AXIS_TOP_GAP = 4;
+
+type XAxisScale = ScalePoint<string> | ScaleBand<string>;
+
+interface XAxisProps {
+ scale: XAxisScale;
+ tickVariant: XAxisTickVariant;
+ widthOfGroup?: number;
+ labelHeight: number;
+ labelInterval?: number;
+ /** Line cap for "multiLine" labels. */
+ maxLines?: number;
+ classPrefix: string;
+}
+
+function isBandScale(scale: XAxisScale): scale is ScaleBand<string> {
+ return typeof (scale as ScaleBand<string>).paddingInner === "function";
+}
+
+/**
+ * X-axis category labels as native SVG `<text>` (multi-line via `<tspan>`,
+ * measured-trim ellipsis), matching the YAxis/CondensedXAxis. Native text — rather
+ * than `<foreignObject>` HTML — so labels survive print/PDF and server-side
+ * rasterization. A transparent `<rect>` provides the hover target for the
+ * full-label tooltip when a label is truncated.
+ */
+export const XAxis: React.FC<XAxisProps> = ({
+ scale,
+ tickVariant,
+ widthOfGroup,
+ labelHeight,
+ labelInterval = 1,
+ maxLines = MAX_LABEL_LINES,
+ classPrefix,
+}) => {
+ const ctx = useCanvasContextForLabelSize();
+ const lineHeight = parseLineHeight(ctx.font);
+ const domain = scale.domain();
+ const band = isBandScale(scale);
+ const labelWidth = band ? (scale as ScaleBand<string>).bandwidth() : (widthOfGroup ?? 0);
+
+ return (
+ <g className={`${classPrefix}-x-axis`}>
+ {domain.map((category, i) => {
+ const show = labelInterval <= 1 || i % labelInterval === 0 || i === domain.length - 1;
+ if (!show) return null;
+
+ const rawX = scale(category) ?? 0;
+ const cx = band ? rawX + labelWidth / 2 : rawX;
+ const label = String(category);
+
+ const lines =
+ tickVariant === "multiLine"
+ ? wrapLabelLines(ctx, label, labelWidth, maxLines)
+ : [truncateToWidth(ctx, label, labelWidth)];
+ const truncated = lines.some((line) => line.endsWith("…"));
+
+ const text = (
+ <text
+ x={cx}
+ y={X_AXIS_TOP_GAP}
+ textAnchor="middle"
+ dominantBaseline="hanging"
+ className={`${classPrefix}-x-tick`}
+ >
+ {lines.map((line, li) => (
+ <tspan key={li} x={cx} dy={li === 0 ? 0 : lineHeight}>
+ {line}
+ </tspan>
+ ))}
+ </text>
+ );
+
+ return (
+ <LabelTooltip key={category} content={label} disabled={!truncated}>
+ <g>
+ {truncated && (
+ <rect
+ x={cx - labelWidth / 2}
+ y={0}
+ width={labelWidth}
+ height={labelHeight}
+ fill="transparent"
+ />
+ )}
+ {text}
+ </g>
+ </LabelTooltip>
+ );
+ })}
+ </g>
+ );
+};
diff --git a/packages/react-ui/src/components/D3Charts/shared/cartesian/axes/YAxis.tsx b/packages/react-ui/src/components/D3Charts/shared/cartesian/axes/YAxis.tsx
new file mode 100644
index 000000000..e6ef22941
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/cartesian/axes/YAxis.tsx
@@ -0,0 +1,47 @@
+import type { ScaleLinear } from "d3-scale";
+import React from "react";
+import { resolveTickCount } from "../../../utils/constants";
+import { numberTickFormatter } from "../../../utils/styleUtils";
+
+interface YAxisProps {
+ scale: ScaleLinear<number, number>;
+ width: number;
+ chartHeight: number;
+ className?: string;
+ tickClassName?: string;
+ /**
+ * Optional y-tick-count hint. When provided it wins (floored at 2) over the
+ * height-derived default. MUST match the value passed to the sibling `Grid`
+ * so labels and gridlines stay aligned.
+ */
+ tickCount?: number;
+}
+
+export const YAxis: React.FC<YAxisProps> = ({
+ scale,
+ width,
+ chartHeight,
+ className,
+ tickClassName,
+ tickCount: tickCountOverride,
+}) => {
+ const tickCount = resolveTickCount(chartHeight, tickCountOverride);
+ const ticks = scale.ticks(tickCount);
+
+ return (
+ <g className={className}>
+ {ticks.map((tick) => (
+ <text
+ key={tick}
+ className={tickClassName}
+ x={width - 8}
+ y={scale(tick)}
+ textAnchor="end"
+ dominantBaseline="middle"
+ >
+ {numberTickFormatter(tick)}
+ </text>
+ ))}
+ </g>
+ );
+};
diff --git a/packages/react-ui/src/components/D3Charts/shared/cartesian/chartBase.scss b/packages/react-ui/src/components/D3Charts/shared/cartesian/chartBase.scss
new file mode 100644
index 000000000..26fdab811
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/cartesian/chartBase.scss
@@ -0,0 +1,162 @@
+@use "../../../../cssUtils" as cssUtils;
+@use "../../prefix" as brand;
+
+// The typography + fill shared by every native-SVG `<text>` tick / axis label
+// (the cartesian y/x/angled ticks below, plus the heatmap/scatter/radar/funnel
+// label sheets). Body-only — `@include` it inside the chart's own selector.
+@mixin svg-tick-label {
+ @include cssUtils.typography(label, extra-small);
+ fill: cssUtils.$text-neutral-secondary;
+}
+
+// The centered column the non-cartesian charts (pie/radial/radar/heatmap/
+// scatter/funnel) use as their root — distinct from chart-base's container
+// (this centers its content and does NOT clip overflow).
+// Horizontal centering here is load-bearing for radarLabelLayout.ts (svgLeft assumes the svg is centered within containerWidth) — update that util if this centering changes.
+@mixin centered-container($prefix) {
+ .#{brand.$prefix}-#{$prefix}-container {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ width: 100%;
+ position: relative;
+ }
+}
+
+// The centered svg box the polar charts (pie/radial/radar) wrap their square
+// chart in.
+// Horizontal centering here is load-bearing for radarLabelLayout.ts (svgLeft assumes the svg is centered within containerWidth) — update that util if this centering changes.
+@mixin centered-svg-wrapper($prefix) {
+ .#{brand.$prefix}-#{$prefix}-svg-wrapper {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ }
+}
+
+@mixin chart-base($prefix) {
+ .#{brand.$prefix}-#{$prefix} {
+ &-container {
+ width: 100%;
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+ }
+
+ &-container-inner {
+ display: flex;
+ width: 100%;
+ flex: 1;
+ min-height: 0;
+ }
+
+ &-y-axis-container {
+ flex-shrink: 0;
+ }
+
+ &-main-container {
+ flex: 1;
+ min-width: 0;
+ overflow-x: auto;
+ overflow-y: hidden;
+ &::-webkit-scrollbar {
+ display: none;
+ }
+ scrollbar-width: none;
+ -ms-overflow-style: none;
+ }
+ }
+
+ .#{brand.$prefix}-#{$prefix}-grid line {
+ stroke: cssUtils.$border-default;
+ stroke-dasharray: 3 3;
+ }
+
+ // The y=0 baseline renders solid so it reads at a glance when the domain
+ // spans negative values (the extra selector outweighs the dashed rule).
+ .#{brand.$prefix}-#{$prefix}-grid line.#{brand.$prefix}-grid-zero-line {
+ stroke-dasharray: none;
+ }
+
+ .#{brand.$prefix}-#{$prefix}-y-tick {
+ @include svg-tick-label;
+ }
+
+ .#{brand.$prefix}-#{$prefix}-x-tick {
+ @include svg-tick-label;
+ }
+
+ .#{brand.$prefix}-#{$prefix}-x-tick-angled {
+ @include svg-tick-label;
+ }
+}
+
+.#{brand.$prefix}-chart-empty {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ min-height: 200px;
+
+ &-text {
+ @include cssUtils.typography(body, default);
+ color: cssUtils.$text-neutral-secondary;
+ }
+}
+
+// Fit/condensed-mode axis labels — standalone HTML divs the CartesianChartLayout
+// renders around the chart (y top-left, x bottom-centered), mirroring react-ui's
+// *Condensed charts. Prefix-independent (shared by bar/line/area fit mode), so
+// declared once at top level rather than inside chart-base($prefix). HTML text,
+// so `color` (not the SVG `fill` used by svg-tick-label).
+.#{brand.$prefix}-cartesian-y-axis-label {
+ @include cssUtils.typography(label, extra-small);
+ color: cssUtils.$text-neutral-secondary;
+ padding-bottom: cssUtils.$space-s;
+}
+
+.#{brand.$prefix}-cartesian-x-axis-label {
+ @include cssUtils.typography(label, extra-small);
+ color: cssUtils.$text-neutral-secondary;
+ text-align: center;
+}
+
+@mixin crosshair-styles($prefix) {
+ .#{brand.$prefix}-#{$prefix}-crosshair-line {
+ stroke: cssUtils.$border-default;
+ stroke-width: 1;
+ stroke-dasharray: 4 4;
+ }
+
+ .#{brand.$prefix}-#{$prefix}-active-dot-outer {
+ fill: cssUtils.$foreground;
+ stroke: cssUtils.$border-default;
+ stroke-width: 1;
+ }
+
+ .#{brand.$prefix}-#{$prefix}-active-dot-inner {
+ stroke: none;
+ }
+}
+
+// The draw-on used by line + area series strokes (via AnimatedPath). Top-level
+// (not in a mixin) so Sass emits it exactly once however many sheets @use this
+// module. `--path-length` is set by AnimatedPath before paint.
+@keyframes #{brand.$prefix}-draw-line {
+ to {
+ stroke-dashoffset: 0;
+ }
+}
+
+// The opacity-only entrance fade shared by area / heatmap / radial. Top-level
+// (like draw-line above) so Sass emits it exactly once. Each sheet's
+// `--animated` rule sets the `opacity: 0` pre-state and owns its own
+// duration/delay in the `animation:` shorthand.
+@keyframes #{brand.$prefix}-fade-appear {
+ from {
+ opacity: 0;
+ }
+ to {
+ opacity: 1;
+ }
+}
diff --git a/packages/react-ui/src/components/D3Charts/shared/cartesian/layouts/CartesianChartLayout.tsx b/packages/react-ui/src/components/D3Charts/shared/cartesian/layouts/CartesianChartLayout.tsx
new file mode 100644
index 000000000..ba8751d26
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/cartesian/layouts/CartesianChartLayout.tsx
@@ -0,0 +1,293 @@
+import clsx from "clsx";
+import type { ScaleLinear } from "d3-scale";
+import React from "react";
+
+import type { CartesianChartOrchestrator } from "../../../hooks";
+import { MeasureFontScopeContext } from "../../../hooks/core/measureFontScope";
+import { CHART_CLASS_PREFIX } from "../../../utils/constants";
+import { DefaultLegend } from "../../core/DefaultLegend/DefaultLegend";
+import { LabelTooltipProvider } from "../../core/LabelTooltip/LabelTooltip";
+import { ChartTooltip } from "../../core/PortalTooltip/ChartTooltip";
+import { Grid } from "../Grid";
+import { ScrollButtonsHorizontal } from "../ScrollButtonsHorizontal/ScrollButtonsHorizontal";
+import { YAxis } from "../axes/YAxis";
+
+// Handlers are produced by `orch.hover.createMouseHandlers`, which types them on
+// the SVGElement base. The scroll body attaches them to its `<svg>` and the fit
+// body to an inner `<g>`; an SVGElement handler is assignable to both (param
+// contravariance), so one element-agnostic type serves both modes.
+interface MouseHandlers {
+ handleMouseMove: React.MouseEventHandler<SVGElement>;
+ handleMouseLeave: React.MouseEventHandler<SVGElement>;
+ handleTouchMove: React.TouchEventHandler<SVGElement>;
+ handleTouchEnd: React.TouchEventHandler<SVGElement>;
+ handleClick?: React.MouseEventHandler<SVGElement>;
+}
+
+export interface CartesianChartLayoutProps {
+ orch: CartesianChartOrchestrator;
+ yScale: ScaleLinear<number, number>;
+ mouseHandlers: MouseHandlers;
+ defs?: React.ReactNode;
+ series: React.ReactNode;
+ xAxis: React.ReactNode;
+ classPrefix: string;
+ chartType: string;
+ ariaLabel: string;
+ showYAxis: boolean;
+ grid: boolean;
+ showLegend: boolean;
+ xAxisLabel?: React.ReactNode;
+ yAxisLabel?: React.ReactNode;
+ /**
+ * Y-tick-count hint. Threaded UNCHANGED to both the `YAxis` (labels) and the
+ * `Grid` (horizontal lines) so they resolve the identical tick count and stay
+ * aligned. Undefined → each falls back to the height-derived default.
+ */
+ yTickCount?: number;
+ className?: string;
+ /**
+ * The PPTX print-export JSON (from `useExportChartData`). Present only on the
+ * print path; when set it takes precedence over `chartType` on the root's
+ * `data-openui-chart` attribute, so the exporter reads full chart JSON instead
+ * of the bare type string. Undefined off the print path — the attribute then
+ * keeps its existing `chartType` value (no behavior change).
+ */
+ exportData?: string;
+}
+
+/**
+ * The two cartesian layouts unified. `orch.layout` is the discriminant:
+ * "scroll" keeps the y-axis in a fixed `<svg>` beside a horizontally-scrolling
+ * main `<svg>` (with scroll buttons); "fit" packs everything into one `<svg>`
+ * with translated `<g>`s (no scroll). The shared chrome — container, legend,
+ * tooltip — is identical and lives here; the divergent SVG trees are
+ * `ScrollBody`/`FitBody`.
+ */
+export function CartesianChartLayout(props: CartesianChartLayoutProps) {
+ const { orch } = props;
+ const prefix = `${CHART_CLASS_PREFIX}-${props.classPrefix}`;
+
+ // Fit (condensed) mode mirrors react-ui's *Condensed charts: the axis labels
+ // render as standalone text divs — yAxisLabel top-left above the chart,
+ // xAxisLabel bottom-centered below it — and are kept OUT of the legend strip.
+ // Scroll mode keeps them in the legend strip (react-ui's non-condensed look).
+ const isFit = orch.layout === "fit";
+
+ return (
+ <LabelTooltipProvider>
+ {/* Measurement-font scope: XAxis/legend children resolve the tick font
+ from this container's computed style (the render channel) instead of
+ the JS theme context — see measureFontScope.ts. */}
+ <MeasureFontScopeContext.Provider value={orch.refs.containerRef}>
+ <div
+ ref={orch.refs.containerRef}
+ className={clsx(`${prefix}-container`, props.className)}
+ style={orch.style.containerStyle as React.CSSProperties}
+ // PPTX-exporter contract attribute — not derived from the class prefix.
+ data-openui-chart={props.exportData ?? props.chartType}
+ >
+ {isFit && props.yAxisLabel && (
+ <div className={`${CHART_CLASS_PREFIX}-cartesian-y-axis-label`}>{props.yAxisLabel}</div>
+ )}
+
+ {orch.layout === "scroll" ? (
+ <ScrollBody {...props} prefix={prefix} />
+ ) : (
+ <FitBody {...props} prefix={prefix} />
+ )}
+
+ {isFit && props.xAxisLabel && (
+ <div className={`${CHART_CLASS_PREFIX}-cartesian-x-axis-label`}>{props.xAxisLabel}</div>
+ )}
+
+ {props.showLegend && (
+ <DefaultLegend
+ ref={orch.refs.legendRef}
+ items={orch.legend.legendItems}
+ hiddenSeries={orch.legend.hiddenSeries}
+ onItemClick={orch.legend.toggleSeries}
+ isExpanded={orch.legend.isLegendExpanded}
+ setIsExpanded={orch.legend.setIsLegendExpanded}
+ containerWidth={orch.dimensions.containerWidth}
+ xAxisLabel={isFit ? undefined : props.xAxisLabel}
+ yAxisLabel={isFit ? undefined : props.yAxisLabel}
+ />
+ )}
+
+ {orch.tooltip.tooltipPayload && orch.hover.mousePos && (
+ <ChartTooltip
+ label={orch.tooltip.tooltipPayload.label}
+ items={orch.tooltip.tooltipPayload.items}
+ viewportPosition={orch.hover.mousePos}
+ />
+ )}
+ </div>
+ </MeasureFontScopeContext.Provider>
+ </LabelTooltipProvider>
+ );
+}
+
+// ── scroll mode: fixed y-axis svg + scrolling main svg + scroll buttons ──────
+function ScrollBody({
+ orch,
+ yScale,
+ mouseHandlers,
+ defs,
+ series,
+ xAxis,
+ showYAxis,
+ grid,
+ yTickCount,
+ ariaLabel,
+ prefix,
+}: CartesianChartLayoutProps & { prefix: string }) {
+ return (
+ <>
+ <div className={`${prefix}-container-inner`}>
+ {showYAxis && (
+ <div className={`${prefix}-y-axis-container`}>
+ <svg
+ width={orch.dimensions.effectiveYAxisWidth}
+ height={orch.dimensions.totalHeight}
+ style={{ overflow: "visible" }}
+ >
+ <g transform={`translate(0, ${orch.dimensions.marginTop})`}>
+ <YAxis
+ className={`${prefix}-y-axis`}
+ tickClassName={`${prefix}-y-tick`}
+ scale={yScale}
+ width={orch.dimensions.effectiveYAxisWidth}
+ chartHeight={orch.dimensions.chartInnerHeight}
+ tickCount={yTickCount}
+ />
+ </g>
+ </svg>
+ </div>
+ )}
+
+ <div
+ ref={orch.refs.mainContainerRef}
+ className={`${prefix}-main-container`}
+ onScroll={orch.scroll.handleScroll}
+ >
+ <svg
+ role="img"
+ aria-label={ariaLabel}
+ width={orch.dimensions.chartAreaWidth}
+ height={orch.dimensions.totalHeight}
+ onMouseMove={mouseHandlers.handleMouseMove}
+ onMouseLeave={mouseHandlers.handleMouseLeave}
+ onTouchMove={mouseHandlers.handleTouchMove}
+ onTouchEnd={mouseHandlers.handleTouchEnd}
+ onClick={mouseHandlers.handleClick}
+ >
+ {defs}
+ <g
+ transform={`translate(0, ${orch.dimensions.marginTop})`}
+ clipPath={`url(#clip-${orch.identity.chartId})`}
+ >
+ {grid && (
+ <Grid
+ className={`${prefix}-grid`}
+ yScale={yScale}
+ chartWidth={orch.dimensions.chartAreaWidth}
+ chartHeight={orch.dimensions.chartInnerHeight}
+ tickCount={yTickCount}
+ />
+ )}
+ {series}
+ </g>
+ <g
+ transform={`translate(0, ${orch.dimensions.chartInnerHeight + orch.dimensions.marginTop})`}
+ >
+ {xAxis}
+ </g>
+ </svg>
+ </div>
+ </div>
+
+ <ScrollButtonsHorizontal
+ dataWidth={orch.dimensions.dataWidth}
+ effectiveWidth={orch.dimensions.containerWidth - orch.dimensions.effectiveYAxisWidth}
+ canScrollLeft={orch.scroll.canScrollLeft}
+ canScrollRight={orch.scroll.canScrollRight}
+ onScrollLeft={() => orch.scroll.scrollTo("left")}
+ onScrollRight={() => orch.scroll.scrollTo("right")}
+ />
+ </>
+ );
+}
+
+// ── fit mode: one svg, translated g's, transparent hit-rect, no scroll ───────
+function FitBody({
+ orch,
+ yScale,
+ mouseHandlers,
+ defs,
+ series,
+ xAxis,
+ showYAxis,
+ grid,
+ yTickCount,
+ ariaLabel,
+ prefix,
+}: CartesianChartLayoutProps & { prefix: string }) {
+ return (
+ <svg
+ role="img"
+ aria-label={ariaLabel}
+ width={orch.dimensions.totalSvgWidth}
+ height={orch.dimensions.totalHeight}
+ style={{ overflow: "visible" }}
+ >
+ {defs}
+
+ {showYAxis && (
+ <g transform={`translate(0, ${orch.dimensions.marginTop})`}>
+ <YAxis
+ className={`${prefix}-y-axis`}
+ tickClassName={`${prefix}-y-tick`}
+ scale={yScale}
+ width={orch.dimensions.effectiveYAxisWidth}
+ chartHeight={orch.dimensions.chartInnerHeight}
+ tickCount={yTickCount}
+ />
+ </g>
+ )}
+
+ <g
+ transform={`translate(${orch.dimensions.effectiveYAxisWidth}, ${orch.dimensions.marginTop})`}
+ onMouseMove={mouseHandlers.handleMouseMove}
+ onMouseLeave={mouseHandlers.handleMouseLeave}
+ onTouchMove={mouseHandlers.handleTouchMove}
+ onTouchEnd={mouseHandlers.handleTouchEnd}
+ onClick={mouseHandlers.handleClick}
+ >
+ <rect
+ width={orch.dimensions.chartAreaWidth}
+ height={orch.dimensions.chartInnerHeight}
+ fill="transparent"
+ />
+ <g clipPath={`url(#clip-${orch.identity.chartId})`}>
+ {grid && (
+ <Grid
+ className={`${prefix}-grid`}
+ yScale={yScale}
+ chartWidth={orch.dimensions.chartAreaWidth}
+ chartHeight={orch.dimensions.chartInnerHeight}
+ tickCount={yTickCount}
+ />
+ )}
+ {series}
+ </g>
+ </g>
+
+ <g
+ transform={`translate(${orch.dimensions.effectiveYAxisWidth}, ${orch.dimensions.chartInnerHeight + orch.dimensions.marginTop})`}
+ >
+ {xAxis}
+ </g>
+ </svg>
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/shared/cartesian/roundedBarPath.test.ts b/packages/react-ui/src/components/D3Charts/shared/cartesian/roundedBarPath.test.ts
new file mode 100644
index 000000000..2c07334f9
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/cartesian/roundedBarPath.test.ts
@@ -0,0 +1,93 @@
+import { describe, expect, it } from "vitest";
+import { BAR_RADIUS } from "../../BarChart/parts/horizontalBarGeometry";
+import { MIN_BAR_WIDTH, roundedBarPath } from "./roundedBarPath";
+
+/**
+ * Extract the endpoint coordinates of every path command in a `roundedBarPath`
+ * `d` string. `M`/`L` endpoints are their single `x,y`; an `A` command's
+ * endpoint is its trailing `x,y` (the leading `rx,ry` radii are skipped). Used
+ * to assert the drawn path stays inside the bar's box.
+ */
+function pathPoints(d: string): Array<[number, number]> {
+ const points: Array<[number, number]> = [];
+ const commands = d.match(/[MLAZ][^MLAZ]*/g) ?? [];
+ for (const cmd of commands) {
+ const type = cmd[0];
+ const nums = (cmd.slice(1).match(/-?\d+(?:\.\d+)?/g) ?? []).map(Number);
+ if (type === "M" || type === "L") {
+ points.push([nums[0]!, nums[1]!]);
+ } else if (type === "A") {
+ // A rx,ry rot large-arc sweep x y → endpoint is the last two numbers.
+ points.push([nums[nums.length - 2]!, nums[nums.length - 1]!]);
+ }
+ }
+ return points;
+}
+
+describe("MIN_BAR_WIDTH", () => {
+ it("matches the openui reference value", () => {
+ expect(MIN_BAR_WIDTH).toBe(2);
+ });
+});
+
+describe("roundedBarPath", () => {
+ const positive: [number, number, number, number] = [0, BAR_RADIUS, BAR_RADIUS, 0];
+
+ it("always starts with a move command", () => {
+ expect(roundedBarPath(0, 0, 100, 16, positive).startsWith("M ")).toBe(true);
+ });
+ it("draws arcs when radii > 0 and the bar clears both thresholds", () => {
+ const d = roundedBarPath(0, 0, 100, 16, positive);
+ expect(d).toContain("A ");
+ // both right-side corners round; left side stays straight
+ expect(d.match(/A /g)).toHaveLength(2);
+ });
+ it("rounds only the left end for a negative-shaped radii array", () => {
+ const negative: [number, number, number, number] = [BAR_RADIUS, 0, 0, BAR_RADIUS];
+ const d = roundedBarPath(0, 0, 100, 16, negative);
+ expect(d.match(/A /g)).toHaveLength(2);
+ });
+ it("suppresses all rounding when the bar is too thin (h < 7)", () => {
+ const d = roundedBarPath(0, 0, 100, 6, positive);
+ expect(d).not.toContain("A ");
+ expect(d.startsWith("M ")).toBe(true);
+ expect(d.endsWith("Z")).toBe(true);
+ });
+ it("keeps rounding at the thickness boundary (h = 7)", () => {
+ expect(roundedBarPath(0, 0, 100, 7, positive)).toContain("A ");
+ });
+ it("suppresses all rounding when the bar is too short (w < MIN_BAR_WIDTH)", () => {
+ const d = roundedBarPath(0, 0, 1, 16, positive);
+ expect(d).not.toContain("A ");
+ });
+ it("clamps rounding at the width boundary so the rounded end never overhangs x (w = MIN_BAR_WIDTH)", () => {
+ // A 2px-wide bar still rounds, but the per-corner clamp (min(r, w/2, h/2) →
+ // radius 1) keeps every coordinate at or right of x — no self-crossing /
+ // overhanging path (openui would draw radius 4 here and shoot left of x).
+ const d = roundedBarPath(0, 0, MIN_BAR_WIDTH, 16, positive);
+ expect(d).toContain("A ");
+ const xs = pathPoints(d).map(([px]) => px);
+ expect(Math.min(...xs)).toBeGreaterThanOrEqual(0);
+ });
+ it("draws convex (sweep=1) arcs that stay inside the bar box on a normal positive bar", () => {
+ const d = roundedBarPath(0, 0, 100, 16, positive);
+ // Both rounded (right-end) corners are convex quarter-arcs: sweep flag = 1.
+ const sweeps = d.match(/A [\d.]+,[\d.]+ 0 0 1 /g) ?? [];
+ expect(sweeps).toHaveLength(2);
+ // No path coordinate escapes [x, x+w] × [y, y+h].
+ for (const [px, py] of pathPoints(d)) {
+ expect(px).toBeGreaterThanOrEqual(0);
+ expect(px).toBeLessThanOrEqual(100);
+ expect(py).toBeGreaterThanOrEqual(0);
+ expect(py).toBeLessThanOrEqual(16);
+ }
+ });
+ it("emits no arc for an all-zero radii array even on a large bar", () => {
+ const d = roundedBarPath(0, 0, 100, 16, [0, 0, 0, 0]);
+ expect(d).not.toContain("A ");
+ expect(d.startsWith("M ")).toBe(true);
+ });
+ it("closes the path", () => {
+ expect(roundedBarPath(5, 5, 50, 16, positive).endsWith("Z")).toBe(true);
+ });
+});
diff --git a/packages/react-ui/src/components/D3Charts/shared/cartesian/roundedBarPath.ts b/packages/react-ui/src/components/D3Charts/shared/cartesian/roundedBarPath.ts
new file mode 100644
index 000000000..92771cc28
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/cartesian/roundedBarPath.ts
@@ -0,0 +1,59 @@
+// Orientation-neutral rounded-bar geometry shared by the vertical and
+// horizontal BarChart renderers: the per-corner rounded-rect SVG path (plus the
+// minimum-width threshold that suppresses its rounding). Kept out of the React
+// layer so every value is unit-testable in isolation (node env, no DOM).
+//
+// Ported from openui's LineInBarShape path geometry.
+
+/** A bar's extent (its rounded dimension) must reach this before its corners
+ * round; narrower bars render as plain rectangles (px). openui MIN_BAR_WIDTH. */
+export const MIN_BAR_WIDTH = 2;
+
+/**
+ * SVG `<path d>` for a bar as a rounded rectangle at `(x, y)` of size `w × h`,
+ * with per-corner radii `[tl, tr, br, bl]`. Traversed clockwise (top edge
+ * →, right ↓, bottom ←, left ↑) with `sweep=1` convex quarter-arcs; a corner
+ * with radius 0 is a plain `L`. All rounding is SUPPRESSED — the bar becomes a
+ * plain rectangle — when the bar is too thin (`h < 7`) or too short
+ * (`w < MIN_BAR_WIDTH`), matching openui's LineInBarShape thresholds. Each
+ * corner radius is then CLAMPED per corner to the bar's half-dimensions
+ * (`min(r, w/2, h/2)`) so a narrow or short bar can never produce a
+ * self-crossing or overhanging path (a coordinate left of `x` / above `y`) —
+ * stricter than openui, which omits this clamp. The caller always passes a
+ * non-negative `w` (it positions `x` at the left edge for negative bars), so
+ * this stays sign-agnostic. Orientation-neutral: vertical bars round their
+ * top/bottom corners, horizontal bars their left/right — the caller picks the
+ * radii array.
+ */
+export function roundedBarPath(
+ x: number,
+ y: number,
+ w: number,
+ h: number,
+ radii: [number, number, number, number],
+): string {
+ const base = h < 7 || w < MIN_BAR_WIDTH ? [0, 0, 0, 0] : radii;
+ // Clamp each corner independently to half the bar's smaller dimension so the
+ // quarter-arcs can never overshoot the bar box (no path point < x or < y).
+ const maxRadius = Math.min(w / 2, h / 2);
+ const tl = Math.min(base[0]!, maxRadius);
+ const tr = Math.min(base[1]!, maxRadius);
+ const br = Math.min(base[2]!, maxRadius);
+ const bl = Math.min(base[3]!, maxRadius);
+
+ const right = x + w;
+ const bottom = y + h;
+
+ return [
+ `M ${x + tl},${y}`,
+ `L ${right - tr},${y}`,
+ tr > 0 ? `A ${tr},${tr} 0 0 1 ${right},${y + tr}` : `L ${right},${y}`,
+ `L ${right},${bottom - br}`,
+ br > 0 ? `A ${br},${br} 0 0 1 ${right - br},${bottom}` : `L ${right},${bottom}`,
+ `L ${x + bl},${bottom}`,
+ bl > 0 ? `A ${bl},${bl} 0 0 1 ${x},${bottom - bl}` : `L ${x},${bottom}`,
+ `L ${x},${y + tl}`,
+ tl > 0 ? `A ${tl},${tl} 0 0 1 ${x + tl},${y}` : `L ${x},${y}`,
+ "Z",
+ ].join(" ");
+}
diff --git a/packages/react-ui/src/components/D3Charts/shared/cartesian/seriesGeometry.test.ts b/packages/react-ui/src/components/D3Charts/shared/cartesian/seriesGeometry.test.ts
new file mode 100644
index 000000000..3c261ee7e
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/cartesian/seriesGeometry.test.ts
@@ -0,0 +1,61 @@
+import { curveLinear, curveMonotoneX, area as d3Area, line as d3Line } from "d3-shape";
+import { describe, expect, it } from "vitest";
+import { AREA_STRIDE, buildAreaD, buildAreaEdgeD, buildLineD, LINE_STRIDE } from "./seriesGeometry";
+
+type Pt = { x: number; y0: number; y1: number; yEdge: number };
+
+const pts: Pt[] = [
+ { x: 0, y0: 200, y1: 120, yEdge: 120 },
+ { x: 50, y0: 200, y1: 80, yEdge: 80 },
+ { x: 100, y0: 200, y1: 150, yEdge: 150 },
+ { x: 150, y0: 200, y1: 60, yEdge: 60 },
+];
+
+const lineVector = Float64Array.from(pts.flatMap((p) => [p.x, p.y1]));
+const areaVector = Float64Array.from(pts.flatMap((p) => [p.x, p.y0, p.y1, p.yEdge]));
+
+describe("flat-vector path builders match direct d3 output", () => {
+ it.each([
+ ["linear", curveLinear],
+ ["monotoneX", curveMonotoneX],
+ ] as const)("buildLineD (%s curve)", (_name, curve) => {
+ const direct = d3Line<Pt>()
+ .x((p) => p.x)
+ .y((p) => p.y1)
+ .curve(curve)(pts);
+ expect(buildLineD(lineVector, curve)).toBe(direct);
+ expect(lineVector.length).toBe(pts.length * LINE_STRIDE);
+ });
+
+ it.each([
+ ["linear", curveLinear],
+ ["monotoneX", curveMonotoneX],
+ ] as const)("buildAreaD (%s curve)", (_name, curve) => {
+ const direct = d3Area<Pt>()
+ .x((p) => p.x)
+ .y0((p) => p.y0)
+ .y1((p) => p.y1)
+ .curve(curve)(pts);
+ expect(buildAreaD(areaVector, curve)).toBe(direct);
+ expect(areaVector.length).toBe(pts.length * AREA_STRIDE);
+ });
+
+ it("buildAreaEdgeD strokes the yEdge scalar, not y1", () => {
+ // A diverging-stack shape: the edge differs from y1 on the "negative"
+ // point (index 2), which is exactly what the edge scalar exists for.
+ const edgy = areaVector.slice();
+ edgy[2 * AREA_STRIDE + 3] = 230; // negative segment: edge = y(d[0]) below zero
+ const direct = d3Line<number>()
+ .x((i) => edgy[i * AREA_STRIDE]!)
+ .y((i) => edgy[i * AREA_STRIDE + 3]!)
+ .curve(curveLinear)(pts.map((_, i) => i));
+ expect(buildAreaEdgeD(edgy, curveLinear)).toBe(direct);
+ expect(buildAreaEdgeD(edgy, curveLinear)).not.toBe(buildLineD(lineVector, curveLinear));
+ });
+
+ it("empty vectors build empty path data", () => {
+ expect(buildLineD(new Float64Array(0), curveLinear)).toBe("");
+ expect(buildAreaD(new Float64Array(0), curveLinear)).toBe("");
+ expect(buildAreaEdgeD(new Float64Array(0), curveLinear)).toBe("");
+ });
+});
diff --git a/packages/react-ui/src/components/D3Charts/shared/cartesian/seriesGeometry.ts b/packages/react-ui/src/components/D3Charts/shared/cartesian/seriesGeometry.ts
new file mode 100644
index 000000000..a694fa592
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/cartesian/seriesGeometry.ts
@@ -0,0 +1,57 @@
+// Flat-vector geometry builders for the line/area series data morph.
+//
+// A series' rendered geometry is flattened into one Float64Array of pixel
+// scalars — the shape the spring engine animates (dataMorph springs each
+// scalar). These builders turn such a vector back into SVG path data. Both
+// the React render (target attributes) and the morph's per-tick regeneration
+// go through the SAME builder, so the two can never disagree about what a set
+// of points looks like.
+//
+// Layouts (documented here, encoded in the strides):
+// line: [x, y] per point (LINE_STRIDE = 2)
+// area: [x, y0, y1, yEdge] per point (AREA_STRIDE = 4)
+// `yEdge` is the area's stroked value edge as its own scalar (the running
+// total y(d[1]) for stacked series, the value itself otherwise), decided at
+// TARGET-build time rather than per morph tick.
+//
+// Pure (no DOM, no React) — unit-tested directly.
+
+import { area as d3Area, line as d3Line, type CurveFactory } from "d3-shape";
+
+export const LINE_STRIDE = 2;
+export const AREA_STRIDE = 4;
+
+/** Index array [0..n) — what the d3 generators iterate while accessors read
+ * the flat vector. Tiny (≤ point count) and short-lived. */
+const indices = (n: number): number[] => Array.from({ length: n }, (_, i) => i);
+
+/** Line `d` from `[x, y]` scalars. */
+export function buildLineD(values: ArrayLike<number>, curve: CurveFactory): string {
+ const n = Math.floor(values.length / LINE_STRIDE);
+ const gen = d3Line<number>()
+ .x((i) => values[i * LINE_STRIDE] ?? 0)
+ .y((i) => values[i * LINE_STRIDE + 1] ?? 0)
+ .curve(curve);
+ return gen(indices(n)) ?? "";
+}
+
+/** Area fill `d` from `[x, y0, y1, yEdge]` scalars (yEdge unused here). */
+export function buildAreaD(values: ArrayLike<number>, curve: CurveFactory): string {
+ const n = Math.floor(values.length / AREA_STRIDE);
+ const gen = d3Area<number>()
+ .x((i) => values[i * AREA_STRIDE] ?? 0)
+ .y0((i) => values[i * AREA_STRIDE + 1] ?? 0)
+ .y1((i) => values[i * AREA_STRIDE + 2] ?? 0)
+ .curve(curve);
+ return gen(indices(n)) ?? "";
+}
+
+/** Area value-edge stroke `d` from the same `[x, y0, y1, yEdge]` scalars. */
+export function buildAreaEdgeD(values: ArrayLike<number>, curve: CurveFactory): string {
+ const n = Math.floor(values.length / AREA_STRIDE);
+ const gen = d3Line<number>()
+ .x((i) => values[i * AREA_STRIDE] ?? 0)
+ .y((i) => values[i * AREA_STRIDE + 3] ?? 0)
+ .curve(curve);
+ return gen(indices(n)) ?? "";
+}
diff --git a/packages/react-ui/src/components/D3Charts/shared/core/ChartShell.tsx b/packages/react-ui/src/components/D3Charts/shared/core/ChartShell.tsx
new file mode 100644
index 000000000..488ce0473
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/core/ChartShell.tsx
@@ -0,0 +1,81 @@
+import clsx from "clsx";
+import React from "react";
+
+import { MeasureFontScopeContext } from "../../hooks/core/measureFontScope";
+import { CHART_CLASS_PREFIX } from "../../utils/constants";
+import { LabelTooltipProvider } from "./LabelTooltip/LabelTooltip";
+
+interface ChartShellProps {
+ containerRef: React.Ref<HTMLDivElement>;
+ /** e.g. `${CHART_CLASS_PREFIX}-pie-chart` → the persistent div gets `${classPrefix}-container`. */
+ classPrefix: string;
+ /** The consumer's passthrough `className`. */
+ className?: string;
+ style: React.CSSProperties;
+ isEmpty: boolean;
+ /**
+ * The PPTX print-export JSON (from `useExportChartData`) for the persistent
+ * container's `data-openui-chart` attribute. Set only on
+ * the print path (Pie/Radial/HorizontalBar pass it); `undefined` otherwise,
+ * so React omits the attribute entirely and the six charts that never pass
+ * it are unchanged.
+ */
+ exportData?: string;
+ /**
+ * The chart content, as a render function so it is constructed ONLY when not
+ * empty — mirroring the inline `isEmpty ? <span/> : <>…</>` ternary it
+ * replaces (which never built the content branch on an empty frame).
+ */
+ children: () => React.ReactNode;
+}
+
+/**
+ * The persistent-container shell shared by the six non-cartesian charts
+ * (pie / radial / radar / scatter / heatmap / funnel).
+ *
+ * The div is measured by a ResizeObserver and MUST NOT unmount: the empty state
+ * swaps the div's CONTENT (a "No data" span ↔ the chart), never the div itself.
+ * Unmounting it on an empty stream frame would leave the observer reporting a
+ * final 0×0 with the replacement node never re-observed — freezing the chart at
+ * zero size for the rest of its life. The cartesian charts dodge this with a
+ * hook-free wrapper guard instead; the two empty-state strategies are
+ * deliberately separate — do not merge them.
+ */
+export const ChartShell: React.FC<ChartShellProps> = ({
+ containerRef,
+ classPrefix,
+ className,
+ style,
+ isEmpty,
+ exportData,
+ children,
+}) => (
+ <LabelTooltipProvider>
+ {/* Measurement-font scope: children measuring text (axis label sheets,
+ legend) resolve the tick font from THIS container's computed style —
+ the render channel — rather than the JS theme context. Callback refs
+ can't be dereferenced, so they get no scope (theme fallback applies);
+ every in-repo chart passes a useRef object. */}
+ <MeasureFontScopeContext.Provider
+ value={typeof containerRef === "object" ? containerRef : null}
+ >
+ <div
+ ref={containerRef}
+ className={clsx(
+ `${classPrefix}-container`,
+ isEmpty && `${CHART_CLASS_PREFIX}-chart-empty`,
+ className,
+ )}
+ style={style}
+ // PPTX-exporter contract attribute — not derived from the class prefix.
+ data-openui-chart={exportData}
+ >
+ {isEmpty ? (
+ <span className={`${CHART_CLASS_PREFIX}-chart-empty-text`}>No data available</span>
+ ) : (
+ children()
+ )}
+ </div>
+ </MeasureFontScopeContext.Provider>
+ </LabelTooltipProvider>
+);
diff --git a/packages/react-ui/src/components/D3Charts/shared/core/DefaultLegend/DefaultLegend.tsx b/packages/react-ui/src/components/D3Charts/shared/core/DefaultLegend/DefaultLegend.tsx
new file mode 100644
index 000000000..45fb231c7
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/core/DefaultLegend/DefaultLegend.tsx
@@ -0,0 +1,164 @@
+import clsx from "clsx";
+import { ChevronDownIcon, ChevronUpIcon } from "lucide-react";
+import React, { memo, useCallback, useState } from "react";
+import { Button } from "../../../../Button";
+import { type LegendItem } from "../../../types";
+import { CHART_CLASS_PREFIX } from "../../../utils/constants";
+import { useDefaultLegend } from "./hooks/useDefaultLegend";
+
+interface DefaultLegendProps {
+ items: LegendItem[];
+ className?: string;
+ yAxisLabel?: React.ReactNode;
+ xAxisLabel?: React.ReactNode;
+ containerWidth?: number;
+ isExpanded: boolean;
+ setIsExpanded: (isExpanded: boolean) => void;
+ style?: React.CSSProperties;
+ onItemClick?: (key: string) => void;
+ hiddenSeries?: Set<string>;
+}
+
+const DefaultLegend = memo(
+ React.forwardRef<HTMLDivElement, DefaultLegendProps>(
+ (
+ {
+ items,
+ className,
+ yAxisLabel,
+ xAxisLabel,
+ containerWidth,
+ isExpanded,
+ setIsExpanded,
+ style,
+ onItemClick,
+ hiddenSeries,
+ },
+ ref,
+ ) => {
+ const [buttonWidth, setButtonWidth] = useState(0);
+ const { displayItems, hasMoreItems, toggleButtonText } = useDefaultLegend({
+ items,
+ containerWidth,
+ buttonWidth,
+ isExpanded,
+ });
+
+ const buttonRef = useCallback(
+ (node: HTMLButtonElement | null) => {
+ if (node) {
+ if (node.clientWidth !== buttonWidth) {
+ setButtonWidth(node.clientWidth);
+ }
+ }
+ },
+ [buttonWidth],
+ );
+
+ const handleToggleExpanded = () => {
+ setIsExpanded(!isExpanded);
+ };
+
+ const showToggleButton = hasMoreItems;
+
+ return (
+ <div
+ ref={ref}
+ className={clsx(
+ `${CHART_CLASS_PREFIX}-chart-legend-container ${CHART_CLASS_PREFIX}-chart-legend--bottom`,
+ className,
+ )}
+ style={style}
+ >
+ {(xAxisLabel || yAxisLabel) && (
+ <div className={`${CHART_CLASS_PREFIX}-chart-legend-axis-label-container`}>
+ {xAxisLabel && (
+ <span className={`${CHART_CLASS_PREFIX}-chart-legend-axis-label`}>
+ X-Axis:{" "}
+ <span className={`${CHART_CLASS_PREFIX}-chart-legend-axis-label-text`}>
+ {xAxisLabel}
+ </span>
+ </span>
+ )}
+ {yAxisLabel && (
+ <span className={`${CHART_CLASS_PREFIX}-chart-legend-axis-label`}>
+ Y-Axis:{" "}
+ <span className={`${CHART_CLASS_PREFIX}-chart-legend-axis-label-text`}>
+ {yAxisLabel}
+ </span>
+ </span>
+ )}
+ </div>
+ )}
+ <div
+ className={clsx(`${CHART_CLASS_PREFIX}-chart-legend`, {
+ [`${CHART_CLASS_PREFIX}-chart-legend--expanded`]: isExpanded,
+ [`${CHART_CLASS_PREFIX}-chart-legend--collapsed`]: !isExpanded && showToggleButton,
+ })}
+ >
+ {displayItems.map((item) => {
+ const isHidden = hiddenSeries?.has(item.key);
+ return (
+ <div
+ key={item.key}
+ className={`${CHART_CLASS_PREFIX}-chart-legend-item`}
+ style={{
+ cursor: onItemClick ? "pointer" : undefined,
+ opacity: isHidden ? 0.3 : 1,
+ }}
+ onClick={onItemClick ? () => onItemClick(item.key) : undefined}
+ >
+ {item.icon ? (
+ <item.icon />
+ ) : (
+ <div
+ className={`${CHART_CLASS_PREFIX}-chart-legend-item-indicator`}
+ style={{ backgroundColor: item.color }}
+ />
+ )}
+ <div className={`${CHART_CLASS_PREFIX}-chart-legend-item-label-container`}>
+ <span className={`${CHART_CLASS_PREFIX}-chart-legend-item-label`}>
+ {item.label}
+ </span>
+ {item.percentage !== undefined && (
+ <span className={`${CHART_CLASS_PREFIX}-chart-legend-item-percentage`}>
+ {item.percentage.toFixed(1)}%
+ </span>
+ )}
+ </div>
+ </div>
+ );
+ })}
+
+ {showToggleButton && (
+ <Button
+ variant="tertiary"
+ size="small"
+ ref={buttonRef}
+ className={`${CHART_CLASS_PREFIX}-chart-legend-toggle-button`}
+ onClick={handleToggleExpanded}
+ iconRight={
+ isExpanded ? (
+ <ChevronUpIcon
+ className={`${CHART_CLASS_PREFIX}-chart-legend-toggle-button-icon`}
+ />
+ ) : (
+ <ChevronDownIcon
+ className={`${CHART_CLASS_PREFIX}-chart-legend-toggle-button-icon`}
+ />
+ )
+ }
+ >
+ {toggleButtonText}
+ </Button>
+ )}
+ </div>
+ </div>
+ );
+ },
+ ),
+);
+
+DefaultLegend.displayName = "DefaultLegend";
+export { DefaultLegend };
+export type { DefaultLegendProps };
diff --git a/packages/react-ui/src/components/D3Charts/shared/core/DefaultLegend/defaultLegend.scss b/packages/react-ui/src/components/D3Charts/shared/core/DefaultLegend/defaultLegend.scss
new file mode 100644
index 000000000..512db29f0
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/core/DefaultLegend/defaultLegend.scss
@@ -0,0 +1,98 @@
+@use "../../../../../cssUtils" as cssUtils;
+@use "../../../prefix" as brand;
+
+.#{brand.$prefix}-chart-legend-container {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: cssUtils.$space-s;
+}
+
+.#{brand.$prefix}-chart-legend-axis-label-container {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: cssUtils.$space-m;
+ flex-wrap: wrap;
+}
+
+.#{brand.$prefix}-chart-legend-axis-label {
+ @include cssUtils.typography(label, extra-small);
+ color: cssUtils.$text-neutral-secondary;
+
+ &-text {
+ color: cssUtils.$text-neutral-primary;
+ }
+}
+
+.#{brand.$prefix}-chart-legend {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: cssUtils.$space-m;
+ text-transform: capitalize;
+ flex-wrap: wrap;
+
+ &--bottom {
+ padding-top: cssUtils.$space-m;
+ }
+
+ &--collapsed {
+ flex-wrap: nowrap;
+ overflow: hidden;
+ }
+
+ &--expanded {
+ flex-wrap: wrap;
+ }
+
+ &-item {
+ display: flex;
+ align-items: center;
+ gap: cssUtils.$space-xs;
+
+ svg {
+ height: 10px;
+ width: 10px;
+ color: cssUtils.$text-neutral-primary;
+ }
+
+ &-indicator {
+ height: 10px;
+ width: 10px;
+ flex-shrink: 0;
+ border-radius: cssUtils.$radius-2xs;
+ background-color: var(--color-bg);
+ }
+
+ &-label {
+ @include cssUtils.typography(label, extra-small);
+ color: cssUtils.$text-neutral-primary;
+ }
+ }
+
+ &-toggle-button {
+ @include cssUtils.typography(label, extra-small);
+ color: cssUtils.$text-neutral-primary;
+ padding-left: cssUtils.$space-2xs;
+ padding-right: cssUtils.$space-3xs;
+
+ &-icon {
+ width: 1em;
+ height: 1em;
+ color: cssUtils.$text-neutral-primary;
+ }
+ }
+
+ &-item-label-container {
+ display: flex;
+ align-items: center;
+ gap: cssUtils.$space-2xs;
+ }
+
+ &-item-percentage {
+ @include cssUtils.typography(label, extra-small);
+ color: cssUtils.$text-neutral-secondary;
+ }
+}
diff --git a/packages/react-ui/src/components/D3Charts/shared/core/DefaultLegend/hooks/useDefaultLegend.ts b/packages/react-ui/src/components/D3Charts/shared/core/DefaultLegend/hooks/useDefaultLegend.ts
new file mode 100644
index 000000000..a3f58e1aa
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/core/DefaultLegend/hooks/useDefaultLegend.ts
@@ -0,0 +1,102 @@
+import { useMemo } from "react";
+import { useCanvasContextForLabelSize } from "../../../../hooks";
+import { LegendItem } from "../../../../types";
+
+const CHARACTER_WIDTH = 7;
+const INDICATOR_WIDTH = 10;
+const GAP_WIDTH = 12;
+
+interface UseDefaultLegendProps {
+ items: LegendItem[];
+ containerWidth?: number;
+ buttonWidth?: number;
+ isExpanded: boolean;
+}
+
+interface UseDefaultLegendResult {
+ displayItems: LegendItem[];
+ hasMoreItems: boolean;
+ toggleButtonText: string;
+}
+
+export const useDefaultLegend = ({
+ items,
+ containerWidth,
+ buttonWidth,
+ isExpanded,
+}: UseDefaultLegendProps): UseDefaultLegendResult => {
+ const canvasContext = useCanvasContextForLabelSize();
+
+ const calculateItemWidth = useMemo(
+ () =>
+ (item: LegendItem): number => {
+ let displayText = item.label;
+ if (item.percentage !== undefined) {
+ displayText += ` (${item.percentage.toFixed(1)}%)`;
+ }
+ if (canvasContext) {
+ return canvasContext.measureText(displayText).width + INDICATOR_WIDTH + GAP_WIDTH;
+ }
+ return displayText.length * CHARACTER_WIDTH + INDICATOR_WIDTH + GAP_WIDTH;
+ },
+ [canvasContext],
+ );
+
+ const { visibleItems, hasMoreItems } = useMemo(() => {
+ if (!containerWidth || items.length === 0) {
+ return { visibleItems: items, hasMoreItems: false };
+ }
+
+ const availableWidth = containerWidth - (buttonWidth ?? 0);
+ let currentWidth = 0;
+ let visibleCount = 0;
+
+ for (let i = 0; i < items.length; i++) {
+ const item = items[i];
+ if (!item) continue;
+ const itemWidth = calculateItemWidth(item);
+ const requiredWidth = visibleCount > 0 ? itemWidth + GAP_WIDTH : itemWidth;
+ if (currentWidth + requiredWidth <= availableWidth) {
+ currentWidth += requiredWidth;
+ visibleCount++;
+ } else {
+ break;
+ }
+ }
+
+ if (visibleCount === items.length) {
+ return { visibleItems: items, hasMoreItems: false };
+ }
+
+ if (visibleCount === 0 && items[0]) {
+ return {
+ visibleItems: [items[0]],
+ hasMoreItems: items.length > 1,
+ };
+ }
+
+ return {
+ visibleItems: items.slice(0, visibleCount),
+ hasMoreItems: items.length > visibleCount,
+ };
+ }, [items, containerWidth, buttonWidth, calculateItemWidth]);
+
+ const displayItems = useMemo(
+ () => (isExpanded ? items : visibleItems),
+ [isExpanded, items, visibleItems],
+ );
+
+ const toggleButtonText = useMemo(() => {
+ if (isExpanded) {
+ return "Show Less";
+ }
+ const hiddenCount = items.length - visibleItems.length;
+ return `${hiddenCount} more`;
+ }, [isExpanded, items.length, visibleItems.length]);
+
+ return {
+ displayItems,
+ hasMoreItems,
+ toggleButtonText,
+ };
+};
diff --git a/packages/react-ui/src/components/D3Charts/shared/core/LabelTooltip/LabelTooltip.tsx b/packages/react-ui/src/components/D3Charts/shared/core/LabelTooltip/LabelTooltip.tsx
new file mode 100644
index 000000000..d4b6be191
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/core/LabelTooltip/LabelTooltip.tsx
@@ -0,0 +1,86 @@
+import * as Tooltip from "@radix-ui/react-tooltip";
+import React from "react";
+import { CHART_CLASS_PREFIX } from "../../../utils/constants";
+
+interface LabelTooltipProviderProps {
+ children: React.ReactNode;
+ delayDuration?: number;
+ skipDelayDuration?: number;
+ disableHoverableContent?: boolean;
+}
+
+interface LabelTooltipProps {
+ children: React.ReactNode;
+ content: string;
+ side?: "top" | "bottom" | "left" | "right";
+ sideOffset?: number;
+ delayDuration?: number;
+ className?: string;
+ disabled?: boolean;
+ open?: boolean;
+ defaultOpen?: boolean;
+ onOpenChange?: (open: boolean) => void;
+}
+
+const DEFAULT_DELAY_DURATION = 300;
+const DEFAULT_SKIP_DELAY_DURATION = 300;
+const DEFAULT_DISABLE_HOVERABLE_CONTENT = false;
+
+const LabelTooltipProvider: React.FC<LabelTooltipProviderProps> = (props) => {
+ const {
+ children,
+ delayDuration = DEFAULT_DELAY_DURATION,
+ skipDelayDuration = DEFAULT_SKIP_DELAY_DURATION,
+ disableHoverableContent = DEFAULT_DISABLE_HOVERABLE_CONTENT,
+ } = props;
+
+ return (
+ <Tooltip.Provider
+ delayDuration={delayDuration}
+ skipDelayDuration={skipDelayDuration}
+ disableHoverableContent={disableHoverableContent}
+ >
+ {children}
+ </Tooltip.Provider>
+ );
+};
+
+const LabelTooltip = React.forwardRef<HTMLDivElement, LabelTooltipProps>((props, ref) => {
+ const {
+ children,
+ content,
+ side = "top",
+ sideOffset = 1,
+ delayDuration = DEFAULT_DELAY_DURATION,
+ className = `${CHART_CLASS_PREFIX}-chart-label-tooltip`,
+ disabled = false,
+ open,
+ defaultOpen,
+ onOpenChange,
+ } = props;
+
+ if (disabled) {
+ return children;
+ }
+
+ return (
+ <Tooltip.Root
+ delayDuration={delayDuration}
+ open={open}
+ defaultOpen={defaultOpen}
+ onOpenChange={onOpenChange}
+ >
+ <Tooltip.Trigger asChild>{children}</Tooltip.Trigger>
+ <Tooltip.Portal>
+ <Tooltip.Content ref={ref} className={className} side={side} sideOffset={sideOffset}>
+ {content}
+ </Tooltip.Content>
+ </Tooltip.Portal>
+ </Tooltip.Root>
+ );
+});
+
+LabelTooltip.displayName = "LabelTooltip";
+
+export { LabelTooltip, LabelTooltipProvider };
+export type { LabelTooltipProps, LabelTooltipProviderProps };
diff --git a/packages/react-ui/src/components/D3Charts/shared/core/PortalTooltip/ChartTooltip.tsx b/packages/react-ui/src/components/D3Charts/shared/core/PortalTooltip/ChartTooltip.tsx
new file mode 100644
index 000000000..b84e76143
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/core/PortalTooltip/ChartTooltip.tsx
@@ -0,0 +1,172 @@
+import { flip, offset, type Placement, shift, useFloating } from "@floating-ui/react-dom";
+import clsx from "clsx";
+import React, { memo, useCallback, useLayoutEffect, useMemo, useRef } from "react";
+import { createPortal } from "react-dom";
+import { useTheme } from "../../../../ThemeProvider";
+import { CHART_CLASS_PREFIX } from "../../../utils/constants";
+import { springPresets, useTranslate } from "../spring";
+import { tooltipNumberFormatter } from "./utils";
+
+export interface TooltipItem {
+ name: string;
+ /** Numbers go through the compact tooltip formatter; strings render as-is
+ * (e.g. the heatmap's "No value" for empty cells). */
+ value: number | string;
+ color: string;
+}
+
+interface ChartTooltipProps {
+ label: string;
+ items: TooltipItem[];
+ viewportPosition: { x: number; y: number };
+ className?: string;
+ /**
+ * Floating UI placement of the panel relative to `viewportPosition`.
+ * Defaults to `'right-start'` — the behavior every other chart relies on.
+ * SegmentedBar passes `'top'` to float the panel above the hovered segment.
+ */
+ placement?: Placement;
+}
+
+function ChartTooltipRender({
+ label,
+ items,
+ viewportPosition,
+ className,
+ placement = "right-start",
+}: ChartTooltipProps) {
+ const { portalThemeClassName } = useTheme();
+
+ const virtualEl = useMemo(
+ () => ({
+ getBoundingClientRect: () => ({
+ x: viewportPosition.x,
+ y: viewportPosition.y,
+ width: 0,
+ height: 0,
+ top: viewportPosition.y,
+ left: viewportPosition.x,
+ right: viewportPosition.x,
+ bottom: viewportPosition.y,
+ }),
+ }),
+ [viewportPosition.x, viewportPosition.y],
+ );
+
+ // Floating UI still does the smart positioning (offset / flip / shift); we just
+ // spring the panel toward its computed (x, y) instead of snapping there.
+ const { x, y, strategy, refs, isPositioned } = useFloating({
+ placement,
+ middleware: [offset(20), flip(), shift({ padding: 8 })],
+ elements: { reference: virtualEl },
+ });
+
+ const follow = useTranslate(springPresets.tooltip);
+ const seeded = useRef(false);
+
+ // Conditionally mounted (only while hovering), so plain useLayoutEffect is safe
+ // — this never renders on the server. Jump into place on first position, then
+ // soft-follow. (Mounts/unmounts per hover; the lag is within a hover session.)
+ // `follow` is a ref-backed stable handle (see useTranslate) — listing it
+ // satisfies exhaustive-deps without ever re-running the effect for it.
+ useLayoutEffect(() => {
+ if (!isPositioned) return;
+ if (seeded.current) {
+ follow.to(x, y);
+ } else {
+ follow.jump(x, y);
+ seeded.current = true;
+ }
+ }, [x, y, isPositioned, follow]);
+
+ // Compose Floating UI's ref (it measures the panel) with the spring's ref (it
+ // writes the transform). Both objects are stable (Floating UI memoizes
+ // `refs`; `follow` is ref-backed), so this callback identity is stable too.
+ const setFloatingRef = useCallback(
+ (el: HTMLDivElement | null) => {
+ refs.setFloating(el);
+ follow.bind(el);
+ },
+ [refs, follow],
+ );
+
+ const isGreaterThanTen = items.length > 10;
+ const remainingItems = isGreaterThanTen ? items.length - 5 : 0;
+ const displayItems = isGreaterThanTen ? items.slice(0, 5) : items;
+ const isTwoItemsLayout = items.length <= 2;
+
+ return createPortal(
+ <div
+ ref={setFloatingRef}
+ className={clsx(`${CHART_CLASS_PREFIX}-portal-tooltip`, portalThemeClassName)}
+ // position/top/left from Floating UI; transform is spring-driven; fade in
+ // once positioned so it never flashes at the origin.
+ style={{
+ position: strategy,
+ top: 0,
+ left: 0,
+ opacity: isPositioned ? 1 : 0,
+ transition: "opacity 0.12s ease",
+ }}
+ >
+ <div className={clsx(`${CHART_CLASS_PREFIX}-chart-tooltip`, className)}>
+ <div className={`${CHART_CLASS_PREFIX}-chart-tooltip-label`}>{label}</div>
+ <div className={`${CHART_CLASS_PREFIX}-chart-tooltip-content-item-separator`} />
+ <div className={`${CHART_CLASS_PREFIX}-chart-tooltip-content`}>
+ {displayItems.map((item, index) => (
+ <div
+ key={`${item.name}-${index}`}
+ className={clsx(
+ `${CHART_CLASS_PREFIX}-chart-tooltip-content-item`,
+ !isTwoItemsLayout && `${CHART_CLASS_PREFIX}-chart-tooltip-content-item--dot`,
+ )}
+ >
+ <div
+ className={clsx(
+ `${CHART_CLASS_PREFIX}-chart-tooltip-content-indicator`,
+ `${CHART_CLASS_PREFIX}-chart-tooltip-content-indicator--dot`,
+ isTwoItemsLayout &&
+ `${CHART_CLASS_PREFIX}-chart-tooltip-content-indicator--two-items`,
+ )}
+ style={
+ {
+ "--color-bg": item.color,
+ "--color-border": item.color,
+ } as React.CSSProperties
+ }
+ />
+ <div
+ className={clsx(
+ `${CHART_CLASS_PREFIX}-chart-tooltip-content-value-wrapper`,
+ isTwoItemsLayout &&
+ `${CHART_CLASS_PREFIX}-chart-tooltip-content-value-wrapper--vertical`,
+ `${CHART_CLASS_PREFIX}-chart-tooltip-content-value-wrapper--standard`,
+ )}
+ >
+ <div className={`${CHART_CLASS_PREFIX}-chart-tooltip-content-label`}>
+ <span>{item.name}</span>
+ </div>
+ <span className={`${CHART_CLASS_PREFIX}-chart-tooltip-content-value`}>
+ {typeof item.value === "number" ? tooltipNumberFormatter(item.value) : item.value}
+ </span>
+ </div>
+ <div className={`${CHART_CLASS_PREFIX}-chart-tooltip-content-item-separator`} />
+ </div>
+ ))}
+ </div>
+ {isGreaterThanTen && (
+ <div className={`${CHART_CLASS_PREFIX}-chart-tooltip-content-item-separator`} />
+ )}
+ {isGreaterThanTen && (
+ <div className={`${CHART_CLASS_PREFIX}-chart-tooltip-content-view-more`}>
+ Click to view all {remainingItems}
+ </div>
+ )}
+ </div>
+ </div>,
+ document.body,
+ );
+}
+
+export const ChartTooltip = memo(ChartTooltipRender);
+ChartTooltip.displayName = "ChartTooltip";
diff --git a/packages/react-ui/src/components/D3Charts/shared/core/PortalTooltip/portalTooltip.scss b/packages/react-ui/src/components/D3Charts/shared/core/PortalTooltip/portalTooltip.scss
new file mode 100644
index 000000000..c210dac8b
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/core/PortalTooltip/portalTooltip.scss
@@ -0,0 +1,157 @@
+@use "../../../../../cssUtils" as cssUtils;
+@use "../../../prefix" as brand;
+
+.#{brand.$prefix}-portal-tooltip {
+ pointer-events: none;
+ z-index: 1000;
+ position: absolute;
+}
+
+.#{brand.$prefix}-chart-tooltip {
+ display: grid;
+ align-items: start;
+ min-width: 128px;
+ max-width: 240px;
+ gap: cssUtils.$space-xs;
+ padding: cssUtils.$space-xs;
+ color: cssUtils.$text-neutral-primary;
+ @include cssUtils.typography(label, extra-small);
+ border-radius: cssUtils.$radius-l;
+ border: 1px solid cssUtils.$border-default;
+ background-color: cssUtils.$foreground;
+ box-shadow: cssUtils.$shadow-s;
+ text-transform: capitalize;
+
+ &-label {
+ @include cssUtils.typography(label, extra-small);
+ color: cssUtils.$text-neutral-primary;
+ overflow-wrap: break-word;
+ word-break: break-word;
+ }
+
+ &-label-heavy {
+ @include cssUtils.typography(label, extra-small-heavy);
+ color: cssUtils.$text-neutral-primary;
+ overflow-wrap: break-word;
+ word-break: break-word;
+ }
+
+ &-content {
+ display: grid;
+ align-items: start;
+ min-width: 128px;
+ gap: cssUtils.$space-xs;
+ color: cssUtils.$text-neutral-primary;
+ @include cssUtils.typography(label, extra-small);
+ background-color: cssUtils.$foreground;
+ text-transform: capitalize;
+
+ &-item {
+ display: flex;
+ width: 100%;
+ flex-wrap: wrap;
+ gap: cssUtils.$space-xs;
+ align-items: flex-start;
+ &--dot {
+ align-items: center;
+ }
+
+ svg {
+ height: 10px;
+ width: 10px;
+ color: cssUtils.$text-neutral-primary;
+ }
+ }
+
+ &-indicator {
+ flex-shrink: 0;
+ border-radius: cssUtils.$radius-2xs;
+
+ &--dot {
+ height: 10px;
+ width: 10px;
+ background-color: var(--color-bg);
+ border-color: var(--color-border);
+ }
+
+ &--line {
+ width: 4px;
+ background-color: var(--color-bg);
+ border-color: var(--color-border);
+ }
+
+ &--dashed {
+ width: 0;
+ border: 1.5px dashed var(--color-border);
+ background-color: transparent;
+ }
+
+ &--two-items {
+ margin-top: 2px;
+ }
+ }
+
+ &-value-wrapper {
+ display: flex;
+ flex: 1;
+ gap: cssUtils.$space-s;
+ justify-content: space-between;
+ line-height: 1;
+
+ &--nested {
+ align-items: flex-end;
+ }
+
+ &--standard {
+ align-items: center;
+ }
+
+ &--vertical {
+ flex-direction: column;
+ align-items: flex-start;
+ justify-content: flex-start;
+ gap: cssUtils.$space-2xs;
+ }
+ }
+
+ &-label {
+ display: grid;
+ gap: cssUtils.$space-xs;
+ color: cssUtils.$text-neutral-secondary;
+ @include cssUtils.typography(label, extra-small);
+
+ span {
+ display: block;
+ overflow-wrap: break-word;
+ word-break: break-word;
+ }
+ }
+
+ &-value {
+ font-variant-numeric: tabular-nums;
+ color: cssUtils.$text-neutral-primary;
+ @include cssUtils.typography(label, extra-small);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+
+ &-item-separator {
+ width: 100%;
+ height: 1px;
+ background-color: cssUtils.$border-default;
+ margin: 0;
+ }
+ &-item:last-child &-item-separator {
+ display: none;
+ }
+
+ &-view-more {
+ @include cssUtils.typography(label, extra-small);
+ color: cssUtils.$text-neutral-primary;
+ text-align: left;
+ overflow-wrap: break-word;
+ word-break: break-word;
+ }
+ }
+}
diff --git a/packages/react-ui/src/components/D3Charts/shared/core/PortalTooltip/utils/index.ts b/packages/react-ui/src/components/D3Charts/shared/core/PortalTooltip/utils/index.ts
new file mode 100644
index 000000000..9de8b1951
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/core/PortalTooltip/utils/index.ts
@@ -0,0 +1,23 @@
+const tooltipNumberFormatter = (value: number) => {
+ const isNegative = value < 0;
+ const absValue = Math.abs(value);
+
+ if (absValue < 100000) {
+ return (isNegative ? "-" : "") + absValue.toLocaleString();
+ }
+
+ const units = ["", "K", "M", "B", "T"];
+ let unitIndex = 0;
+ let scaledValue = absValue;
+
+ while (scaledValue >= 1000 && unitIndex < units.length - 1) {
+ scaledValue /= 1000;
+ unitIndex++;
+ }
+
+ const formattedValue = Math.floor(scaledValue * 10) / 10;
+
+ return (isNegative ? "-" : "") + `${formattedValue}${units[unitIndex]}`;
+};
+
+export { tooltipNumberFormatter };
diff --git a/packages/react-ui/src/components/D3Charts/shared/core/StackedLegend/ChartWithStackedLegend.tsx b/packages/react-ui/src/components/D3Charts/shared/core/StackedLegend/ChartWithStackedLegend.tsx
new file mode 100644
index 000000000..81fda05b6
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/core/StackedLegend/ChartWithStackedLegend.tsx
@@ -0,0 +1,56 @@
+import clsx from "clsx";
+import { type ReactNode, useId, useRef } from "react";
+import { useContainerSize } from "../../../hooks/core/useContainerSize";
+import { CHART_CLASS_PREFIX } from "../../../utils/constants";
+import { LegendStoreProvider } from "../legend/LegendStoreProvider";
+import { StackedLegend } from "./StackedLegend";
+
+/** Width from which the chart and its stacked legend sit side by side. */
+export const STACKED_LEGEND_ROW_BREAKPOINT = 400;
+
+const CLASS = `${CHART_CLASS_PREFIX}-chart-with-stacked-legend`;
+
+const toCssSize = (value: number | string | undefined) =>
+ typeof value === "number" ? `${value}px` : value;
+
+/**
+ * A polar chart with its built-in stacked legend — the `legendVariant="stacked"`
+ * layout of react-ui's Recharts Pie and Radial charts: chart and legend side by
+ * side (half the width each) from 400px up, the legend under the chart when
+ * narrower. Chart and legend share a local legend store, so hovering or
+ * toggling a legend row drives the chart and the reverse. `width`, `height`
+ * and `className` size and style the whole layout, as in Recharts.
+ */
+export function ChartWithStackedLegend({
+ children,
+ width,
+ height,
+ className,
+}: {
+ children: ReactNode;
+ width?: number | string;
+ height?: number | string;
+ className?: string;
+}) {
+ const legendKey = useId();
+ const ref = useRef<HTMLDivElement>(null);
+ const { width: layoutWidth } = useContainerSize(ref, width);
+ const isRow = layoutWidth >= STACKED_LEGEND_ROW_BREAKPOINT;
+
+ return (
+ <LegendStoreProvider legendKey={legendKey}>
+ <div
+ ref={ref}
+ className={clsx(CLASS, isRow ? `${CLASS}--row` : `${CLASS}--column`, className)}
+ style={{ width: toCssSize(width), height: toCssSize(height) }}
+ >
+ <div className={`${CLASS}__chart`}>{children}</div>
+ <div className={`${CLASS}__legend`}>
+ {/* Side by side the list scrolls; stacked, the width drives show-more.
+ Rows show each item's share, as Recharts' stacked legend does. */}
+ <StackedLegend format="percentage" containerWidth={isRow ? undefined : layoutWidth} />
+ </div>
+ </div>
+ </LegendStoreProvider>
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/shared/core/StackedLegend/StackedLegend.tsx b/packages/react-ui/src/components/D3Charts/shared/core/StackedLegend/StackedLegend.tsx
new file mode 100644
index 000000000..31c6e65f3
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/core/StackedLegend/StackedLegend.tsx
@@ -0,0 +1,50 @@
+import { useContext } from "react";
+import {
+ LegendStoreContext,
+ useLegendEntry,
+ useResolvedLegendKey,
+} from "../legend/LegendStoreProvider";
+import { StackedLegendView, type StackedLegendViewProps } from "./StackedLegendView";
+
+type CommonProps = Omit<
+ StackedLegendViewProps,
+ "items" | "activeKey" | "hiddenKeys" | "onItemHover" | "onItemToggle"
+>;
+
+export type StackedLegendProps =
+ | ({
+ items: StackedLegendViewProps["items"];
+ legendKey?: undefined;
+ } & StackedLegendViewProps)
+ // Connected path. `legendKey` may be omitted when the nearest
+ // LegendStoreProvider supplies one (an explicit prop still wins).
+ | ({ legendKey?: string; items?: undefined } & CommonProps);
+
+export function StackedLegend(props: StackedLegendProps) {
+ if (props.items != null) {
+ // Standalone / presentational path.
+ const { legendKey: _ignored, ...viewProps } = props;
+ return <StackedLegendView {...(viewProps as StackedLegendViewProps)} />;
+ }
+ const { legendKey, items: _items, ...rest } = props;
+ return <ConnectedStackedLegend legendKey={legendKey} {...rest} />;
+}
+
+function ConnectedStackedLegend({ legendKey, ...rest }: { legendKey?: string } & CommonProps) {
+ const store = useContext(LegendStoreContext);
+ const key = useResolvedLegendKey(legendKey);
+ const entry = useLegendEntry(key);
+ // Degrade gracefully: no key resolvable, no provider, or not yet published.
+ if (!key || !entry) return null;
+ return (
+ <StackedLegendView
+ {...rest}
+ items={entry.items}
+ activeKey={entry.activeKey}
+ hiddenKeys={new Set(entry.hiddenKeys)}
+ format={rest.format ?? entry.format}
+ onItemHover={(k) => store?.getState().setActive(key, k)}
+ onItemToggle={(k) => store?.getState().toggle(key, k)}
+ />
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/shared/core/StackedLegend/StackedLegendView.tsx b/packages/react-ui/src/components/D3Charts/shared/core/StackedLegend/StackedLegendView.tsx
new file mode 100644
index 000000000..eefac1f51
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/core/StackedLegend/StackedLegendView.tsx
@@ -0,0 +1,193 @@
+import clsx from "clsx";
+import { ChevronDown, ChevronUp } from "lucide-react";
+import React, { useEffect, useRef, useState } from "react";
+import { Button } from "../../../../Button";
+import { IconButton } from "../../../../IconButton";
+import { Separator } from "../../../../Separator";
+import { CHART_CLASS_PREFIX } from "../../../utils/constants";
+import type { StackedLegendItem } from "../legend/types";
+import {
+ formatStackedValue,
+ LEGEND_ITEM_LIMIT,
+ resolveStackedLegendLayout,
+ type StackedLegendLayout,
+} from "./stackedLegendLayout";
+
+const ITEM_HEIGHT = 36;
+const ITEM_GAP = 2;
+
+export interface StackedLegendViewProps {
+ items: StackedLegendItem[];
+ format?: "percentage" | "number";
+ activeKey?: string | null;
+ hiddenKeys?: Set<string>;
+ onItemHover?: (key: string | null) => void;
+ onItemToggle?: (key: string) => void;
+ layout?: StackedLegendLayout;
+ containerWidth?: number;
+ showTitle?: boolean;
+ separator?: boolean;
+ className?: string;
+ style?: React.CSSProperties;
+}
+
+export const StackedLegendView = ({
+ items,
+ format = "percentage",
+ activeKey,
+ hiddenKeys,
+ onItemHover,
+ onItemToggle,
+ layout = "auto",
+ containerWidth,
+ separator = false,
+ showTitle = true,
+ className,
+ style,
+}: StackedLegendViewProps) => {
+ const listRef = useRef<HTMLDivElement>(null);
+ const [showUpButton, setShowUpButton] = useState(false);
+ const [showDownButton, setShowDownButton] = useState(false);
+ const [showAll, setShowAll] = useState(false);
+ const [isOverflowing, setIsOverflowing] = useState(false);
+
+ const { isShowMore, isScrollable } = resolveStackedLegendLayout(
+ layout,
+ containerWidth,
+ items.length,
+ );
+
+ useEffect(() => {
+ if (isShowMore) {
+ setShowUpButton(false);
+ setShowDownButton(false);
+ return;
+ }
+ const el = listRef.current;
+ const checkScroll = () => {
+ if (!el) return;
+ const { scrollTop, scrollHeight, clientHeight } = el;
+ setIsOverflowing(scrollHeight > clientHeight);
+ setShowUpButton(scrollTop > 0);
+ setShowDownButton(scrollTop < scrollHeight - clientHeight - 1);
+ };
+ checkScroll();
+ if (!el) return;
+ el.addEventListener("scroll", checkScroll);
+ const ro = new ResizeObserver(checkScroll);
+ ro.observe(el);
+ return () => {
+ el.removeEventListener("scroll", checkScroll);
+ ro.disconnect();
+ };
+ }, [isShowMore, items.length]);
+
+ const scrollBy = (dir: 1 | -1) =>
+ listRef.current?.scrollBy({
+ top: dir * (ITEM_HEIGHT + ITEM_GAP),
+ behavior: "smooth",
+ });
+
+ // Re-normalize percentages over the VISIBLE set so visible rows match the
+ // (re-normalized) wedges. Hidden rows are dimmed; their % over the visible
+ // total is informational.
+ const total = items
+ .filter((it) => !hiddenKeys?.has(it.key))
+ .reduce((sum, it) => sum + it.value, 0);
+ const itemsToDisplay = isShowMore && !showAll ? items.slice(0, LEGEND_ITEM_LIMIT) : items;
+ // Overflow alone decides the scroll affordance: the scrollbar is CSS-hidden,
+ // so even a short (≤ LEGEND_ITEM_LIMIT) list that overflows its container
+ // needs the buttons. (The show-more path is gated separately on `isShowMore`.)
+ const showScrollControls = isScrollable && isOverflowing;
+
+ return (
+ <div
+ className={clsx(`${CHART_CLASS_PREFIX}-stacked-legend-container`, className)}
+ style={{
+ width: containerWidth ? `${containerWidth}px` : "100%",
+ ...style,
+ }}
+ >
+ {showScrollControls && (
+ <div className={`${CHART_CLASS_PREFIX}-stacked-legend-header`}>
+ {showTitle && (
+ <div className={`${CHART_CLASS_PREFIX}-stacked-legend-header-title`}>
+ {items.length} labels
+ </div>
+ )}
+ <div className={`${CHART_CLASS_PREFIX}-stacked-legend-header-buttons`}>
+ <IconButton
+ className={`${CHART_CLASS_PREFIX}-stacked-legend-scroll-button`}
+ onClick={() => scrollBy(-1)}
+ aria-label="Scroll legend up"
+ icon={<ChevronUp />}
+ variant="secondary"
+ size="extra-small"
+ disabled={!showUpButton}
+ />
+ <IconButton
+ className={`${CHART_CLASS_PREFIX}-stacked-legend-scroll-button`}
+ onClick={() => scrollBy(1)}
+ aria-label="Scroll legend down"
+ icon={<ChevronDown />}
+ variant="secondary"
+ size="extra-small"
+ disabled={!showDownButton}
+ />
+ </div>
+ </div>
+ )}
+
+ <div ref={listRef} className={`${CHART_CLASS_PREFIX}-stacked-legend`}>
+ {itemsToDisplay.map((item, index) => {
+ const isHidden = hiddenKeys?.has(item.key);
+ return (
+ <React.Fragment key={item.key}>
+ <div
+ className={clsx(`${CHART_CLASS_PREFIX}-stacked-legend__item`, {
+ [`${CHART_CLASS_PREFIX}-stacked-legend__item--active`]: activeKey === item.key,
+ })}
+ style={{
+ opacity: isHidden ? 0.3 : 1,
+ cursor: onItemToggle ? "pointer" : undefined,
+ }}
+ onMouseEnter={() => onItemHover?.(item.key)}
+ onMouseLeave={() => onItemHover?.(null)}
+ onClick={onItemToggle ? () => onItemToggle(item.key) : undefined}
+ >
+ <div className={`${CHART_CLASS_PREFIX}-stacked-legend__item-label`}>
+ <div className={`${CHART_CLASS_PREFIX}-stacked-legend__item-color-container`}>
+ <div
+ className={`${CHART_CLASS_PREFIX}-stacked-legend__item-color`}
+ style={{ backgroundColor: item.color }}
+ />
+ </div>
+ <div className={`${CHART_CLASS_PREFIX}-stacked-legend__item-label-text`}>
+ {item.label}
+ </div>
+ </div>
+ <div className={`${CHART_CLASS_PREFIX}-stacked-legend__item-value`}>
+ {formatStackedValue(item.value, total, format)}
+ </div>
+ </div>
+ {index !== itemsToDisplay.length - 1 && separator && (
+ <Separator className={`${CHART_CLASS_PREFIX}-stacked-legend-separator`} />
+ )}
+ </React.Fragment>
+ );
+ })}
+ </div>
+
+ {isShowMore && items.length > LEGEND_ITEM_LIMIT && (
+ <Button
+ variant="secondary"
+ size="small"
+ onClick={() => setShowAll((v) => !v)}
+ className={`${CHART_CLASS_PREFIX}-stacked-legend-show-more-button`}
+ >
+ {showAll ? "Show less" : "Show more"}
+ </Button>
+ )}
+ </div>
+ );
+};
diff --git a/packages/react-ui/src/components/D3Charts/shared/core/StackedLegend/index.ts b/packages/react-ui/src/components/D3Charts/shared/core/StackedLegend/index.ts
new file mode 100644
index 000000000..b17400617
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/core/StackedLegend/index.ts
@@ -0,0 +1,4 @@
+export { StackedLegend } from "./StackedLegend";
+export type { StackedLegendProps } from "./StackedLegend";
+export { StackedLegendView } from "./StackedLegendView";
+export type { StackedLegendViewProps } from "./StackedLegendView";
diff --git a/packages/react-ui/src/components/D3Charts/shared/core/StackedLegend/stackedLegend.scss b/packages/react-ui/src/components/D3Charts/shared/core/StackedLegend/stackedLegend.scss
new file mode 100644
index 000000000..8ffd757c5
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/core/StackedLegend/stackedLegend.scss
@@ -0,0 +1,201 @@
+@use "../../../../../cssUtils" as cssUtils;
+@use "../../../prefix" as brand;
+
+.#{brand.$prefix}-stacked-legend-container {
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ height: 100%;
+}
+
+.#{brand.$prefix}-stacked-legend-header {
+ width: 100%;
+ display: flex;
+ flex-direction: row;
+ align-items: center;
+ justify-content: space-between;
+ gap: 10px;
+ padding: 0 cssUtils.$space-xs cssUtils.$space-xs cssUtils.$space-l;
+ color: cssUtils.$text-neutral-secondary;
+
+ &-buttons {
+ display: flex;
+ flex-direction: row;
+ align-items: center;
+ gap: cssUtils.$space-xs;
+ }
+}
+
+.#{brand.$prefix}-stacked-legend-header-title {
+ @include cssUtils.typography(label, small);
+ color: cssUtils.$text-neutral-secondary;
+}
+
+.#{brand.$prefix}-stacked-legend-scroll-button {
+ z-index: 100;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ cursor: pointer;
+}
+
+.#{brand.$prefix}-stacked-legend {
+ width: 100%;
+ display: flex;
+ flex-direction: column;
+ // Center rows vertically within the legend's full height (matches the
+ // pie beside it). `safe` falls back to flex-start when the list overflows,
+ // so long lists still scroll from the top without clipping.
+ justify-content: safe center;
+ min-width: 200px;
+ overflow-y: scroll;
+ height: 100%;
+ scrollbar-width: none;
+ -ms-overflow-style: none;
+ scroll-behavior: smooth;
+
+ &::-webkit-scrollbar {
+ display: none;
+ }
+
+ &__item {
+ width: 100%;
+ display: flex;
+ flex-direction: row;
+ justify-content: space-between;
+ align-items: center;
+ gap: 10px;
+ padding: 4px 8px;
+ border-radius: cssUtils.$radius-m;
+ transition: all 0.2s ease-in-out;
+ height: 32px;
+
+ &:hover {
+ background-color: cssUtils.$sunk;
+ }
+
+ &--active {
+ background-color: cssUtils.$sunk;
+ }
+
+ &-label {
+ display: flex;
+ flex-direction: row;
+ align-items: center;
+ gap: 8px;
+ min-width: 0;
+ flex: 1;
+ }
+
+ &-color-container {
+ display: flex;
+ flex-direction: row;
+ align-items: center;
+ justify-content: center;
+ gap: 10px;
+ // The row's height, not taller: a taller box spills past the last row
+ // and reads as list overflow (scroll arrows on a list that fits).
+ height: 100%;
+ width: 32px;
+ flex-shrink: 0;
+ }
+
+ &-color {
+ width: 10px;
+ height: 10px;
+ border-radius: 2px;
+ transition: all 0.2s ease-in-out;
+
+ .#{brand.$prefix}-stacked-legend__item:hover & {
+ transform: scale(1.2);
+ }
+
+ .#{brand.$prefix}-stacked-legend__item--active & {
+ transform: scale(1.3);
+ }
+ }
+
+ &-label-text {
+ @include cssUtils.typography(label, small);
+ color: cssUtils.$text-neutral-primary;
+ transition: color 0.2s ease-in-out;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ min-width: 0;
+ }
+
+ &-value {
+ @include cssUtils.typography(label, small);
+ color: cssUtils.$text-neutral-primary;
+ transition: all 0.2s ease-in-out;
+ flex-shrink: 0;
+ }
+ }
+
+ &-show-more-button {
+ width: 100%;
+ justify-content: center;
+ margin-top: cssUtils.$space-2xs;
+ }
+}
+
+.#{brand.$prefix}-stacked-legend-separator {
+ margin: cssUtils.$space-2xs 0;
+}
+
+// Chart + built-in stacked legend (ChartWithStackedLegend) — mirrors react-ui's
+// Recharts Pie/Radial `legendVariant="stacked"` layout: legend under the chart
+// on narrow containers, side by side (half the width each) from 400px up.
+.#{brand.$prefix}-chart-with-stacked-legend {
+ display: flex;
+ position: relative;
+ gap: 20px;
+ align-items: center;
+
+ &--column {
+ flex-direction: column;
+ }
+
+ &--row {
+ flex-direction: row;
+ min-height: 296px;
+ }
+
+ &__chart {
+ width: 100%;
+ min-width: 0;
+ }
+
+ &__legend {
+ display: flex;
+ justify-content: center;
+ width: 100%;
+ }
+
+ &--column &__legend {
+ align-items: flex-start;
+ }
+
+ &--row &__chart {
+ flex: 1;
+ }
+
+ &--row &__legend {
+ flex: 1;
+ min-width: 0;
+ height: 296px;
+ align-items: center;
+
+ // Vertically center the list alongside the chart.
+ .#{brand.$prefix}-stacked-legend-container {
+ justify-content: center;
+ }
+
+ .#{brand.$prefix}-stacked-legend {
+ height: auto;
+ max-height: 100%;
+ }
+ }
+}
diff --git a/packages/react-ui/src/components/D3Charts/shared/core/StackedLegend/stackedLegendLayout.test.ts b/packages/react-ui/src/components/D3Charts/shared/core/StackedLegend/stackedLegendLayout.test.ts
new file mode 100644
index 000000000..49c07bca5
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/core/StackedLegend/stackedLegendLayout.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it } from "vitest";
+import { formatStackedValue, resolveStackedLegendLayout } from "./stackedLegendLayout";
+
+describe("resolveStackedLegendLayout", () => {
+ it("forces showMore / scrollable explicitly", () => {
+ expect(resolveStackedLegendLayout("showMore", 1000, 2)).toEqual({
+ isShowMore: true,
+ isScrollable: false,
+ });
+ expect(resolveStackedLegendLayout("scrollable", 100, 50)).toEqual({
+ isShowMore: false,
+ isScrollable: true,
+ });
+ });
+ it("auto → showMore when narrow or many items", () => {
+ expect(resolveStackedLegendLayout("auto", 300, 2).isShowMore).toBe(true); // narrow
+ expect(resolveStackedLegendLayout("auto", 1000, 10).isShowMore).toBe(true); // > limit
+ });
+ it("auto → scrollable when wide and few items", () => {
+ expect(resolveStackedLegendLayout("auto", 1000, 3)).toEqual({
+ isShowMore: false,
+ isScrollable: true,
+ });
+ });
+ it("auto without containerWidth → scrollable (no width to judge)", () => {
+ expect(resolveStackedLegendLayout("auto", undefined, 3).isScrollable).toBe(true);
+ });
+ it("locks the exact breakpoint/limit boundaries (strict < / >)", () => {
+ // width === SHOW_MORE_BREAKPOINT (450) is NOT < 450 → scrollable.
+ expect(resolveStackedLegendLayout("auto", 450, 2)).toEqual({
+ isShowMore: false,
+ isScrollable: true,
+ });
+ // itemCount === LEGEND_ITEM_LIMIT (6) is NOT > 6 → scrollable.
+ expect(resolveStackedLegendLayout("auto", 1000, 6)).toEqual({
+ isShowMore: false,
+ isScrollable: true,
+ });
+ });
+});
+
+describe("formatStackedValue", () => {
+ it("percentage of total to 1 decimal", () => {
+ expect(formatStackedValue(25, 100, "percentage")).toBe("25.0%");
+ expect(formatStackedValue(1, 3, "percentage")).toBe("33.3%");
+ });
+ it("number returns the raw value as string", () => {
+ expect(formatStackedValue(42, 100, "number")).toBe("42");
+ });
+ it("guards divide-by-zero total", () => {
+ expect(formatStackedValue(0, 0, "percentage")).toBe("0.0%");
+ });
+});
diff --git a/packages/react-ui/src/components/D3Charts/shared/core/StackedLegend/stackedLegendLayout.ts b/packages/react-ui/src/components/D3Charts/shared/core/StackedLegend/stackedLegendLayout.ts
new file mode 100644
index 000000000..bfbcb831b
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/core/StackedLegend/stackedLegendLayout.ts
@@ -0,0 +1,28 @@
+export type StackedLegendLayout = "auto" | "showMore" | "scrollable";
+
+export const LEGEND_ITEM_LIMIT = 6;
+export const SHOW_MORE_BREAKPOINT = 450;
+
+export const resolveStackedLegendLayout = (
+ layout: StackedLegendLayout,
+ containerWidth: number | undefined,
+ itemCount: number,
+): { isShowMore: boolean; isScrollable: boolean } => {
+ const isShowMore =
+ layout === "showMore" ||
+ (layout === "auto" &&
+ containerWidth !== undefined &&
+ (containerWidth < SHOW_MORE_BREAKPOINT || itemCount > LEGEND_ITEM_LIMIT));
+ const isScrollable = layout === "scrollable" || (layout === "auto" && !isShowMore);
+ return { isShowMore, isScrollable };
+};
+
+export const formatStackedValue = (
+ value: number,
+ total: number,
+ format: "percentage" | "number",
+): string => {
+ if (format === "number") return `${value}`;
+ const pct = total > 0 ? (value / total) * 100 : 0;
+ return `${pct.toFixed(1)}%`;
+};
diff --git a/packages/react-ui/src/components/D3Charts/shared/core/legend/ARCHITECTURE.md b/packages/react-ui/src/components/D3Charts/shared/core/legend/ARCHITECTURE.md
new file mode 100644
index 000000000..a8eb14344
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/core/legend/ARCHITECTURE.md
@@ -0,0 +1,131 @@
+# Legend store architecture
+
+Reference for maintainers/agents. Written 2026-07-10, after the
+provider-default-key refactor. `README.md` (same folder) is the quick-start;
+this file records the internals, invariants, and the decisions behind them.
+
+## Module map
+
+```
+shared/core/legend/
+ LegendStoreProvider.tsx provider (store + default-key contexts), hooks:
+ useResolvedLegendKey / useLegendEntry /
+ useLegendPublisher / useLegendBridge
+ legendStore.ts createLegendStore() — Zustand store FACTORY
+ legendSelectors.ts indexToKey / keyToIndex / stackedItemsFromSlices
+ types.ts LegendEntry, StackedLegendItem, LegendStoreState
+ index.ts barrel (what the rest of D3Charts imports)
+
+shared/core/StackedLegend/
+ StackedLegend.tsx connected (store-backed) vs presentational split
+ StackedLegendView.tsx pure view — rows, header, scroll affordance
+
+hooks/polar/
+ useCategoricalChartOrchestrator.ts the CHART side of the bridge
+```
+
+Public exports (`D3Charts/index.ts`): `LegendStoreProvider`, `useLegendEntry`,
+`StackedLegend` + types. The publisher/bridge hooks and
+`useResolvedLegendKey` are internal (legend barrel only).
+
+## Data flow
+
+```
+ LegendStoreProvider (one store per mount, useRef-lazy)
+ ├── LegendStoreContext : the store
+ └── LegendKeyContext : optional default key ("uid")
+ │
+ ┌────────────────────┴──────────────────────┐
+ │ CHART (Pie/Radial orchestrator) │ StackedLegend (connected)
+ │ resolvedKey = prop ?? contextKey │ key = prop ?? contextKey
+ │ │
+ │ useLegendPublisher(key, rows, format) ──► entries[key].items
+ │ useLegendBridge(key): │
+ │ reads entries[key].activeKey ◄──────── onItemHover → setActive(key,…)
+ │ reads entries[key].hiddenKeys ◄─────── onItemToggle → toggle(key,…)
+ │ writes setActive on slice hover ──────► row gets --active class
+ └───────────────────────────────────────────┘
+```
+
+One store holds N entries; each entry is one chart↔legend pair. The key is
+the address; the store is the transport.
+
+## Key resolution
+
+`useResolvedLegendKey(key) = key ?? useContext(LegendKeyContext)`
+
+- Explicit `legendKey` prop **always wins** over the provider default.
+- Resolution happens in every consumer hook (`useLegendEntry`,
+ `useLegendPublisher`, `useLegendBridge`) AND once at the top of the polar
+ orchestrator — the orchestrator needs the resolved value itself because its
+ hover-sync effect uses the key as a dependency (see below). Double
+ resolution is idempotent.
+- `StackedLegend` discriminates on `items` (presence → presentational path);
+ the connected path treats `legendKey` as optional and resolves it.
+
+## Invariants (enforced in legendStore.ts)
+
+1. **Store per provider.** `createLegendStore()` is a factory; the provider
+ instantiates via `useRef`. Never a module singleton — SSR-safe, GC'd with
+ the subtree. (`EMPTY_LEGEND_STORE` is a shared module-level _read-only_
+ fallback for hook calls outside any provider; nothing ever writes to it.)
+2. **One publisher per key.** `registerPublisher` counts mounts per key and
+ `console.warn`s on >1. Publisher counts live OUTSIDE reactive state (a
+ closed-over Map) so they can't cause re-renders.
+3. **Never zero visible slices.** `toggle` refuses to hide the last visible
+ item; `publish` reconciles `hiddenKeys` against the incoming items (drops
+ keys for vanished slices, resets to all-visible if everything would be
+ hidden) and nulls a stale `activeKey`.
+4. **Unmount cleanup.** The publisher effect unregisters + unpublishes its
+ key, so a chart unmounting removes its entry (the connected legend then
+ renders `null`).
+
+## Graceful-degradation matrix
+
+| Situation | Chart | StackedLegend |
+| ----------------------------------- | -------------------------------------------------- | ------------------------- |
+| No provider | bridge `null` → local state, inline legend renders | `null` |
+| Provider, no key resolvable | same as above | `null` |
+| Key resolves, nothing published yet | publishes on mount | `null` until entry exists |
+| Key resolves + published | inline legend suppressed (`usesRemoteLegend`) | renders entry |
+
+The "inline legend suppressed" gate is `showLegend && !usesRemoteLegend` in
+the chart components; `usesRemoteLegend = bridge != null`.
+
+## Orchestrator subtleties (do not "fix" these)
+
+- The slice-hover → `setActive` effect depends on
+ `[hoveredIndex, resolvedLegendKey]` and deliberately **excludes `bridge`**
+ (fresh object every render — including it would run the effect every
+ render and wipe legend-set highlights). `resolvedLegendKey` is the stable
+ proxy for "which bridge is active". It also reads `visibleSlices` through
+ a ref for the same reason. A comment in the file documents this (no
+ disable directive needed).
+- `publish` is driven by `stackedItems`, memoized from `slices` — keep it
+ memoized or the publish effect loops.
+
+## Scoping decision (2026-07-10): provider stays LOCAL
+
+One provider per chart+legend composition, wrapped immediately around the
+pair. Rationale:
+
+- **Blast radius of one chart.** Key collisions, stale entries, publisher
+ leaks — all confined to a subtree that dies with the composition.
+- **`useId` is only unique per React root.** Chat surfaces can host multiple
+ roots (streaming remounts, portals); a hoisted shared store + `useId` keys
+ could genuinely collide. Local stores make that class of bug impossible.
+- **No current consumer needs cross-subtree reach.** Hoisting is the
+ documented escape hatch for a future _remote_ legend (e.g. one dashboard
+ legend panel driving several charts): mount one provider higher, give each
+ pair explicit keys. The API needs no changes for that day — that is the
+ point of keeping entries key-addressable even though today every store
+ holds exactly one entry.
+
+The provider `legendKey` default (added in this refactor) exists purely so
+the common one-pair case states the uid once instead of threading it into
+both sides — it does not change scoping.
+
+## Test coverage map
+
+- `legendStore.test.ts`, `legendSelectors.test.ts` — store invariants (pure,
+ no DOM).
diff --git a/packages/react-ui/src/components/D3Charts/shared/core/legend/LegendStoreProvider.tsx b/packages/react-ui/src/components/D3Charts/shared/core/legend/LegendStoreProvider.tsx
new file mode 100644
index 000000000..fd6cd0cba
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/core/legend/LegendStoreProvider.tsx
@@ -0,0 +1,119 @@
+import React, { createContext, useContext, useEffect, useMemo, useRef } from "react";
+import { useShallow } from "zustand/react/shallow";
+import { createLegendStore } from "./legendStore";
+import type { LegendEntry, StackedLegendItem } from "./types";
+
+type LegendStore = ReturnType<typeof createLegendStore>;
+
+export const LegendStoreContext = createContext<LegendStore | null>(null);
+
+/**
+ * Default legend key supplied by the nearest provider. Charts and
+ * <StackedLegend> fall back to it when they have no explicit `legendKey`
+ * prop, so a locally-scoped composition only states its key once — on the
+ * provider — instead of threading the same id into both sides.
+ */
+const LegendKeyContext = createContext<string | undefined>(undefined);
+
+/**
+ * Resolve the effective legend key: an explicit prop wins, else the nearest
+ * provider's `legendKey`, else undefined (no store participation).
+ */
+export const useResolvedLegendKey = (key: string | undefined): string | undefined => {
+ const contextKey = useContext(LegendKeyContext);
+ return key ?? contextKey;
+};
+
+/**
+ * Shared read-only fallback used when there's no provider. It is never written
+ * (no publisher mounts without a provider, and the hooks below only READ from
+ * it), so a single module-level instance is safe to share across all
+ * subscribers and SSR-safe.
+ */
+const EMPTY_LEGEND_STORE = createLegendStore();
+
+export const LegendStoreProvider = ({
+ legendKey,
+ children,
+}: {
+ /**
+ * Optional default key for every keyed consumer in this subtree. The store
+ * stays scoped to this provider either way; the key only saves each child
+ * from repeating it. Explicit `legendKey` props on children still win.
+ */
+ legendKey?: string;
+ children: React.ReactNode;
+}) => {
+ const ref = useRef<LegendStore | null>(null);
+ if (!ref.current) {
+ ref.current = createLegendStore();
+ }
+ return (
+ <LegendStoreContext.Provider value={ref.current}>
+ <LegendKeyContext.Provider value={legendKey}>{children}</LegendKeyContext.Provider>
+ </LegendStoreContext.Provider>
+ );
+};
+
+/**
+ * Subscribe to a single key's entry. Degrades gracefully: with no provider we
+ * read from a stable empty fallback store, so the store hook is ALWAYS called
+ * (no conditional-hook violation) and the result is simply `undefined`.
+ */
+export const useLegendEntry = (key: string | undefined): LegendEntry | undefined => {
+ const store = useContext(LegendStoreContext);
+ const resolvedKey = useResolvedLegendKey(key);
+ const active = store ?? EMPTY_LEGEND_STORE;
+ return active(useShallow((s) => (resolvedKey ? s.entries[resolvedKey] : undefined)));
+};
+
+/** Chart side: register on mount (dup-warn), publish items on change, clean up on unmount. */
+export const useLegendPublisher = (
+ key: string | undefined,
+ items: StackedLegendItem[],
+ format?: "percentage" | "number",
+): void => {
+ const store = useContext(LegendStoreContext);
+ const resolvedKey = useResolvedLegendKey(key);
+
+ useEffect(() => {
+ if (!resolvedKey || !store) return;
+ store.getState().registerPublisher(resolvedKey);
+ return () => {
+ store.getState().unregisterPublisher(resolvedKey);
+ store.getState().unpublish(resolvedKey);
+ };
+ }, [resolvedKey, store]);
+
+ useEffect(() => {
+ if (!resolvedKey || !store) return;
+ store.getState().publish(resolvedKey, items, format);
+ }, [resolvedKey, store, items, format]);
+};
+
+export interface LegendBridge {
+ activeKey: string | null;
+ hiddenKeys: Set<string>;
+ setActive: (itemKey: string | null) => void;
+ toggle: (itemKey: string) => void;
+}
+
+/**
+ * Chart side: store-backed interaction handles when `key` + provider exist,
+ * else `null` (chart falls back to local state). The entry subscription hook is
+ * always called; the null decision happens after.
+ */
+export const useLegendBridge = (key: string | undefined): LegendBridge | null => {
+ const store = useContext(LegendStoreContext);
+ const resolvedKey = useResolvedLegendKey(key);
+ const entry = useLegendEntry(resolvedKey);
+ const hiddenKeys = useMemo(() => new Set(entry?.hiddenKeys ?? []), [entry?.hiddenKeys]);
+
+ if (!resolvedKey || !store) return null;
+ return {
+ activeKey: entry?.activeKey ?? null,
+ hiddenKeys,
+ setActive: (itemKey) => store.getState().setActive(resolvedKey, itemKey),
+ toggle: (itemKey) => store.getState().toggle(resolvedKey, itemKey),
+ };
+};
diff --git a/packages/react-ui/src/components/D3Charts/shared/core/legend/README.md b/packages/react-ui/src/components/D3Charts/shared/core/legend/README.md
new file mode 100644
index 000000000..fc6adf738
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/core/legend/README.md
@@ -0,0 +1,61 @@
+# Legend store — detached, key-addressable legends
+
+The pieces that let a chart and a legend live in **different places in the
+tree** but stay in sync: the legend shows the chart's rows, hovering a row
+highlights the matching slice, clicking a row hides/shows it.
+
+## The three pieces
+
+| Piece | Role |
+| ---------------------------------- | ---------------------------------------------------------------------------------------- |
+| `LegendStoreProvider` | Owns one Zustand store, scoped to its subtree. Optionally carries a default `legendKey`. |
+| Chart (`PieChart` / `RadialChart`) | Publishes its legend rows into the store, reads hover/hidden state back. |
+| `StackedLegend` | Renders the published rows, writes hover/toggle into the store. |
+
+Chart and legend meet on a **key** — the address of one entry inside the
+store. Both sides must resolve the _same_ key.
+
+## Usage
+
+**Common case — one chart + one legend. Say the key once, on the provider:**
+
+```tsx
+const uid = useId()
+
+<LegendStoreProvider legendKey={uid}>
+ <PieChart data={data} legend /> {/* publishes to uid */}
+ <StackedLegend /> {/* reads uid */}
+</LegendStoreProvider>
+```
+
+**Several pairs in one provider — explicit keys (a prop always beats the
+provider default):**
+
+```tsx
+<LegendStoreProvider>
+ <PieChart legend legendKey="pie" />
+ <StackedLegend legendKey="pie" />
+ <RadialChart legend legendKey="radial" />
+ <StackedLegend legendKey="radial" />
+</LegendStoreProvider>
+```
+
+**Presentational only — no store at all:**
+
+```tsx
+<StackedLegend items={rows} />
+```
+
+## Rules of thumb
+
+- **Keep the provider local** — wrap exactly the chart+legend composition,
+ not the page. Every composition gets its own store; nothing can cross-talk.
+- Use `useId()` for the key so multiple instances on one page never collide.
+- A chart with **no resolvable key** (or no provider) simply renders its own
+ inline legend. `StackedLegend` with no resolvable key renders nothing.
+- Two charts publishing to the same key is a bug — you'll get a console
+ warning about a duplicate `legendKey`.
+- The store never lets the last visible slice be hidden (toggle is a no-op).
+
+See `ARCHITECTURE.md` in this folder for internals, invariants, and the
+scoping decision record.
diff --git a/packages/react-ui/src/components/D3Charts/shared/core/legend/index.ts b/packages/react-ui/src/components/D3Charts/shared/core/legend/index.ts
new file mode 100644
index 000000000..6b69a458f
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/core/legend/index.ts
@@ -0,0 +1,10 @@
+export { indexToKey, keyToIndex, stackedItemsFromSlices } from "./legendSelectors";
+export {
+ LegendStoreProvider,
+ useLegendBridge,
+ useLegendEntry,
+ useLegendPublisher,
+ useResolvedLegendKey,
+} from "./LegendStoreProvider";
+export type { LegendBridge } from "./LegendStoreProvider";
+export type { LegendEntry, LegendStoreState, StackedLegendItem } from "./types";
diff --git a/packages/react-ui/src/components/D3Charts/shared/core/legend/legendSelectors.test.ts b/packages/react-ui/src/components/D3Charts/shared/core/legend/legendSelectors.test.ts
new file mode 100644
index 000000000..2161faef7
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/core/legend/legendSelectors.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from "vitest";
+import { indexToKey, keyToIndex, stackedItemsFromSlices } from "./legendSelectors";
+
+const slices = [
+ { label: "Apples", value: 10, color: "#a00" },
+ { label: "Pears", value: 5, color: "#0a0" },
+];
+
+describe("stackedItemsFromSlices", () => {
+ it("maps slices to items keyed by label", () => {
+ expect(stackedItemsFromSlices(slices)).toEqual([
+ { key: "Apples", label: "Apples", color: "#a00", value: 10 },
+ { key: "Pears", label: "Pears", color: "#0a0", value: 5 },
+ ]);
+ });
+});
+
+describe("indexToKey / keyToIndex", () => {
+ it("round-trips a valid index/key", () => {
+ expect(indexToKey(slices, 1)).toBe("Pears");
+ expect(keyToIndex(slices, "Pears")).toBe(1);
+ });
+ it("returns null for null/out-of-range/missing", () => {
+ expect(indexToKey(slices, null)).toBeNull();
+ expect(indexToKey(slices, 9)).toBeNull();
+ expect(keyToIndex(slices, null)).toBeNull();
+ expect(keyToIndex(slices, "Bananas")).toBeNull();
+ });
+ it("returns null for negative index and empty slice arrays", () => {
+ expect(indexToKey(slices, -1)).toBeNull();
+ expect(indexToKey([], 0)).toBeNull();
+ expect(keyToIndex([], "x")).toBeNull();
+ });
+});
diff --git a/packages/react-ui/src/components/D3Charts/shared/core/legend/legendSelectors.ts b/packages/react-ui/src/components/D3Charts/shared/core/legend/legendSelectors.ts
new file mode 100644
index 000000000..78b3543a0
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/core/legend/legendSelectors.ts
@@ -0,0 +1,24 @@
+import type { StackedLegendItem } from "./types";
+
+/** Build legend items from the orchestrator's slices. Item key = slice label
+ * (the same key space hiddenSlices/toggleSlice already use). */
+export const stackedItemsFromSlices = (
+ slices: Array<{ label: string; value: number; color: string }>,
+): StackedLegendItem[] =>
+ slices.map((s) => ({
+ key: s.label,
+ label: s.label,
+ color: s.color,
+ value: s.value,
+ }));
+
+export const indexToKey = (
+ slices: Array<{ label: string }>,
+ index: number | null,
+): string | null => (index == null ? null : (slices[index]?.label ?? null));
+
+export const keyToIndex = (slices: Array<{ label: string }>, key: string | null): number | null => {
+ if (key == null) return null;
+ const i = slices.findIndex((s) => s.label === key);
+ return i < 0 ? null : i;
+};
diff --git a/packages/react-ui/src/components/D3Charts/shared/core/legend/legendStore.test.ts b/packages/react-ui/src/components/D3Charts/shared/core/legend/legendStore.test.ts
new file mode 100644
index 000000000..a466ad24e
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/core/legend/legendStore.test.ts
@@ -0,0 +1,150 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { createLegendStore } from "./legendStore";
+import type { StackedLegendItem } from "./types";
+
+const items = (n: number): StackedLegendItem[] =>
+ Array.from({ length: n }, (_, i) => ({
+ key: `k${i}`,
+ label: `L${i}`,
+ color: "#123456",
+ value: i + 1,
+ }));
+
+const itemsFromKeys = (keys: string[]): StackedLegendItem[] =>
+ keys.map((key, i) => ({ key, label: key, color: "#123456", value: i + 1 }));
+
+afterEach(() => vi.restoreAllMocks());
+
+describe("createLegendStore", () => {
+ it("publish creates an entry with empty active/hidden", () => {
+ const store = createLegendStore();
+ store.getState().publish("a", items(2));
+ expect(store.getState().entries["a"]!.items).toHaveLength(2);
+ expect(store.getState().entries["a"]!.activeKey).toBeNull();
+ expect(store.getState().entries["a"]!.hiddenKeys).toEqual([]);
+ });
+
+ it("publish preserves existing active/hidden across re-publish", () => {
+ const store = createLegendStore();
+ store.getState().publish("a", items(2));
+ store.getState().setActive("a", "k1");
+ store.getState().toggle("a", "k0");
+ store.getState().publish("a", items(3));
+ expect(store.getState().entries["a"]!.activeKey).toBe("k1");
+ expect(store.getState().entries["a"]!.hiddenKeys).toEqual(["k0"]);
+ expect(store.getState().entries["a"]!.items).toHaveLength(3);
+ });
+
+ it("publish reconciles hidden keys after a data swap — never leaves zero visible", () => {
+ const store = createLegendStore();
+ store.getState().publish("a", itemsFromKeys(["A", "B", "C"]));
+ store.getState().toggle("a", "A"); // hide A → B, C visible
+ store.getState().toggle("a", "B"); // hide B → C still visible
+ expect(store.getState().entries["a"]!.hiddenKeys).toEqual(["A", "B"]);
+ // Data swap drops C (the last-visible slice); only the previously-hidden
+ // A, B survive. Reconciled: every survivor would be hidden → reset to all
+ // visible so the chart never goes blank.
+ store.getState().publish("a", itemsFromKeys(["A", "B"]));
+ expect(store.getState().entries["a"]!.hiddenKeys).toEqual([]);
+ expect(store.getState().entries["a"]!.items).toHaveLength(2);
+ });
+
+ it("publish drops a stale activeKey that no longer exists", () => {
+ const store = createLegendStore();
+ store.getState().publish("a", itemsFromKeys(["A", "B", "C"]));
+ store.getState().setActive("a", "C");
+ expect(store.getState().entries["a"]!.activeKey).toBe("C");
+ store.getState().publish("a", itemsFromKeys(["A", "B"]));
+ expect(store.getState().entries["a"]!.activeKey).toBeNull();
+ });
+
+ it("publish keeps a still-present hidden key on a normal re-publish", () => {
+ const store = createLegendStore();
+ store.getState().publish("a", itemsFromKeys(["A", "B", "C"]));
+ store.getState().toggle("a", "A"); // hide A → B, C visible
+ store.getState().publish("a", itemsFromKeys(["A", "B", "C", "D"]));
+ // A still exists and ≥ 1 item stays visible → it remains hidden.
+ expect(store.getState().entries["a"]!.hiddenKeys).toEqual(["A"]);
+ });
+
+ it("publish stores, updates, and preserves the format on the entry", () => {
+ const store = createLegendStore();
+ store.getState().publish("a", items(2), "number");
+ expect(store.getState().entries["a"]!.format).toBe("number");
+ // A re-publish with a new format updates it.
+ store.getState().publish("a", items(2), "percentage");
+ expect(store.getState().entries["a"]!.format).toBe("percentage");
+ // A re-publish WITHOUT a format preserves the last one.
+ store.getState().publish("a", items(2));
+ expect(store.getState().entries["a"]!.format).toBe("percentage");
+ });
+
+ it("setActive / toggle are no-ops when key is absent", () => {
+ const store = createLegendStore();
+ store.getState().setActive("missing", "k0");
+ store.getState().toggle("missing", "k0");
+ expect(store.getState().entries["missing"]).toBeUndefined();
+ });
+
+ it("toggle flips membership", () => {
+ const store = createLegendStore();
+ store.getState().publish("a", items(2));
+ store.getState().toggle("a", "k0");
+ expect(store.getState().entries["a"]!.hiddenKeys).toEqual(["k0"]);
+ store.getState().toggle("a", "k0");
+ expect(store.getState().entries["a"]!.hiddenKeys).toEqual([]);
+ });
+
+ it("toggle keeps at least one item visible (cannot hide the last)", () => {
+ const store = createLegendStore();
+ store.getState().publish("a", items(2));
+ // Hiding the first one is fine — one stays visible.
+ store.getState().toggle("a", "k0");
+ expect(store.getState().entries["a"]!.hiddenKeys).toEqual(["k0"]);
+ // Hiding the second would blank the chart → blocked, no-op.
+ store.getState().toggle("a", "k1");
+ expect(store.getState().entries["a"]!.hiddenKeys).toEqual(["k0"]);
+ // Un-hiding is always allowed even at the boundary.
+ store.getState().toggle("a", "k0");
+ expect(store.getState().entries["a"]!.hiddenKeys).toEqual([]);
+ });
+
+ it("keys are isolated — writing one does not touch another", () => {
+ const store = createLegendStore();
+ store.getState().publish("a", items(1));
+ store.getState().publish("b", items(1));
+ store.getState().setActive("a", "k0");
+ expect(store.getState().entries["b"]!.activeKey).toBeNull();
+ });
+
+ it("unpublish removes the entry", () => {
+ const store = createLegendStore();
+ store.getState().publish("a", items(1));
+ store.getState().unpublish("a");
+ expect(store.getState().entries["a"]).toBeUndefined();
+ });
+
+ it("warns when a key gets a second publisher", () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const store = createLegendStore();
+ store.getState().registerPublisher("a");
+ expect(warn).not.toHaveBeenCalled();
+ store.getState().registerPublisher("a");
+ expect(warn).toHaveBeenCalledOnce();
+ expect(warn.mock.calls[0]![0]).toContain("a");
+ });
+
+ it("unregisterPublisher resets the count so a fresh register warns again", () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const store = createLegendStore();
+ store.getState().registerPublisher("a");
+ store.getState().unregisterPublisher("a");
+ expect(warn).not.toHaveBeenCalled();
+ // Back to zero → registering again is a first publisher, no warning.
+ store.getState().registerPublisher("a");
+ expect(warn).not.toHaveBeenCalled();
+ // A genuine second concurrent publisher still warns.
+ store.getState().registerPublisher("a");
+ expect(warn).toHaveBeenCalledOnce();
+ });
+});
diff --git a/packages/react-ui/src/components/D3Charts/shared/core/legend/legendStore.ts b/packages/react-ui/src/components/D3Charts/shared/core/legend/legendStore.ts
new file mode 100644
index 000000000..1aea8c6ef
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/core/legend/legendStore.ts
@@ -0,0 +1,97 @@
+import { create } from "zustand";
+import type { LegendStoreState, StackedLegendItem } from "./types";
+
+/**
+ * Factory — one store per LegendStoreProvider instance (NOT a module singleton),
+ * so state is scoped to the subtree and SSR-safe.
+ */
+export const createLegendStore = () => {
+ // Publisher counts are tracked outside reactive state (they must not trigger
+ // re-renders). Closed over by the actions; per store instance.
+ const publisherCounts = new Map<string, number>();
+
+ return create<LegendStoreState>((set) => ({
+ entries: {},
+
+ publish: (key, items: StackedLegendItem[], format) =>
+ set((s) => {
+ const prev = s.entries[key];
+ const newKeys = new Set(items.map((it) => it.key));
+ // Reconcile hidden state against the new items: drop keys for slices that
+ // no longer exist (e.g. after a data swap).
+ let nextHidden = (prev?.hiddenKeys ?? []).filter((k) => newKeys.has(k));
+ // Never leave zero visible after a publish — if every surviving item
+ // would be hidden, reset to all-visible (mirrors the toggle guard).
+ if (nextHidden.length >= items.length) nextHidden = [];
+ // Drop a stale activeKey that no longer maps to an item.
+ const nextActive = prev?.activeKey && newKeys.has(prev.activeKey) ? prev.activeKey : null;
+ return {
+ entries: {
+ ...s.entries,
+ [key]: {
+ items,
+ activeKey: nextActive,
+ hiddenKeys: nextHidden,
+ format: format ?? prev?.format,
+ },
+ },
+ };
+ }),
+
+ unpublish: (key) =>
+ set((s) => {
+ if (!s.entries[key]) return {};
+ const next = { ...s.entries };
+ delete next[key];
+ return { entries: next };
+ }),
+
+ setActive: (key, itemKey) =>
+ set((s) => {
+ const prev = s.entries[key];
+ if (!prev || prev.activeKey === itemKey) return {};
+ return {
+ entries: { ...s.entries, [key]: { ...prev, activeKey: itemKey } },
+ };
+ }),
+
+ toggle: (key, itemKey) =>
+ set((s) => {
+ const prev = s.entries[key];
+ if (!prev) return {};
+ const hidden = new Set(prev.hiddenKeys);
+ if (hidden.has(itemKey)) {
+ hidden.delete(itemKey);
+ } else {
+ // At least one item stays visible — mirrors the local-mode
+ // useSeriesVisibility guard so a remote legend can't blank the chart.
+ if (prev.items.length - prev.hiddenKeys.length <= 1) return {};
+ hidden.add(itemKey);
+ }
+ return {
+ entries: {
+ ...s.entries,
+ [key]: { ...prev, hiddenKeys: [...hidden] },
+ },
+ };
+ }),
+
+ registerPublisher: (key) => {
+ const count = (publisherCounts.get(key) ?? 0) + 1;
+ publisherCounts.set(key, count);
+ if (count > 1) {
+ // Misuse-only path: two charts publishing one key would stomp each other.
+ console.warn(
+ `[@openuidev/react-ui] Duplicate legendKey "${key}": more than one chart ` +
+ `publishes to it. Legends will collide — give each chart a unique legendKey.`,
+ );
+ }
+ },
+
+ unregisterPublisher: (key) => {
+ const count = (publisherCounts.get(key) ?? 0) - 1;
+ if (count <= 0) publisherCounts.delete(key);
+ else publisherCounts.set(key, count);
+ },
+ }));
+};
diff --git a/packages/react-ui/src/components/D3Charts/shared/core/legend/types.ts b/packages/react-ui/src/components/D3Charts/shared/core/legend/types.ts
new file mode 100644
index 000000000..8060eaf63
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/core/legend/types.ts
@@ -0,0 +1,34 @@
+export interface StackedLegendItem {
+ key: string;
+ label: string;
+ color: string;
+ value: number;
+}
+
+export interface LegendEntry {
+ items: StackedLegendItem[];
+ activeKey: string | null;
+ hiddenKeys: string[];
+ /** Value format the publishing chart uses; a detached legend inherits it. */
+ format?: "percentage" | "number";
+}
+
+export interface LegendStoreState {
+ entries: Record<string, LegendEntry>;
+ /**
+ * Chart publishes its current items. Reconciles active/hidden against the new
+ * item keys (drops stale keys, never leaves zero visible) and carries the
+ * chart's value format for detached legends to inherit.
+ */
+ publish: (key: string, items: StackedLegendItem[], format?: "percentage" | "number") => void;
+ /** Chart unmount: drop the entry entirely. */
+ unpublish: (key: string) => void;
+ /** Either side: set the highlighted item (null clears). No-op if key absent. */
+ setActive: (key: string, itemKey: string | null) => void;
+ /** Either side: flip an item's hidden state. No-op if key absent. */
+ toggle: (key: string, itemKey: string) => void;
+ /** Chart mount: track publisher count; warns on duplicate publisher for a key. */
+ registerPublisher: (key: string) => void;
+ /** Chart unmount: decrement publisher count. */
+ unregisterPublisher: (key: string) => void;
+}
diff --git a/packages/react-ui/src/components/D3Charts/shared/core/spring/FadeFollower.tsx b/packages/react-ui/src/components/D3Charts/shared/core/spring/FadeFollower.tsx
new file mode 100644
index 000000000..461225cc3
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/core/spring/FadeFollower.tsx
@@ -0,0 +1,57 @@
+import React from "react";
+
+import { springPresets } from "./presets";
+import type { SpringConfig } from "./spring";
+import { useSeededAim } from "./useSeededAim";
+import { useTranslate } from "./useTranslate";
+
+interface FadeFollowerProps {
+ /** Spring target in chart coordinates. Ignored while `!visible`. */
+ x: number;
+ /** Default 0 — most followers slide along one axis. */
+ y?: number;
+ visible: boolean;
+ /** Default springPresets.crosshair. */
+ config?: SpringConfig;
+ /** Opacity-fade duration on show/hide. Default 120. */
+ fadeMs?: number;
+ /** Static geometry drawn at the origin; the wrapper <g> is what translates. */
+ children: React.ReactNode;
+}
+
+/**
+ * The complete translate-shaped hover follower: an always-mounted <g> that
+ * springs to (x, y) under the seeded protocol (jump on first show, glide
+ * after, reset on hide) and hides via CSS opacity so the spring persists and
+ * re-hover glides. Render it UNCONDITIONALLY inside the plot group with
+ * static children at the origin — "add a hover highlight to chart X" is this
+ * plus a nullable hover index. Followers whose spring drives something other
+ * than a translate (arc-length dots, the highlight band's clip rect) use
+ * useSeededAim directly instead.
+ */
+export function FadeFollower({
+ x,
+ y = 0,
+ visible,
+ config = springPresets.crosshair,
+ fadeMs = 120,
+ children,
+}: FadeFollowerProps) {
+ const follow = useTranslate(config);
+ useSeededAim(visible, [x, y], (first) => {
+ if (first) follow.jump(x, y);
+ else follow.to(x, y);
+ });
+
+ return (
+ <g
+ ref={follow.bind}
+ style={{
+ opacity: visible ? 1 : 0,
+ transition: `opacity ${fadeMs}ms ease`,
+ }}
+ >
+ {children}
+ </g>
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/shared/core/spring/dataMorph.test.ts b/packages/react-ui/src/components/D3Charts/shared/core/spring/dataMorph.test.ts
new file mode 100644
index 000000000..d23c7026a
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/core/spring/dataMorph.test.ts
@@ -0,0 +1,115 @@
+import { describe, expect, it } from "vitest";
+import {
+ advanceVector,
+ morphAimMode,
+ retargetVector,
+ vectorAtRest,
+ type VectorSpringState,
+} from "./dataMorph";
+import { springPresets } from "./presets";
+import { advance, type SpringState } from "./spring";
+
+const cfg = springPresets.dataMorph;
+const DT = 1 / 60;
+
+function mkState(values: number[], targets = values): VectorSpringState {
+ return {
+ values: Float64Array.from(values),
+ velocities: new Float64Array(values.length),
+ targets: Float64Array.from(targets),
+ };
+}
+
+describe("advanceVector / vectorAtRest", () => {
+ it("converges every scalar to its target and settles in finite steps", () => {
+ const state = mkState([0, 50, -20], [100, 50, 30]);
+ let steps = 0;
+ for (; steps < 2000 && !vectorAtRest(state, cfg); steps++) {
+ advanceVector(state, DT, cfg);
+ }
+ expect(steps).toBeLessThan(2000);
+ expect(state.values[0]).toBeCloseTo(100, 0);
+ expect(state.values[1]).toBeCloseTo(50, 1);
+ expect(state.values[2]).toBeCloseTo(30, 0);
+ });
+
+ it("is component-wise identical to the scalar spring physics", () => {
+ const vector = mkState([0], [100]);
+ const scalar: SpringState = { value: 0, velocity: 0, target: 100 };
+ for (let i = 0; i < 30; i++) {
+ advanceVector(vector, DT, cfg);
+ advance(scalar, DT, cfg);
+ expect(vector.values[0]).toBeCloseTo(scalar.value, 12);
+ expect(vector.velocities[0]).toBeCloseTo(scalar.velocity, 12);
+ }
+ });
+});
+
+describe("retargetVector", () => {
+ it("same length: keeps live values + velocities, only targets move", () => {
+ const state = mkState([10, 20], [50, 60]);
+ advanceVector(state, DT, cfg); // pick up some velocity
+ const midValues = [...state.values];
+ const midVelocities = [...state.velocities];
+ const next = retargetVector(state, [70, 80]);
+ expect(next.resized).toBe(false);
+ expect(next.state).toBe(state);
+ expect([...next.state.values]).toEqual(midValues);
+ expect([...next.state.velocities]).toEqual(midVelocities);
+ expect([...next.state.targets]).toEqual([70, 80]);
+ });
+
+ it("length change: rebuilds snapped AT the targets (no correspondence)", () => {
+ const state = mkState([10, 20], [50, 60]);
+ const next = retargetVector(state, [1, 2, 3, 4]);
+ expect(next.resized).toBe(true);
+ expect([...next.state.values]).toEqual([1, 2, 3, 4]);
+ expect([...next.state.velocities]).toEqual([0, 0, 0, 0]);
+ });
+
+ it("no prior state: snaps at the targets", () => {
+ const next = retargetVector(null, [5, 6]);
+ expect(next.resized).toBe(true);
+ expect([...next.state.values]).toEqual([5, 6]);
+ });
+});
+
+describe("morphAimMode (the snap-vs-glide decision)", () => {
+ it.each([
+ // snapRequested, reducedMotion, resized → mode
+ [false, false, false, "glide"],
+ [true, false, false, "snap"], // isAnimationActive off / printing
+ [false, true, false, "snap"], // prefers-reduced-motion
+ [false, false, true, "snap"], // point count changed
+ [true, true, true, "snap"],
+ ] as const)("snap=%s reduced=%s resized=%s → %s", (snap, reduced, resized, mode) => {
+ expect(morphAimMode(snap, reduced, resized)).toBe(mode);
+ });
+});
+
+describe("per-frame retarget churn (the streaming freeze scenario)", () => {
+ it("keeps moving toward the target when retargeted EVERY frame", () => {
+ // The CSS `transition: d` failure mode: a restart per frame re-sampled
+ // progress 0 forever, so the rendered value never moved. The spring must
+ // make real progress under the same churn: retarget every frame (fresh
+ // targets array identity, jittering values), advance one frame, repeat.
+ let state = retargetVector(null, [0]).state;
+ state.values[0] = 0; // start away from the target band around 100
+ const positions: number[] = [];
+ for (let frame = 0; frame < 120; frame++) {
+ const jitter = frame % 2 === 0 ? 2 : -2;
+ state = retargetVector(state, [100 + jitter]).state;
+ advanceVector(state, DT, cfg);
+ positions.push(state.values[0]!);
+ }
+ // Liveness: visible progress within the first 10 frames (~166ms), unlike
+ // the pinned-at-0 CSS restart.
+ expect(positions[9]!).toBeGreaterThan(5);
+ // Convergence: after 2s of churn the value sits inside the jitter band.
+ expect(Math.abs(positions.at(-1)! - 100)).toBeLessThan(5);
+ // Monotone-ish liveness: every frame in the approach phase moved.
+ for (let i = 1; i < 30; i++) {
+ expect(positions[i]!).not.toBe(positions[i - 1]!);
+ }
+ });
+});
diff --git a/packages/react-ui/src/components/D3Charts/shared/core/spring/dataMorph.ts b/packages/react-ui/src/components/D3Charts/shared/core/spring/dataMorph.ts
new file mode 100644
index 000000000..c097ca873
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/core/spring/dataMorph.ts
@@ -0,0 +1,183 @@
+// The data morph: N scalars (a series' pixel geometry, flattened) springing
+// toward retargetable targets, sharing ONE ticker registration. This is what
+// animates a line/area series between data states — the job the CSS
+// `transition: d` used to do, minus its failure mode: a restarted CSS tween
+// re-samples from progress 0 on every `d` write, so per-frame streaming
+// rewrites starved it and the rendered geometry froze. A spring retargets
+// from its live position + velocity, so the same churn converges instead.
+//
+// Layering mirrors spring.ts: `advanceVector` / `vectorAtRest` /
+// `retargetVector` / `morphAimMode` are PURE (unit-tested with fixed dt);
+// `createDataMorph` is the runtime wrapper wiring them to the shared ticker
+// and an `onUpdate` callback (the series component regenerates its `d` string
+// there). Component-wise the physics IS spring.ts's `advance`, applied per
+// scalar — one tuning table, one behavior.
+
+import { advance, isAtRest, type SpringConfig, type SpringState } from "./spring";
+import { registerTick, unregisterTick } from "./ticker";
+
+export interface VectorSpringState {
+ values: Float64Array;
+ velocities: Float64Array;
+ targets: Float64Array;
+}
+
+export interface DataMorph {
+ /**
+ * Retarget toward `targets`. `snap` forces an instant jump (the
+ * `isAnimationActive={false}` path — no ticker work at all). A length
+ * change also snaps: geometry with a different point count has no
+ * correspondence to glide along (the CSS tween jumped there too).
+ */
+ aim(targets: ArrayLike<number>, snap?: boolean): void;
+ /** Retune live without recreating. */
+ setConfig(config: SpringConfig): void;
+ /** Stop and detach from the ticker. Idempotent. */
+ stop(): void;
+}
+
+// Scratch state so advanceVector reuses spring.ts's `advance` (the exact same
+// integration, substepping and clamping) without per-scalar allocation.
+const scratch: SpringState = { value: 0, velocity: 0, target: 0 };
+
+/**
+ * Advance every scalar by `dt` seconds under `config`. Component-wise
+ * identical to spring.ts's `advance`. Pure: mutates and returns `state`.
+ */
+export function advanceVector(
+ state: VectorSpringState,
+ dt: number,
+ config: SpringConfig,
+): VectorSpringState {
+ for (let i = 0; i < state.values.length; i++) {
+ scratch.value = state.values[i]!;
+ scratch.velocity = state.velocities[i]!;
+ scratch.target = state.targets[i]!;
+ advance(scratch, dt, config);
+ state.values[i] = scratch.value;
+ state.velocities[i] = scratch.velocity;
+ }
+ return state;
+}
+
+/** Whether EVERY scalar is within its rest thresholds (the slowest one gates). */
+export function vectorAtRest(state: VectorSpringState, config: SpringConfig): boolean {
+ for (let i = 0; i < state.values.length; i++) {
+ scratch.value = state.values[i]!;
+ scratch.velocity = state.velocities[i]!;
+ scratch.target = state.targets[i]!;
+ if (!isAtRest(scratch, config)) return false;
+ }
+ return true;
+}
+
+/**
+ * Point the state at `targets`. Same length → glide (values + velocities
+ * survive, only targets move — the retarget-from-flight property). Different
+ * length (or no state yet) → rebuild snapped AT the targets, since old and
+ * new geometry have no point correspondence. Pure.
+ */
+export function retargetVector(
+ state: VectorSpringState | null,
+ targets: ArrayLike<number>,
+): { state: VectorSpringState; resized: boolean } {
+ if (state === null || state.values.length !== targets.length) {
+ return {
+ state: {
+ values: Float64Array.from(targets),
+ velocities: new Float64Array(targets.length),
+ targets: Float64Array.from(targets),
+ },
+ resized: true,
+ };
+ }
+ state.targets.set(targets);
+ return { state, resized: false };
+}
+
+/**
+ * The snap-vs-glide decision, in one testable place:
+ * snap when the caller says so (`isAnimationActive` off — the default and
+ * every c1 surface — or printing, folded upstream by useEffectiveAnimation),
+ * when the user prefers reduced motion, or when the point count changed.
+ */
+export function morphAimMode(
+ snapRequested: boolean,
+ reducedMotion: boolean,
+ resized: boolean,
+): "snap" | "glide" {
+ return snapRequested || reducedMotion || resized ? "snap" : "glide";
+}
+
+// Cached MediaQueryList: aim() runs per data tick (every frame under
+// streaming), so unlike spring.ts's per-create probe this one must not
+// allocate per call. `undefined` = not probed yet, `null` = unavailable.
+let reducedMotionQuery: MediaQueryList | null | undefined;
+function prefersReducedMotion(): boolean {
+ if (reducedMotionQuery === undefined) {
+ reducedMotionQuery =
+ typeof window !== "undefined" && typeof window.matchMedia === "function"
+ ? window.matchMedia("(prefers-reduced-motion: reduce)")
+ : null;
+ }
+ return reducedMotionQuery?.matches ?? false;
+}
+
+export function createDataMorph(
+ config: SpringConfig,
+ onUpdate: (values: Float64Array) => void,
+): DataMorph {
+ let state: VectorSpringState | null = null;
+ let cfg = config;
+ let running = false;
+
+ const tick = (dt: number): boolean => {
+ if (state === null) {
+ running = false;
+ return false;
+ }
+ advanceVector(state, dt, cfg);
+ if (vectorAtRest(state, cfg)) {
+ state.values.set(state.targets);
+ state.velocities.fill(0);
+ onUpdate(state.values);
+ running = false;
+ return false; // settled → deregister
+ }
+ onUpdate(state.values);
+ return true;
+ };
+
+ return {
+ aim(targets, snap = false) {
+ const next = retargetVector(state, targets);
+ state = next.state;
+ if (morphAimMode(snap, prefersReducedMotion(), next.resized) === "snap") {
+ state.values.set(state.targets);
+ state.velocities.fill(0);
+ if (running) {
+ running = false;
+ unregisterTick(tick);
+ }
+ onUpdate(state.values);
+ return;
+ }
+ // Write the CURRENT animated values synchronously: aim() runs in a
+ // layout effect right after React committed the new target `d`, so this
+ // pre-paint write is what keeps a mid-glide retarget from flashing the
+ // target for one frame.
+ onUpdate(state.values);
+ if (!vectorAtRest(state, cfg) && !running) {
+ running = true;
+ registerTick(tick);
+ }
+ },
+ setConfig(next) {
+ cfg = next;
+ },
+ stop() {
+ running = false;
+ unregisterTick(tick);
+ },
+ };
+}
diff --git a/packages/react-ui/src/components/D3Charts/shared/core/spring/index.ts b/packages/react-ui/src/components/D3Charts/shared/core/spring/index.ts
new file mode 100644
index 000000000..40381e509
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/core/spring/index.ts
@@ -0,0 +1,26 @@
+// A dependency-free spring primitive: a scalar value that eases toward a target,
+// retargetable any time, driven by one shared rAF loop. Internal — not part of the
+// public API. Used to make hover interactions (crosshair, dots, …) glide instead of
+// snap.
+
+export { useIsomorphicLayoutEffect } from "../../../hooks/core/useIsomorphicLayoutEffect";
+export {
+ advanceVector,
+ createDataMorph,
+ morphAimMode,
+ retargetVector,
+ vectorAtRest,
+} from "./dataMorph";
+export type { DataMorph, VectorSpringState } from "./dataMorph";
+export { FadeFollower } from "./FadeFollower";
+export { springPresets } from "./presets";
+export { advance, createSpring, isAtRest } from "./spring";
+export type { Spring, SpringConfig, SpringState } from "./spring";
+export { activeTickCount } from "./ticker";
+export { useDataMorph } from "./useDataMorph";
+export type { DataMorphAim } from "./useDataMorph";
+export { useSeededAim } from "./useSeededAim";
+export { useSpring } from "./useSpring";
+export type { SpringHandle } from "./useSpring";
+export { useTranslate } from "./useTranslate";
+export type { TranslateHandle } from "./useTranslate";
diff --git a/packages/react-ui/src/components/D3Charts/shared/core/spring/presets.ts b/packages/react-ui/src/components/D3Charts/shared/core/spring/presets.ts
new file mode 100644
index 000000000..735e2ea25
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/core/spring/presets.ts
@@ -0,0 +1,32 @@
+import type { SpringConfig } from "./spring";
+
+/**
+ * Named motion presets — the one table that defines how hover motion FEELS
+ * across the library. Cross-chart parity (the bar band matching the line/area
+ * crosshair, for instance) is structural here instead of comment-enforced in
+ * scattered per-file constants. Tuning guide: stiffness ↑ = tighter tracking;
+ * damping ≈ 2·√stiffness is critical (no overshoot), lower = bouncier. Edit a
+ * value and the bench shows it live via HMR.
+ *
+ * Internal — never export from src/index.ts.
+ */
+export const springPresets = {
+ /** Snappy-but-smooth follower: crosshair line, active dots, bar hover band. */
+ crosshair: { stiffness: 320, damping: 26 },
+ /** Softer — the highlight band glides/stretches a touch behind the dots. */
+ highlight: { stiffness: 180, damping: 28 },
+ /** Pie slice pop-out (matches bklit's pie hover feel). */
+ popOut: { stiffness: 400, damping: 25 },
+ /** Tooltip soft-follow — fast, critical damping (480/38 ⇒ no overshoot). */
+ tooltip: { stiffness: 480, damping: 38 },
+ /**
+ * Line/area series data morph (replaces the removed `transition: d 0.3s`).
+ * Critical damping (44 ≈ 2·√480) — data must never overshoot its value —
+ * tuned so a typical retarget is visually settled in ~300–400ms, matching
+ * the old tween's feel. Rest thresholds are much looser than the hover
+ * springs': these scalars are pixel geometry, so a quarter-pixel at under
+ * 5px/s is invisible — a tight threshold only kept the ticker running
+ * through a motionless tail.
+ */
+ dataMorph: { stiffness: 480, damping: 44, restDelta: 0.25, restSpeed: 5 },
+} satisfies Record<string, SpringConfig>;
diff --git a/packages/react-ui/src/components/D3Charts/shared/core/spring/spring.test.ts b/packages/react-ui/src/components/D3Charts/shared/core/spring/spring.test.ts
new file mode 100644
index 000000000..bc29b9e78
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/core/spring/spring.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, it } from "vitest";
+import { advance, isAtRest, type SpringConfig, type SpringState } from "./spring";
+
+// Critically-ish damped config (ζ ≈ 0.9), matching how a page maps a slider.
+const cfg = (stiffness: number): SpringConfig => ({
+ stiffness,
+ damping: 2 * Math.sqrt(stiffness) * 0.9,
+});
+
+function simulate(stiffness: number, target: number, fps = 60) {
+ const config = cfg(stiffness);
+ const state: SpringState = { value: 0, velocity: 0, target };
+ let steps = 0;
+ let maxValue = 0;
+ for (; steps < 2000; steps++) {
+ advance(state, 1 / fps, config);
+ maxValue = Math.max(maxValue, state.value);
+ if (isAtRest(state, config)) break;
+ }
+ return { steps, value: state.value, maxValue };
+}
+
+describe("spring physics", () => {
+ it("converges to the target and settles in finite steps", () => {
+ for (const k of [120, 300, 640]) {
+ const { steps, value } = simulate(k, 100);
+ expect(steps).toBeLessThan(2000);
+ expect(value).toBeCloseTo(100, 1);
+ }
+ });
+
+ it("does not overshoot meaningfully at ζ ≈ 0.9", () => {
+ const { maxValue } = simulate(300, 100);
+ expect(maxValue).toBeLessThan(100 * 1.05);
+ });
+
+ it("stays finite under a large (clamped) frame gap", () => {
+ const config = cfg(300);
+ const state: SpringState = { value: 0, velocity: 0, target: 100 };
+ advance(state, 5, config);
+ expect(Number.isFinite(state.value)).toBe(true);
+ });
+
+ it("isAtRest reflects distance + speed thresholds", () => {
+ const config = cfg(300);
+ expect(isAtRest({ value: 0, velocity: 0, target: 100 }, config)).toBe(false);
+ expect(isAtRest({ value: 100, velocity: 0, target: 100 }, config)).toBe(true);
+ expect(isAtRest({ value: 100, velocity: 5, target: 100 }, config)).toBe(false);
+ });
+});
diff --git a/packages/react-ui/src/components/D3Charts/shared/core/spring/spring.ts b/packages/react-ui/src/components/D3Charts/shared/core/spring/spring.ts
new file mode 100644
index 000000000..1682626da
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/core/spring/spring.ts
@@ -0,0 +1,139 @@
+// The spring primitive: a scalar value that eases toward a target, retargetable
+// at any time, driven by the shared ticker. This is the whole "engine" — bklit
+// gets the equivalent from Framer's `useSpring`; here it's ~one file, dep-free.
+//
+// `advance` and `isAtRest` are PURE (no rAF, no DOM) so the physics can be
+// verified deterministically — step with a fixed dt and assert convergence.
+// `createSpring` is the runtime wrapper that wires that physics to the ticker and
+// an `onUpdate` callback (the caller decides what to do with the value: translate
+// an element, regenerate an arc path, set opacity, …).
+
+import { registerTick, unregisterTick } from "./ticker";
+
+export interface SpringConfig {
+ stiffness: number;
+ damping: number;
+ /** Distance from target below which (with low speed) the spring settles. Default 0.01. */
+ restDelta?: number;
+ /** Speed below which (near the target) the spring settles. Default 0.01. */
+ restSpeed?: number;
+}
+
+export interface SpringState {
+ value: number;
+ velocity: number;
+ target: number;
+}
+
+export interface Spring {
+ /** Retarget; the value springs toward `target`. */
+ set(target: number): void;
+ /** Snap to `value` instantly (no animation), e.g. to seed position on first show. */
+ jump(value: number): void;
+ get(): number;
+ /** Retune live without recreating (changing responsiveness mid-flight). */
+ setConfig(config: SpringConfig): void;
+ /** Stop and detach from the ticker. Idempotent. */
+ stop(): void;
+}
+
+/** Fixed substep (s) — integrate in small steps so behaviour is frame-rate
+ * independent and stable even when a frame is late (tab refocus). */
+const FIXED_STEP = 1 / 120;
+/** Clamp a single frame's dt (s) so a long gap can't explode the integration. */
+const MAX_FRAME = 0.064;
+
+/**
+ * Advance `state` by `dt` seconds under `config` (semi-implicit Euler, substepped).
+ * Pure: mutates and returns `state`, touches nothing else. Unit-test this directly.
+ */
+export function advance(state: SpringState, dt: number, config: SpringConfig): SpringState {
+ const k = config.stiffness;
+ const c = config.damping;
+ let remaining = Math.min(dt, MAX_FRAME);
+ while (remaining > 0) {
+ const h = Math.min(FIXED_STEP, remaining);
+ const force = -k * (state.value - state.target) - c * state.velocity;
+ state.velocity += force * h; // update velocity first …
+ state.value += state.velocity * h; // … then position with the new velocity
+ remaining -= h;
+ }
+ return state;
+}
+
+/** Whether the spring is within its rest thresholds of the target. */
+export function isAtRest(state: SpringState, config: SpringConfig): boolean {
+ const restDelta = config.restDelta ?? 0.01;
+ const restSpeed = config.restSpeed ?? 0.01;
+ return Math.abs(state.value - state.target) < restDelta && Math.abs(state.velocity) < restSpeed;
+}
+
+function prefersReducedMotion(): boolean {
+ return (
+ typeof window !== "undefined" &&
+ typeof window.matchMedia === "function" &&
+ window.matchMedia("(prefers-reduced-motion: reduce)").matches
+ );
+}
+
+export function createSpring(
+ initial: number,
+ config: SpringConfig,
+ onUpdate: (value: number) => void,
+): Spring {
+ const state: SpringState = { value: initial, velocity: 0, target: initial };
+ let cfg = config;
+ let reduced = prefersReducedMotion();
+ let running = false;
+
+ const tick: (dt: number) => boolean = (dt) => {
+ advance(state, dt, cfg);
+ if (isAtRest(state, cfg)) {
+ state.value = state.target;
+ state.velocity = 0;
+ onUpdate(state.value);
+ running = false;
+ return false; // settled → deregister; loop stops when nothing's left
+ }
+ onUpdate(state.value);
+ return true;
+ };
+
+ const start = () => {
+ if (!running) {
+ running = true;
+ registerTick(tick);
+ }
+ };
+
+ return {
+ set(target) {
+ state.target = target;
+ if (reduced) {
+ // Respect reduced-motion: snap, never animate.
+ state.value = target;
+ state.velocity = 0;
+ onUpdate(target);
+ return;
+ }
+ if (state.value !== target || state.velocity !== 0) {
+ start();
+ }
+ },
+ jump(value) {
+ state.value = value;
+ state.target = value;
+ state.velocity = 0;
+ onUpdate(value);
+ },
+ get: () => state.value,
+ setConfig(next) {
+ cfg = next;
+ reduced = prefersReducedMotion();
+ },
+ stop() {
+ running = false;
+ unregisterTick(tick);
+ },
+ };
+}
diff --git a/packages/react-ui/src/components/D3Charts/shared/core/spring/ticker.ts b/packages/react-ui/src/components/D3Charts/shared/core/spring/ticker.ts
new file mode 100644
index 000000000..00481d41a
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/core/spring/ticker.ts
@@ -0,0 +1,50 @@
+// One shared requestAnimationFrame loop for every active spring.
+//
+// A spring registers its tick fn when it starts moving; the loop removes it when
+// the fn returns false (settled). So N springs share ONE rAF loop — a chart with
+// 30 dots or 8 slices pays for one loop, not 30. The loop starts on first
+// register and stops itself the moment nothing is active (no leaked loop).
+
+export type TickFn = (dtSeconds: number) => boolean;
+
+const active = new Set<TickFn>();
+let rafId: number | null = null;
+let lastTime = 0;
+
+function frame(now: number) {
+ const dt = lastTime === 0 ? 0 : (now - lastTime) / 1000;
+ lastTime = now;
+
+ // Snapshot so a tick that unregisters itself (or another) mid-iteration is safe.
+ for (const tick of [...active]) {
+ if (!tick(dt)) {
+ active.delete(tick);
+ }
+ }
+
+ if (active.size > 0) {
+ rafId = requestAnimationFrame(frame);
+ } else {
+ rafId = null;
+ lastTime = 0;
+ }
+}
+
+export function registerTick(tick: TickFn): void {
+ active.add(tick);
+ if (rafId === null) {
+ lastTime = 0;
+ rafId = requestAnimationFrame(frame);
+ }
+}
+
+export function unregisterTick(tick: TickFn): void {
+ // Set.delete is a no-op if absent → unregister/stop is idempotent. The loop
+ // notices the empty set on its next frame and halts itself.
+ active.delete(tick);
+}
+
+/** Debug/verification only: number of active ticks (0 ⇒ the rAF loop is idle). */
+export function activeTickCount(): number {
+ return active.size;
+}
diff --git a/packages/react-ui/src/components/D3Charts/shared/core/spring/useDataMorph.ts b/packages/react-ui/src/components/D3Charts/shared/core/spring/useDataMorph.ts
new file mode 100644
index 000000000..d6ad17630
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/core/spring/useDataMorph.ts
@@ -0,0 +1,60 @@
+// React hook over `createDataMorph`, mirroring useSpring's ref discipline: the
+// morph lives in a ref, retargeting never re-renders React, and the shared
+// ticker drops it on unmount.
+//
+// The morph is created LAZILY on the first ANIMATED aim. While every aim
+// snaps (`isAnimationActive={false}` — the default, and what every c1 surface
+// passes), no morph exists at all: React's own `d`/`cx`/`cy` attribute commit
+// IS the snapped geometry, so the streaming hot path costs nothing beyond the
+// render it already paid for. Only if a morph was created (animate was on at
+// some point) does a snap aim need to run through it — the DOM may hold
+// mid-glide geometry that React's props no longer describe.
+
+import { useEffect, useRef } from "react";
+import { createDataMorph, type DataMorph } from "./dataMorph";
+import type { SpringConfig } from "./spring";
+
+export type DataMorphAim = (targets: ArrayLike<number>, snap: boolean) => void;
+
+export function useDataMorph(
+ config: SpringConfig,
+ onUpdate: (values: Float64Array) => void,
+): DataMorphAim {
+ // Keep `onUpdate` fresh without recreating the morph.
+ const onUpdateRef = useRef(onUpdate);
+ onUpdateRef.current = onUpdate;
+
+ const configRef = useRef(config);
+ configRef.current = config;
+
+ const morphRef = useRef<DataMorph | null>(null);
+
+ // Live retune (parity with useSpring) — only relevant once a morph exists.
+ useEffect(() => {
+ morphRef.current?.setConfig(config);
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- keyed on the scalar fields, not `config` itself: callers pass inline object literals, so object identity churns every render while the values are what matter
+ }, [config.stiffness, config.damping, config.restDelta, config.restSpeed]);
+
+ // Teardown: detach from the shared ticker (no leaked loop).
+ useEffect(() => {
+ return () => morphRef.current?.stop();
+ }, []);
+
+ // Stable aim (delegates through refs) so layout effects can depend on it
+ // without churn.
+ const aimRef = useRef<DataMorphAim | null>(null);
+ if (aimRef.current === null) {
+ aimRef.current = (targets, snap) => {
+ if (morphRef.current === null) {
+ // No morph yet + snapping: React committed these targets as
+ // attributes this very render — nothing to do.
+ if (snap || typeof window === "undefined") return;
+ morphRef.current = createDataMorph(configRef.current, (values) =>
+ onUpdateRef.current(values),
+ );
+ }
+ morphRef.current.aim(targets, snap);
+ };
+ }
+ return aimRef.current;
+}
diff --git a/packages/react-ui/src/components/D3Charts/shared/core/spring/useSeededAim.ts b/packages/react-ui/src/components/D3Charts/shared/core/spring/useSeededAim.ts
new file mode 100644
index 000000000..bb9edf2ea
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/core/spring/useSeededAim.ts
@@ -0,0 +1,36 @@
+import { useRef } from "react";
+import { useIsomorphicLayoutEffect } from "../../../hooks/core/useIsomorphicLayoutEffect";
+
+/**
+ * The follower protocol shared by every always-mounted hover follower: while
+ * `visible`, aim the spring(s) before paint — JUMP on the first show of a
+ * hover session (so a newly-shown follower never glides in from stale
+ * coordinates), GLIDE on every aim after that, and reset the session when
+ * `visible` goes false. The consumer owns its spring(s); `aim(first)` decides
+ * what jumping/gliding means (translate, arc-length, a band's x+width pair…).
+ *
+ * `aim` may return `false` to skip seeding — e.g. the target geometry isn't
+ * ready yet — so a session that has never seeded still jumps on its first
+ * successful aim. (It never UN-seeds: only `visible` going false resets.)
+ *
+ * Deliberate non-consumers (do not migrate them onto this): pie's `Slice`
+ * (rest IS home — it never seeds) and `ChartTooltip` (mount-per-session;
+ * its remount is the reset).
+ */
+export function useSeededAim(
+ visible: boolean,
+ deps: readonly unknown[],
+ aim: (first: boolean) => boolean | void,
+): void {
+ const seeded = useRef(false);
+ // Protocol hook: the consumer supplies its own dep list via `deps`.
+ useIsomorphicLayoutEffect(() => {
+ if (!visible) {
+ seeded.current = false;
+ return;
+ }
+ if (aim(!seeded.current) !== false) {
+ seeded.current = true;
+ }
+ }, [visible, ...deps]);
+}
diff --git a/packages/react-ui/src/components/D3Charts/shared/core/spring/useSpring.ts b/packages/react-ui/src/components/D3Charts/shared/core/spring/useSpring.ts
new file mode 100644
index 000000000..8fa6ad4c7
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/core/spring/useSpring.ts
@@ -0,0 +1,50 @@
+// React hook over `createSpring`. The spring lives in a ref (created once, never
+// recreated), so retargeting it from a pointer handler never re-renders React —
+// the continuous motion runs entirely off the render path. Config retunes live;
+// the spring stops (and the shared ticker drops it) on unmount.
+
+import { useEffect, useRef } from "react";
+import { createSpring, type Spring, type SpringConfig } from "./spring";
+
+export interface SpringHandle {
+ set(target: number): void;
+ jump(value: number): void;
+}
+
+export function useSpring(
+ config: SpringConfig,
+ onUpdate: (value: number) => void,
+ initial = 0,
+): SpringHandle {
+ // Keep `onUpdate` fresh without recreating the spring.
+ const onUpdateRef = useRef(onUpdate);
+ onUpdateRef.current = onUpdate;
+
+ const springRef = useRef<Spring | null>(null);
+ if (springRef.current === null && typeof window !== "undefined") {
+ springRef.current = createSpring(initial, config, (v) => onUpdateRef.current(v));
+ }
+
+ // Live retune — change responsiveness without recreating / restarting.
+ useEffect(() => {
+ springRef.current?.setConfig(config);
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- keyed on the scalar fields, not `config` itself: callers pass inline object literals, so object identity churns every render while the values are what matter
+ }, [config.stiffness, config.damping, config.restDelta, config.restSpeed]);
+
+ // Teardown: stop the spring so the shared ticker drops it (no leaked loop).
+ useEffect(() => {
+ const spring = springRef.current;
+ return () => spring?.stop();
+ }, []);
+
+ // Stable handle (delegates to the ref) so consumers can keep it out of deps and
+ // ref callbacks built on it don't churn every render.
+ const handleRef = useRef<SpringHandle | null>(null);
+ if (handleRef.current === null) {
+ handleRef.current = {
+ set: (target) => springRef.current?.set(target),
+ jump: (value) => springRef.current?.jump(value),
+ };
+ }
+ return handleRef.current;
+}
diff --git a/packages/react-ui/src/components/D3Charts/shared/core/spring/useTranslate.ts b/packages/react-ui/src/components/D3Charts/shared/core/spring/useTranslate.ts
new file mode 100644
index 000000000..641374bb5
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/core/spring/useTranslate.ts
@@ -0,0 +1,62 @@
+// Convenience over the scalar spring: drive one element's CSS `transform:
+// translate(x, y)` from two springs. This is a THIN layer — the real primitive is
+// the scalar `useSpring`; translate is just one thing you can do with the value.
+// (The line/area dots spring an arc-length along the path, and the highlight band
+// springs its x + width, directly via `useSpring` — proving the core isn't
+// translate-bound.)
+
+import { useRef } from "react";
+import type { SpringConfig } from "./spring";
+import { useSpring } from "./useSpring";
+
+export interface TranslateHandle {
+ /** Ref callback for the element to drive. */
+ bind: (el: HTMLElement | SVGElement | null) => void;
+ /** Spring toward (x, y). */
+ to: (x: number, y: number) => void;
+ /** Snap to (x, y) instantly. */
+ jump: (x: number, y: number) => void;
+}
+
+export function useTranslate(config: SpringConfig): TranslateHandle {
+ const elRef = useRef<HTMLElement | SVGElement | null>(null);
+ const pos = useRef({ x: 0, y: 0 });
+
+ const write = () => {
+ const el = elRef.current;
+ if (el) {
+ el.style.transform = `translate(${pos.current.x}px, ${pos.current.y}px)`;
+ }
+ };
+
+ const sx = useSpring(config, (v) => {
+ pos.current.x = v;
+ write();
+ });
+ const sy = useSpring(config, (v) => {
+ pos.current.y = v;
+ write();
+ });
+
+ // Stable api (sx/sy are ref-backed handles, so this never needs to change).
+ const apiRef = useRef<TranslateHandle | null>(null);
+ if (apiRef.current === null) {
+ apiRef.current = {
+ bind: (el) => {
+ elRef.current = el;
+ write();
+ },
+ to: (x, y) => {
+ sx.set(x);
+ sy.set(y);
+ },
+ jump: (x, y) => {
+ pos.current = { x, y };
+ sx.jump(x);
+ sy.jump(y);
+ write();
+ },
+ };
+ }
+ return apiRef.current;
+}
diff --git a/packages/react-ui/src/components/D3Charts/shared/mini/MiniChartFrame.tsx b/packages/react-ui/src/components/D3Charts/shared/mini/MiniChartFrame.tsx
new file mode 100644
index 000000000..461b873bc
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/mini/MiniChartFrame.tsx
@@ -0,0 +1,52 @@
+import clsx from "clsx";
+import { type MouseEventHandler, type ReactNode, useRef } from "react";
+import { useContainerSize } from "../../hooks/core/useContainerSize";
+import { CHART_CLASS_PREFIX } from "../../utils/constants";
+
+/**
+ * The square frame every mini chart draws in, as react-ui's Recharts mini
+ * charts do: `size` sets width and height (default "100%"), kept square and at
+ * least 100px each way. Measures itself and hands the svg size to `children`.
+ */
+export function MiniChartFrame({
+ chart,
+ size = "100%",
+ className,
+ onClick,
+ children,
+}: {
+ chart: "area" | "bar" | "line";
+ size?: number | string;
+ className?: string;
+ onClick?: MouseEventHandler<HTMLDivElement>;
+ children: (width: number, height: number) => ReactNode;
+}) {
+ const ref = useRef<HTMLDivElement>(null);
+ const { width, height } = useContainerSize(ref, size, size);
+
+ return (
+ <div
+ ref={ref}
+ className={clsx(
+ `${CHART_CLASS_PREFIX}-mini-chart`,
+ `${CHART_CLASS_PREFIX}-mini-${chart}-chart-container`,
+ onClick && `${CHART_CLASS_PREFIX}-mini-chart--clickable`,
+ className,
+ )}
+ style={{ width: size, height: size }}
+ onClick={onClick}
+ >
+ {width > 0 && height > 0 && (
+ <svg
+ width={width}
+ height={height}
+ viewBox={`0 0 ${width} ${height}`}
+ role="img"
+ aria-label={`Mini ${chart} chart`}
+ >
+ {children(width, height)}
+ </svg>
+ )}
+ </div>
+ );
+}
diff --git a/packages/react-ui/src/components/D3Charts/shared/mini/miniChart.scss b/packages/react-ui/src/components/D3Charts/shared/mini/miniChart.scss
new file mode 100644
index 000000000..1d4e1d5c0
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/mini/miniChart.scss
@@ -0,0 +1,28 @@
+@use "../cartesian/chartBase" as base;
+@use "../../prefix" as brand;
+
+// The mini charts' frame (MiniChartFrame): square, at least 100px each way,
+// as react-ui's Recharts mini charts are.
+.#{brand.$prefix}-mini-chart {
+ position: relative;
+ aspect-ratio: 1 / 1;
+ min-width: 100px;
+ min-height: 100px;
+
+ > svg {
+ display: block;
+ }
+
+ &--clickable {
+ cursor: pointer;
+ }
+}
+
+// Entrance: marks fade in. The whole rule is gated so reduced-motion users
+// never sit at the opacity: 0 start.
+@media (prefers-reduced-motion: no-preference) {
+ .#{brand.$prefix}-mini-chart-mark--animated {
+ opacity: 0;
+ animation: #{brand.$prefix}-fade-appear 0.6s ease-out forwards;
+ }
+}
diff --git a/packages/react-ui/src/components/D3Charts/shared/mini/miniChartUtils.test.ts b/packages/react-ui/src/components/D3Charts/shared/mini/miniChartUtils.test.ts
new file mode 100644
index 000000000..9d9d4f436
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/mini/miniChartUtils.test.ts
@@ -0,0 +1,113 @@
+import { describe, expect, it } from "vitest";
+import {
+ miniBarGeometry,
+ miniBarsLeftPadding,
+ miniLineGeometry,
+ miniValueDomain,
+ recentBarsThatFit,
+ recentPointsThatFit,
+ rechartsNiceDomain,
+ toMiniChartPoints,
+} from "./miniChartUtils";
+
+describe("toMiniChartPoints", () => {
+ it("accepts numbers and { value, label } objects, labelling by position", () => {
+ expect(toMiniChartPoints([4, 7])).toEqual([
+ { value: 4, label: "Item 1" },
+ { value: 7, label: "Item 2" },
+ ]);
+ expect(toMiniChartPoints([{ value: 3, label: "Mon" }, { value: 5 }])).toEqual([
+ { value: 3, label: "Mon" },
+ { value: 5, label: "Item 2" },
+ ]);
+ });
+});
+
+describe("recentPointsThatFit (area / line)", () => {
+ const data = Array.from({ length: 30 }, (_, i) => i);
+
+ it("keeps everything when unmeasured or when it all fits", () => {
+ expect(recentPointsThatFit(data, 0)).toEqual(data);
+ expect(recentPointsThatFit(data.slice(0, 5), 454)).toHaveLength(5);
+ });
+
+ it("keeps the most recent points, one per 20px", () => {
+ // floor((200 + 20) / 20) = 11
+ expect(recentPointsThatFit(data, 200)).toEqual(data.slice(-11));
+ });
+});
+
+describe("recentBarsThatFit / miniBarsLeftPadding (bar)", () => {
+ const data = Array.from({ length: 40 }, (_, i) => i);
+
+ it("keeps the most recent bars, 18px each after 8px padding", () => {
+ // floor((200 - 8) / 18) = 10
+ expect(recentBarsThatFit(data, 200)).toEqual(data.slice(-10));
+ expect(recentBarsThatFit(data, 0)).toEqual(data);
+ });
+
+ it("right-aligns short series with left padding, none when full", () => {
+ // 454 - 8 - 9 * 18 = 284 (react-ui's Recharts MiniBarChart getPadding)
+ expect(miniBarsLeftPadding(9, 454)).toBe(284);
+ expect(miniBarsLeftPadding(40, 200)).toBe(0);
+ });
+});
+
+describe("miniValueDomain", () => {
+ it("anchors through zero", () => {
+ expect(miniValueDomain([12, 40, 9])).toEqual([0, 40]);
+ expect(miniValueDomain([-5, 10])).toEqual([-5, 10]);
+ expect(miniValueDomain([])).toEqual([0, 0]);
+ });
+});
+
+// Coordinates measured from react-ui's Recharts mini charts at 454×454 with
+// [12, 18, 9, 22, 30, 26, 34, 28, 40].
+const SPARK = [12, 18, 9, 22, 30, 26, 34, 28, 40];
+
+describe("miniLineGeometry (matches Recharts' mini area/line)", () => {
+ it("spreads points edge to edge under a 10px top margin", () => {
+ const { points, x, y } = miniLineGeometry(SPARK, 454, 454);
+ expect(points).toHaveLength(9);
+ expect(x(0)).toBe(0);
+ expect(x(1)).toBeCloseTo(56.75);
+ expect(x(8)).toBe(454);
+ expect(y(12)).toBeCloseTo(320.8);
+ expect(y(40)).toBe(10);
+ expect(y(0)).toBe(454);
+ });
+});
+
+describe("miniBarGeometry (matches Recharts' mini bar)", () => {
+ it("right-aligns 8px bars inside a 5px margin", () => {
+ const bars = miniBarGeometry(SPARK, 454, 454);
+ expect(bars).toHaveLength(9);
+ expect(bars[0]!.x).toBe(293);
+ expect(bars[0]!.y).toBeCloseTo(315.8);
+ expect(bars[0]!.y + bars[0]!.height).toBeCloseTo(449);
+ expect(bars[8]!.y).toBe(5);
+ });
+
+ it("hangs negative bars below zero", () => {
+ const [bar] = miniBarGeometry([-10, 10], 200, 200);
+ expect(bar!.negative).toBe(true);
+ expect(bar!.y).toBeCloseTo(100);
+ });
+});
+
+describe("rechartsNiceDomain (recharts-scale getNiceTickValues, 5 ticks)", () => {
+ it("rounds up in 5%-of-magnitude steps", () => {
+ expect(rechartsNiceDomain(0, 40)).toEqual([0, 40]);
+ expect(rechartsNiceDomain(0, 50)).toEqual([0, 60]);
+ expect(rechartsNiceDomain(0, 58)).toEqual([0, 60]);
+ expect(rechartsNiceDomain(0, 7900)).toEqual([0, 8000]);
+ });
+
+ it("widens the step until five ticks cover signed data", () => {
+ expect(rechartsNiceDomain(-5, 10)).toEqual([-5, 15]);
+ });
+
+ it("spans 0..4 for all-zero data", () => {
+ expect(rechartsNiceDomain(0, 0)).toEqual([0, 4]);
+ });
+});
diff --git a/packages/react-ui/src/components/D3Charts/shared/mini/miniChartUtils.ts b/packages/react-ui/src/components/D3Charts/shared/mini/miniChartUtils.ts
new file mode 100644
index 000000000..9fca66037
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/shared/mini/miniChartUtils.ts
@@ -0,0 +1,181 @@
+// Pure geometry for the mini charts (MiniAreaChart / MiniLineChart /
+// MiniBarChart) — the sizing rules of react-ui's Recharts mini charts, kept out
+// of the React layer so they are unit-testable in node.
+
+import { scaleLinear, scalePoint } from "d3-scale";
+import { curveLinear, curveMonotoneX, curveStep } from "d3-shape";
+
+export type MiniChartDatum = number | { value: number; label?: string };
+
+export interface MiniChartPoint {
+ value: number;
+ label: string;
+}
+
+/** Numbers or `{ value, label? }` objects → `{ value, label }`, labels defaulting to "Item N". */
+export const toMiniChartPoints = (data: readonly MiniChartDatum[]): MiniChartPoint[] =>
+ data.map((item, index) =>
+ typeof item === "number"
+ ? { value: item, label: `Item ${index + 1}` }
+ : { value: item.value, label: item.label || `Item ${index + 1}` },
+ );
+
+/** Area/line: one point every 20px. */
+export const MINI_POINT_SPACING = 20;
+
+/**
+ * The most recent area/line points that fit `width`: n points span
+ * (n - 1) gaps of MINI_POINT_SPACING. Everything when unmeasured (width 0).
+ */
+export const recentPointsThatFit = <T>(data: readonly T[], width: number): T[] => {
+ if (width <= 0 || data.length === 0) return [...data];
+ const maxItems = Math.floor((width + MINI_POINT_SPACING) / MINI_POINT_SPACING);
+ return maxItems >= data.length ? [...data] : data.slice(-maxItems);
+};
+
+export const MINI_BAR_WIDTH = 8;
+export const MINI_BAR_SPACING = 10;
+/** Horizontal room the bar chart keeps free: its 4px side padding, both sides. */
+const MINI_BAR_HORIZONTAL_PADDING = 8;
+
+/** The most recent bars that fit `width` (8px bar + 10px gap each). */
+export const recentBarsThatFit = <T>(data: readonly T[], width: number): T[] => {
+ if (width <= 0 || data.length === 0) return [...data];
+ const maxItems = Math.floor(
+ (width - MINI_BAR_HORIZONTAL_PADDING) / (MINI_BAR_WIDTH + MINI_BAR_SPACING),
+ );
+ return maxItems >= data.length ? [...data] : data.slice(-Math.max(0, maxItems));
+};
+
+/** Empty room left of the bars: they sit right-aligned when they don't fill the width. */
+export const miniBarsLeftPadding = (count: number, width: number): number =>
+ Math.max(0, width - MINI_BAR_HORIZONTAL_PADDING - count * (MINI_BAR_WIDTH + MINI_BAR_SPACING));
+
+// Recharts' default value axis ("auto" domain, 5 ticks) rounds its range with
+// recharts-scale's getNiceTickValues: steps of 5% of the value's order of
+// magnitude (10% below 10), widened until 5 ticks cover the data. It can end
+// above d3's `.nice()` (max 50 → 0‥60 where d3 gives 0‥50), and on the
+// axis-free minis that shows directly as mark height — so they use this.
+const clean = (n: number) => Number(n.toPrecision(12));
+const digitCount = (v: number) => (v === 0 ? 1 : Math.floor(Math.log10(Math.abs(v))) + 1);
+
+const niceStep = (roughStep: number, correction: number): number => {
+ if (roughStep <= 0) return 0;
+ const digits = digitCount(roughStep);
+ const unit = 10 ** digits;
+ const ratioScale = digits !== 1 ? 0.05 : 0.1;
+ return clean((Math.ceil(clean(roughStep / unit / ratioScale)) + correction) * ratioScale * unit);
+};
+
+/** The [min, max] range Recharts' default 5-tick value axis spans for this data range. */
+export const rechartsNiceDomain = (
+ min: number,
+ max: number,
+ tickCount = 5,
+ correction = 0,
+): [number, number] => {
+ if (min === max) {
+ // recharts-scale's single-value case: ticks around the value, step 1
+ // (all-zero data spans 0‥4).
+ const middle = min === 0 ? Math.floor((tickCount - 1) / 2) : Math.floor(min);
+ const middleIndex = Math.floor((tickCount - 1) / 2);
+ return [middle - middleIndex, middle + (tickCount - 1 - middleIndex)];
+ }
+ const step = niceStep((max - min) / (tickCount - 1), correction);
+ if (step === 0) return [min, max];
+ const middle = min <= 0 && max >= 0 ? 0 : clean((min + max) / 2 - (((min + max) / 2) % step));
+ let below = Math.ceil(clean((middle - min) / step));
+ let up = Math.ceil(clean((max - middle) / step));
+ const count = below + up + 1;
+ if (count > tickCount) return rechartsNiceDomain(min, max, tickCount, correction + 1);
+ if (count < tickCount) {
+ if (max > 0) up += tickCount - count;
+ else below += tickCount - count;
+ }
+ return [clean(middle - below * step), clean(middle + up * step)];
+};
+
+/** Value domain, always anchored through zero. */
+export const miniValueDomain = (values: readonly number[]): [number, number] => {
+ let min = 0;
+ let max = 0;
+ for (const v of values) {
+ if (!Number.isFinite(v)) continue;
+ if (v < min) min = v;
+ if (v > max) max = v;
+ }
+ return [min, max];
+};
+
+/**
+ * Curves by `variant`, as Recharts draws its mini charts: "natural" is
+ * monotone, "step" steps at the midpoint between points.
+ */
+export const miniCurves = {
+ linear: curveLinear,
+ natural: curveMonotoneX,
+ step: curveStep,
+} as const;
+
+/** Room above the highest point on the area/line minis (Recharts' `margin.top`). */
+export const MINI_TOP_MARGIN = 10;
+
+/**
+ * Area/line geometry: the most recent points that fit, spread edge to edge,
+ * over a zero-anchored value range rounded as Recharts does, top margin 10px.
+ */
+export function miniLineGeometry(data: readonly MiniChartDatum[], width: number, height: number) {
+ const points = toMiniChartPoints(recentPointsThatFit(data, width));
+ const xScale = scalePoint<number>()
+ .domain(points.map((_, i) => i))
+ .range([0, width]);
+ const yScale = scaleLinear()
+ .domain(rechartsNiceDomain(...miniValueDomain(points.map((p) => p.value))))
+ .range([height, MINI_TOP_MARGIN]);
+ return {
+ points,
+ x: (index: number) => xScale(index) ?? 0,
+ y: (value: number) => yScale(value),
+ };
+}
+
+/** Margin on every side of the bar mini (Recharts' default chart margin). */
+export const MINI_BAR_MARGIN = 5;
+
+export interface MiniBar extends MiniChartPoint {
+ x: number;
+ y: number;
+ height: number;
+ negative: boolean;
+}
+
+/**
+ * Bar geometry: the most recent bars that fit, right-aligned, each 8px wide
+ * and centered in its slot (offset truncated, as Recharts does), over a
+ * zero-anchored value range rounded as Recharts does.
+ */
+export function miniBarGeometry(
+ data: readonly MiniChartDatum[],
+ width: number,
+ height: number,
+): MiniBar[] {
+ const bars = toMiniChartPoints(recentBarsThatFit(data, width));
+ if (bars.length === 0) return [];
+ const start = MINI_BAR_MARGIN + miniBarsLeftPadding(bars.length, width);
+ const slot = (width - MINI_BAR_MARGIN - start) / bars.length;
+ const offset = Math.trunc((slot - MINI_BAR_WIDTH) / 2);
+ const yScale = scaleLinear()
+ .domain(rechartsNiceDomain(...miniValueDomain(bars.map((b) => b.value))))
+ .range([height - MINI_BAR_MARGIN, MINI_BAR_MARGIN]);
+ const zero = yScale(0);
+ return bars.map((bar, i) => {
+ const top = yScale(bar.value);
+ return {
+ ...bar,
+ x: start + i * slot + offset,
+ y: Math.min(top, zero),
+ height: Math.abs(zero - top),
+ negative: bar.value < 0,
+ };
+ });
+}
diff --git a/packages/react-ui/src/components/D3Charts/stories/rechartsStoryAdapters.tsx b/packages/react-ui/src/components/D3Charts/stories/rechartsStoryAdapters.tsx
new file mode 100644
index 000000000..64212b75e
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/stories/rechartsStoryAdapters.tsx
@@ -0,0 +1,110 @@
+// The Recharts chart names, typed with the Recharts props, each rendering the
+// D3Charts chart that replaces it. The stories under D3Charts/*/stories are
+// copies of the Recharts chart stories that import these instead of the
+// Recharts charts — same args, same renders — so every Recharts story renders
+// the D3 charts with its props unchanged. Props a D3 chart doesn't take are
+// passed through and ignored.
+import type {
+ AreaChartCondensedProps,
+ AreaChartData,
+ AreaChartProps,
+ BarChartCondensedProps,
+ BarChartData,
+ BarChartProps,
+ HorizontalBarChartData,
+ HorizontalBarChartProps,
+ LineChartCondensedProps,
+ LineChartData,
+ LineChartProps,
+ MiniAreaChartProps,
+ MiniBarChartProps,
+ MiniLineChartProps,
+ PieChartData,
+ PieChartProps,
+ RadarChartData,
+ RadarChartProps,
+ RadialChartData,
+ RadialChartProps,
+ ScatterChartProps,
+ SingleStackedBarData,
+ SingleStackedBarProps,
+} from "../../Charts";
+import { AreaChart as D3AreaChart } from "../AreaChart";
+import { BarChart as D3BarChart } from "../BarChart";
+import { LineChart as D3LineChart } from "../LineChart";
+import { MiniAreaChart as D3MiniAreaChart } from "../MiniAreaChart";
+import { MiniBarChart as D3MiniBarChart } from "../MiniBarChart";
+import { MiniLineChart as D3MiniLineChart } from "../MiniLineChart";
+import { PieChart as D3PieChart } from "../PieChart";
+import { RadarChart as D3RadarChart } from "../RadarChart";
+import { RadialChart as D3RadialChart } from "../RadialChart";
+import { ScatterChart as D3ScatterChart } from "../ScatterChart";
+import { SegmentedBar } from "../SegmentedBar";
+
+export type {
+ AreaChartCondensedProps,
+ AreaChartProps,
+ BarChartCondensedProps,
+ BarChartProps,
+ HorizontalBarChartProps,
+ LineChartCondensedProps,
+ LineChartProps,
+ MiniBarChartProps,
+ PieChartProps,
+ RadarChartProps,
+ RadialChartProps,
+ ScatterChartProps,
+ SingleStackedBarProps,
+};
+
+export const AreaChart = <T extends AreaChartData>(props: AreaChartProps<T>) => (
+ <D3AreaChart {...(props as any)} />
+);
+
+export const AreaChartCondensed = <T extends AreaChartData>(props: AreaChartCondensedProps<T>) => (
+ <D3AreaChart {...(props as any)} condensed />
+);
+
+export const BarChart = <T extends BarChartData>(props: BarChartProps<T>) => (
+ <D3BarChart {...(props as any)} />
+);
+
+export const BarChartCondensed = <T extends BarChartData>(props: BarChartCondensedProps<T>) => (
+ <D3BarChart {...(props as any)} condensed />
+);
+
+export const HorizontalBarChart = <T extends HorizontalBarChartData>(
+ props: HorizontalBarChartProps<T>,
+) => <D3BarChart {...(props as any)} orientation="horizontal" />;
+
+export const LineChart = <T extends LineChartData>(props: LineChartProps<T>) => (
+ <D3LineChart {...(props as any)} />
+);
+
+export const LineChartCondensed = <T extends LineChartData>(props: LineChartCondensedProps<T>) => (
+ <D3LineChart {...(props as any)} condensed />
+);
+
+export const PieChart = <T extends PieChartData>(props: PieChartProps<T>) => (
+ <D3PieChart {...(props as any)} />
+);
+
+export const RadarChart = <T extends RadarChartData>(props: RadarChartProps<T>) => (
+ <D3RadarChart {...(props as any)} />
+);
+
+export const RadialChart = <T extends RadialChartData>(props: RadialChartProps<T>) => (
+ <D3RadialChart {...(props as any)} />
+);
+
+export const ScatterChart = (props: ScatterChartProps) => <D3ScatterChart {...(props as any)} />;
+
+export const SingleStackedBar = <T extends SingleStackedBarData>(
+ props: SingleStackedBarProps<T>,
+) => <SegmentedBar {...(props as any)} />;
+
+export const MiniAreaChart = (props: MiniAreaChartProps) => <D3MiniAreaChart {...(props as any)} />;
+
+export const MiniBarChart = (props: MiniBarChartProps) => <D3MiniBarChart {...(props as any)} />;
+
+export const MiniLineChart = (props: MiniLineChartProps) => <D3MiniLineChart {...(props as any)} />;
diff --git a/packages/react-ui/src/components/D3Charts/types/common.ts b/packages/react-ui/src/components/D3Charts/types/common.ts
new file mode 100644
index 000000000..f441914d9
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/types/common.ts
@@ -0,0 +1,88 @@
+export interface LegendItem {
+ key: string;
+ label: string;
+ color: string;
+ icon?: React.ComponentType;
+ percentage?: number;
+}
+
+export type XAxisTickVariant = "singleLine" | "multiLine" | "angled";
+
+export type ChartData = Array<Record<string, string | number>>;
+
+export interface BaseChartProps<T extends ChartData> {
+ data: T;
+ categoryKey: keyof T[number];
+ customPalette?: string[];
+ /**
+ * How the x-axis category labels are drawn. The label band never takes more
+ * than half the chart's height; labels that don't fit are truncated with an
+ * ellipsis and show their full text on hover.
+ * - `"singleLine"`: one horizontal line. Default when `condensed`.
+ * - `"multiLine"`: wraps onto up to three lines. Default otherwise.
+ * - `"angled"`: rotates labels 45° when they don't fit horizontally.
+ * `condensed` only; the scrolling layout draws it as `"singleLine"`.
+ */
+ tickVariant?: XAxisTickVariant;
+ grid?: boolean;
+ /**
+ * Show the legend. NOTE: `xAxisLabel`/`yAxisLabel` render inside the legend
+ * strip, so `legend={false}` hides them too.
+ */
+ legend?: boolean;
+ icons?: Partial<Record<keyof T[number], React.ComponentType>>;
+ /**
+ * Play the entrance animation. Gates the entrance ONLY — any hover or
+ * data-update motion is independent of this flag, and printing always
+ * disables it.
+ * Default false (streaming-safe: marks mounted while data streams in don't
+ * replay staggered entrances).
+ */
+ isAnimationActive?: boolean;
+ showYAxis?: boolean;
+ /** Axis caption — rendered in the legend strip (hidden when `legend` is false). */
+ xAxisLabel?: React.ReactNode;
+ yAxisLabel?: React.ReactNode;
+ className?: string;
+ height?: number | string;
+ width?: number | string;
+ /** When true, legend height is subtracted from container height so chart + legend
+ * fit within specified dimensions. Defaults to true when `height` is set, false otherwise. */
+ fitLegendInHeight?: boolean;
+ /** When true, all data fits within the container width (no scrolling). Default false. */
+ condensed?: boolean;
+ /** Controls spacing between data points in scrollable mode. Default "default". */
+ density?: "compact" | "default" | "spacious";
+ /**
+ * Hint for the number of y-axis ticks (and the matching horizontal
+ * gridlines — they share the y-scale, so this drives both in lockstep).
+ * d3 treats it as a target and picks nice round values near it, so the
+ * rendered count can differ from the number given; the value is floored at 2.
+ * Default: derived from chart height (~1 tick per 40px).
+ *
+ * Vertical orientation only. The horizontal BarChart's value axis is the
+ * X axis and ignores this prop for now.
+ */
+ yTickCount?: number;
+}
+
+/**
+ * Toggles for the hover overlay on line/area charts. Each element toggles
+ * independently: `activeDots` defaults `true`, while `crosshair` and `highlight`
+ * default `false` (opt-in — the gliding line and the traveling curve highlight
+ * are off unless asked for).
+ * Plain booleans for now — they can widen to a config object
+ * (e.g. `boolean | {...}`) later without breaking.
+ */
+export interface HoverOverlayProps {
+ /** The vertical crosshair line that tracks the hovered x. Default `false` for
+ * Line/Area — pass `crosshair` to turn it on. */
+ crosshair?: boolean;
+ /** The highlight segment — a brighter slice of the curve that travels along it
+ * around the hovered point. Default `false` for Line/Area — pass `highlight`
+ * to turn it on. */
+ highlight?: boolean;
+ /** The dots that ride the curve at the hovered point, one per series. Distinct from
+ * the static series dots (`showDots`/`dotRadius`). Default `true`. */
+ activeDots?: boolean;
+}
diff --git a/packages/react-ui/src/components/D3Charts/types/index.ts b/packages/react-ui/src/components/D3Charts/types/index.ts
new file mode 100644
index 000000000..6b5716089
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/types/index.ts
@@ -0,0 +1 @@
+export * from "./common";
diff --git a/packages/react-ui/src/components/D3Charts/utils/buildContainerStyle.ts b/packages/react-ui/src/components/D3Charts/utils/buildContainerStyle.ts
new file mode 100644
index 000000000..2d0b1c15b
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/utils/buildContainerStyle.ts
@@ -0,0 +1,10 @@
+export function buildContainerStyle(
+ chartStyle: Record<string, string | undefined>,
+ fixedWidth?: number | string,
+ height?: number | string,
+): Record<string, string | number | undefined> {
+ const s: Record<string, string | number | undefined> = { ...chartStyle };
+ if (typeof fixedWidth === "string") s["width"] = fixedWidth;
+ if (typeof height === "string") s["height"] = height;
+ return s;
+}
diff --git a/packages/react-ui/src/components/D3Charts/utils/colorLuminance.test.ts b/packages/react-ui/src/components/D3Charts/utils/colorLuminance.test.ts
new file mode 100644
index 000000000..4ab0f7d4b
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/utils/colorLuminance.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from "vitest";
+import { LUMINANCE_TEXT_PIVOT, relativeLuminanceFromRgb } from "./colorLuminance";
+
+describe("relativeLuminanceFromRgb (WCAG)", () => {
+ it("anchors: black is 0, white is 1", () => {
+ expect(relativeLuminanceFromRgb(0, 0, 0)).toBe(0);
+ expect(relativeLuminanceFromRgb(255, 255, 255)).toBeCloseTo(1, 10);
+ });
+
+ it("matches the published value for sRGB primaries", () => {
+ expect(relativeLuminanceFromRgb(255, 0, 0)).toBeCloseTo(0.2126, 4);
+ expect(relativeLuminanceFromRgb(0, 255, 0)).toBeCloseTo(0.7152, 4);
+ expect(relativeLuminanceFromRgb(0, 0, 255)).toBeCloseTo(0.0722, 4);
+ });
+
+ it("the text pivot splits the ramp the way contrast math says", () => {
+ // Dark navy (ocean ramp low end) → below pivot → light text wins.
+ expect(relativeLuminanceFromRgb(0x0d, 0x47, 0xa1)).toBeLessThan(LUMINANCE_TEXT_PIVOT);
+ // Pale blue (ocean ramp high end) → above pivot → dark text wins.
+ expect(relativeLuminanceFromRgb(0xef, 0xf8, 0xff)).toBeGreaterThan(LUMINANCE_TEXT_PIVOT);
+ });
+});
diff --git a/packages/react-ui/src/components/D3Charts/utils/colorLuminance.ts b/packages/react-ui/src/components/D3Charts/utils/colorLuminance.ts
new file mode 100644
index 000000000..96f584cf4
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/utils/colorLuminance.ts
@@ -0,0 +1,67 @@
+// Text-on-color contrast support for in-cell labels: resolve any CSS color
+// string to a WCAG relative luminance, then pick dark or light text against
+// it. Client-only at the normalization layer (callers gate on hydration; the
+// pure math is exported separately for tests).
+
+/** WCAG 2.x relative luminance from 8-bit sRGB channels. Pure. */
+export const relativeLuminanceFromRgb = (r: number, g: number, b: number): number => {
+ const linear = (v: number) => {
+ const s = v / 255;
+ return s <= 0.04045 ? s / 12.92 : Math.pow((s + 0.055) / 1.055, 2.4);
+ };
+ return 0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b);
+};
+
+/**
+ * The equal-contrast pivot: above this background luminance, black text has
+ * the higher WCAG contrast ratio; below it, white text does. (Solve
+ * (L+0.05)/(0+0.05) = (1+0.05)/(L+0.05) for L.)
+ */
+export const LUMINANCE_TEXT_PIVOT = 0.179;
+
+let normalizerContext: CanvasRenderingContext2D | null | undefined;
+const luminanceCache = new Map<string, number | null>();
+// Ramps are ~11 colors, so the cache stays tiny in practice — the cap only
+// guards a pathological consumer cycling unique customPalettes for hours.
+const LUMINANCE_CACHE_LIMIT = 512;
+
+/**
+ * Relative luminance of any CSS color string, or null when it can't be
+ * resolved (SSR, canvas unavailable). Uses canvas fillStyle normalization:
+ * assigning any valid CSS color reads back as '#rrggbb' (or 'rgba(…)' with
+ * alpha) per the canvas spec — named colors, hsl(), rgb(), hex shorthand all
+ * covered with zero parsing code. Invalid colors leave the priming black in
+ * place and resolve to luminance 0 (light text), a deterministic fallback.
+ */
+export const getColorLuminance = (color: string): number | null => {
+ const cached = luminanceCache.get(color);
+ if (cached !== undefined) return cached;
+
+ if (normalizerContext === undefined) {
+ normalizerContext =
+ typeof document === "undefined" ? null : document.createElement("canvas").getContext("2d");
+ }
+ if (!normalizerContext) return null;
+
+ normalizerContext.fillStyle = "#000000";
+ normalizerContext.fillStyle = color;
+ const normalized = String(normalizerContext.fillStyle);
+
+ let luminance: number | null = null;
+ if (normalized.startsWith("#") && normalized.length === 7) {
+ luminance = relativeLuminanceFromRgb(
+ parseInt(normalized.slice(1, 3), 16),
+ parseInt(normalized.slice(3, 5), 16),
+ parseInt(normalized.slice(5, 7), 16),
+ );
+ } else {
+ const match = normalized.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
+ if (match) {
+ luminance = relativeLuminanceFromRgb(Number(match[1]), Number(match[2]), Number(match[3]));
+ }
+ }
+
+ if (luminanceCache.size >= LUMINANCE_CACHE_LIMIT) luminanceCache.clear();
+ luminanceCache.set(color, luminance);
+ return luminance;
+};
diff --git a/packages/react-ui/src/components/D3Charts/utils/constants.test.ts b/packages/react-ui/src/components/D3Charts/utils/constants.test.ts
new file mode 100644
index 000000000..a78eef7cd
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/utils/constants.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, it } from "vitest";
+import { MIN_TICK_SPACING, resolveTickCount } from "./constants";
+
+describe("resolveTickCount", () => {
+ it("derives the count from chart height at ~1 per MIN_TICK_SPACING when no override", () => {
+ // Byte-identical to the old inline formula
+ // `Math.max(2, Math.floor(chartHeight / MIN_TICK_SPACING))`.
+ expect(resolveTickCount(200)).toBe(Math.floor(200 / MIN_TICK_SPACING));
+ expect(resolveTickCount(296)).toBe(Math.floor(296 / MIN_TICK_SPACING));
+ expect(resolveTickCount(400)).toBe(10); // 400 / 40
+ });
+
+ it("floors the height-derived count at 2 for short charts", () => {
+ expect(resolveTickCount(0)).toBe(2);
+ expect(resolveTickCount(40)).toBe(2); // 40/40 = 1 → floored to 2
+ expect(resolveTickCount(79)).toBe(2); // 79/40 = 1.97 → floor 1 → 2
+ expect(resolveTickCount(80)).toBe(2); // 80/40 = 2
+ });
+
+ it("lets an explicit override win over the height-derived value", () => {
+ // Same tall chart, different override → override drives the count.
+ expect(resolveTickCount(400, 3)).toBe(3);
+ expect(resolveTickCount(400, 10)).toBe(10);
+ expect(resolveTickCount(100, 8)).toBe(8);
+ });
+
+ it("floors an override at 2", () => {
+ expect(resolveTickCount(400, 0)).toBe(2);
+ expect(resolveTickCount(400, 1)).toBe(2);
+ expect(resolveTickCount(400, -5)).toBe(2);
+ });
+
+ it("floors a fractional override toward zero", () => {
+ expect(resolveTickCount(400, 5.9)).toBe(5);
+ });
+
+ it("ignores a non-finite override and falls back to the height-derived count", () => {
+ expect(resolveTickCount(400, NaN)).toBe(10);
+ expect(resolveTickCount(400, Infinity)).toBe(10);
+ });
+});
diff --git a/packages/react-ui/src/components/D3Charts/utils/constants.ts b/packages/react-ui/src/components/D3Charts/utils/constants.ts
new file mode 100644
index 000000000..036b909e8
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/utils/constants.ts
@@ -0,0 +1,40 @@
+/**
+ * Brand prefix for every chart class name and `@keyframes` name the library
+ * emits (`openui-d3-bar-chart-container`, `openui-d3-chart-tooltip`,
+ * `openui-d3-fade-appear`, …). Distinct from the Recharts `Charts/` folder's
+ * `openui-` classes so both stylesheets can ship side by side. Always compose
+ * class names from this constant; never hardcode the brand token in TSX/TS.
+ * SCSS can't read TS constants: `_prefix.scss` mirrors this as `$prefix`
+ * — change BOTH or the stylesheets stop matching the DOM.
+ * NOTE: the `data-openui-chart` print/PPTX attribute is a backend contract and
+ * deliberately NOT derived from this prefix (see `useExportChartData`).
+ */
+export const CHART_CLASS_PREFIX = "openui-d3";
+
+export const CHART_MARGIN_TOP = 10;
+// Minimum vertical px between y-ticks. Grid and YAxis must share this value:
+// both derive tickCount from it, and gridlines only align with tick labels
+// because the two computations are identical.
+export const MIN_TICK_SPACING = 40;
+export const DEFAULT_CHART_HEIGHT = 296;
+export const SINGLE_LINE_BREAKPOINT = 300;
+
+/**
+ * Resolve the d3 tick-count hint for the y-axis (labels) AND the horizontal
+ * gridlines — they share the y-scale, so both MUST call this with the same
+ * arguments to stay in lockstep.
+ *
+ * - When `override` is a finite number the caller-supplied hint wins, floored
+ * at 2 (a chart with fewer than two ticks reads as broken).
+ * - Otherwise the count is derived from the chart height at ~1 tick per
+ * `MIN_TICK_SPACING` (40) px, floored at 2 — the historical default. With
+ * `override` absent this is byte-identical to the old inline formula
+ * `Math.max(2, Math.floor(chartHeight / MIN_TICK_SPACING))`.
+ *
+ * The result is only a HINT: d3's `scale.ticks(count)` treats it as a target
+ * and returns nice round values near it, so the rendered tick count can differ.
+ */
+export const resolveTickCount = (chartHeight: number, override?: number): number =>
+ override != null && Number.isFinite(override)
+ ? Math.max(2, Math.floor(override))
+ : Math.max(2, Math.floor(chartHeight / MIN_TICK_SPACING));
diff --git a/packages/react-ui/src/components/D3Charts/utils/dataUtils.ts b/packages/react-ui/src/components/D3Charts/utils/dataUtils.ts
new file mode 100644
index 000000000..2c294b326
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/utils/dataUtils.ts
@@ -0,0 +1,50 @@
+import { LegendItem } from "../types";
+
+export interface ChartConfig {
+ [key: string]: {
+ label: string;
+ icon?: React.ComponentType;
+ color?: string;
+ transformed?: string;
+ };
+}
+
+export const getDataKeys = (
+ data: Array<Record<string, string | number>>,
+ categoryKey: string,
+): string[] => {
+ return Object.keys(data[0] || {}).filter((key) => key !== categoryKey);
+};
+
+export const get2dChartConfig = (
+ dataKeys: string[],
+ colors: string[],
+ transformedKeys: Record<string, string>,
+ icons?: Partial<Record<string | number, React.ComponentType>>,
+): ChartConfig => {
+ return dataKeys.reduce(
+ (config, key, index) => ({
+ ...config,
+ [key]: {
+ label: key,
+ icon: icons?.[key],
+ color: colors[index],
+ transformed: transformedKeys[key],
+ },
+ }),
+ {},
+ );
+};
+
+export const getLegendItems = (
+ dataKeys: string[],
+ colors: string[],
+ icons?: Partial<Record<string | number, React.ComponentType>>,
+): LegendItem[] => {
+ return dataKeys.map((key, index) => ({
+ key,
+ label: key,
+ color: colors[index] ?? "#000000",
+ icon: icons?.[key] as React.ComponentType | undefined,
+ }));
+};
diff --git a/packages/react-ui/src/components/D3Charts/utils/entranceUtils.test.ts b/packages/react-ui/src/components/D3Charts/utils/entranceUtils.test.ts
new file mode 100644
index 000000000..af2d3b766
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/utils/entranceUtils.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it } from "vitest";
+import { entranceProps } from "./entranceUtils";
+
+describe("entranceProps (painter entrance stagger)", () => {
+ it("applies the modifier class and formats the delay when animating", () => {
+ expect(entranceProps(true, "c1-x--animated", 120)).toEqual({
+ className: "c1-x--animated",
+ animationDelay: "120ms",
+ });
+ });
+
+ it("drops the class and the delay when not animating", () => {
+ expect(entranceProps(false, "c1-x--animated", 120)).toEqual({
+ className: "",
+ animationDelay: undefined,
+ });
+ });
+
+ it("treats undefined animate as off (BarSeries passes an optional flag)", () => {
+ expect(entranceProps(undefined, "c1-x--animated", 120)).toEqual({
+ className: "",
+ animationDelay: undefined,
+ });
+ });
+
+ it("formats a zero delay as 0ms, not undefined (the first element animates)", () => {
+ expect(entranceProps(true, "c1-x--animated", 0)).toEqual({
+ className: "c1-x--animated",
+ animationDelay: "0ms",
+ });
+ });
+
+ it("passes the caller-computed delay through verbatim (basis/cap stay in the caller)", () => {
+ // e.g. heatmap's capped Math.min(col * 15, 300) arrives here already clamped
+ expect(entranceProps(true, "c", 300).animationDelay).toBe("300ms");
+ });
+});
diff --git a/packages/react-ui/src/components/D3Charts/utils/entranceUtils.ts b/packages/react-ui/src/components/D3Charts/utils/entranceUtils.ts
new file mode 100644
index 000000000..5a9e18de2
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/utils/entranceUtils.ts
@@ -0,0 +1,25 @@
+/**
+ * Per-element entrance stagger, shared by every painter's element map.
+ *
+ * PURE, not a hook — 6 of the 7 painters call this inside `data.map(...)`,
+ * where a hook would violate rules-of-hooks. The caller passes a pre-computed
+ * `delayMs` so each chart keeps its own intentional stagger basis (scatter
+ * per-point, radar per-series, heatmap per-column, …) and cap (heatmap clamps
+ * the delay; the others don't).
+ *
+ * Owns only the half that's identical everywhere: gate the `--animated`
+ * modifier and format the delay on `animate`. The base class and any other
+ * modifiers (`--negative`, `--empty`, funnel's `-stage`) stay in the caller's
+ * className expression; the returned `animationDelay` is the raw value (not a
+ * wrapped `style`) so callers merge it into their own style object.
+ */
+const entranceProps = (
+ animate: boolean | undefined,
+ animatedClass: string,
+ delayMs: number,
+): { className: string; animationDelay: string | undefined } => ({
+ className: animate ? animatedClass : "",
+ animationDelay: animate ? `${delayMs}ms` : undefined,
+});
+
+export { entranceProps };
diff --git a/packages/react-ui/src/components/D3Charts/utils/heatmapUtils.test.ts b/packages/react-ui/src/components/D3Charts/utils/heatmapUtils.test.ts
new file mode 100644
index 000000000..67b0b7399
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/utils/heatmapUtils.test.ts
@@ -0,0 +1,92 @@
+import { scaleQuantize } from "d3-scale";
+import { describe, expect, it } from "vitest";
+import { buildColumnKeys, computeHeatmapColorDomain, computeLabelInterval } from "./heatmapUtils";
+
+describe("computeHeatmapColorDomain", () => {
+ it("sequential: passes the extent through", () => {
+ expect(computeHeatmapColorDomain(3, 91, "sequential")).toEqual([3, 91]);
+ expect(computeHeatmapColorDomain(-50, 100, "sequential")).toEqual([-50, 100]);
+ });
+
+ it("sequential: widens a collapsed extent so quantize can bucket it", () => {
+ expect(computeHeatmapColorDomain(7, 7, "sequential")).toEqual([7, 8]);
+ expect(computeHeatmapColorDomain(0, 0, "sequential")).toEqual([0, 1]);
+ });
+
+ it("diverging: symmetric about zero regardless of asymmetry", () => {
+ expect(computeHeatmapColorDomain(-50, 100, "diverging")).toEqual([-100, 100]);
+ expect(computeHeatmapColorDomain(-80, 20, "diverging")).toEqual([-80, 80]);
+ // one-signed data still pivots at zero — that is the contract
+ expect(computeHeatmapColorDomain(10, 90, "diverging")).toEqual([-90, 90]);
+ });
+
+ it("diverging: all-zero data widens to ±1", () => {
+ expect(computeHeatmapColorDomain(0, 0, "diverging")).toEqual([-1, 1]);
+ });
+
+ it("diverging: negative-only data still pivots at zero", () => {
+ expect(computeHeatmapColorDomain(-90, -10, "diverging")).toEqual([-90, 90]);
+ });
+
+ it("diverging: zero maps to the middle bucket of an odd ramp", () => {
+ const [lo, hi] = computeHeatmapColorDomain(-50, 100, "diverging");
+ const ramp = ["a", "b", "c", "d", "e"]; // odd length: one middle bucket
+ const scale = scaleQuantize<string>().domain([lo, hi]).range(ramp);
+ expect(scale(0)).toBe("c");
+ // and the middle bucket straddles zero exactly
+ const [bucketLo, bucketHi] = scale.invertExtent("c");
+ expect(bucketLo).toBeLessThan(0);
+ expect(bucketHi).toBeGreaterThan(0);
+ expect(bucketLo).toBeCloseTo(-bucketHi);
+ });
+});
+
+describe("computeLabelInterval", () => {
+ it("wide bands show every label", () => {
+ expect(computeLabelInterval(80, 28)).toBe(1);
+ expect(computeLabelInterval(28, 28)).toBe(1);
+ });
+
+ it("thin bands skip labels so each shown one gets the minimum width", () => {
+ expect(computeLabelInterval(14, 28)).toBe(2);
+ expect(computeLabelInterval(7, 28)).toBe(4);
+ expect(computeLabelInterval(1, 28)).toBe(28);
+ });
+
+ it('degenerate bandwidth degrades to "every label"', () => {
+ expect(computeLabelInterval(0, 28)).toBe(1);
+ expect(computeLabelInterval(-5, 28)).toBe(1);
+ expect(computeLabelInterval(Number.NaN, 28)).toBe(1);
+ });
+});
+
+describe("buildColumnKeys", () => {
+ it("unique labels pass through untouched", () => {
+ expect(buildColumnKeys(["Jan", "Feb", "Mar"])).toEqual(["Jan", "Feb", "Mar"]);
+ });
+
+ it("duplicates get occurrence suffixes; first occurrence stays bare", () => {
+ const keys = buildColumnKeys(["Jan", "Feb", "Jan", "Jan"]);
+ expect(keys[0]).toBe("Jan");
+ expect(keys[1]).toBe("Feb");
+ expect(new Set(keys).size).toBe(4);
+ });
+
+ it("suffixed keys cannot collide with real labels", () => {
+ // The trap: a " 1"-style suffix would make ['Jan','Jan','Jan 1'] collide.
+ const keys = buildColumnKeys(["Jan", "Jan", "Jan 1"]);
+ expect(new Set(keys).size).toBe(3);
+ });
+
+ it("streaming append never re-keys existing columns", () => {
+ const before = buildColumnKeys(["Jan", "Feb", "Jan"]);
+ const after = buildColumnKeys(["Jan", "Feb", "Jan", "Mar"]);
+ expect(after.slice(0, 3)).toEqual(before);
+ });
+
+ it("numeric-looking labels (already stringified upstream) dedupe too", () => {
+ const keys = buildColumnKeys(["1", "2", "1", "10"]);
+ expect(new Set(keys).size).toBe(4);
+ expect(keys[0]).toBe("1");
+ });
+});
diff --git a/packages/react-ui/src/components/D3Charts/utils/heatmapUtils.ts b/packages/react-ui/src/components/D3Charts/utils/heatmapUtils.ts
new file mode 100644
index 000000000..567df37a5
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/utils/heatmapUtils.ts
@@ -0,0 +1,57 @@
+// Pure helpers for the heatmap's color scale and x-axis layout. Kept out of
+// the orchestrator so the quantize-domain, label-thinning, and key-dedup
+// rules are unit-testable.
+
+export type HeatmapRampMode = "sequential" | "diverging";
+
+/**
+ * The quantize domain for the cell color scale.
+ *
+ * - `sequential`: the visible value extent, widened when it collapses —
+ * scaleQuantize cannot bucket a zero-width domain, so all-equal data
+ * renders every cell as the ramp's first color.
+ * - `diverging`: symmetric about zero (±max|value|), so the ramp's middle
+ * bucket always contains zero no matter how asymmetric the data is — the
+ * whole point of a diverging ramp. An all-zero extent widens to ±1.
+ */
+export const computeHeatmapColorDomain = (
+ minValue: number,
+ maxValue: number,
+ rampMode: HeatmapRampMode,
+): [number, number] => {
+ if (rampMode === "diverging") {
+ const magnitude = Math.max(Math.abs(minValue), Math.abs(maxValue));
+ return magnitude > 0 ? [-magnitude, magnitude] : [-1, 1];
+ }
+ return maxValue > minValue ? [minValue, maxValue] : [minValue, minValue + 1];
+};
+
+/**
+ * Show every n-th x label so each shown label gets at least `minLabelPx` of
+ * band — 100+ streamed columns must not render an ellipsis (plus a tooltip
+ * wrapper) per column. 1 = every label, the XAxis default.
+ */
+export const computeLabelInterval = (bandwidth: number, minLabelPx: number): number => {
+ if (!Number.isFinite(bandwidth) || bandwidth <= 0) return 1;
+ return Math.max(1, Math.ceil(minLabelPx / bandwidth));
+};
+
+/**
+ * Stable React keys for columns whose labels may repeat — LLMs re-emit
+ * categories routinely, and duplicate keys make React drop/overdraw siblings.
+ * First occurrence keeps the bare label (streaming appends never re-key
+ * existing columns); repeats get an occurrence suffix. Same-label columns
+ * still share one x band (d3 ordinal domains intern duplicates), so the last
+ * one drawn wins visually — a data pathology rendered deterministically
+ * rather than corrupting reconciliation.
+ */
+export const buildColumnKeys = (labels: string[]): string[] => {
+ const seen = new Map<string, number>();
+ return labels.map((label) => {
+ const occurrence = seen.get(label) ?? 0;
+ seen.set(label, occurrence + 1);
+ // NUL separator: a plain-text suffix could collide with a REAL label
+ // ("Jan", "Jan", "Jan 1" would key "Jan 1" twice); no real label has \0.
+ return occurrence === 0 ? label : `${label}\u0000${occurrence}`;
+ });
+};
diff --git a/packages/react-ui/src/components/D3Charts/utils/labelWrap.test.ts b/packages/react-ui/src/components/D3Charts/utils/labelWrap.test.ts
new file mode 100644
index 000000000..212a52106
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/utils/labelWrap.test.ts
@@ -0,0 +1,58 @@
+import { describe, expect, it } from "vitest";
+import { MAX_LABEL_LINES, parseLineHeight, truncateToWidth, wrapLabelLines } from "./labelWrap";
+
+// Deterministic stand-in for canvas text metrics: width == 10px per character.
+const ctx = {
+ measureText: (s: string) => ({ width: s.length * 10 }),
+} as unknown as CanvasRenderingContext2D;
+
+describe("parseLineHeight", () => {
+ it("handles a unitless multiplier (12px/1.25 → 15)", () => {
+ expect(parseLineHeight("400 12px/1.25 Inter")).toBe(15);
+ });
+ it("handles a px line-height (12px/16px → 16)", () => {
+ expect(parseLineHeight("400 12px/16px Inter")).toBe(16);
+ });
+ it("falls back to 1.2× when no line-height is given (14px → 17)", () => {
+ expect(parseLineHeight("400 14px Inter")).toBe(17);
+ });
+});
+
+describe("truncateToWidth (single-line ellipsis)", () => {
+ it("returns the text unchanged when it fits", () => {
+ expect(truncateToWidth(ctx, "Jan", 100)).toBe("Jan");
+ });
+ it("trims and appends an ellipsis when it overflows", () => {
+ const out = truncateToWidth(ctx, "San Francisco", 100); // 13 chars > 10
+ expect(out.endsWith("…")).toBe(true);
+ expect(out.length * 10).toBeLessThanOrEqual(100);
+ });
+ it("trims by code points, never splitting surrogate pairs (emoji)", () => {
+ // '🎉🎉🎉' is 6 UTF-16 units (60px). Budget 45px forces a mid-pair cut
+ // under unit-based slicing: the old code returned '🎉\uD83C…' (lone
+ // surrogate). Code-point slicing must land on '🎉…' instead.
+ const out = truncateToWidth(ctx, "🎉🎉🎉", 45);
+ expect(out).toBe("🎉…");
+ // No unpaired high surrogate anywhere in the output.
+ expect(out).not.toMatch(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])/);
+ });
+});
+
+describe("wrapLabelLines (multi-line tspans)", () => {
+ it("keeps a short single word on one line", () => {
+ expect(wrapLabelLines(ctx, "Jan", 100)).toEqual(["Jan"]);
+ });
+ it("wraps a multi-word label across lines", () => {
+ expect(wrapLabelLines(ctx, "San Francisco", 100)).toEqual(["San", "Francisco"]);
+ });
+ it("caps at MAX_LABEL_LINES and ellipsizes the last kept line", () => {
+ const out = wrapLabelLines(ctx, "aa bb cc dd ee ff", 20);
+ expect(out.length).toBe(MAX_LABEL_LINES);
+ expect(out[out.length - 1]!.endsWith("…")).toBe(true);
+ });
+ it("breaks an over-long word mid-word, every line within width", () => {
+ const out = wrapLabelLines(ctx, "Supercalifragilistic", 50);
+ expect(out.length).toBeGreaterThan(1);
+ expect(out.every((l) => l.length * 10 <= 50)).toBe(true);
+ });
+});
diff --git a/packages/react-ui/src/components/D3Charts/utils/labelWrap.ts b/packages/react-ui/src/components/D3Charts/utils/labelWrap.ts
new file mode 100644
index 000000000..1178cf66d
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/utils/labelWrap.ts
@@ -0,0 +1,112 @@
+/**
+ * Pure text layout helpers for native SVG `<text>` axis labels.
+ *
+ * SVG `<text>` has no equivalent of CSS `-webkit-line-clamp` or
+ * `text-overflow: ellipsis`, so we hand-roll wrapping + measured-trim ellipsis
+ * over a canvas 2D context (the same context used to size the axis band). The
+ * renderers (`XAxis`, `CondensedXAxis`) and the band sizing
+ * (`layoutXAxisLabels`, `useXAxisHeight`) all call these, so the rendered line
+ * count and the reserved band height stay in agreement — no SCSS↔TS
+ * magic-number contract.
+ *
+ * Note: canvas `measureText` ignores theme letter-spacing — a pre-existing
+ * limitation shared with the y-axis width measurement.
+ */
+
+/** Max wrapped lines for a multi-line tick label (was `-webkit-line-clamp: 3`). */
+export const MAX_LABEL_LINES = 3;
+
+const ELLIPSIS = "…";
+
+const measure = (ctx: CanvasRenderingContext2D, s: string): number => ctx.measureText(s).width;
+
+/**
+ * Parse line-height (px) from a CSS font shorthand.
+ * Handles px line-heights ("400 12px/15px Inter") and unitless multipliers
+ * ("400 12px/1.25 Inter"); falls back to the browser default (1.2×).
+ */
+export function parseLineHeight(fontShorthand: string): number {
+ const sizeMatch = fontShorthand.match(/(\d+(?:\.\d+)?)px/);
+ const fontSize = sizeMatch ? parseFloat(sizeMatch[1]!) : 12;
+
+ const lhMatch = fontShorthand.match(/\/(\d+(?:\.\d+)?)(px)?/);
+ if (!lhMatch) return Math.ceil(fontSize * 1.2);
+
+ const lhValue = parseFloat(lhMatch[1]!);
+ const hasPxUnit = !!lhMatch[2];
+ return hasPxUnit ? lhValue : Math.ceil(fontSize * lhValue);
+}
+
+/** Trim `line` and append an ellipsis so it fits within `maxWidth`. */
+function withEllipsis(ctx: CanvasRenderingContext2D, line: string, maxWidth: number): string {
+ // Trim by code points (Array.from iterates code points, not UTF-16 units)
+ // so an astral character at the cut never leaves a lone surrogate behind.
+ let chars = Array.from(line);
+ while (chars.length > 0 && measure(ctx, chars.join("") + ELLIPSIS) > maxWidth) {
+ chars = chars.slice(0, -1);
+ }
+ return chars.join("").trimEnd() + ELLIPSIS;
+}
+
+/** Single-line: return `text` unchanged if it fits, else a measured-trim ellipsis. */
+export function truncateToWidth(
+ ctx: CanvasRenderingContext2D,
+ text: string,
+ maxWidth: number,
+): string {
+ if (maxWidth <= 0 || !text) return text;
+ if (measure(ctx, text) <= maxWidth) return text;
+ return withEllipsis(ctx, text, maxWidth);
+}
+
+/**
+ * Wrap `text` into lines that each fit `maxWidth` (CSS `break-word` behaviour:
+ * over-long words break mid-word), capped at `maxLines`. If the text overflows
+ * the cap, the last kept line is ellipsized. Returns the lines to render as
+ * `<tspan>`s — and `.length` is the line count the axis band reserves space for.
+ */
+export function wrapLabelLines(
+ ctx: CanvasRenderingContext2D,
+ text: string,
+ maxWidth: number,
+ maxLines: number = MAX_LABEL_LINES,
+): string[] {
+ if (!text) return [""];
+ if (maxWidth <= 0) return [text];
+
+ const words = text.split(/\s+/).filter(Boolean);
+ const lines: string[] = [];
+ let line = "";
+ const commit = () => {
+ if (line) {
+ lines.push(line);
+ line = "";
+ }
+ };
+
+ for (const word of words) {
+ if (measure(ctx, word) > maxWidth) {
+ // Word exceeds the line — break it character by character.
+ for (const ch of word) {
+ if (line && measure(ctx, line + ch) > maxWidth) commit();
+ line += ch;
+ }
+ } else {
+ const candidate = line ? `${line} ${word}` : word;
+ if (line && measure(ctx, candidate) > maxWidth) {
+ commit();
+ line = word;
+ } else {
+ line = candidate;
+ }
+ }
+ }
+ commit();
+
+ if (lines.length === 0) return [text];
+ if (lines.length <= maxLines) return lines;
+
+ const kept = lines.slice(0, maxLines);
+ kept[maxLines - 1] = withEllipsis(ctx, kept[maxLines - 1]!, maxWidth);
+ return kept;
+}
diff --git a/packages/react-ui/src/components/D3Charts/utils/mouseUtils.test.ts b/packages/react-ui/src/components/D3Charts/utils/mouseUtils.test.ts
new file mode 100644
index 000000000..4dd043a18
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/utils/mouseUtils.test.ts
@@ -0,0 +1,60 @@
+import { scaleBand, scalePoint } from "d3-scale";
+import { describe, expect, it } from "vitest";
+import { findBandIndex, findNearestDataIndex } from "./mouseUtils";
+
+describe("findNearestDataIndex (point-scale hover → data index)", () => {
+ // domain of 4 over [0, 300] → points at x = 0, 100, 200, 300
+ const xScale = scalePoint<string>().domain(["a", "b", "c", "d"]).range([0, 300]);
+
+ it("picks the point with the smallest |mouseX − pointX|", () => {
+ expect(findNearestDataIndex(xScale, 0)).toBe(0);
+ expect(findNearestDataIndex(xScale, 149)).toBe(1);
+ expect(findNearestDataIndex(xScale, 151)).toBe(2);
+ expect(findNearestDataIndex(xScale, 300)).toBe(3);
+ });
+
+ it("breaks exact ties toward the lower index (strict < keeps the first hit)", () => {
+ // x = 50 is exactly halfway between points 0 (x=0) and 1 (x=100)
+ expect(findNearestDataIndex(xScale, 50)).toBe(0);
+ expect(findNearestDataIndex(xScale, 250)).toBe(2);
+ });
+
+ it("clamps to the nearest end when the mouse is outside the range", () => {
+ expect(findNearestDataIndex(xScale, -500)).toBe(0);
+ expect(findNearestDataIndex(xScale, 9999)).toBe(3);
+ });
+
+ it("returns 0 for an empty domain", () => {
+ const empty = scalePoint<string>().domain([]).range([0, 300]);
+ expect(findNearestDataIndex(empty, 150)).toBe(0);
+ });
+});
+
+describe("findBandIndex (band-scale hover → band index)", () => {
+ // n=4, paddingInner=0, paddingOuter=0.5 over [0, 500]:
+ // step = 500 / (4 + 2·0.5) = 100, outer gutter = 0.5·step = 50px,
+ // so bands occupy [50,150) [150,250) [250,350) [350,450).
+ const xScale = scaleBand<string>().domain(["a", "b", "c", "d"]).range([0, 500]).paddingOuter(0.5);
+
+ it("subtracts the paddingOuter offset before dividing by step", () => {
+ // Without the offset, floor(120 / 100) = 1 — the offset math is load-bearing.
+ expect(findBandIndex(xScale, 120)).toBe(0);
+ expect(findBandIndex(xScale, 50)).toBe(0);
+ expect(findBandIndex(xScale, 150)).toBe(1);
+ expect(findBandIndex(xScale, 349)).toBe(2);
+ expect(findBandIndex(xScale, 350)).toBe(3);
+ });
+
+ it("clamps to [0, n-1] in the outer gutters and beyond the range", () => {
+ expect(findBandIndex(xScale, 0)).toBe(0); // left gutter
+ expect(findBandIndex(xScale, -999)).toBe(0);
+ expect(findBandIndex(xScale, 460)).toBe(3); // right gutter
+ expect(findBandIndex(xScale, 9999)).toBe(3);
+ });
+
+ it("guards step === 0 (degenerate zero-width range) by returning 0", () => {
+ const degenerate = scaleBand<string>().domain(["a", "b"]).range([0, 0]);
+ expect(degenerate.step()).toBe(0);
+ expect(findBandIndex(degenerate, 123)).toBe(0);
+ });
+});
diff --git a/packages/react-ui/src/components/D3Charts/utils/mouseUtils.ts b/packages/react-ui/src/components/D3Charts/utils/mouseUtils.ts
new file mode 100644
index 000000000..4a0fa3d87
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/utils/mouseUtils.ts
@@ -0,0 +1,25 @@
+import type { ScaleBand, ScalePoint } from "d3-scale";
+
+export function findNearestDataIndex(xScale: ScalePoint<string>, mouseX: number): number {
+ const domain = xScale.domain();
+ let nearestIdx = 0;
+ let minDist = Infinity;
+ domain.forEach((cat, idx) => {
+ const catX = xScale(cat) ?? 0;
+ const dist = Math.abs(mouseX - catX);
+ if (dist < minDist) {
+ minDist = dist;
+ nearestIdx = idx;
+ }
+ });
+ return nearestIdx;
+}
+
+export function findBandIndex(xScale: ScaleBand<string>, mouseX: number): number {
+ const domain = xScale.domain();
+ const step = xScale.step();
+ if (step === 0) return 0;
+ const paddingOuter = xScale.paddingOuter() * step;
+ const index = Math.floor((mouseX - paddingOuter) / step);
+ return Math.max(0, Math.min(domain.length - 1, index));
+}
diff --git a/packages/react-ui/src/components/D3Charts/utils/paletteUtils.test.ts b/packages/react-ui/src/components/D3Charts/utils/paletteUtils.test.ts
new file mode 100644
index 000000000..4faff706a
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/utils/paletteUtils.test.ts
@@ -0,0 +1,98 @@
+import { describe, expect, it } from "vitest";
+import type { ChartColorPalette } from "../../ThemeProvider";
+import { getDistributedColors, OCEAN_DEFAULT, resolvePalette } from "./paletteUtils";
+
+const bar = ["#b1", "#b2"];
+const def = ["#d1", "#d2"];
+const custom = ["#c1", "#c2"];
+
+describe("resolvePalette (react-ui ChartColorPalette integration)", () => {
+ it("customPalette overrides everything", () => {
+ const theme: ChartColorPalette = {
+ barChartPalette: bar,
+ defaultChartPalette: def,
+ };
+ expect(resolvePalette(theme, "barChartPalette", custom)).toBe(custom);
+ });
+
+ it("the per-type token beats defaultChartPalette", () => {
+ const theme: ChartColorPalette = {
+ barChartPalette: bar,
+ defaultChartPalette: def,
+ };
+ expect(resolvePalette(theme, "barChartPalette")).toBe(bar);
+ });
+
+ it("falls back to defaultChartPalette when the per-type token is unset", () => {
+ const theme: ChartColorPalette = { defaultChartPalette: def };
+ expect(resolvePalette(theme, "lineChartPalette")).toBe(def);
+ });
+
+ it("falls back to OCEAN_DEFAULT when the theme provides no chart palette", () => {
+ // The real react-ui default theme ships no chart palettes — this is the floor.
+ expect(resolvePalette({}, "barChartPalette")).toBe(OCEAN_DEFAULT);
+ expect(resolvePalette({}, "defaultChartPalette")).toBe(OCEAN_DEFAULT);
+ });
+
+ it("treats an EMPTY palette array as not provided at every layer", () => {
+ const theme: ChartColorPalette = {
+ barChartPalette: bar,
+ defaultChartPalette: def,
+ };
+ // empty customPalette → per-type token
+ expect(resolvePalette(theme, "barChartPalette", [])).toBe(bar);
+ // empty token → defaultChartPalette
+ expect(
+ resolvePalette({ barChartPalette: [], defaultChartPalette: def }, "barChartPalette"),
+ ).toBe(def);
+ // everything empty → the floor
+ expect(resolvePalette({ defaultChartPalette: [] }, "barChartPalette", [])).toBe(OCEAN_DEFAULT);
+ });
+});
+
+describe("getDistributedColors (center-out distribution over a ramp)", () => {
+ const ramp = OCEAN_DEFAULT; // 11 stops
+
+ it("keeps the established center-out picks on a full ramp", () => {
+ // midIndex = 5 — these pin the pre-fix behavior for in-range cases.
+ expect(getDistributedColors(ramp, 1)).toEqual([ramp[5]]);
+ expect(getDistributedColors(ramp, 2)).toEqual([ramp[4], ramp[6]]);
+ expect(getDistributedColors(ramp, 3)).toEqual([ramp[4], ramp[5], ramp[6]]);
+ expect(getDistributedColors(ramp, 5)).toEqual([ramp[3], ramp[4], ramp[5], ramp[6], ramp[7]]);
+ });
+
+ it("two series on a two-color palette get both colors (was: undefined)", () => {
+ // Pre-fix: [colors[0], colors[2]] → second series undefined → black fill.
+ expect(getDistributedColors(["#a", "#b"], 2)).toEqual(["#a", "#b"]);
+ });
+
+ it("tiny palettes never index out of bounds (was: undefined)", () => {
+ expect(getDistributedColors(["#only"], 1)).toEqual(["#only"]);
+ expect(getDistributedColors(["#only"], 2)).toEqual(["#only", "#only"]);
+ expect(getDistributedColors(["#only"], 3)).toEqual(["#only", "#only", "#only"]);
+ });
+
+ it("wraps correctly when series far outnumber colors (was: OOB at negative multiples)", () => {
+ // 33 series / 11 colors: the first index lands at mid − 16 = −11, a negative
+ // multiple of n — the pre-fix wrap computed colors[11] → undefined.
+ const result = getDistributedColors(ramp, 33);
+ expect(result).toHaveLength(33);
+ expect(result.every((c) => typeof c === "string")).toBe(true);
+ });
+
+ it("never returns undefined for any palette-size × series-count combination", () => {
+ for (let n = 1; n <= 12; n++) {
+ const colors = Array.from({ length: n }, (_, i) => `#c${i}`);
+ for (let len = 1; len <= 40; len++) {
+ const result = getDistributedColors(colors, len);
+ expect(result).toHaveLength(len);
+ expect(result.every((c) => colors.includes(c))).toBe(true);
+ }
+ }
+ });
+
+ it("returns [] for an empty palette or non-positive length", () => {
+ expect(getDistributedColors([], 5)).toEqual([]);
+ expect(getDistributedColors(["#a"], 0)).toEqual([]);
+ });
+});
diff --git a/packages/react-ui/src/components/D3Charts/utils/paletteUtils.ts b/packages/react-ui/src/components/D3Charts/utils/paletteUtils.ts
new file mode 100644
index 000000000..3a222253c
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/utils/paletteUtils.ts
@@ -0,0 +1,137 @@
+import { useMemo } from "react";
+import { ChartColorPalette, useTheme } from "../../ThemeProvider";
+
+/**
+ * The single built-in default ramp.
+ *
+ * Predefined named palettes were removed: chart colors now come from the
+ * react-ui `ThemeProvider`'s `ChartColorPalette` (its `defaultChartPalette` plus
+ * the per-type tokens). This ramp is only the *floor* — used when the active
+ * theme provides no chart palette at all. Future presets are expressed by
+ * configuring that theme layer (e.g. `createTheme({ defaultChartPalette: … })`),
+ * not by baking palettes into this package.
+ */
+export const OCEAN_DEFAULT: string[] = [
+ "#0D47A1",
+ "#1565C0",
+ "#1976D2",
+ "#1E88E5",
+ "#2196F3",
+ "#42A5F5",
+ "#64B5F6",
+ "#90CAF9",
+ "#BBDEFB",
+ "#E3F2FD",
+ "#EFF8FF",
+];
+
+/**
+ * Built-in diverging ramps for the heatmap's `rampMode="diverging"` when no
+ * `customPalette` is given. Two hues (blue = negative, orange = positive —
+ * colorblind-safer than red/green) meeting at a quiet neutral middle bucket;
+ * zero always lands there because the domain is forced symmetric. Mode-keyed
+ * because "visually quiet at zero" inverts with the background: near-white
+ * mid on light surfaces, near-black mid on dark ones, with the EXTREMES
+ * carrying the saturation in both. Replace with a react-ui
+ * `divergingChartPalette` token when upstream ships one (same upstream gap
+ * as `heatmapChartPalette`).
+ */
+export const DIVERGING_DEFAULT_LIGHT: string[] = [
+ "#0D47A1",
+ "#1976D2",
+ "#42A5F5",
+ "#90CAF9",
+ "#D2E6F9",
+ "#EEF1F4",
+ "#FFE3BF",
+ "#FFC97E",
+ "#FB9E2C",
+ "#EF6C00",
+ "#B74D00",
+];
+
+export const DIVERGING_DEFAULT_DARK: string[] = [
+ "#8AB8FF",
+ "#5C9BF5",
+ "#3578D6",
+ "#1F56A3",
+ "#143A6E",
+ "#20242B",
+ "#6E4A1A",
+ "#A56A1D",
+ "#D88B20",
+ "#F5A623",
+ "#FFC85C",
+];
+
+export const getDistributedColors = (colors: string[], dataLength: number): string[] => {
+ const n = colors.length;
+ if (n === 0 || dataLength <= 0) return [];
+
+ const midIndex = Math.floor(n / 2);
+ // Positive modulo — safe for any distance below/above the ramp. The naive
+ // `n + (index % n)` form returns n (out of bounds) whenever index is a
+ // negative multiple of n.
+ const wrap = (index: number) => colors[((index % n) + n) % n]!;
+
+ if (dataLength === 1) {
+ return [colors[midIndex]!];
+ }
+
+ if (dataLength === 2) {
+ // Clamp instead of wrap: on a 2-color ramp, midIndex±1 would wrap both
+ // picks onto the same color; clamping keeps them distinct.
+ return [colors[Math.max(midIndex - 1, 0)]!, colors[Math.min(midIndex + 1, n - 1)]!];
+ }
+
+ const result: string[] = [];
+ const offset = Math.floor((dataLength - 1) / 2);
+
+ for (let i = 0; i < dataLength; i++) {
+ result.push(wrap(midIndex + (i - offset)));
+ }
+
+ return result;
+};
+
+/**
+ * Resolve the color ramp for a chart, in priority order:
+ * 1. `customPalette` — explicit per-call override (a raw array)
+ * 2. `theme[themePaletteName]` — the per-type token (e.g. `barChartPalette`)
+ * 3. `theme.defaultChartPalette`— the theme's catch-all chart palette
+ * 4. `OCEAN_DEFAULT` — the built-in floor
+ *
+ * Pure (no hooks) so it can be unit-tested directly.
+ */
+export const resolvePalette = (
+ theme: ChartColorPalette,
+ themePaletteName: keyof ChartColorPalette,
+ customPalette?: string[],
+): string[] => {
+ // An empty array can't color anything — treat it as "not provided" and fall
+ // through to the next layer instead of propagating [] into every series.
+ const candidates = [customPalette, theme[themePaletteName], theme.defaultChartPalette];
+ return candidates.find((p) => p && p.length > 0) ?? OCEAN_DEFAULT;
+};
+
+/**
+ * Distributed series colors for a chart, themed via the react-ui ThemeProvider.
+ * `themePaletteName` is the per-type token the chart asks for (callers pass
+ * `"barChartPalette"`, `"lineChartPalette"`, … or `"defaultChartPalette"`).
+ */
+export const useChartPalette = ({
+ customPalette,
+ themePaletteName,
+ dataLength,
+}: {
+ customPalette?: string[];
+ themePaletteName: keyof ChartColorPalette;
+ dataLength: number;
+}) => {
+ const { theme } = useTheme();
+ const palette = resolvePalette(theme, themePaletteName, customPalette);
+
+ return useMemo(() => {
+ return getDistributedColors(palette, dataLength);
+ }, [palette, dataLength]);
+};
diff --git a/packages/react-ui/src/components/D3Charts/utils/polarUtils.test.ts b/packages/react-ui/src/components/D3Charts/utils/polarUtils.test.ts
new file mode 100644
index 000000000..f859eef24
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/utils/polarUtils.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it } from "vitest";
+import { formatPercentage, getSliceStyle } from "./polarUtils";
+
+describe("getSliceStyle (pie/radial hover dim)", () => {
+ it("returns no styles when nothing is hovered", () => {
+ expect(getSliceStyle(0, null)).toEqual({});
+ expect(getSliceStyle(3, null)).toEqual({});
+ });
+
+ it("highlights the hovered slice with full fill-opacity + brightness", () => {
+ expect(getSliceStyle(2, 2)).toEqual({
+ fillOpacity: 1,
+ filter: "brightness(1.08)",
+ });
+ });
+
+ it("dims non-hovered slices via fillOpacity (not opacity — see impl comment)", () => {
+ expect(getSliceStyle(0, 2)).toEqual({ fillOpacity: 0.4 });
+ expect(getSliceStyle(0, 2)).not.toHaveProperty("opacity");
+ });
+});
+
+describe("formatPercentage (slice labels)", () => {
+ it("formats value/total with one decimal place", () => {
+ expect(formatPercentage(25, 100)).toBe("25.0%");
+ expect(formatPercentage(100, 100)).toBe("100.0%");
+ });
+
+ it("rounds to one decimal", () => {
+ expect(formatPercentage(1, 3)).toBe("33.3%");
+ expect(formatPercentage(2, 3)).toBe("66.7%");
+ });
+
+ it("returns 0% (no decimal) when the total is 0 — no NaN/Infinity leak", () => {
+ expect(formatPercentage(5, 0)).toBe("0%");
+ expect(formatPercentage(0, 0)).toBe("0%");
+ });
+});
diff --git a/packages/react-ui/src/components/D3Charts/utils/polarUtils.ts b/packages/react-ui/src/components/D3Charts/utils/polarUtils.ts
new file mode 100644
index 000000000..11c13df1f
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/utils/polarUtils.ts
@@ -0,0 +1,45 @@
+import type { ChartData } from "../types";
+
+/**
+ * The hover transition shared by the polar fill shapes (pie wedge, radial bar):
+ * the non-hovered `fill-opacity` dim + the hovered `filter` brightness, both
+ * 200ms. One const so the two charts can't drift apart.
+ */
+export const POLAR_HOVER_TRANSITION = "fill-opacity 0.2s ease, filter 0.2s ease";
+
+export function sortByValueDescending<T extends ChartData>(data: T, dataKey: string): T {
+ return [...data].sort((a, b) => {
+ const aVal = Number(a[dataKey]) || 0;
+ const bVal = Number(b[dataKey]) || 0;
+ return bVal - aVal;
+ }) as T;
+}
+
+export function getSliceStyle(index: number, hoveredIndex: number | null): React.CSSProperties {
+ if (hoveredIndex === null) return {};
+ if (index === hoveredIndex) {
+ return { fillOpacity: 1, filter: "brightness(1.08)" };
+ }
+ // fill-opacity, NOT opacity: the entrance keyframe's forwards fill holds
+ // `opacity: 1` on these elements forever (the class is never removed), and
+ // CSS-animation declarations beat inline styles even in the fill phase — an
+ // opacity dim is silently dead after the entrance plays. fill-opacity isn't
+ // animated, so it composes. Slices/bars are pure fills: visually identical.
+ return { fillOpacity: 0.4 };
+}
+
+export function formatPercentage(value: number, total: number): string {
+ if (total === 0) return "0%";
+ return `${((value / total) * 100).toFixed(1)}%`;
+}
+
+export function radarAxisAngle(index: number, total: number): number {
+ return (2 * Math.PI * index) / total - Math.PI / 2;
+}
+
+export function radarLabelAnchor(angle: number): "start" | "middle" | "end" {
+ const EPSILON = 0.1;
+ const cos = Math.cos(angle);
+ if (Math.abs(cos) < EPSILON) return "middle";
+ return cos > 0 ? "start" : "end";
+}
diff --git a/packages/react-ui/src/components/D3Charts/utils/radarLabelLayout.test.ts b/packages/react-ui/src/components/D3Charts/utils/radarLabelLayout.test.ts
new file mode 100644
index 000000000..930257246
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/utils/radarLabelLayout.test.ts
@@ -0,0 +1,89 @@
+import { describe, expect, it } from "vitest";
+import { MIN_RADAR_LABEL_BUDGET, radarLabelLayout, radarLabelPadding } from "./radarLabelLayout";
+
+// Reference geometry: chartSize 300 → maxRadius 105 (0.35·300), lineHeight 15
+// (the default '400 12px/1.25 Inter' theme font). radarLabelPadding(300, 15)
+// is 16, so the label ring radius r = 121.
+const GEOM = {
+ chartSize: 300,
+ maxRadius: 105,
+ containerWidth: 800,
+ lineHeight: 15,
+};
+
+describe("radarLabelPadding (adaptive vertical reserve)", () => {
+ it("keeps the legacy 16px at comfortable sizes (300+)", () => {
+ expect(radarLabelPadding(300, 15)).toBe(16);
+ expect(radarLabelPadding(500, 15)).toBe(16);
+ });
+ it("shrinks at small sizes so a one-line label still fits the svg (150 → 7.5)", () => {
+ // 0.15·150 − 15 = 7.5 → top label: y = −(52.5+7.5) = −60, minus one
+ // lineHeight of ascent = −75 = exactly the svg edge. No spill.
+ expect(radarLabelPadding(150, 15)).toBe(7.5);
+ });
+ it("never goes below the 6px floor", () => {
+ expect(radarLabelPadding(100, 15)).toBe(6);
+ });
+});
+
+describe("radarLabelLayout — N=4 cardinal axes, wide container (800px)", () => {
+ // svgLeft = (800−300)/2 = 250; svg center in container coords = 250+150 = 400.
+ it("top axis (i=0): middle-anchored, bottom-aligned, 1 line, near-full-width budget", () => {
+ const l = radarLabelLayout(0, 4, GEOM);
+ expect(l.x).toBeCloseTo(0, 6);
+ expect(l.y).toBeCloseTo(-121, 6);
+ expect(l.hAlign).toBe("middle");
+ expect(l.vAlign).toBe("bottom");
+ expect(l.maxLines).toBe(1); // |sin| ≥ 0.7 → single line (vertical safety)
+ expect(l.maxWidth).toBeCloseTo(2 * (400 - 4), 6); // 2·(min(400,400) − margin)
+ });
+ it("right axis (i=1): start-anchored, middle-aligned, 2 lines, budget to right edge", () => {
+ const l = radarLabelLayout(1, 4, GEOM);
+ expect(l.x).toBeCloseTo(121, 6);
+ expect(l.y).toBeCloseTo(0, 6);
+ expect(l.hAlign).toBe("start");
+ expect(l.vAlign).toBe("middle");
+ expect(l.maxLines).toBe(2);
+ expect(l.maxWidth).toBeCloseTo(800 - (400 + 121) - 4, 6); // = 275
+ });
+ it("bottom axis (i=2): middle/top/1-line", () => {
+ const l = radarLabelLayout(2, 4, GEOM);
+ expect(l.y).toBeCloseTo(121, 6);
+ expect(l.vAlign).toBe("top");
+ expect(l.maxLines).toBe(1);
+ });
+ it("left axis (i=3): end-anchored, budget to left edge", () => {
+ const l = radarLabelLayout(3, 4, GEOM);
+ expect(l.x).toBeCloseTo(-121, 6);
+ expect(l.hAlign).toBe("end");
+ expect(l.maxWidth).toBeCloseTo(400 - 121 - 4, 6); // = 275
+ });
+});
+
+describe("radarLabelLayout — degenerate containers", () => {
+ it("square container: side budget collapses to the svg slack, not below", () => {
+ const l = radarLabelLayout(1, 4, { ...GEOM, containerWidth: 300 });
+ // svgLeft = 0, anchor at 150+121 = 271 → 300 − 271 − 4 = 25
+ expect(l.maxWidth).toBeCloseTo(25, 6);
+ });
+ it("containerWidth 0 (pre-measure frame) is clamped to chartSize", () => {
+ const zero = radarLabelLayout(1, 4, { ...GEOM, containerWidth: 0 });
+ const square = radarLabelLayout(1, 4, { ...GEOM, containerWidth: 300 });
+ expect(zero.maxWidth).toBeCloseTo(square.maxWidth, 6);
+ });
+ it("budget is never negative", () => {
+ const l = radarLabelLayout(1, 4, {
+ chartSize: 150,
+ maxRadius: 150 * 0.35,
+ containerWidth: 0,
+ lineHeight: 15,
+ });
+ expect(l.maxWidth).toBeGreaterThanOrEqual(0);
+ });
+});
+
+describe("MIN_RADAR_LABEL_BUDGET", () => {
+ it("is 12 (labels below this are hidden, never overflowed)", () => {
+ expect(MIN_RADAR_LABEL_BUDGET).toBe(12);
+ });
+});
diff --git a/packages/react-ui/src/components/D3Charts/utils/radarLabelLayout.ts b/packages/react-ui/src/components/D3Charts/utils/radarLabelLayout.ts
new file mode 100644
index 000000000..fd85b7254
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/utils/radarLabelLayout.ts
@@ -0,0 +1,97 @@
+import { radarAxisAngle, radarLabelAnchor } from "./polarUtils";
+
+/**
+ * Pure layout math for radar axis labels.
+ *
+ * Labels render as native SVG text inside the radar's square svg, but the svg
+ * has `overflow: visible` (radarChart.scss) and each label's truncation budget
+ * is computed against the CONTAINER width — the horizontal slack between the
+ * square chart and the container edges is paintable label room. The svg is
+ * flex-centered in the container (chartBase.scss `centered-container` /
+ * `centered-svg-wrapper` mixins — a TS↔SCSS contract: if that centering ever
+ * changes, `svgLeft` below must change with it), so the offset is closed-form:
+ * no getBoundingClientRect, no portals.
+ *
+ * Vertical room is NOT borrowed from the container (the legend sits directly
+ * below in a non-clipping column): `radarLabelPadding` adapts so a one-line
+ * top/bottom label always fits inside the svg, and axes near vertical
+ * (|sin| ≥ 0.7) are capped to one line.
+ */
+
+/** Budget inset from the container edges (absorbs measureText letter-spacing slop). */
+const EDGE_MARGIN = 4;
+/** Hide a label entirely when its budget is below this — never render overflow. */
+export const MIN_RADAR_LABEL_BUDGET = 12;
+
+const MAX_LABEL_PADDING = 16;
+const MIN_LABEL_PADDING = 6;
+
+export interface RadarLabelGeometry {
+ chartSize: number;
+ maxRadius: number;
+ /** Measured chart container width; 0 on the pre-measure frame (clamped to chartSize). */
+ containerWidth: number;
+ /** From parseLineHeight(ctx.font). */
+ lineHeight: number;
+}
+
+export interface RadarLabelLayout {
+ /** Anchor x, relative to the radar center (the translated <g>). */
+ x: number;
+ /** Anchor y, relative to the radar center. */
+ y: number;
+ hAlign: "start" | "middle" | "end";
+ vAlign: "top" | "middle" | "bottom";
+ /** Truncation budget in px (container-coordinate, per-anchor). Never negative. */
+ maxWidth: number;
+ maxLines: 1 | 2;
+}
+
+/**
+ * Gap between the outer ring and the label anchor. 16px when the svg has
+ * vertical room to spare; shrinks (floor 6) so `maxRadius + padding +
+ * lineHeight <= chartSize/2` keeps one-line top/bottom labels inside the svg.
+ */
+export function radarLabelPadding(chartSize: number, lineHeight: number): number {
+ return Math.min(MAX_LABEL_PADDING, Math.max(MIN_LABEL_PADDING, 0.15 * chartSize - lineHeight));
+}
+
+export function radarLabelLayout(
+ index: number,
+ numAxes: number,
+ geom: RadarLabelGeometry,
+): RadarLabelLayout {
+ const { chartSize, maxRadius, lineHeight } = geom;
+ // Pre-measure frames report 0; minChartSize can also exceed a tiny
+ // container. Either way the svg box is the floor for budget math.
+ const containerWidth = Math.max(geom.containerWidth, chartSize);
+
+ const angle = radarAxisAngle(index, numAxes);
+ const cos = Math.cos(angle);
+ const sin = Math.sin(angle);
+ const r = maxRadius + radarLabelPadding(chartSize, lineHeight);
+ const x = r * cos;
+ const y = r * sin;
+
+ const hAlign = radarLabelAnchor(angle);
+ let vAlign: RadarLabelLayout["vAlign"] = "middle";
+ if (sin < -0.3) vAlign = "bottom";
+ else if (sin > 0.3) vAlign = "top";
+
+ // Near-vertical axes grow away from the anchor toward the svg edge, where
+ // the adaptive padding reserves exactly one lineHeight — cap them to 1 line.
+ const maxLines: RadarLabelLayout["maxLines"] = Math.abs(sin) >= 0.7 ? 1 : 2;
+
+ const svgLeft = (containerWidth - chartSize) / 2;
+ const anchorX = svgLeft + chartSize / 2 + x;
+ let maxWidth: number;
+ if (hAlign === "start") {
+ maxWidth = containerWidth - anchorX - EDGE_MARGIN;
+ } else if (hAlign === "end") {
+ maxWidth = anchorX - EDGE_MARGIN;
+ } else {
+ maxWidth = 2 * (Math.min(anchorX, containerWidth - anchorX) - EDGE_MARGIN);
+ }
+
+ return { x, y, hAlign, vAlign, maxWidth: Math.max(0, maxWidth), maxLines };
+}
diff --git a/packages/react-ui/src/components/D3Charts/utils/rampUtils.test.ts b/packages/react-ui/src/components/D3Charts/utils/rampUtils.test.ts
new file mode 100644
index 000000000..36e9003e7
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/utils/rampUtils.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from "vitest";
+
+import { sampleRampStops } from "./rampUtils";
+
+const ELEVEN = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"];
+
+describe("sampleRampStops", () => {
+ it("samples 5 endpoint-inclusive stops from an 11-color ramp", () => {
+ // positions 0, 2.5→3, 5, 7.5→8, 10 (Math.round rounds .5 up)
+ expect(sampleRampStops(ELEVEN, 5)).toEqual(["a", "d", "f", "i", "k"]);
+ });
+
+ it("always keeps both endpoints", () => {
+ const out = sampleRampStops(ELEVEN, 4);
+ expect(out[0]).toBe("a");
+ expect(out[out.length - 1]).toBe("k");
+ expect(out).toHaveLength(4);
+ });
+
+ it("repeats a single-color ramp to fill the count", () => {
+ expect(sampleRampStops(["x"], 5)).toEqual(["x", "x", "x", "x", "x"]);
+ });
+
+ it("returns the first color for count 1", () => {
+ expect(sampleRampStops(ELEVEN, 1)).toEqual(["a"]);
+ });
+
+ it("returns [] for an empty ramp or non-positive count", () => {
+ expect(sampleRampStops([], 5)).toEqual([]);
+ expect(sampleRampStops(ELEVEN, 0)).toEqual([]);
+ expect(sampleRampStops(ELEVEN, -3)).toEqual([]);
+ });
+
+ it("passes a shorter ramp through when count equals its length", () => {
+ expect(sampleRampStops(["a", "b", "c"], 3)).toEqual(["a", "b", "c"]);
+ });
+
+ it("never returns undefined across ramp-size × count combinations", () => {
+ for (let n = 1; n <= 12; n++) {
+ const colors = Array.from({ length: n }, (_, i) => `#c${i}`);
+ for (let count = 1; count <= 8; count++) {
+ const out = sampleRampStops(colors, count);
+ expect(out).toHaveLength(count);
+ expect(out.every((c) => colors.includes(c))).toBe(true);
+ }
+ }
+ });
+});
diff --git a/packages/react-ui/src/components/D3Charts/utils/rampUtils.ts b/packages/react-ui/src/components/D3Charts/utils/rampUtils.ts
new file mode 100644
index 000000000..a58347a86
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/utils/rampUtils.ts
@@ -0,0 +1,28 @@
+// Sampling a fixed-size discrete color scale out of an ordered ramp. Pure; no
+// React/DOM/d3. Shared by the CalendarHeatmap (5 contribution levels) and the
+// choropleth bins (Task 8) so neither duplicates the endpoint-inclusive
+// even-spacing pick.
+
+/**
+ * Evenly-spaced stops sampled from an ordered ramp, endpoints always included.
+ *
+ * Collapses a palette of any length to exactly `count` colors: stop `i` maps to
+ * ramp position `i / (count - 1)`, rounded to the nearest source index. Stop 0
+ * is always `colors[0]` and the last stop always `colors[last]`, so the sampled
+ * scale keeps the ramp's low→high ordering (the same convention HeatmapChart's
+ * quantize ramp uses). A single-color ramp repeats that color; an empty ramp
+ * yields an empty array (callers resolve a non-empty ramp via `resolvePalette`
+ * first).
+ */
+export function sampleRampStops(colors: readonly string[], count: number): string[] {
+ if (count <= 0 || colors.length === 0) return [];
+ if (colors.length === 1) return Array.from({ length: count }, () => colors[0]!);
+ if (count === 1) return [colors[0]!];
+
+ const lastSource = colors.length - 1;
+ const lastStop = count - 1;
+ return Array.from({ length: count }, (_, i) => {
+ const index = Math.round((i / lastStop) * lastSource);
+ return colors[index]!;
+ });
+}
diff --git a/packages/react-ui/src/components/D3Charts/utils/resolveShouldFitLegend.test.ts b/packages/react-ui/src/components/D3Charts/utils/resolveShouldFitLegend.test.ts
new file mode 100644
index 000000000..969aaede5
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/utils/resolveShouldFitLegend.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it } from "vitest";
+import { resolveShouldFitLegend } from "./resolveShouldFitLegend";
+
+describe("resolveShouldFitLegend", () => {
+ it("honors an explicit fitLegendInHeight regardless of height", () => {
+ expect(resolveShouldFitLegend(true, undefined)).toBe(true);
+ expect(resolveShouldFitLegend(false, 400)).toBe(false);
+ });
+
+ it("defaults to fit when a height is pinned, not when it is auto", () => {
+ expect(resolveShouldFitLegend(undefined, 400)).toBe(true);
+ expect(resolveShouldFitLegend(undefined, undefined)).toBe(false);
+ });
+
+ it('treats a pinned height of 0 or "" as explicit — the R10 fix', () => {
+ // The cartesian outlier used `?? !!height`, which wrongly collapsed these to
+ // false; `?? height !== undefined` keeps an explicitly pinned 0/"" as "fit".
+ expect(resolveShouldFitLegend(undefined, 0)).toBe(true);
+ expect(resolveShouldFitLegend(undefined, "")).toBe(true);
+ });
+});
diff --git a/packages/react-ui/src/components/D3Charts/utils/resolveShouldFitLegend.ts b/packages/react-ui/src/components/D3Charts/utils/resolveShouldFitLegend.ts
new file mode 100644
index 000000000..0b0fe2823
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/utils/resolveShouldFitLegend.ts
@@ -0,0 +1,17 @@
+/**
+ * Whether the legend's measured height should be deducted from the chart's
+ * drawing height (legend laid out INSIDE the pinned box) versus placed below an
+ * auto-height chart.
+ *
+ * An explicit `fitLegendInHeight` always wins; otherwise default to "fit" when
+ * the consumer pinned a `height`. The test is `height !== undefined`, NOT
+ * `!!height` — a pinned `height: 0` (or `""`) is still an explicit height and
+ * must count as "fit"; `!!height` wrongly collapsed those to false (the R10
+ * skew, where one cartesian site disagreed with the five non-cartesian ones).
+ */
+export function resolveShouldFitLegend(
+ fitLegendInHeight: boolean | undefined,
+ height: number | string | undefined,
+): boolean {
+ return fitLegendInHeight ?? height !== undefined;
+}
diff --git a/packages/react-ui/src/components/D3Charts/utils/scrollUtils.test.ts b/packages/react-ui/src/components/D3Charts/utils/scrollUtils.test.ts
new file mode 100644
index 000000000..d746cea75
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/utils/scrollUtils.test.ts
@@ -0,0 +1,61 @@
+import { describe, expect, it } from "vitest";
+import { findNearestSnapPosition, getWidthOfData, getWidthOfGroup } from "./scrollUtils";
+
+const rows = (n: number) => Array.from({ length: n }, (_, i) => ({ x: i }));
+
+describe("getWidthOfGroup (density → px per category group)", () => {
+ it("maps the three densities to 48 / 72 / 96", () => {
+ expect(getWidthOfGroup("compact")).toBe(48);
+ expect(getWidthOfGroup("default")).toBe(72);
+ expect(getWidthOfGroup("spacious")).toBe(96);
+ });
+
+ it("defaults to the default density", () => {
+ expect(getWidthOfGroup()).toBe(72);
+ });
+});
+
+describe("getWidthOfData (inner scroll width)", () => {
+ it("is data.length × group width when that exceeds the container", () => {
+ expect(getWidthOfData(rows(10), 300)).toBe(720);
+ expect(getWidthOfData(rows(10), 300, "compact")).toBe(480);
+ expect(getWidthOfData(rows(10), 300, "spacious")).toBe(960);
+ });
+
+ it("floors at the available container width (no horizontal scroll)", () => {
+ expect(getWidthOfData(rows(10), 1000)).toBe(1000);
+ expect(getWidthOfData(rows(10), 720)).toBe(720); // exact fit counts as fitting
+ });
+
+ it("returns the container width for empty data", () => {
+ expect(getWidthOfData([], 555)).toBe(555);
+ });
+
+ it("floors a single point at 200px when the container is narrower than a group", () => {
+ expect(getWidthOfData(rows(1), 40, "compact")).toBe(200);
+ // …but a container wider than the group still wins
+ expect(getWidthOfData(rows(1), 500, "compact")).toBe(500);
+ });
+});
+
+describe("findNearestSnapPosition (scroll-button stepping)", () => {
+ const positions = [0, 72, 144, 216];
+
+ it("steps to the neighbor of the last snap at or before the current scroll", () => {
+ // currentScroll 100 sits in [72, 144) → current index 1
+ expect(findNearestSnapPosition(positions, 100, "left")).toBe(0);
+ expect(findNearestSnapPosition(positions, 100, "right")).toBe(2);
+ // exactly on a snap counts as being at it
+ expect(findNearestSnapPosition(positions, 72, "left")).toBe(0);
+ expect(findNearestSnapPosition(positions, 72, "right")).toBe(2);
+ });
+
+ it("clamps at both ends", () => {
+ expect(findNearestSnapPosition(positions, 0, "left")).toBe(0);
+ expect(findNearestSnapPosition(positions, 9999, "right")).toBe(3);
+ });
+
+ it("scrolled past the last snap, left steps back to the second-to-last", () => {
+ expect(findNearestSnapPosition(positions, 9999, "left")).toBe(2);
+ });
+});
diff --git a/packages/react-ui/src/components/D3Charts/utils/scrollUtils.ts b/packages/react-ui/src/components/D3Charts/utils/scrollUtils.ts
new file mode 100644
index 000000000..c0520469f
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/utils/scrollUtils.ts
@@ -0,0 +1,70 @@
+type ChartData = Array<Record<string, string | number>>;
+
+export type ChartDensity = "compact" | "default" | "spacious";
+
+const DENSITY_SPACING: Record<ChartDensity, number> = {
+ compact: 48,
+ default: 72,
+ spacious: 96,
+};
+const MIN_SINGLE_POINT_WIDTH = 200;
+
+export const getWidthOfData = (
+ data: ChartData,
+ containerWidth: number,
+ density: ChartDensity = "default",
+) => {
+ if (data.length === 0) {
+ return containerWidth;
+ }
+ const width = data.length * getWidthOfGroup(density);
+
+ if (containerWidth >= width) {
+ return containerWidth;
+ }
+
+ if (data.length === 1) {
+ return Math.max(width, MIN_SINGLE_POINT_WIDTH);
+ }
+
+ return width;
+};
+
+export const findNearestSnapPosition = (
+ snapPositions: number[],
+ currentScroll: number,
+ direction: "left" | "right",
+): number => {
+ let currentIndex = 0;
+ for (let i = 0; i < snapPositions.length; i++) {
+ const snapPosition = snapPositions[i];
+ if (snapPosition !== undefined && currentScroll >= snapPosition) {
+ currentIndex = i;
+ } else {
+ break;
+ }
+ }
+
+ if (direction === "left") {
+ return Math.max(0, currentIndex - 1);
+ } else {
+ return Math.min(snapPositions.length - 1, currentIndex + 1);
+ }
+};
+
+export function getWidthOfGroup(density: ChartDensity = "default"): number {
+ return DENSITY_SPACING[density];
+}
+
+export const getSnapPositions = (data: ChartData, density: ChartDensity = "default"): number[] => {
+ if (data.length === 0) return [0];
+
+ const positions = [0];
+ const groupWidthValue = getWidthOfGroup(density);
+
+ for (let i = 1; i < data.length; i++) {
+ positions.push(i * groupWidthValue);
+ }
+
+ return positions;
+};
diff --git a/packages/react-ui/src/components/D3Charts/utils/styleUtils.test.ts b/packages/react-ui/src/components/D3Charts/utils/styleUtils.test.ts
new file mode 100644
index 000000000..d80750620
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/utils/styleUtils.test.ts
@@ -0,0 +1,68 @@
+import { scaleLinear } from "d3-scale";
+import { describe, expect, it } from "vitest";
+import { measureYAxisWidth, numberTickFormatter } from "./styleUtils";
+
+// Deterministic stand-in for canvas text metrics: width == 10px per character.
+// (Real CanvasRenderingContext2D isn't available under vitest's node env; the
+// logic under test is "which strings get measured", not the exact font metrics.)
+const mockContext = {
+ measureText: (s: string) => ({ width: s.length * 10 }),
+} as unknown as CanvasRenderingContext2D;
+
+const PADDING = 10;
+const MIN = 20;
+
+describe("numberTickFormatter", () => {
+ it("renders plain integers as-is", () => {
+ expect(numberTickFormatter(0)).toBe("0");
+ expect(numberTickFormatter(950)).toBe("950");
+ });
+
+ it("abbreviates K/M/B/T with one decimal until 10×, then none", () => {
+ expect(numberTickFormatter(1000)).toBe("1.0K");
+ expect(numberTickFormatter(9500)).toBe("9.5K");
+ expect(numberTickFormatter(12000)).toBe("12K");
+ expect(numberTickFormatter(1_000_000)).toBe("1.0M");
+ expect(numberTickFormatter(2_500_000_000)).toBe("2.5B");
+ });
+
+ it("shows two decimals for fractional values", () => {
+ expect(numberTickFormatter(47.38)).toBe("47.38");
+ });
+});
+
+describe("measureYAxisWidth sizes against the rendered ticks (F4)", () => {
+ it("reserves width for the .nice() top tick, not the raw data max", () => {
+ // data max 950 → .nice() domain [0, 1000] → top tick 1000 → "1.0K" (4 chars).
+ // The OLD hook measured the raw "950" (3 chars) and the real "1.0K" clipped.
+ const ticks = scaleLinear().domain([0, 950]).nice().ticks();
+ expect(ticks).toContain(1000);
+ // widest tick "1.0K" = 4 chars × 10 + 10 padding = 50
+ expect(measureYAxisWidth(ticks, mockContext)).toBe(4 * 10 + PADDING);
+ // proof of the bug it fixes: measuring the raw value would under-reserve.
+ expect(mockContext.measureText("950").width).toBeLessThan(
+ mockContext.measureText("1.0K").width,
+ );
+ });
+
+ it("does not over-reserve for fractional data the axis never shows", () => {
+ // raw max 47.38 ("47.38", 5 chars) but ticks are 0..50 (≤ 2 chars).
+ const ticks = scaleLinear().domain([0, 47.38]).nice().ticks();
+ const widest = Math.max(...ticks.map((t) => numberTickFormatter(t).length));
+ expect(widest).toBeLessThanOrEqual(2);
+ expect(measureYAxisWidth(ticks, mockContext)).toBe(2 * 10 + PADDING);
+ });
+
+ it("takes the widest tick (often the top-of-domain abbreviation), not min/max position", () => {
+ // [0 .. 9500] → top "9.5K" (4) is wider than any 3-digit interior tick.
+ const ticks = scaleLinear().domain([0, 9500]).nice().ticks();
+ const widthByFormatter = Math.max(...ticks.map((t) => numberTickFormatter(t).length));
+ expect(measureYAxisWidth(ticks, mockContext)).toBe(widthByFormatter * 10 + PADDING);
+ });
+
+ it("clamps to min and max", () => {
+ expect(measureYAxisWidth([5], mockContext)).toBe(MIN); // 1×10+10=20 → min
+ expect(measureYAxisWidth([], mockContext)).toBe(MIN); // no ticks → min
+ expect(measureYAxisWidth([1000], mockContext, { maxWidth: 25 })).toBe(25);
+ });
+});
diff --git a/packages/react-ui/src/components/D3Charts/utils/styleUtils.ts b/packages/react-ui/src/components/D3Charts/utils/styleUtils.ts
new file mode 100644
index 000000000..c76566764
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/utils/styleUtils.ts
@@ -0,0 +1,45 @@
+const numberTickFormatter = (value: number) => {
+ if (typeof value === "number") {
+ const absValue = Math.abs(value);
+
+ if (absValue >= 1e12) {
+ return (value / 1e12).toFixed(absValue >= 10e12 ? 0 : 1) + "T";
+ } else if (absValue >= 1e9) {
+ return (value / 1e9).toFixed(absValue >= 10e9 ? 0 : 1) + "B";
+ } else if (absValue >= 1e6) {
+ return (value / 1e6).toFixed(absValue >= 10e6 ? 0 : 1) + "M";
+ } else if (absValue >= 1e3) {
+ return (value / 1e3).toFixed(absValue >= 10e3 ? 0 : 1) + "K";
+ } else {
+ if (value % 1 !== 0) {
+ return value.toFixed(2);
+ }
+ return value.toString();
+ }
+ }
+ return String(value);
+};
+
+const DEFAULT_MIN_Y_AXIS_WIDTH = 20;
+const DEFAULT_MAX_Y_AXIS_WIDTH = 200;
+const DEFAULT_Y_AXIS_PADDING = 10;
+
+const measureYAxisWidth = (
+ ticks: number[],
+ context: CanvasRenderingContext2D,
+ options?: { minWidth?: number; maxWidth?: number; padding?: number },
+): number => {
+ const minWidth = options?.minWidth ?? DEFAULT_MIN_Y_AXIS_WIDTH;
+ const maxWidth = options?.maxWidth ?? DEFAULT_MAX_Y_AXIS_WIDTH;
+ const padding = options?.padding ?? DEFAULT_Y_AXIS_PADDING;
+
+ let maxTextWidth = 0;
+ for (const tick of ticks) {
+ const w = context.measureText(numberTickFormatter(tick)).width;
+ if (w > maxTextWidth) maxTextWidth = w;
+ }
+
+ return Math.max(minWidth, Math.min(maxWidth, Math.ceil(maxTextWidth) + padding));
+};
+
+export { measureYAxisWidth, numberTickFormatter };
diff --git a/packages/react-ui/src/components/D3Charts/utils/xAxisLabelLayout.test.ts b/packages/react-ui/src/components/D3Charts/utils/xAxisLabelLayout.test.ts
new file mode 100644
index 000000000..28c11ae1b
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/utils/xAxisLabelLayout.test.ts
@@ -0,0 +1,106 @@
+import { describe, expect, it } from "vitest";
+import { ANGLED_LABEL_ROTATION, layoutXAxisLabels } from "./xAxisLabelLayout";
+
+// Deterministic stand-in for canvas text metrics: width == 10px per character.
+const ctx = {
+ measureText: (s: string) => ({ width: s.length * 10 }),
+} as unknown as CanvasRenderingContext2D;
+
+const LINE = 15;
+const LONG = "Extremely Long Category Name That Needs Truncation"; // 500px
+const layout = (labels: string[], opts: Partial<Parameters<typeof layoutXAxisLabels>[2]> = {}) =>
+ layoutXAxisLabels(ctx, labels, {
+ variant: "singleLine",
+ slotWidth: 100,
+ maxHeight: 120,
+ lineHeight: LINE,
+ condensed: true,
+ ...opts,
+ });
+
+describe("layoutXAxisLabels — condensed", () => {
+ it("draws short labels horizontally, one per category", () => {
+ expect(layout(["Jan", "Feb", "Mar"])).toEqual({
+ angle: 0,
+ interval: 1,
+ labelWidth: 92,
+ maxLines: 1,
+ height: 30,
+ });
+ });
+
+ it("keeps a single-line band for long labels; the renderer truncates them", () => {
+ const out = layout([LONG, LONG], { slotWidth: 60 });
+ expect(out.height).toBe(30);
+ expect(out.labelWidth).toBe(52);
+ expect(out.angle).toBe(0);
+ });
+
+ it("draws every n-th label when categories are too narrow to read", () => {
+ // min(60, 40) + 8 gap = 48px needed per label → every 4th 12px category.
+ const out = layout(Array(24).fill("Jan 23"), { slotWidth: 12 });
+ expect(out.interval).toBe(4);
+ expect(out.labelWidth).toBe(40);
+ });
+
+ it("wraps multiLine labels, with no more lines than the band cap allows", () => {
+ expect(layout([LONG], { variant: "multiLine", slotWidth: 200 }).maxLines).toBe(3);
+ // (45 − 13 padding) / 15 → 2 lines.
+ const capped = layout([LONG], { variant: "multiLine", slotWidth: 200, maxHeight: 45 });
+ expect(capped.maxLines).toBe(2);
+ expect(capped.height).toBeLessThanOrEqual(45);
+ });
+
+ it("reserves only the lines the wrapped labels need", () => {
+ const out = layout(["Jan", "Feb"], { variant: "multiLine" });
+ expect(out.maxLines).toBe(1);
+ expect(out.height).toBe(30);
+ });
+
+ it("keeps angled labels horizontal when they fit", () => {
+ expect(layout(["Jan", "Feb"], { variant: "angled" }).angle).toBe(0);
+ });
+
+ it("rotates angled labels 45° and caps the band, truncating what doesn't fit", () => {
+ const out = layout([LONG, LONG], { variant: "angled", slotWidth: 50, maxHeight: 100 });
+ expect(out.angle).toBe(ANGLED_LABEL_ROTATION);
+ expect(out.height).toBe(100);
+ // (100 − 4 gap) / sin 45° − 15 line height
+ expect(out.labelWidth).toBeCloseTo(96 / Math.SQRT1_2 - LINE);
+ expect(out.labelWidth).toBeLessThan(500);
+ });
+
+ it("sizes the angled band to the labels when they fit under the cap", () => {
+ const out = layout(["Quarter One", "Quarter Two"], { variant: "angled", slotWidth: 50 });
+ expect(out.height).toBeLessThan(120);
+ expect(out.labelWidth).toBeGreaterThanOrEqual(110);
+ });
+
+ it("thins rotated labels closer than a line-height apart", () => {
+ // 15 / sin 45° ≈ 21.2px apart needed → every 3rd 8px category.
+ expect(layout(Array(30).fill(LONG), { variant: "angled", slotWidth: 8 }).interval).toBe(3);
+ });
+
+ it("never lets the band exceed the cap, beyond one line in tiny charts", () => {
+ for (const variant of ["singleLine", "multiLine", "angled"] as const) {
+ expect(layout([LONG], { variant, slotWidth: 30, maxHeight: 60 }).height).toBeLessThanOrEqual(
+ 60,
+ );
+ expect(layout([LONG], { variant, slotWidth: 30, maxHeight: 10 }).height).toBe(30);
+ }
+ });
+});
+
+describe("layoutXAxisLabels — scrolling", () => {
+ it("draws every label at its category width, never rotated", () => {
+ const out = layout([LONG], { condensed: false, variant: "angled", slotWidth: 70 });
+ expect(out).toEqual({ angle: 0, interval: 1, labelWidth: 70, maxLines: 1, height: 30 });
+ });
+
+ it("reserves the wrapped line count for multiLine", () => {
+ // "Extremely Long Category…" wraps to 3+ lines at 150px → capped at 3.
+ const out = layout([LONG], { condensed: false, variant: "multiLine", slotWidth: 150 });
+ expect(out.maxLines).toBe(3);
+ expect(out.height).toBe(3 * LINE + 13);
+ });
+});
diff --git a/packages/react-ui/src/components/D3Charts/utils/xAxisLabelLayout.ts b/packages/react-ui/src/components/D3Charts/utils/xAxisLabelLayout.ts
new file mode 100644
index 000000000..3286ef447
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/utils/xAxisLabelLayout.ts
@@ -0,0 +1,115 @@
+import type { XAxisTickVariant } from "../types";
+import { MAX_LABEL_LINES, wrapLabelLines } from "./labelWrap";
+
+/**
+ * The x-axis label band never takes more than this share of the chart's
+ * drawable height, so the plot always keeps the rest. Labels that don't fit
+ * are truncated instead of growing the band.
+ */
+export const MAX_X_AXIS_HEIGHT_SHARE = 0.5;
+
+/** Gap between the plot's bottom edge and the labels. */
+export const X_AXIS_TOP_GAP = 4;
+
+/** Rotation for "angled" labels that don't fit horizontally. */
+export const ANGLED_LABEL_ROTATION = -45;
+
+const X_AXIS_LABEL_PADDING = 13;
+const MIN_X_AXIS_HEIGHT = 30;
+/** Horizontal space kept between neighbouring labels in the condensed layout. */
+const LABEL_GAP = 8;
+/**
+ * The narrowest box a horizontal condensed label is truncated into. When a
+ * category is narrower than this, only every n-th label is drawn so each one
+ * still has room for a few characters.
+ */
+const MIN_LABEL_WIDTH = 40;
+
+export interface XAxisLabelLayout {
+ /** 0 for horizontal labels, `ANGLED_LABEL_ROTATION` for rotated ones. */
+ angle: number;
+ /** Draw every `interval`-th label (1 = every label). */
+ interval: number;
+ /**
+ * Horizontal labels: the width each drawn label wraps or truncates to.
+ * Rotated labels: the longest text a label keeps before truncating.
+ */
+ labelWidth: number;
+ /** Lines the band holds; wrapped ("multiLine") labels truncate past it. */
+ maxLines: number;
+ /** Height of the label band. */
+ height: number;
+}
+
+export interface XAxisLabelLayoutOptions {
+ variant: XAxisTickVariant;
+ /** Width of one category on the x-axis. */
+ slotWidth: number;
+ /** The most height the label band may take. */
+ maxHeight: number;
+ lineHeight: number;
+ /**
+ * The condensed layout: every category shares the container width, so
+ * labels may be thinned, rotated ("angled") and get a gap between them. The
+ * scrolling layout draws every label at its category width.
+ */
+ condensed: boolean;
+}
+
+/**
+ * Lays out the x-axis category labels inside a band capped at `maxHeight`.
+ * The band never grows past the cap; labels that don't fit it are truncated
+ * with an ellipsis (the renderer shows the full text on hover).
+ */
+export function layoutXAxisLabels(
+ ctx: CanvasRenderingContext2D,
+ labels: string[],
+ { variant, slotWidth, maxHeight, lineHeight, condensed }: XAxisLabelLayoutOptions,
+): XAxisLabelLayout {
+ const singleLineHeight = Math.max(lineHeight + X_AXIS_LABEL_PADDING, MIN_X_AXIS_HEIGHT);
+ // One line of text always gets room, even in a chart too short to honour the cap.
+ const cap = Math.max(singleLineHeight, Math.floor(maxHeight));
+ const singleLine: XAxisLabelLayout = {
+ angle: 0,
+ interval: 1,
+ labelWidth: slotWidth,
+ maxLines: 1,
+ height: singleLineHeight,
+ };
+ if (labels.length === 0 || slotWidth <= 0) return singleLine;
+
+ const widest = Math.max(...labels.map((label) => ctx.measureText(label).width));
+
+ if (condensed && variant === "angled" && widest > slotWidth - LABEL_GAP) {
+ const sin = Math.sin((Math.abs(ANGLED_LABEL_ROTATION) * Math.PI) / 180);
+ // Neighbouring rotated labels are `slotWidth · sin` apart, measured across
+ // the text; below one line-height they would overlap, so thin them.
+ const interval = Math.max(1, Math.ceil(lineHeight / sin / slotWidth));
+ // A rotated label of text width L spans (L + lineHeight) · sin vertically.
+ const needed = Math.ceil((widest + lineHeight) * sin) + X_AXIS_TOP_GAP;
+ const height = Math.min(cap, Math.max(singleLineHeight, needed));
+ const labelWidth = Math.max(0, (height - X_AXIS_TOP_GAP) / sin - lineHeight);
+ return { angle: ANGLED_LABEL_ROTATION, interval, labelWidth, maxLines: 1, height };
+ }
+
+ let interval = 1;
+ let labelWidth = slotWidth;
+ if (condensed) {
+ const minWidth = Math.min(widest, MIN_LABEL_WIDTH) + LABEL_GAP;
+ interval = Math.min(labels.length, Math.max(1, Math.ceil(minWidth / slotWidth)));
+ labelWidth = slotWidth * interval - LABEL_GAP;
+ }
+ if (variant !== "multiLine") return { ...singleLine, interval, labelWidth };
+
+ const lineCap = Math.max(
+ 1,
+ Math.min(MAX_LABEL_LINES, Math.floor((cap - X_AXIS_LABEL_PADDING) / lineHeight)),
+ );
+ let lines = 1;
+ labels.forEach((label, i) => {
+ if (i % interval !== 0) return;
+ lines = Math.max(lines, wrapLabelLines(ctx, label, labelWidth, lineCap).length);
+ });
+ const height = Math.max(lines * lineHeight + X_AXIS_LABEL_PADDING, MIN_X_AXIS_HEIGHT);
+ return { angle: 0, interval, labelWidth, maxLines: lines, height };
+}
diff --git a/packages/react-ui/src/components/D3Charts/utils/yDomain.test.ts b/packages/react-ui/src/components/D3Charts/utils/yDomain.test.ts
new file mode 100644
index 000000000..f759b5c31
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/utils/yDomain.test.ts
@@ -0,0 +1,135 @@
+import { stack, stackOffsetNone, stackOrderNone } from "d3-shape";
+import { describe, expect, it } from "vitest";
+import { stackOffsetDivergingZeroPreserving } from "../hooks/cartesian/useStackedData";
+import { computeYDomain } from "./yDomain";
+
+const mixed = [
+ { m: "Jan", a: 40, b: -25, c: 10 },
+ { m: "Feb", a: -10, b: 60, c: -5 },
+ { m: "Mar", a: 0, b: 15, c: 20 },
+];
+const keys = ["a", "b", "c"];
+
+describe("computeYDomain (the shared scale/axis-width domain)", () => {
+ it("all-non-negative data keeps the historical [0, max] domain", () => {
+ const data = [
+ { m: "Jan", a: 40, b: 100 },
+ { m: "Feb", a: 70, b: 30 },
+ ];
+ expect(computeYDomain(data, ["a", "b"], false)).toEqual([0, 100]);
+ // stacked: max row sum = 140
+ expect(computeYDomain(data, ["a", "b"], true)).toEqual([0, 140]);
+ });
+
+ it("mixed-sign data spans the extent, always anchored through zero", () => {
+ expect(computeYDomain(mixed, keys, false)).toEqual([-25, 60]);
+ });
+
+ it("all-negative data yields [min, 0]", () => {
+ const data = [
+ { m: "Jan", a: -40 },
+ { m: "Feb", a: -5 },
+ ];
+ expect(computeYDomain(data, ["a"], false)).toEqual([-40, 0]);
+ });
+
+ it("stacked mixed-sign data = [lowest negative sum, highest positive sum]", () => {
+ // Jan: pos 40+10=50, neg -25 · Feb: pos 60, neg -15 · Mar: pos 35, neg 0
+ expect(computeYDomain(mixed, keys, true)).toEqual([-25, 60]);
+ });
+
+ it("matches the extent of the stack useStackedData actually renders", () => {
+ const series = stack<Record<string, string | number>>()
+ .keys(keys)
+ .order(stackOrderNone)
+ .offset(stackOffsetDivergingZeroPreserving)(mixed as Iterable<{ [key: string]: number }>);
+ let min = 0;
+ let max = 0;
+ for (const s of series) {
+ for (const point of s) {
+ min = Math.min(min, point[0], point[1]);
+ max = Math.max(max, point[0], point[1]);
+ }
+ }
+ expect(computeYDomain(mixed, keys, true)).toEqual([min, max]);
+ });
+
+ it('stacked "none" spans every running total — a negative lowers the stack', () => {
+ // Jan: 40, 15, 25 · Feb: -10, 50, 45 · Mar: 0, 15, 35
+ expect(computeYDomain(mixed, keys, true, "none")).toEqual([-10, 50]);
+ });
+
+ it('"none" matches the extent of the stackOffsetNone stack areas render', () => {
+ const series = stack<Record<string, string | number>>()
+ .keys(keys)
+ .order(stackOrderNone)
+ .offset(stackOffsetNone)(mixed as Iterable<{ [key: string]: number }>);
+ let min = 0;
+ let max = 0;
+ for (const s of series) {
+ for (const point of s) {
+ min = Math.min(min, point[0], point[1]);
+ max = Math.max(max, point[0], point[1]);
+ }
+ }
+ expect(computeYDomain(mixed, keys, true, "none")).toEqual([min, max]);
+ });
+
+ it('"none" and "sign" agree on all-non-negative data', () => {
+ const data = [
+ { m: "Jan", a: 40, b: 100 },
+ { m: "Feb", a: 70, b: 30 },
+ ];
+ expect(computeYDomain(data, ["a", "b"], true, "none")).toEqual(
+ computeYDomain(data, ["a", "b"], true, "sign"),
+ );
+ });
+
+ it("handles empty data and non-numeric cells", () => {
+ expect(computeYDomain([], keys, false)).toEqual([0, 0]);
+ expect(computeYDomain([{ m: "Jan", a: "oops" }], ["a"], false)).toEqual([0, 0]);
+ });
+});
+
+describe("stackOffsetDivergingZeroPreserving (the rendered stack offset)", () => {
+ const runStack = (
+ data: Array<Record<string, string | number>>,
+ offsetFn: typeof stackOffsetDivergingZeroPreserving,
+ stackKeys: string[],
+ ) =>
+ stack<Record<string, string | number>>()
+ .keys(stackKeys)
+ .order(stackOrderNone)
+ .offset(offsetFn)(data as Iterable<{ [key: string]: number }>)
+ .map((series) => series.map((p) => [p[0], p[1]]));
+
+ it("is IDENTICAL to stackOffsetNone for all-non-negative data — zeros included", () => {
+ // The pixel-identity guarantee. d3's own stackOffsetDiverging fails this:
+ // its zero branch re-bases [cum, cum] segments to [0, 0], dropping a
+ // stacked area band/line to the baseline wherever a value is exactly 0.
+ const data = [
+ { m: "Jan", a: 10, b: 0, c: 5 },
+ { m: "Feb", a: 0, b: 0, c: 0 },
+ { m: "Mar", a: 3.5, b: 7, c: 0 },
+ ];
+ const ks = ["a", "b", "c"];
+ expect(runStack(data, stackOffsetDivergingZeroPreserving, ks)).toEqual(
+ runStack(data, stackOffsetNone, ks),
+ );
+ });
+
+ it("diverges mixed signs: positives stack up from zero, negatives down", () => {
+ const data = [{ m: "Jan", a: 10, b: -5, c: 20, d: -15 }];
+ const [a, b, c, d] = runStack(data, stackOffsetDivergingZeroPreserving, ["a", "b", "c", "d"]);
+ expect(a![0]).toEqual([0, 10]); // positive, from zero up
+ expect(b![0]).toEqual([-5, 0]); // negative, from zero down
+ expect(c![0]).toEqual([10, 30]); // stacks on the positive total
+ expect(d![0]).toEqual([-20, -5]); // stacks on the negative total
+ });
+
+ it("zeros in mixed rows ride the positive running total", () => {
+ const data = [{ m: "Jan", a: 10, b: 0, c: -5 }];
+ const [, b] = runStack(data, stackOffsetDivergingZeroPreserving, ["a", "b", "c"]);
+ expect(b![0]).toEqual([10, 10]);
+ });
+});
diff --git a/packages/react-ui/src/components/D3Charts/utils/yDomain.ts b/packages/react-ui/src/components/D3Charts/utils/yDomain.ts
new file mode 100644
index 000000000..7f66d8615
--- /dev/null
+++ b/packages/react-ui/src/components/D3Charts/utils/yDomain.ts
@@ -0,0 +1,64 @@
+import type { ChartData } from "../types";
+
+/**
+ * How stacked series combine — the values mirror Recharts' `stackOffset`:
+ * - `"sign"`: positive values stack up from zero, negative values stack down
+ * (bars — Recharts bar charts use `stackOffset="sign"`).
+ * - `"none"`: one running total per row; a negative value lowers it (areas —
+ * Recharts area charts use the default `stackOffset`).
+ */
+export type StackOffset = "sign" | "none";
+
+/**
+ * The y domain for cartesian value charts, always anchored through zero.
+ *
+ * Non-stacked: `[min(0, dataMin), max(0, dataMax)]`. Stacked with `"sign"`:
+ * per-row positive values stack up from zero and negative values stack down —
+ * the offset `useStackedData` applies — so the extent is
+ * `[min(0, lowest negative sum), max(0, highest positive sum)]`. Stacked with
+ * `"none"`: the extent covers every intermediate running total of each row.
+ * All-non-negative data yields `[0, max]` either way.
+ *
+ * Single source of truth for BOTH `useYScale` (the rendered scale) and
+ * `useYAxisWidth` (tick-label measurement): the measured ticks are exactly the
+ * rendered ones by construction, including stacked totals — the old width hook
+ * measured per-value maxima and clipped stacked top ticks.
+ */
+export const computeYDomain = (
+ data: ChartData,
+ dataKeys: string[],
+ stacked: boolean,
+ stackOffset: StackOffset = "sign",
+): [number, number] => {
+ let min = 0;
+ let max = 0;
+
+ for (const row of data) {
+ if (stacked && stackOffset === "none") {
+ let total = 0;
+ for (const key of dataKeys) {
+ total += Number(row[key]) || 0;
+ if (total > max) max = total;
+ if (total < min) min = total;
+ }
+ } else if (stacked) {
+ let positiveSum = 0;
+ let negativeSum = 0;
+ for (const key of dataKeys) {
+ const value = Number(row[key]) || 0;
+ if (value >= 0) positiveSum += value;
+ else negativeSum += value;
+ }
+ if (positiveSum > max) max = positiveSum;
+ if (negativeSum < min) min = negativeSum;
+ } else {
+ for (const key of dataKeys) {
+ const value = Number(row[key]) || 0;
+ if (value > max) max = value;
+ if (value < min) min = value;
+ }
+ }
+ }
+
+ return [min, max];
+};
diff --git a/packages/react-ui/src/components/index.scss b/packages/react-ui/src/components/index.scss
index c8986403f..fce173441 100644
--- a/packages/react-ui/src/components/index.scss
+++ b/packages/react-ui/src/components/index.scss
@@ -22,6 +22,7 @@
@forward "./CodeBlock/codeBlock.scss";
@forward "./CompositeCardBlock/compositeCardBlock.scss";
@forward "./ContextCardBlock/contextCardBlock.scss";
+@forward "./D3Charts/d3Charts.scss";
@forward "./DatePicker/datePicker.scss";
@forward "./DotMatrixLoader/dotMatrixLoader.scss";
@forward "./EditableTable/editableTable.scss";
diff --git a/packages/react-ui/tsconfig.build.json b/packages/react-ui/tsconfig.build.json
index ccef19110..c84a837eb 100644
--- a/packages/react-ui/tsconfig.build.json
+++ b/packages/react-ui/tsconfig.build.json
@@ -4,6 +4,8 @@
"exclude": [
"vitest.config.ts",
"src/**/__tests__/**",
+ "src/**/*.test.ts",
+ "src/**/*.test.tsx",
"src/**/stories/**",
"src/__test-helpers/**",
"src/scripts/**",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index eb59f0c8b..3ade92a3e 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -724,6 +724,15 @@ importers:
clsx:
specifier: ^2.1.1
version: 2.1.1
+ 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
date-fns:
specifier: ^4.1.0
version: 4.4.0
@@ -821,6 +830,15 @@ importers:
'@storybook/theming':
specifier: ^8.5.3
+ '@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.1.8
+ version: 3.1.8
'@types/lodash-es':
specifier: ^4.17.12
version: 4.17.12