Skip to content

The Open Standard for Generative UI

fix(react-ui): refactor step curve, scrolling x-axis labels, donut and radar hover in the D3 charts (#1269)

Subham Dasdd4f45074ac5
diff --git a/.changeset/slimy-suits-look.md b/.changeset/slimy-suits-look.md
new file mode 100644
index 000000000..0b2d40bab
--- /dev/null
+++ b/.changeset/slimy-suits-look.md
@@ -0,0 +1,10 @@
+---
+"@openuidev/react-ui": patch
+---
+
+Fixes to the D3 charts from QA:
+
+- Area and line charts with `variant="step"` step halfway between points, as the Recharts charts did, so the first and last values get a flat run too.
+- The scrolling `BarChart`, `AreaChart` and `LineChart` widen their categories so long x-axis labels show in full, and scroll further. A category grows to at most three times its usual width and at most half the chart; longer labels, and labels in the condensed charts, are truncated with the full text on hover.
+- The donut `PieChart` is a thin band in the slice colors over grey track wedges again, with slices 0.5° apart; `paddingAngle` sets the pie's gaps only.
+- `RadarChart` marks the hovered axis with a dot on each series. The dots glide between axes and fade in and out, like the line and area charts' hover dots.
diff --git a/packages/react-ui/src/components/Charts/AreaChart/parts/AreaSeries.tsx b/packages/react-ui/src/components/Charts/AreaChart/parts/AreaSeries.tsx
index 0f382451b..8eef062b3 100644
--- a/packages/react-ui/src/components/Charts/AreaChart/parts/AreaSeries.tsx
+++ b/packages/react-ui/src/components/Charts/AreaChart/parts/AreaSeries.tsx
@@ -1,19 +1,18 @@
import type { ScaleLinear, ScalePoint } from "d3-scale";
-import { type CurveFactory, curveLinear, curveMonotoneX, curveStepAfter } from "d3-shape";
+import type { CurveFactory } 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 {
+ AREA_STRIDE,
+ buildAreaD,
+ buildAreaEdgeD,
+ seriesCurve,
+} 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[];
@@ -41,13 +40,7 @@ export const AreaSeries: React.FC<AreaSeriesProps> = ({
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;
+ const curve = seriesCurve(variant);
// Target geometry per series: flat `[x, y0, y1, yEdge]` pixel scalars (see
// seriesGeometry.ts for the layout) + the two paths built from them. React
diff --git a/packages/react-ui/src/components/Charts/BarChart/BarChart.tsx b/packages/react-ui/src/components/Charts/BarChart/BarChart.tsx
index f355a9494..7b526cbd3 100644
--- a/packages/react-ui/src/components/Charts/BarChart/BarChart.tsx
+++ b/packages/react-ui/src/components/Charts/BarChart/BarChart.tsx
@@ -2,6 +2,7 @@ import clsx from "clsx";
import { useCallback } from "react";
import {
+ BAND_PADDING_INNER,
useCartesianChartOrchestrator,
useEffectiveAnimation,
useExportChartData,
@@ -93,6 +94,8 @@ function BarChartImpl<T extends BarChartData>({
density,
stacked: variant === "stacked",
yTickCount,
+ // Labels are drawn under the bar's band, not across the whole category.
+ labelShare: 1 - BAND_PADDING_INNER,
});
const isStacked = variant === "stacked";
diff --git a/packages/react-ui/src/components/Charts/LineChart/parts/LineSeries.tsx b/packages/react-ui/src/components/Charts/LineChart/parts/LineSeries.tsx
index a12b3c97c..8906ea777 100644
--- a/packages/react-ui/src/components/Charts/LineChart/parts/LineSeries.tsx
+++ b/packages/react-ui/src/components/Charts/LineChart/parts/LineSeries.tsx
@@ -1,18 +1,12 @@
import type { ScaleLinear, ScalePoint } from "d3-scale";
-import { type CurveFactory, curveLinear, curveMonotoneX, curveStepAfter } from "d3-shape";
+import type { CurveFactory } from "d3-shape";
import React, { useMemo, useRef } from "react";
import { AnimatedPath } from "../../shared/cartesian/AnimatedPath";
-import { buildLineD, LINE_STRIDE } from "../../shared/cartesian/seriesGeometry";
+import { buildLineD, LINE_STRIDE, seriesCurve } 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[];
@@ -38,13 +32,7 @@ export const LineSeries: React.FC<LineSeriesProps> = ({
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;
+ const curve = seriesCurve(variant);
// Target geometry per series: flat point pixels + the d built from them.
// React commits these as the attributes (SSR/print/snap correct by
diff --git a/packages/react-ui/src/components/Charts/PieChart/PieChart.tsx b/packages/react-ui/src/components/Charts/PieChart/PieChart.tsx
index 70c40ed54..cce73b8b6 100644
--- a/packages/react-ui/src/components/Charts/PieChart/PieChart.tsx
+++ b/packages/react-ui/src/components/Charts/PieChart/PieChart.tsx
@@ -16,6 +16,15 @@ import { CHART_CLASS_PREFIX } from "../utils/constants";
import { PieSlices } from "./parts/PieSlices";
import type { PieChartData, PieChartProps } from "./types";
+// The donut is the Recharts two-ring design: a thin band in the slice colors
+// over sunk-colored "track" wedges, with a small hole at the center.
+/** Where the colored band starts, as a share of the radius (the outer tenth). */
+const DONUT_BAND_INNER = 0.9;
+/** The center hole's radius, as a share of the band's inner radius. */
+const DONUT_HOLE = 0.28;
+/** Degrees between donut slices; `paddingAngle` sets the pie's only. */
+const DONUT_PADDING_ANGLE = 0.5;
+
/**
* `legendVariant="stacked"` (the default) 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
@@ -80,8 +89,11 @@ function PieChartImpl<T extends PieChartData>(props: PieChartProps<T>) {
const animate = useEffectiveAnimation(isAnimationActive);
// Pie-specific geometry
+ const isDonut = variant === "donut";
+ const padAngle = isDonut ? DONUT_PADDING_ANGLE : paddingAngle;
const outerRadius = orch.dimensions.chartSize * 0.45;
- const innerRadius = variant === "donut" ? outerRadius * 0.6 : 0;
+ const innerRadius = isDonut ? outerRadius * DONUT_BAND_INNER : 0;
+ const holeRadius = innerRadius * DONUT_HOLE;
const startAngle = isSemiCircular ? -Math.PI / 2 : 0;
const endAngle = isSemiCircular ? Math.PI / 2 : 2 * Math.PI;
@@ -93,18 +105,34 @@ function PieChartImpl<T extends PieChartData>(props: PieChartProps<T>) {
.sort(null)
.startAngle(startAngle)
.endAngle(endAngle)
- .padAngle((paddingAngle * Math.PI) / 180),
- [startAngle, endAngle, paddingAngle],
+ .padAngle((padAngle * Math.PI) / 180),
+ [startAngle, endAngle, padAngle],
);
- const arcGenerator = useMemo(
- () =>
+ const arcGenerator = useMemo(() => {
+ const generator = arc<unknown, PieArcDatum<CategoricalSlice>>()
+ .innerRadius(innerRadius)
+ .outerRadius(outerRadius)
+ .cornerRadius(cornerRadius);
+ // The donut's band and track share one pad radius, so each gap between
+ // slices runs straight through both rings.
+ return isDonut ? generator.padRadius(outerRadius) : generator;
+ }, [isDonut, innerRadius, outerRadius, cornerRadius]);
+
+ // Donut only: the track wedge under each band segment, and the hover area
+ // that spans both.
+ const donutArcs = useMemo(() => {
+ if (!isDonut) return undefined;
+ const donutArc = (inner: number, outer: number) =>
arc<unknown, PieArcDatum<CategoricalSlice>>()
- .innerRadius(innerRadius)
- .outerRadius(outerRadius)
- .cornerRadius(cornerRadius),
- [innerRadius, outerRadius, cornerRadius],
- );
+ .innerRadius(inner)
+ .outerRadius(outer)
+ .padRadius(outerRadius);
+ return {
+ track: donutArc(holeRadius, innerRadius).cornerRadius(cornerRadius),
+ hit: donutArc(holeRadius, outerRadius),
+ };
+ }, [isDonut, holeRadius, innerRadius, outerRadius, cornerRadius]);
const arcs = useMemo(
() => pieGenerator(orch.data.visibleSlices),
@@ -146,6 +174,8 @@ function PieChartImpl<T extends PieChartData>(props: PieChartProps<T>) {
<PieSlices
arcs={arcs}
arcGenerator={arcGenerator}
+ trackArcGenerator={donutArcs?.track}
+ hitArcGenerator={donutArcs?.hit}
slices={orch.data.visibleSlices}
hoveredIndex={orch.hover.hoveredIndex}
entrance={animate}
diff --git a/packages/react-ui/src/components/Charts/PieChart/parts/PieSlices.tsx b/packages/react-ui/src/components/Charts/PieChart/parts/PieSlices.tsx
index 780d3aac4..094932baf 100644
--- a/packages/react-ui/src/components/Charts/PieChart/parts/PieSlices.tsx
+++ b/packages/react-ui/src/components/Charts/PieChart/parts/PieSlices.tsx
@@ -1,3 +1,4 @@
+import clsx from "clsx";
import type { Arc, PieArcDatum } from "d3-shape";
import React from "react";
import type { CategoricalSlice } from "../../hooks";
@@ -10,6 +11,9 @@ 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;
+// The donut's track wedges take their sunk fill from the stylesheet.
+const TRACK_CLASS = `${CHART_CLASS_PREFIX}-pie-chart-track`;
+
// 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) {
@@ -23,6 +27,10 @@ function sliceOffset(startAngle: number, endAngle: number, distance: number) {
interface PieSlicesProps<T> {
arcs: PieArcDatum<CategoricalSlice>[];
arcGenerator: Arc<unknown, PieArcDatum<CategoricalSlice>>;
+ /** Donut: the sunk-colored track wedge drawn under each band segment. */
+ trackArcGenerator?: Arc<unknown, PieArcDatum<CategoricalSlice>>;
+ /** Donut: the hover area of a slice, band and track together. Default: the slice itself. */
+ hitArcGenerator?: Arc<unknown, PieArcDatum<CategoricalSlice>>;
slices: CategoricalSlice[];
hoveredIndex: number | null;
/** Play the entrance animation (pre-folded with ¬printing at the entry). */
@@ -38,6 +46,8 @@ interface PieSlicesProps<T> {
export function PieSlices<T>({
arcs,
arcGenerator,
+ trackArcGenerator,
+ hitArcGenerator,
slices,
hoveredIndex,
entrance,
@@ -56,27 +66,30 @@ export function PieSlices<T>({
if (!slice) return null;
const pathD = arcGenerator(arc);
if (!pathD) return null;
+ const trackD = trackArcGenerator?.(arc) ?? undefined;
- // Print: one inert path, handlers on it, no hitbox, no spring.
+ // Print: inert paths (the donut adds its track), handlers on them, 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) {
+ const staticProps = {
+ style: {
+ ...getSliceStyle(i, hoveredIndex),
+ cursor: onClick ? "pointer" : undefined,
+ transition: POLAR_HOVER_TRANSITION,
+ },
+ onMouseMove: (e: React.MouseEvent) => onMouseMove(e, i),
+ onMouseLeave,
+ onClick: () => handleClick(i),
+ };
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)}
- />
+ <React.Fragment key={slice.label}>
+ {trackD && <path d={trackD} className={TRACK_CLASS} {...staticProps} />}
+ <path d={pathD} fill={slice.color} {...staticProps} />
+ </React.Fragment>
);
}
@@ -84,6 +97,8 @@ export function PieSlices<T>({
<Slice
key={slice.label}
pathD={pathD}
+ trackD={trackD}
+ hitD={hitArcGenerator?.(arc) ?? pathD}
color={slice.color}
sliceStyle={getSliceStyle(i, hoveredIndex)}
hovered={hoveredIndex === i}
@@ -103,6 +118,8 @@ export function PieSlices<T>({
interface SliceProps {
pathD: string;
+ trackD?: string;
+ hitD: string;
color: string;
sliceStyle: React.CSSProperties;
hovered: boolean;
@@ -128,6 +145,8 @@ interface SliceProps {
*/
function Slice({
pathD,
+ trackD,
+ hitD,
color,
sliceStyle,
hovered,
@@ -164,7 +183,7 @@ function Slice({
`transparent` (a painted region) — `none` would make the interior non-painted
and silently kill hover under the default `visiblePainted`. */}
<path
- d={pathD}
+ d={hitD}
fill="transparent"
style={{
pointerEvents: "all",
@@ -177,6 +196,13 @@ function Slice({
{/* 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" }}>
+ {trackD && (
+ <path
+ d={trackD}
+ className={clsx(TRACK_CLASS, entranceClass)}
+ style={{ ...baseStyle, animationDelay: entranceDelay }}
+ />
+ )}
<path
d={pathD}
fill={color}
diff --git a/packages/react-ui/src/components/Charts/PieChart/pieChart.scss b/packages/react-ui/src/components/Charts/PieChart/pieChart.scss
index 8fac0e63a..13b845ef3 100644
--- a/packages/react-ui/src/components/Charts/PieChart/pieChart.scss
+++ b/packages/react-ui/src/components/Charts/PieChart/pieChart.scss
@@ -1,9 +1,15 @@
+@use "../../../cssUtils" as cssUtils;
@use "../shared/cartesian/chartBase" as base;
@use "../prefix" as brand;
@include base.centered-container("pie-chart");
@include base.centered-svg-wrapper("pie-chart");
+// The donut's inner wedges, under the thin colored band.
+.#{brand.$prefix}-pie-chart-track {
+ fill: cssUtils.$sunk;
+}
+
// 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.
diff --git a/packages/react-ui/src/components/Charts/PieChart/types.ts b/packages/react-ui/src/components/Charts/PieChart/types.ts
index b6cbafcb1..38b63fb4b 100644
--- a/packages/react-ui/src/components/Charts/PieChart/types.ts
+++ b/packages/react-ui/src/components/Charts/PieChart/types.ts
@@ -31,6 +31,10 @@ export interface PieChartProps<T extends PieChartData> {
*/
isAnimationActive?: boolean;
cornerRadius?: number;
+ /**
+ * Degrees between the pie's slices. Default 0. The donut always keeps a
+ * 0.5° gap, as the Recharts donut did.
+ */
paddingAngle?: number;
maxChartSize?: number;
minChartSize?: number;
diff --git a/packages/react-ui/src/components/Charts/RadarChart/parts/RadarSeries.tsx b/packages/react-ui/src/components/Charts/RadarChart/parts/RadarSeries.tsx
index b85f72894..b76fb5740 100644
--- a/packages/react-ui/src/components/Charts/RadarChart/parts/RadarSeries.tsx
+++ b/packages/react-ui/src/components/Charts/RadarChart/parts/RadarSeries.tsx
@@ -1,5 +1,6 @@
import type { ScaleLinear } from "d3-scale";
+import { FadeFollower } from "../../shared/core/spring";
import type { ChartData } from "../../types";
import { CHART_CLASS_PREFIX } from "../../utils/constants";
import { entranceProps } from "../../utils/entranceUtils";
@@ -46,11 +47,15 @@ export function RadarSeries<T extends ChartData>({
hoveredIndex,
animate,
}: RadarSeriesProps<T>) {
+ const series = dataKeys.map((key) => ({
+ key,
+ color: colorMap[key] ?? "#000",
+ vertices: computeVertices(data, key, numAxes, radialScale),
+ }));
+
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);
+ {series.map(({ key, color, vertices }, seriesIdx) => {
const points = vertices.map((v) => `${v.x},${v.y}`).join(" ");
const { className: animationClass, animationDelay } = entranceProps(
@@ -95,6 +100,27 @@ export function RadarSeries<T extends ChartData>({
</g>
);
})}
+ {/* The hovered axis gets an active dot where each series crosses it (the
+ Recharts radar's activeDot). Like the line/area crosshair dots they stay
+ mounted, glide from axis to axis and fade in and out. Vertex dots, when
+ on, show the hover themselves. */}
+ {!showDots && (
+ <g className={`${CHART_CLASS_PREFIX}-radar-chart-active-dots`}>
+ {series.map(({ key, color, vertices }) => {
+ const v = hoveredIndex !== null ? vertices[hoveredIndex] : undefined;
+ return (
+ <FadeFollower key={key} x={v?.x ?? 0} y={v?.y ?? 0} visible={v !== undefined}>
+ <circle r={4} className={`${CHART_CLASS_PREFIX}-radar-chart-active-dot-outer`} />
+ <circle
+ r={2}
+ fill={color}
+ className={`${CHART_CLASS_PREFIX}-radar-chart-active-dot-inner`}
+ />
+ </FadeFollower>
+ );
+ })}
+ </g>
+ )}
</g>
);
}
diff --git a/packages/react-ui/src/components/Charts/RadarChart/radarChart.scss b/packages/react-ui/src/components/Charts/RadarChart/radarChart.scss
index f63a12f19..6bdd490d4 100644
--- a/packages/react-ui/src/components/Charts/RadarChart/radarChart.scss
+++ b/packages/react-ui/src/components/Charts/RadarChart/radarChart.scss
@@ -41,6 +41,12 @@
opacity 0.15s ease;
}
+@include base.active-dot-styles("radar-chart");
+
+.#{brand.$prefix}-radar-chart-active-dots {
+ pointer-events: none;
+}
+
.#{brand.$prefix}-radar-chart-axis-label {
@include base.svg-tick-label;
}
diff --git a/packages/react-ui/src/components/Charts/hooks/cartesian/useCartesianChartOrchestrator.ts b/packages/react-ui/src/components/Charts/hooks/cartesian/useCartesianChartOrchestrator.ts
index 63f272f69..fc2819ea6 100644
--- a/packages/react-ui/src/components/Charts/hooks/cartesian/useCartesianChartOrchestrator.ts
+++ b/packages/react-ui/src/components/Charts/hooks/cartesian/useCartesianChartOrchestrator.ts
@@ -40,6 +40,12 @@ export interface UseCartesianChartOrchestratorParams<T extends ChartData> {
* same tick strings the axis will draw.
*/
yTickCount?: number;
+ /**
+ * Share of a category's width its x-axis label is drawn in: bar charts draw
+ * it under the bar's band, line and area charts across the whole category
+ * (the default, 1). Lets the scrolling layout size categories for full labels.
+ */
+ labelShare?: number;
}
/**
@@ -68,6 +74,7 @@ export function useCartesianChartOrchestrator<T extends ChartData>({
stacked,
stackOffset,
yTickCount,
+ labelShare,
}: UseCartesianChartOrchestratorParams<T>): CartesianChartOrchestrator {
const containerRef = useRef<HTMLDivElement>(null);
const mainContainerRef = useRef<HTMLDivElement>(null);
@@ -101,6 +108,7 @@ export function useCartesianChartOrchestrator<T extends ChartData>({
stacked,
stackOffset,
yTickCount,
+ labelShare,
});
// Hover: index, mouse position, handler factory
@@ -111,7 +119,7 @@ export function useCartesianChartOrchestrator<T extends ChartData>({
mainContainerRef,
data,
needsScroll: dimensions.needsScroll,
- density,
+ widthOfGroup: dimensions.widthOfGroup,
});
// Legend expand/collapse
diff --git a/packages/react-ui/src/components/Charts/hooks/cartesian/useChartDimensions.ts b/packages/react-ui/src/components/Charts/hooks/cartesian/useChartDimensions.ts
index 6ae649f8f..178fad771 100644
--- a/packages/react-ui/src/components/Charts/hooks/cartesian/useChartDimensions.ts
+++ b/packages/react-ui/src/components/Charts/hooks/cartesian/useChartDimensions.ts
@@ -46,6 +46,11 @@ export interface UseChartDimensionsParams<T extends ChartData> {
* ones when the consumer pins the count (YAxis/Grid receive the same hint).
*/
yTickCount?: number;
+ /**
+ * Share of a category's width its x-axis label is drawn in (see
+ * `XAxisLabelLayoutOptions.labelShare`). Default 1.
+ */
+ labelShare?: number;
}
/**
@@ -71,6 +76,7 @@ export function useChartDimensions<T extends ChartData>({
stacked = false,
stackOffset,
yTickCount,
+ labelShare,
}: UseChartDimensionsParams<T>) {
const isFit = layout === "fit";
@@ -94,25 +100,6 @@ export function useChartDimensions<T extends ChartData>({
// 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
@@ -129,18 +116,40 @@ export function useChartDimensions<T extends ChartData>({
: "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.
+ // the rest. Fit divides the available width across all points and truncates
+ // the labels that don't fit. Scroll starts from a fixed density-derived width
+ // (which is what lets it overflow) and widens it — never past the visible
+ // plot — until every label shows in full.
const labelLayout = useXAxisLabelLayout(
data,
catKey,
{
variant: tickVariant,
- slotWidth: widthOfGroup,
+ slotWidth: isFit
+ ? data.length > 0
+ ? availableWidth / data.length
+ : 0
+ : getWidthOfGroup(density),
maxHeight: (svgAvailableHeight - CHART_MARGIN_TOP) * MAX_X_AXIS_HEIGHT_SHARE,
condensed: isFit,
+ visibleWidth: isFit ? undefined : availableWidth,
+ labelShare,
},
containerRef,
);
+ // Per-point group width.
+ const widthOfGroup = labelLayout.slotWidth;
+
+ const dataWidth = useMemo(
+ () => (isFit ? availableWidth : getWidthOfData(data, availableWidth, widthOfGroup)),
+ [isFit, data, availableWidth, widthOfGroup],
+ );
+ 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 labelInterval = labelLayout.interval;
const xAxis = {
angle: labelLayout.angle,
diff --git a/packages/react-ui/src/components/Charts/hooks/cartesian/useChartScroll.ts b/packages/react-ui/src/components/Charts/hooks/cartesian/useChartScroll.ts
index abe430952..485d98654 100644
--- a/packages/react-ui/src/components/Charts/hooks/cartesian/useChartScroll.ts
+++ b/packages/react-ui/src/components/Charts/hooks/cartesian/useChartScroll.ts
@@ -3,20 +3,20 @@ 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;
+ /** Width of one category group; the scroll buttons step one group at a time. */
+ widthOfGroup: number;
}
export function useChartScroll<T extends ChartData>({
mainContainerRef,
data,
needsScroll,
- density,
+ widthOfGroup,
}: UseChartScrollParams<T>) {
const [canScrollLeft, setCanScrollLeft] = useState(false);
const [canScrollRight, setCanScrollRight] = useState(needsScroll);
@@ -47,12 +47,12 @@ export function useChartScroll<T extends ChartData>({
(direction: "left" | "right") => {
const el = mainContainerRef.current;
if (!el) return;
- const snaps = getSnapPositions(data, density);
+ const snaps = getSnapPositions(data, widthOfGroup);
const idx = findNearestSnapPosition(snaps, el.scrollLeft, direction);
const target = snaps[idx] ?? 0;
el.scrollTo({ left: target, behavior: "smooth" });
},
- [data, mainContainerRef, density],
+ [data, mainContainerRef, widthOfGroup],
);
return {
diff --git a/packages/react-ui/src/components/Charts/hooks/cartesian/useXAxisLabelLayout.ts b/packages/react-ui/src/components/Charts/hooks/cartesian/useXAxisLabelLayout.ts
index 0cd4ac854..b75a469f7 100644
--- a/packages/react-ui/src/components/Charts/hooks/cartesian/useXAxisLabelLayout.ts
+++ b/packages/react-ui/src/components/Charts/hooks/cartesian/useXAxisLabelLayout.ts
@@ -20,15 +20,33 @@ export const useXAxisLabelLayout = (
scopeRef?: React.RefObject<HTMLElement | null>,
): XAxisLabelLayout => {
const context = useCanvasContextForLabelSize(scopeRef);
- const { variant, slotWidth, maxHeight, condensed } = options;
+ const { variant, slotWidth, maxHeight, condensed, visibleWidth, labelShare } = options;
return useMemo(
() =>
layoutXAxisLabels(
context,
data.map((d) => String(d[categoryKey])),
- { variant, slotWidth, maxHeight, condensed, lineHeight: parseLineHeight(context.font) },
+ {
+ variant,
+ slotWidth,
+ maxHeight,
+ condensed,
+ visibleWidth,
+ labelShare,
+ lineHeight: parseLineHeight(context.font),
+ },
),
- [context, data, categoryKey, variant, slotWidth, maxHeight, condensed],
+ [
+ context,
+ data,
+ categoryKey,
+ variant,
+ slotWidth,
+ maxHeight,
+ condensed,
+ visibleWidth,
+ labelShare,
+ ],
);
};
diff --git a/packages/react-ui/src/components/Charts/hooks/cartesian/useXBandScale.ts b/packages/react-ui/src/components/Charts/hooks/cartesian/useXBandScale.ts
index 0bef4f4b5..b0a4ac6da 100644
--- a/packages/react-ui/src/components/Charts/hooks/cartesian/useXBandScale.ts
+++ b/packages/react-ui/src/components/Charts/hooks/cartesian/useXBandScale.ts
@@ -3,6 +3,11 @@ import { scaleBand } from "d3-scale";
import { useMemo } from "react";
import type { ChartData } from "../../types";
+/** Default gap between bands, as a share of each category's step. */
+export const BAND_PADDING_INNER = 0.2;
+/** Default space before the first and after the last band, as a share of a step. */
+export const BAND_PADDING_OUTER = 0.1;
+
export const useXBandScale = (
data: ChartData,
categoryKey: string,
@@ -14,7 +19,7 @@ export const useXBandScale = (
return scaleBand<string>()
.domain(data.map((d) => String(d[categoryKey])))
.range([0, svgWidth])
- .paddingInner(paddingInner ?? 0.2)
- .paddingOuter(paddingOuter ?? 0.1);
+ .paddingInner(paddingInner ?? BAND_PADDING_INNER)
+ .paddingOuter(paddingOuter ?? BAND_PADDING_OUTER);
}, [data, categoryKey, svgWidth, paddingInner, paddingOuter]);
};
diff --git a/packages/react-ui/src/components/Charts/shared/cartesian/chartBase.scss b/packages/react-ui/src/components/Charts/shared/cartesian/chartBase.scss
index 26fdab811..36d145b6e 100644
--- a/packages/react-ui/src/components/Charts/shared/cartesian/chartBase.scss
+++ b/packages/react-ui/src/components/Charts/shared/cartesian/chartBase.scss
@@ -121,13 +121,9 @@
text-align: center;
}
-@mixin crosshair-styles($prefix) {
- .#{brand.$prefix}-#{$prefix}-crosshair-line {
- stroke: cssUtils.$border-default;
- stroke-width: 1;
- stroke-dasharray: 4 4;
- }
-
+// The hover dot on a series: a foreground ring around a dot in the series
+// color. Shared by the line/area crosshair and the radar chart.
+@mixin active-dot-styles($prefix) {
.#{brand.$prefix}-#{$prefix}-active-dot-outer {
fill: cssUtils.$foreground;
stroke: cssUtils.$border-default;
@@ -139,6 +135,16 @@
}
}
+@mixin crosshair-styles($prefix) {
+ .#{brand.$prefix}-#{$prefix}-crosshair-line {
+ stroke: cssUtils.$border-default;
+ stroke-width: 1;
+ stroke-dasharray: 4 4;
+ }
+
+ @include active-dot-styles($prefix);
+}
+
// 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.
diff --git a/packages/react-ui/src/components/Charts/shared/cartesian/seriesGeometry.test.ts b/packages/react-ui/src/components/Charts/shared/cartesian/seriesGeometry.test.ts
index 3c261ee7e..f645a13b9 100644
--- a/packages/react-ui/src/components/Charts/shared/cartesian/seriesGeometry.test.ts
+++ b/packages/react-ui/src/components/Charts/shared/cartesian/seriesGeometry.test.ts
@@ -1,6 +1,13 @@
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";
+import {
+ AREA_STRIDE,
+ buildAreaD,
+ buildAreaEdgeD,
+ buildLineD,
+ LINE_STRIDE,
+ seriesCurve,
+} from "./seriesGeometry";
type Pt = { x: number; y0: number; y1: number; yEdge: number };
@@ -59,3 +66,20 @@ describe("flat-vector path builders match direct d3 output", () => {
expect(buildAreaEdgeD(new Float64Array(0), curveLinear)).toBe("");
});
});
+
+describe("seriesCurve (line/area variant → curve)", () => {
+ it("steps halfway between points, so the last value keeps a flat run", () => {
+ // Two points 100px apart: flat to the midpoint, up, flat to the last point.
+ const two = Float64Array.from([0, 10, 100, 20]);
+ expect(buildLineD(two, seriesCurve("step"))).toBe("M0,10L50,10L50,20L100,20");
+ });
+
+ it("maps linear and natural, and falls back to natural for anything else", () => {
+ expect(seriesCurve("linear")).toBe(curveLinear);
+ expect(seriesCurve("natural")).toBe(curveMonotoneX);
+ // Streaming placeholders and unknown values must still yield a curve.
+ expect(seriesCurve("")).toBe(curveMonotoneX);
+ expect(seriesCurve(undefined)).toBe(curveMonotoneX);
+ expect(seriesCurve("constructor")).toBe(curveMonotoneX);
+ });
+});
diff --git a/packages/react-ui/src/components/Charts/shared/cartesian/seriesGeometry.ts b/packages/react-ui/src/components/Charts/shared/cartesian/seriesGeometry.ts
index a694fa592..bdddc6615 100644
--- a/packages/react-ui/src/components/Charts/shared/cartesian/seriesGeometry.ts
+++ b/packages/react-ui/src/components/Charts/shared/cartesian/seriesGeometry.ts
@@ -16,11 +16,37 @@
//
// Pure (no DOM, no React) — unit-tested directly.
-import { area as d3Area, line as d3Line, type CurveFactory } from "d3-shape";
+import {
+ curveLinear,
+ curveMonotoneX,
+ curveStep,
+ area as d3Area,
+ line as d3Line,
+ type CurveFactory,
+} from "d3-shape";
export const LINE_STRIDE = 2;
export const AREA_STRIDE = 4;
+/**
+ * The line/area curve for a chart `variant`. "step" steps halfway between
+ * points, as the Recharts charts did, so the first and last values get a flat
+ * run too (step-after left the last value as a bare vertical tick). Anything
+ * else falls back to "natural", the charts' default: while streaming, the
+ * parser can hand over a placeholder (e.g. "") before the real value arrives,
+ * and d3-shape throws "curve is not a function" on an undefined curve.
+ */
+export function seriesCurve(variant: string | undefined): CurveFactory {
+ switch (variant) {
+ case "linear":
+ return curveLinear;
+ case "step":
+ return curveStep;
+ default:
+ return curveMonotoneX;
+ }
+}
+
/** 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);
diff --git a/packages/react-ui/src/components/Charts/types/common.ts b/packages/react-ui/src/components/Charts/types/common.ts
index f441914d9..699f2584e 100644
--- a/packages/react-ui/src/components/Charts/types/common.ts
+++ b/packages/react-ui/src/components/Charts/types/common.ts
@@ -16,8 +16,10 @@ export interface BaseChartProps<T extends ChartData> {
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.
+ * than half the chart's height. Scrolling charts widen their categories (to
+ * at most three times the usual width, and at most half the chart) so the
+ * labels show in full; labels that still don't fit, and labels in condensed
+ * charts, 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.
diff --git a/packages/react-ui/src/components/Charts/utils/scrollUtils.test.ts b/packages/react-ui/src/components/Charts/utils/scrollUtils.test.ts
index d746cea75..f6b796020 100644
--- a/packages/react-ui/src/components/Charts/utils/scrollUtils.test.ts
+++ b/packages/react-ui/src/components/Charts/utils/scrollUtils.test.ts
@@ -1,5 +1,10 @@
import { describe, expect, it } from "vitest";
-import { findNearestSnapPosition, getWidthOfData, getWidthOfGroup } from "./scrollUtils";
+import {
+ findNearestSnapPosition,
+ getSnapPositions,
+ getWidthOfData,
+ getWidthOfGroup,
+} from "./scrollUtils";
const rows = (n: number) => Array.from({ length: n }, (_, i) => ({ x: i }));
@@ -18,8 +23,10 @@ describe("getWidthOfGroup (density → px per category group)", () => {
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);
+ expect(getWidthOfData(rows(10), 300, getWidthOfGroup("compact"))).toBe(480);
+ expect(getWidthOfData(rows(10), 300, getWidthOfGroup("spacious"))).toBe(960);
+ // a group widened to fit its labels
+ expect(getWidthOfData(rows(10), 300, 130)).toBe(1300);
});
it("floors at the available container width (no horizontal scroll)", () => {
@@ -32,9 +39,17 @@ describe("getWidthOfData (inner scroll width)", () => {
});
it("floors a single point at 200px when the container is narrower than a group", () => {
- expect(getWidthOfData(rows(1), 40, "compact")).toBe(200);
+ expect(getWidthOfData(rows(1), 40, getWidthOfGroup("compact"))).toBe(200);
// …but a container wider than the group still wins
- expect(getWidthOfData(rows(1), 500, "compact")).toBe(500);
+ expect(getWidthOfData(rows(1), 500, getWidthOfGroup("compact"))).toBe(500);
+ });
+});
+
+describe("getSnapPositions (one stop per group)", () => {
+ it("steps by the group width", () => {
+ expect(getSnapPositions(rows(4))).toEqual([0, 72, 144, 216]);
+ expect(getSnapPositions(rows(3), 130)).toEqual([0, 130, 260]);
+ expect(getSnapPositions([], 130)).toEqual([0]);
});
});
diff --git a/packages/react-ui/src/components/Charts/utils/scrollUtils.ts b/packages/react-ui/src/components/Charts/utils/scrollUtils.ts
index c0520469f..54fe6318e 100644
--- a/packages/react-ui/src/components/Charts/utils/scrollUtils.ts
+++ b/packages/react-ui/src/components/Charts/utils/scrollUtils.ts
@@ -12,12 +12,12 @@ const MIN_SINGLE_POINT_WIDTH = 200;
export const getWidthOfData = (
data: ChartData,
containerWidth: number,
- density: ChartDensity = "default",
+ groupWidth: number = getWidthOfGroup(),
) => {
if (data.length === 0) {
return containerWidth;
}
- const width = data.length * getWidthOfGroup(density);
+ const width = data.length * groupWidth;
if (containerWidth >= width) {
return containerWidth;
@@ -56,14 +56,16 @@ export function getWidthOfGroup(density: ChartDensity = "default"): number {
return DENSITY_SPACING[density];
}
-export const getSnapPositions = (data: ChartData, density: ChartDensity = "default"): number[] => {
+export const getSnapPositions = (
+ data: ChartData,
+ groupWidth: number = getWidthOfGroup(),
+): 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);
+ positions.push(i * groupWidth);
}
return positions;
diff --git a/packages/react-ui/src/components/Charts/utils/xAxisLabelLayout.test.ts b/packages/react-ui/src/components/Charts/utils/xAxisLabelLayout.test.ts
index 28c11ae1b..83e99c798 100644
--- a/packages/react-ui/src/components/Charts/utils/xAxisLabelLayout.test.ts
+++ b/packages/react-ui/src/components/Charts/utils/xAxisLabelLayout.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";
-import { ANGLED_LABEL_ROTATION, layoutXAxisLabels } from "./xAxisLabelLayout";
+import { wrapLabelLines } from "./labelWrap";
+import { ANGLED_LABEL_ROTATION, fullLabelWidth, layoutXAxisLabels } from "./xAxisLabelLayout";
// Deterministic stand-in for canvas text metrics: width == 10px per character.
const ctx = {
@@ -26,6 +27,7 @@ describe("layoutXAxisLabels — condensed", () => {
labelWidth: 92,
maxLines: 1,
height: 30,
+ slotWidth: 100,
});
});
@@ -94,7 +96,14 @@ describe("layoutXAxisLabels — condensed", () => {
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 });
+ expect(out).toEqual({
+ angle: 0,
+ interval: 1,
+ labelWidth: 70,
+ maxLines: 1,
+ height: 30,
+ slotWidth: 70,
+ });
});
it("reserves the wrapped line count for multiLine", () => {
@@ -104,3 +113,105 @@ describe("layoutXAxisLabels — scrolling", () => {
expect(out.height).toBe(3 * LINE + 13);
});
});
+
+describe("layoutXAxisLabels — scrolling, full labels", () => {
+ const scroll = (labels: string[], opts: Partial<Parameters<typeof layoutXAxisLabels>[2]> = {}) =>
+ layout(labels, {
+ condensed: false,
+ variant: "multiLine",
+ slotWidth: 72,
+ visibleWidth: 1000,
+ ...opts,
+ });
+ /** The label as the axis draws it at the layout's width and line count. */
+ const drawn = (label: string, out: ReturnType<typeof layoutXAxisLabels>) =>
+ wrapLabelLines(ctx, label, out.labelWidth, out.maxLines);
+
+ it("keeps the density width when every label already fits", () => {
+ const out = scroll(["Jan", "Feb", "Mar"]);
+ expect(out.slotWidth).toBe(72);
+ expect(out.maxLines).toBe(1);
+ });
+
+ it("widens the category until a long label wraps in full", () => {
+ const out = scroll([LONG, "Jan"]);
+ // The narrowest 3-line wrap is 180px ("Category Name That"), + the 8px gap.
+ expect(out.slotWidth).toBe(189);
+ expect(out.maxLines).toBe(3);
+ expect(drawn(LONG, out)).toEqual(["Extremely Long", "Category Name That", "Needs Truncation"]);
+ });
+
+ // Wraps into 3 lines from 130px ("Response Time"), 2 lines from 160px.
+ const CSRT = "Customer Support Response Time";
+
+ it("sizes a bar chart's category so the label fits under the band", () => {
+ const out = scroll([CSRT], { labelShare: 0.8 });
+ expect(out.labelWidth).toBeCloseTo(out.slotWidth * 0.8);
+ expect(out.labelWidth).toBeGreaterThanOrEqual(130);
+ expect(drawn(CSRT, out).join(" ")).toBe(CSRT);
+ });
+
+ it("fits the lines a short band holds", () => {
+ // (45 − 13 padding) / 15 → 2 lines, so the label needs a wider category.
+ const out = scroll([CSRT], { maxHeight: 45 });
+ expect(out.maxLines).toBe(2);
+ expect(drawn(CSRT, out)).toEqual(["Customer Support", "Response Time"]);
+ });
+
+ it("fits single-line labels on one line", () => {
+ const out = scroll(["Customer Support"], { variant: "singleLine" });
+ expect(out.slotWidth).toBe(168);
+ expect(out.maxLines).toBe(1);
+ });
+
+ it("grows a category to at most three times its usual width", () => {
+ // 200px + the 8px gap fits under 3 × 72 = 216px; 220px doesn't, so it truncates.
+ expect(scroll(["Twenty characters ok"], { variant: "singleLine" }).slotWidth).toBe(208);
+ expect(scroll(["Twenty-two characters!"], { variant: "singleLine" }).slotWidth).toBe(72);
+ });
+
+ it("never grows a category past half the visible width", () => {
+ // A 300px plot keeps at least two 150px categories in view.
+ const narrow = { variant: "singleLine" as const, visibleWidth: 300 };
+ expect(scroll(["Fourteen chars"], narrow).slotWidth).toBe(148);
+ expect(scroll(["Sixteen chars ok"], narrow).slotWidth).toBe(72);
+ });
+
+ it("never lets the gap between labels make a chart that fits scroll", () => {
+ // Four 160px labels fit a 660px plot at 165px each, just not with the 8px gap.
+ const out = scroll(Array(4).fill("Sixteen chars ok"), {
+ variant: "singleLine",
+ visibleWidth: 660,
+ });
+ expect(out.slotWidth).toBe(165);
+ });
+
+ it("truncates, without widening for, a label that can't show in full", () => {
+ // One 370px word would fit this 1000px plot on one line, but not a
+ // category three times the usual width: it breaks mid-word and truncates.
+ const WORD = "SinglePointDataSetForTestingEdgeCases";
+ const out = scroll([WORD, "Jan"]);
+ expect(out.slotWidth).toBe(72);
+ expect(drawn(WORD, out).at(-1)).toMatch(/…$/);
+ });
+
+ it("leaves the condensed layout's categories alone", () => {
+ expect(layout([LONG], { slotWidth: 60, visibleWidth: 1000 }).slotWidth).toBe(60);
+ });
+});
+
+describe("fullLabelWidth", () => {
+ it("is the one-line width when only one line is allowed", () => {
+ expect(fullLabelWidth(ctx, LONG, 1)).toBe(500);
+ });
+
+ it("is the narrowest width that wraps the label into the allowed lines", () => {
+ expect(fullLabelWidth(ctx, LONG, 3)).toBeCloseTo(180, 0);
+ expect(fullLabelWidth(ctx, LONG, 2)).toBeCloseTo(260, 0);
+ });
+
+ it("never breaks a word", () => {
+ expect(fullLabelWidth(ctx, "Revenue", 3)).toBe(70);
+ expect(fullLabelWidth(ctx, "Q1 Revenue", 3)).toBe(70);
+ });
+});
diff --git a/packages/react-ui/src/components/Charts/utils/xAxisLabelLayout.ts b/packages/react-ui/src/components/Charts/utils/xAxisLabelLayout.ts
index 3286ef447..ca660dcd4 100644
--- a/packages/react-ui/src/components/Charts/utils/xAxisLabelLayout.ts
+++ b/packages/react-ui/src/components/Charts/utils/xAxisLabelLayout.ts
@@ -24,6 +24,8 @@ const LABEL_GAP = 8;
* still has room for a few characters.
*/
const MIN_LABEL_WIDTH = 40;
+/** The scrolling layout grows a category to at most this many times `slotWidth`. */
+const MAX_SLOT_GROWTH = 3;
export interface XAxisLabelLayout {
/** 0 for horizontal labels, `ANGLED_LABEL_ROTATION` for rotated ones. */
@@ -39,6 +41,11 @@ export interface XAxisLabelLayout {
maxLines: number;
/** Height of the label band. */
height: number;
+ /**
+ * Width of one category: `slotWidth`, or wider when the scrolling layout
+ * grows it so the labels show in full.
+ */
+ slotWidth: number;
}
export interface XAxisLabelLayoutOptions {
@@ -54,27 +61,125 @@ export interface XAxisLabelLayoutOptions {
* scrolling layout draws every label at its category width.
*/
condensed: boolean;
+ /**
+ * Scrolling layout only: the width of the visible plot. Categories widen so
+ * that their labels show in full — wrapped between words into the lines the
+ * band holds, or on one line for "singleLine" — instead of being truncated:
+ * the chart scrolls further rather than cutting labels short. A category
+ * grows to at most three times `slotWidth` and never past half the visible
+ * plot, so at least two always show at once. A label that can't show in
+ * full within that (a 60-character identifier, a paragraph) doesn't widen
+ * the categories: it wraps mid-word and truncates as before. Omitted:
+ * categories keep `slotWidth`.
+ */
+ visibleWidth?: number;
+ /**
+ * Scrolling layout only: the share of a category's width its label is drawn
+ * in. Bar charts draw it under the bar's band (`1 − paddingInner` of the
+ * band scale), line and area charts across the whole category. Default 1.
+ */
+ labelShare?: number;
+}
+
+/**
+ * Whether `label` shows in full at `width`: on one line when `maxLines` is 1,
+ * otherwise wrapped into at most `maxLines` lines without breaking a word.
+ */
+function fitsInFull(
+ ctx: CanvasRenderingContext2D,
+ label: string,
+ width: number,
+ maxLines: number,
+): boolean {
+ if (maxLines <= 1) return ctx.measureText(label).width <= width;
+ return (
+ label.split(/\s+/).every((word) => ctx.measureText(word).width <= width) &&
+ wrapLabelLines(ctx, label, width, Number.POSITIVE_INFINITY).length <= maxLines
+ );
+}
+
+/**
+ * The narrowest width at which `label` shows in full (see `fitsInFull`).
+ * Greedy wrapping never needs more lines at a larger width, so this bisects
+ * between the widest word and the whole label on one line.
+ */
+export function fullLabelWidth(
+ ctx: CanvasRenderingContext2D,
+ label: string,
+ maxLines: number,
+): number {
+ let hi = ctx.measureText(label).width;
+ if (maxLines <= 1) return hi;
+ let lo = Math.max(0, ...label.split(/\s+/).map((word) => ctx.measureText(word).width));
+ if (fitsInFull(ctx, label, lo, maxLines)) return lo;
+ while (hi - lo > 0.5) {
+ const mid = (lo + hi) / 2;
+ if (fitsInFull(ctx, label, mid, maxLines)) hi = mid;
+ else lo = mid;
+ }
+ return hi;
}
/**
* 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).
+ * The band never grows past the cap. The condensed layout truncates labels
+ * that don't fit it with an ellipsis (the renderer shows the full text on
+ * hover); the scrolling layout first widens its categories (see
+ * `visibleWidth`) so the labels show in full.
*/
export function layoutXAxisLabels(
ctx: CanvasRenderingContext2D,
labels: string[],
- { variant, slotWidth, maxHeight, lineHeight, condensed }: XAxisLabelLayoutOptions,
+ {
+ variant,
+ slotWidth: minSlotWidth,
+ maxHeight,
+ lineHeight,
+ condensed,
+ visibleWidth = 0,
+ labelShare = 1,
+ }: 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 lineCap = Math.max(
+ 1,
+ Math.min(MAX_LABEL_LINES, Math.floor((cap - X_AXIS_LABEL_PADDING) / lineHeight)),
+ );
+
+ // Scrolling: widen the categories until every label shows in full.
+ let slotWidth = minSlotWidth;
+ if (!condensed && labels.length > 0 && visibleWidth > minSlotWidth) {
+ const maxSlotWidth = Math.max(
+ minSlotWidth,
+ Math.min(MAX_SLOT_GROWTH * minSlotWidth, visibleWidth / 2),
+ );
+ const lines = variant === "multiLine" ? lineCap : 1;
+ let needed = 0;
+ for (const label of labels) {
+ if (fitsInFull(ctx, label, minSlotWidth * labelShare, lines)) continue;
+ const width = fullLabelWidth(ctx, label, lines);
+ if (width <= maxSlotWidth * labelShare) needed = Math.max(needed, width);
+ }
+ if (needed > 0) {
+ const tight = Math.ceil(needed / labelShare);
+ // Leave a gap between neighbouring labels (line and area labels span the
+ // whole category), but never one that makes a chart that fits scroll.
+ const unscrolled = visibleWidth / labels.length;
+ const roomy =
+ tight <= unscrolled ? Math.min(tight + LABEL_GAP, unscrolled) : tight + LABEL_GAP;
+ slotWidth = Math.min(maxSlotWidth, Math.max(minSlotWidth, roomy));
+ }
+ }
+
const singleLine: XAxisLabelLayout = {
angle: 0,
interval: 1,
- labelWidth: slotWidth,
+ labelWidth: condensed ? slotWidth : slotWidth * labelShare,
maxLines: 1,
height: singleLineHeight,
+ slotWidth,
};
if (labels.length === 0 || slotWidth <= 0) return singleLine;
@@ -89,11 +194,11 @@ export function layoutXAxisLabels(
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 };
+ return { angle: ANGLED_LABEL_ROTATION, interval, labelWidth, maxLines: 1, height, slotWidth };
}
let interval = 1;
- let labelWidth = slotWidth;
+ let labelWidth = singleLine.labelWidth;
if (condensed) {
const minWidth = Math.min(widest, MIN_LABEL_WIDTH) + LABEL_GAP;
interval = Math.min(labels.length, Math.max(1, Math.ceil(minWidth / slotWidth)));
@@ -101,15 +206,11 @@ export function layoutXAxisLabels(
}
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 };
+ return { angle: 0, interval, labelWidth, maxLines: lines, height, slotWidth };
}