An open source design system that's fully customizable and agent ready
TypeScript
harden(charts): production-hardening pass (follow-up to #3672) (#3694)
Joeye67829d7351d
diff --git a/apps/storybook/stories/charts/WebGL.stories.tsx b/apps/storybook/stories/charts/WebGL.stories.tsxindex 6c4cfcbac9..9e19328317 100644--- a/apps/storybook/stories/charts/WebGL.stories.tsx+++ b/apps/storybook/stories/charts/WebGL.stories.tsx@@ -91,7 +91,12 @@ export const Heatmap: StoryObj = {colorRange: ['#eff6ff', '#1e40af'],}),]}- axes={axes}+ axes={+ <>+ <ChartAxis position="bottom" />+ <ChartAxis position="left" showAxisLine />+ </>+ }height={280}/>),diff --git a/packages/charts/src/Chart.tsx b/packages/charts/src/Chart.tsxindex c7359cdf21..6ad3d824dc 100644--- a/packages/charts/src/Chart.tsx+++ b/packages/charts/src/Chart.tsx@@ -123,8 +123,19 @@ export function Chart({() => ({...DEFAULT_MARGIN, ...marginOverride}),[marginOverride],);- const innerWidth = Math.max(0, containerWidth - margin.left - margin.right);- const innerHeight = Math.max(0, height - margin.top - margin.bottom);+ // Clamp plot dimensions to finite, non-negative values. layout.ts hardens+ // against NaN in the *data*, but a non-finite `height` prop or margin override+ // would still collapse every scale range — and the clipPath/event-rect+ // geometry — into NaN. `containerWidth` is always finite (from ResizeObserver).+ const safeHeight = Number.isFinite(height) ? Math.max(0, height) : 0;+ const rawInnerWidth = containerWidth - margin.left - margin.right;+ const rawInnerHeight = safeHeight - margin.top - margin.bottom;+ const innerWidth = Number.isFinite(rawInnerWidth)+ ? Math.max(0, rawInnerWidth)+ : 0;+ const innerHeight = Number.isFinite(rawInnerHeight)+ ? Math.max(0, rawInnerHeight)+ : 0;// ─── Color assignment ─────────────────────────────────────────────────// Give every primary series that doesn't supply a static color (auto-colored@@ -164,6 +175,7 @@ export function Chart({xKey,xScale: layout.xScale,yScale: layout.yScale,+ yBandScale: layout.yBandScale,width: innerWidth,height: innerHeight,}),@@ -230,6 +242,7 @@ export function Chart({xKey,xScale: layout.xScale,yScale: layout.yScale,+ yBandScale: layout.yBandScale,resolved: layout.resolved,onPointer,svgRef,@@ -258,7 +271,7 @@ export function Chart({<divref={containerRef}{...stylex.props(styles.container)}- style={{height}}+ style={{height: safeHeight}}/>);}@@ -304,7 +317,7 @@ export function Chart({<svgref={svgRef}width="100%"- height={height}+ height={safeHeight}aria-label={title ?? undefined}aria-describedby={subtitle ? descId : undefined}>{title && <title>{title}</title>}diff --git a/packages/charts/src/ChartAxis.tsx b/packages/charts/src/ChartAxis.tsxindex 6e4c871d2b..6e412beee7 100644--- a/packages/charts/src/ChartAxis.tsx+++ b/packages/charts/src/ChartAxis.tsx@@ -85,10 +85,24 @@ export function ChartAxis({// Tick marks need an axis line to anchor against; force it on when ticks// are enabled so the two visuals stay coherent.const renderAxisLine = showAxisLine || showTicks;- const {width, height, xScale, yScale} = useChart();+ const {width, height, xScale, yScale, yBandScale} = useChart();const isHorizontal = position === 'top' || position === 'bottom';- const scale = isHorizontal ? xScale : yScale;+ // A categorical y-axis (e.g. heatmap rows) is exposed as `yBandScale`; prefer+ // it over the linear `yScale` so a left/right axis renders the row categories+ // (days) aligned to each band instead of meaningless value ticks.+ const scale = isHorizontal ? xScale : (yBandScale ?? yScale);++ // Sanitize the tick count before it reaches d3. `.ticks()` targets ~N ticks+ // and allocates an array that large, so a huge N throws `RangeError: Invalid+ // array length` and crashes the render; a non-finite or negative N would+ // otherwise blank the axis. Clamp to a sane integer (0 still means "no+ // ticks") and fall back to the default for invalid input. Shared by tick+ // generation and the auto formatter so the two stay in sync.+ const safeTickCount =+ Number.isFinite(tickCount) && tickCount >= 0+ ? Math.min(Math.floor(tickCount), 1000)+ : 5;// Default label formatter. For continuous (linear/time) scales, use d3's own// tick formatter so numbers get sensible precision (no floating-point dust@@ -100,9 +114,9 @@ export function ChartAxis({}const continuous = scale asScaleLinear<number, number> | ScaleTime<number, number>;- const fmt = continuous.tickFormat(tickCount);+ const fmt = continuous.tickFormat(safeTickCount);return (v: unknown) => fmt(v as number & Date);- }, [tickFormat, scale, tickCount]);+ }, [tickFormat, scale, safeTickCount]);const format = useCallback((value: unknown): string => {@@ -124,7 +138,7 @@ export function ChartAxis({} else {const linearScale = scale asScaleLinear<number, number> | ScaleTime<number, number>;- allTicks = linearScale.ticks(tickCount).map(d => ({+ allTicks = linearScale.ticks(safeTickCount).map(d => ({value: d,offset: linearScale(d as number & Date),}));@@ -156,7 +170,7 @@ export function ChartAxis({}return allTicks;- }, [scale, tickCount, maxTicks, isHorizontal, width, height, format]);+ }, [scale, safeTickCount, maxTicks, isHorizontal, width, height, format]);const transform =position === 'bottom'@@ -168,7 +182,10 @@ export function ChartAxis({// For the bottom axis, draw the axis line at y=0 when the domain spans// negative values (so the axis line still represents zero, not the chart edge).const axisLineY = (() => {- if (position !== 'bottom') {+ // Categorical y (e.g. heatmap rows): there is no meaningful zero, and the+ // linear yScale is degenerate — anchor the bottom edge line to the plot edge+ // so it frames the grid instead of cutting across the cells.+ if (position !== 'bottom' || yBandScale) {return 0;}const domain = yScale.domain();diff --git a/packages/charts/src/ChartContext.ts b/packages/charts/src/ChartContext.tsindex 38d37be1b4..50f9ecb186 100644--- a/packages/charts/src/ChartContext.ts+++ b/packages/charts/src/ChartContext.ts@@ -1,5 +1,7 @@// Copyright (c) Meta Platforms, Inc. and affiliates.+'use client';+import {createContext, useContext} from 'react';import type {ChartContext} from './types';diff --git a/packages/charts/src/ChartGrid.tsx b/packages/charts/src/ChartGrid.tsxindex 1934cc75ec..eadf8fad27 100644--- a/packages/charts/src/ChartGrid.tsx+++ b/packages/charts/src/ChartGrid.tsx@@ -52,6 +52,16 @@ export function ChartGrid({}: ChartGridProps) {const {width, height, xScale, yScale} = useChart();+ // Sanitize the tick count before it reaches d3's `.ticks()`: it targets ~N+ // ticks and allocates an array that large, so a huge N throws `RangeError:+ // Invalid array length` and crashes the render, while a non-finite or+ // negative N would misbehave. Clamp to a sane integer (0 still means "no+ // lines") and fall back to the default for invalid input.+ const safeTickCount =+ Number.isFinite(tickCount) && tickCount >= 0+ ? Math.min(Math.floor(tickCount), 1000)+ : 5;+// Skip the y=0 line when emphasizing it via the axis. Without this we'd// double-draw on top of the axis line. Each line carries its tick `value`,// used as a stable React key — the pixel position can be NaN/duplicated for@@ -61,10 +71,10 @@ export function ChartGrid({return [];}return yScale- .ticks(tickCount)+ .ticks(safeTickCount).filter(tick => tick !== 0).map(tick => ({value: tick, pos: yScale(tick)}));- }, [horizontal, yScale, tickCount]);+ }, [horizontal, yScale, safeTickCount]);const vLines = useMemo(() => {if (!vertical) {@@ -78,9 +88,9 @@ export function ChartGrid({const linear = xScale asScaleLinear<number, number> | ScaleTime<number, number>;return linear- .ticks(tickCount)+ .ticks(safeTickCount).map(d => ({value: String(d), pos: linear(d as number & Date)}));- }, [vertical, xScale, tickCount]);+ }, [vertical, xScale, safeTickCount]);return (<g>diff --git a/packages/charts/src/ChartTooltip.tsx b/packages/charts/src/ChartTooltip.tsxindex 365e4df0c7..7ecf51cf1e 100644--- a/packages/charts/src/ChartTooltip.tsx+++ b/packages/charts/src/ChartTooltip.tsx@@ -173,6 +173,11 @@ export function ChartTooltip({} = useChart();const [hoveredIndex, setHoveredIndex] = useState<number | null>(null);const cardRef = useRef<HTMLDivElement>(null);+ // Whether the card is currently suppressed (no content, or a custom `render`+ // opted out by returning null). positionCard reads this so a same-index+ // pointer move — which repositions the card without a React commit — can't+ // re-reveal a card the visibility effect below has hidden.+ const cardHiddenRef = useRef(false);// Stable Set of resolved series keys — used by deriveTooltipSeriesValues.// Recomputed only when the resolved map identity changes (per layout pass).@@ -188,7 +193,7 @@ export function ChartTooltip({if (!card) {return;}- if (!svg || !e.nearest) {+ if (!svg || !e.nearest || cardHiddenRef.current) {card.style.display = 'none';return;}@@ -244,6 +249,10 @@ export function ChartTooltip({const newIndex = e.nearest?.dataIndex ?? null;if (newIndex !== currentIndex) {currentIndex = newIndex;+ // Optimistically treat the new index as showable; the visibility effect+ // re-hides it after commit if there's no content (e.g. custom `render`+ // returned null). This keeps the card appearing on the first move.+ cardHiddenRef.current = false;setHoveredIndex(newIndex);}positionCard(e);@@ -272,7 +281,10 @@ export function ChartTooltip({}const points = s._uid ? resolved.get(s._uid) : undefined;const point = points?.find(p => p.dataIndex === hoveredIndex);- if (!point) {+ // A resolved point exists at every index, but its coordinates are NaN when+ // this series' value here is missing/non-finite (the mark itself filters+ // these at render time — mirror that so we never emit cx/cy="NaN").+ if (!point || !Number.isFinite(point.px) || !Number.isFinite(point.py)) {continue;}elements.push(@@ -333,6 +345,11 @@ export function ChartTooltip({// Line / area / dot charts → vertical crosshair through the point// (band-center or linear position, resolved by the shared helper).const px = xPixel(hoveredDatum, xKey, xScale);+ // xPixel returns NaN for a non-finite x on a linear scale; skip rather than+ // emit x1/x2="NaN". (The band branch above is always finite via `?? 0`.)+ if (!Number.isFinite(px)) {+ return null;+ }return (<linex1={px}@@ -355,20 +372,27 @@ export function ChartTooltip({margin.top,]);- // Honor the documented contract: a custom `render` returning null hides the- // card (band highlight + dots still show). Without this, positionCard would- // leave an empty bordered box at the hovered point. Runs after commit so it- // also clears the frame positionCard optimistically displayed; effects never- // run during SSR, so `render` stays off the server path.+ // Single source of truth for whether the card has anything to show. It's+ // hidden when there's no hover, when the hovered index is stale/out-of-range+ // (e.g. `data` shrank while hovering, so `datum` is undefined), or when a+ // custom `render` opts out by returning null — the documented contract, which+ // still shows the band highlight + dots. The decision is stored in a ref so+ // the imperative positionCard honors it on subsequent same-index moves+ // (otherwise it would re-reveal an empty bordered box). Runs after commit, so+ // `render` (which may return null, or throw) never executes on the SSR path.useEffect(() => {- if (!render || hoveredIndex == null) {- return;- }- const card = cardRef.current;- if (card && render(xValue, seriesValues) == null) {- card.style.display = 'none';+ const hidden =+ hoveredIndex == null ||+ datum == null ||+ (render != null && render(xValue, seriesValues) == null);+ cardHiddenRef.current = hidden;+ if (hidden) {+ const card = cardRef.current;+ if (card) {+ card.style.display = 'none';+ }}- }, [render, hoveredIndex, xValue, seriesValues]);+ }, [render, hoveredIndex, datum, xValue, seriesValues]);// ─── Render ────────────────────────────────────────────────────────────if (typeof document === 'undefined') {@@ -381,8 +405,11 @@ export function ChartTooltip({);}+ // Mirrors the visibility effect's first two conditions: no card when there's+ // no hover or the hovered datum is stale/out-of-range (so `render` and the+ // default body are never called with an undefined x-value + empty rows).const cardContent =- hoveredIndex == null ? null : render ? (+ hoveredIndex == null || datum == null ? null : render ? (render(xValue, seriesValues)) : (<DefaultTooltipContent xValue={xValue} rows={seriesValues} />diff --git a/packages/charts/src/formatters.ts b/packages/charts/src/formatters.tsindex 0eb5cc8f41..114c1f77d4 100644--- a/packages/charts/src/formatters.ts+++ b/packages/charts/src/formatters.ts@@ -122,11 +122,21 @@ function toDate(value: unknown): Date {}const dateOnly = /^(\d{4})-(\d{2})-(\d{2})$/.exec(s);if (dateOnly) {- return new Date(- Number(dateOnly[1]),- Number(dateOnly[2]) - 1,- Number(dateOnly[3]),- );+ const year = Number(dateOnly[1]);+ const month = Number(dateOnly[2]);+ const day = Number(dateOnly[3]);+ const local = new Date(year, month - 1, day);+ // Reject out-of-range parts (e.g. "2024-02-31") that the Date constructor+ // would otherwise silently roll into a different day; treat them as+ // invalid so the raw value passes through unchanged.+ if (+ local.getFullYear() !== year ||+ local.getMonth() !== month - 1 ||+ local.getDate() !== day+ ) {+ return new Date(NaN);+ }+ return local;}const asNumber = Number(s);return new Date(Number.isFinite(asNumber) ? asNumber : s);diff --git a/packages/charts/src/getChartColors.ts b/packages/charts/src/getChartColors.tsindex f8e544aca1..f92d1e0125 100644--- a/packages/charts/src/getChartColors.ts+++ b/packages/charts/src/getChartColors.ts@@ -143,7 +143,9 @@ function lerpHex(a: string, b: string, t: number): string {*/function sampleRamp(stops: string[], n: number): string[] {const len = stops.length;- if (n <= 0 || len === 0) {+ // A non-finite count (e.g. Infinity) would make the Array.from calls below+ // attempt a ~2**53 element allocation and hang, so treat it as empty.+ if (!Number.isFinite(n) || n <= 0 || len === 0) {return [];}if (n === 1) {@@ -218,7 +220,9 @@ export function getChartColorsFromResolver(return {categorical(n: number): string[] {- if (n <= 0 || categorical.length === 0) {+ // A non-finite count (e.g. Infinity) would make the wrap-around Array.from+ // below attempt a ~2**53 element allocation and hang, so treat it as empty.+ if (!Number.isFinite(n) || n <= 0 || categorical.length === 0) {return [];}// Wrap around the palette so any series count gets a deterministic color.diff --git a/packages/charts/src/layout.ts b/packages/charts/src/layout.tsindex 1b8f2a1394..2856eb940f 100644--- a/packages/charts/src/layout.ts+++ b/packages/charts/src/layout.ts@@ -47,6 +47,12 @@ export interface LayoutInput {export interface LayoutResult {xScale: ChartScale;yScale: ReturnType<typeof scaleLinear<number, number>>;+ /**+ * Categorical y band scale, built when a series declares `layout.yBandKey`+ * (e.g. a heatmap's rows). When present the y-axis is categorical and the+ * linear `yScale` is unused.+ */+ yBandScale?: ReturnType<typeof scaleBand<string>>;resolved: Map<string, ResolvedPoint[]>;}@@ -95,6 +101,13 @@ export function computeLayout({yDomain,xDomain,}: LayoutInput): LayoutResult {+ // A categorical y-axis (heatmap) means BOTH axes are categorical: columns+ // should tile the plot edge-to-edge just like the rows. Drop the bar-style+ // outer padding on the x band scale for these charts so the grid meets the+ // x/y axis lines flush on every side (no asymmetric gap).+ const yBandKey = series.find(s => s.layout.yBandKey != null)?.layout.yBandKey;+ const isCategoricalGrid = yBandKey != null;+// ─── 1. X scale ──────────────────────────────────────────────────────const xValues = data.map(d => d[xKey]);const isNumericX =@@ -114,7 +127,7 @@ export function computeLayout({xScale = scaleBand<string>().domain(xValues.map(String)).range([0, width])- .padding(0.2);+ .padding(isCategoricalGrid ? 0 : 0.2);}// ─── 2. Y domain from all series dataKeys ────────────────────────────@@ -142,28 +155,41 @@ export function computeLayout({let yMin = Infinity,yMax = -Infinity;- // Stacked series contribute their per-datum accumulated total. `Number.isFinite`- // (not `typeof === 'number'`) so a stray NaN/Infinity can't corrupt the domain- // into a NaN/Infinity scale.+ // Stacked series contribute the full extent of their running cumulative — every+ // layer boundary, not just the net total — mirroring the d3 stackOffsetNone pass+ // in §3 that actually draws them. The 0 baseline is included because stacks are+ // drawn from it. Tracking only the total would let the drawn bars/areas escape+ // the scale: a mixed-sign stack whose interior peaks exceed the net total, or a+ // 'data'-baseline stack whose bars start at 0 (below the smallest positive+ // total), would render outside the y-domain and be clipped. `Number.isFinite`+ // (not `typeof === 'number'`) keeps a stray NaN/Infinity from corrupting the+ // domain into a NaN/Infinity scale; a non-finite layer carries the baseline+ // forward (contributes nothing new) exactly as stackOffsetNone does.const stackedKeys = new Set<string>();for (const [, keys] of stackGroups) {for (const k of keys) {stackedKeys.add(k);}for (const d of data) {- let sum = 0;+ let acc = 0;+ if (acc < yMin) {+ yMin = acc;+ }+ if (acc > yMax) {+ yMax = acc;+ }for (const k of keys) {const v = d[k];if (Number.isFinite(v)) {- sum += v as number;+ acc += v as number;+ if (acc < yMin) {+ yMin = acc;+ }+ if (acc > yMax) {+ yMax = acc;+ }}}- if (sum > yMax) {- yMax = sum;- }- if (sum < yMin) {- yMin = sum;- }}}@@ -239,6 +265,20 @@ export function computeLayout({const yScaleBase = scaleLinear().domain(yDomainFinal).range([height, 0]);const yScale = applyNice ? yScaleBase.nice() : yScaleBase;+ // ─── 2b. Categorical y band scale ────────────────────────────────────+ // If any series declares a `yBandKey` (e.g. a heatmap's rows), the y-axis is+ // categorical: build one band scale over that key's unique values so the+ // marks and the left axis share the same row layout. The linear yScale above+ // is left in place but goes unused for these charts.+ // No band padding: heatmap rows should tile the full plot height edge-to-edge+ // (the mark's own `cellGap` draws the thin grid lines between cells). Padding+ // here would inset the grid and leave a sliver at the top/bottom.+ let yBandScale: ReturnType<typeof scaleBand<string>> | undefined;+ if (yBandKey != null) {+ const cats = [...new Set(data.map(d => String(d[yBandKey])))];+ yBandScale = scaleBand<string>().domain(cats).range([0, height]).padding(0);+ }+// ─── 3. Stacking ─────────────────────────────────────────────────────// Reuses `stackGroups` collected during the domain pass (§2).const stackedData = new Map<string, {y0: number; y1: number}[]>();@@ -276,7 +316,15 @@ export function computeLayout({}// ─── 5. Resolve each series ──────────────────────────────────────────- const ctx: SeriesContext = {data, xKey, xScale, yScale, width, height};+ const ctx: SeriesContext = {+ data,+ xKey,+ xScale,+ yScale,+ yBandScale,+ width,+ height,+ };const resolved = new Map<string, ResolvedPoint[]>();// Determine which series is the topmost in each stack group@@ -320,5 +368,5 @@ export function computeLayout({resolved.set(s._uid, points);}- return {xScale, yScale, resolved};+ return {xScale, yScale, yBandScale, resolved};}diff --git a/packages/charts/src/markColor.ts b/packages/charts/src/markColor.tsindex 5d0d7c018c..abe0d25c3d 100644--- a/packages/charts/src/markColor.ts+++ b/packages/charts/src/markColor.ts@@ -21,9 +21,11 @@ import {type ColorAccessor,} from './types';-/** A usable CSS paint value — a non-empty string. */+/** A usable CSS paint value — a non-blank string. */function isPaint(value: unknown): value is string {- return typeof value === 'string' && value.length > 0;+ // A whitespace-only string is an invalid paint (it renders as the initial+ // color, not the intended fallback), so treat it as "unset" like an empty one.+ return typeof value === 'string' && value.trim().length > 0;}/** The palette color assigned by the chart root, or the last-resort token. */@@ -52,9 +54,14 @@ export function pointFill(index: number,): string {if (typeof color === 'function') {- const resolved = color(datum, index);- if (isPaint(resolved)) {- return resolved;+ try {+ const resolved = color(datum, index);+ if (isPaint(resolved)) {+ return resolved;+ }+ } catch {+ // A consumer accessor can throw on unexpected data; fall through to the+ // palette/token fallback rather than crashing the whole chart render.}} else if (isPaint(color)) {return color;diff --git a/packages/charts/src/marks/band.tsx b/packages/charts/src/marks/band.tsxindex 1960fab5ca..6bdf730901 100644--- a/packages/charts/src/marks/band.tsx+++ b/packages/charts/src/marks/band.tsx@@ -13,7 +13,7 @@ import {type SeriesDef,type ResolvedPoint,} from '../types';-import type {ScaleBand} from 'd3-scale';+import {xPixel} from '../utils';export interface BandOptions {upper: string;@@ -37,21 +37,24 @@ export function band(options: BandOptions): SeriesDef {const points: ResolvedPoint[] = [];for (let i = 0; i < data.length; i++) {const d = data[i];- let px: number;- if ('bandwidth' in xScale) {- px =- ((xScale as ScaleBand<string>)(String(d[xKey])) ?? 0) +- (xScale as ScaleBand<string>).bandwidth() / 2;- } else {- px = xScale(d[xKey] as number);- }// NaN for missing/non-numeric bounds so render() can gap the area// rather than draw a spike down to the axis.const upperVal = d[options.upper];const lowerVal = d[options.lower];- const upper = Number.isFinite(upperVal) ? (upperVal as number) : NaN;- const lower = Number.isFinite(lowerVal) ? (lowerVal as number) : NaN;- points.push({px, py: yScale(upper), py0: yScale(lower), dataIndex: i});+ const upper =+ typeof upperVal === 'number' && Number.isFinite(upperVal)+ ? upperVal+ : NaN;+ const lower =+ typeof lowerVal === 'number' && Number.isFinite(lowerVal)+ ? lowerVal+ : NaN;+ points.push({+ px: xPixel(d, xKey, xScale),+ py: yScale(upper),+ py0: yScale(lower),+ dataIndex: i,+ });}return points;},diff --git a/packages/charts/src/marks/candlestick.tsx b/packages/charts/src/marks/candlestick.tsxindex 9e9db9e2b3..881a259e40 100644--- a/packages/charts/src/marks/candlestick.tsx+++ b/packages/charts/src/marks/candlestick.tsx@@ -7,7 +7,7 @@*/import type {SeriesDef, ResolvedPoint, SeriesContext} from '../types';-import type {ScaleBand} from 'd3-scale';+import {xPixel, isBandScale} from '../utils';export interface CandlestickOptions {open: string;@@ -31,8 +31,8 @@ function readNumber(d: Record<string, unknown>, key: string): number {*/function candleSlot(resolved: ResolvedPoint[], ctx: SeriesContext): number {const {xScale, width} = ctx;- if ('bandwidth' in xScale) {- return (xScale as ScaleBand<string>).bandwidth();+ if (isBandScale(xScale)) {+ return xScale.bandwidth();}const xs = resolved.map(p => p.px)@@ -64,16 +64,13 @@ export function candlestick(options: CandlestickOptions): SeriesDef {const points: ResolvedPoint[] = [];for (let i = 0; i < data.length; i++) {const d = data[i];- let px: number;- if ('bandwidth' in xScale) {- px =- ((xScale as ScaleBand<string>)(String(d[xKey])) ?? 0) +- (xScale as ScaleBand<string>).bandwidth() / 2;- } else {- px = xScale(d[xKey] as number);- }const close = readNumber(d, options.close);- points.push({px, py: yScale(close), py0: yScale(0), dataIndex: i});+ points.push({+ px: xPixel(d, xKey, xScale),+ py: yScale(close),+ py0: yScale(0),+ dataIndex: i,+ });}return points;},diff --git a/packages/charts/src/marks/dot.tsx b/packages/charts/src/marks/dot.tsxindex 6bd7399ee0..c4ebb2fe04 100644--- a/packages/charts/src/marks/dot.tsx+++ b/packages/charts/src/marks/dot.tsx@@ -63,7 +63,10 @@ export function dot(dataKey: string, options: DotOptions = {}): SeriesDef {// horizontally so they don't overlap, centered on the original x.const groups = new Map<number, ResolvedPoint[]>();for (const p of points) {- if (!Number.isFinite(p.px)) {+ // Only points render() will actually draw (finite px AND py) join a+ // dodge group; a missing y-value must not reserve a slot and knock the+ // visible points off-center.+ if (!Number.isFinite(p.px) || !Number.isFinite(p.py)) {continue;}const key = Math.round(p.px);diff --git a/packages/charts/src/marks/dotGLInteractive.tsx b/packages/charts/src/marks/dotGLInteractive.tsxindex 648c03552a..465c8fdd63 100644--- a/packages/charts/src/marks/dotGLInteractive.tsx+++ b/packages/charts/src/marks/dotGLInteractive.tsx@@ -475,7 +475,11 @@ function DotGLInteractiveCanvas({gl.bindFramebuffer(gl.FRAMEBUFFER, fb);const pixel = new Uint8Array(4);- gl.readPixels(px, texH - py, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);+ // Flip Y from top-origin CSS space to the framebuffer's bottom-left,+ // 0-indexed origin. `texH - 1 - py` (not `texH - py`) keeps the read in+ // [0, texH-1] — the bare `texH - py` reads one row too high and samples+ // out of bounds at the very top edge.+ gl.readPixels(px, texH - 1 - py, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);gl.bindFramebuffer(gl.FRAMEBUFFER, null);const idx = colorToIndex(pixel[0], pixel[1], pixel[2]);diff --git a/packages/charts/src/marks/errorBar.tsx b/packages/charts/src/marks/errorBar.tsxindex f25b2de9d9..5ceaec16c8 100644--- a/packages/charts/src/marks/errorBar.tsx+++ b/packages/charts/src/marks/errorBar.tsx@@ -8,7 +8,7 @@*/import type {SeriesDef, ResolvedPoint} from '../types';-import type {ScaleBand} from 'd3-scale';+import {xPixel} from '../utils';export interface ErrorBarOptions {/** Data key for the upper bound */@@ -48,27 +48,28 @@ export function errorBar(options: ErrorBarOptions): SeriesDef {const points: ResolvedPoint[] = [];for (let i = 0; i < data.length; i++) {const d = data[i];- let px: number;- if ('bandwidth' in xScale) {- px =- ((xScale as ScaleBand<string>)(String(d[xKey])) ?? 0) +- (xScale as ScaleBand<string>).bandwidth() / 2;- } else {- px = xScale(d[xKey] as number);- }// NaN for a missing bound so render() skips the whole whisker instead// of anchoring a cap at the axis (a misleading zero-height error bar).const hiVal = d[high];const loVal = d[low];- const upper = Number.isFinite(hiVal) ? (hiVal as number) : NaN;- const lower = Number.isFinite(loVal) ? (loVal as number) : NaN;- points.push({px, py: yScale(upper), py0: yScale(lower), dataIndex: i});+ const upper =+ typeof hiVal === 'number' && Number.isFinite(hiVal) ? hiVal : NaN;+ const lower =+ typeof loVal === 'number' && Number.isFinite(loVal) ? loVal : NaN;+ points.push({+ px: xPixel(d, xKey, xScale),+ py: yScale(upper),+ py0: yScale(lower),+ dataIndex: i,+ });}return points;},render(resolved) {- const half = Math.max(0, capWidth) / 2;+ // Non-finite capWidth (NaN/±Infinity) would leak into the cap x-coords;+ // treat it like a non-positive width — draw the stem, drop the caps.+ const half = Number.isFinite(capWidth) ? Math.max(0, capWidth) / 2 : 0;return (<g>{resolved.map(p => {diff --git a/packages/charts/src/marks/heatmapGL.tsx b/packages/charts/src/marks/heatmapGL.tsxindex da1dea8f4e..7cda01e3e5 100644--- a/packages/charts/src/marks/heatmapGL.tsx+++ b/packages/charts/src/marks/heatmapGL.tsx@@ -10,7 +10,6 @@*/import {useRef, useEffect, useMemo, useState} from 'react';-import {scaleBand} from 'd3-scale';import type {SeriesDef, ResolvedPoint} from '../types';import type {ScaleBand} from 'd3-scale';import {@@ -82,7 +81,8 @@ type HeatmapGLLocations = {};/**- * Inline component — manages the heatmap WebGL canvas and its own y band scale.+ * Inline component — manages the heatmap WebGL canvas. Rows use the chart's+ * shared y band scale so cells stay aligned with the left axis' category labels.*/function HeatmapGLCanvas({data,@@ -90,6 +90,7 @@ function HeatmapGLCanvas({yKey,valueKey,xScale,+ yBandScale,colorRange,domain: domainProp,cellGap,@@ -101,6 +102,7 @@ function HeatmapGLCanvas({yKey: string;valueKey: string;xScale: ScaleBand<string>;+ yBandScale: ScaleBand<string>;colorRange: string[];domain?: [number, number];cellGap: number;@@ -119,11 +121,6 @@ function HeatmapGLCanvas({const ramp = useMemo(() => colorRange.map(hexToGL), [colorRange]);- const yBandScale = useMemo(() => {- const cats = [...new Set(data.map(d => String(d[yKey])))];- return scaleBand<string>().domain(cats).range([0, height]).padding(0.05);- }, [data, yKey, height]);-const domain = useMemo((): [number, number] => {if (domainProp) {return domainProp;@@ -158,6 +155,13 @@ function HeatmapGLCanvas({const gap = cellGap;const xBW = xScale.bandwidth();const yBW = yBandScale.bandwidth();+ // Heatmap cells fill their full slot (step), not just the band width. The+ // shared x-scale carries bar-style padding (~0.2), so sizing cells to the+ // bandwidth leaves gaps between columns while the local y-scale stays tight —+ // an asymmetric, sparse grid. Sizing to the step and centering on the band+ // keeps cells contiguous (a real heatmap); cellGap alone controls spacing.+ const xStep = typeof xScale.step === 'function' ? xScale.step() : xBW;+ const yStep = yBandScale.step();for (const d of data) {const xVal = xScale(String(d[xKey]));@@ -171,10 +175,12 @@ function HeatmapGLCanvas({const t = (v - dMin) / range;const [r, g, b] = sampleRamp(ramp, t);- const x0 = xVal + gap / 2;- const x1 = xVal + xBW - gap / 2;- const y0 = yVal + gap / 2;- const y1 = yVal + yBW - gap / 2;+ const xc = xVal + xBW / 2;+ const yc = yVal + yBW / 2;+ const x0 = xc - xStep / 2 + gap / 2;+ const x1 = xc + xStep / 2 - gap / 2;+ const y0 = yc - yStep / 2 + gap / 2;+ const y1 = yc + yStep / 2 - gap / 2;positions.push(x0, y0, x1, y0, x0, y1, x1, y0, x1, y1, x0, y1);for (let i = 0; i < 6; i++) {@@ -314,7 +320,11 @@ function HeatmapGLCanvas({/*** WebGL heatmap. Renders a 2D grid of colored cells using triangles.- * Manages its own y band scale for rows; uses the chart's x band scale for columns.+ *+ * The rows are categorical: declaring `layout.yBandKey` makes the chart build a+ * shared y band scale over `yKey`, so a left `<ChartAxis>` renders the row+ * labels aligned to each cell (instead of a meaningless linear value axis).+ * Columns use the chart's x band scale.** @example* ```@@ -331,30 +341,35 @@ export function heatmapGL(options: HeatmapGLOptions): SeriesDef {return {type: 'heatmapGL',key: `heatmap-${valueKey}`,- dataKeys: [valueKey],- layout: {},+ // The value drives cell COLOR, not a linear y-domain — no data keys keeps the+ // heatmap out of the shared linear y-scale / left axis / value tooltip.+ // `yBandKey` makes the chart build a categorical y band scale over the rows+ // so the left axis shows the row labels aligned to each cell.+ dataKeys: [],+ layout: {yBandKey: yKey},resolve(ctx) {- // Heatmap doesn't resolve per-point positions the standard way —- // the canvas component handles its own cell layout.- const {data, xScale, yScale} = ctx;+ // The canvas handles its own cell layout; resolve only exposes row/column+ // centers (for hover) using the shared band scales.+ const {data, xScale, yBandScale} = ctx;const points: ResolvedPoint[] = [];- if (!('bandwidth' in xScale)) {+ if (!('bandwidth' in xScale) || !yBandScale) {return points;}+ const xs = xScale as ScaleBand<string>;for (let i = 0; i < data.length; i++) {const d = data[i];- const px =- ((xScale as ScaleBand<string>)(String(d[xKey])) ?? 0) +- (xScale as ScaleBand<string>).bandwidth() / 2;- const v = typeof d[valueKey] === 'number' ? (d[valueKey] as number) : 0;- points.push({px, py: yScale(v), py0: yScale(0), dataIndex: i});+ const px = (xs(String(d[xKey])) ?? 0) + xs.bandwidth() / 2;+ const py =+ (yBandScale(String(d[yKey])) ?? 0) + yBandScale.bandwidth() / 2;+ points.push({px, py, py0: py, dataIndex: i});}return points;},render(_resolved, ctx) {- if (!('bandwidth' in ctx.xScale)) {+ // Needs a categorical x (columns) and the shared y band scale (rows).+ if (!('bandwidth' in ctx.xScale) || !ctx.yBandScale) {return null;}return (@@ -364,6 +379,7 @@ export function heatmapGL(options: HeatmapGLOptions): SeriesDef {yKey={yKey}valueKey={valueKey}xScale={ctx.xScale as ScaleBand<string>}+ yBandScale={ctx.yBandScale}colorRange={colorRange}domain={options.domain}cellGap={cellGap}diff --git a/packages/charts/src/marks/referenceLine.tsx b/packages/charts/src/marks/referenceLine.tsxindex 002b191a2f..e89834601a 100644--- a/packages/charts/src/marks/referenceLine.tsx+++ b/packages/charts/src/marks/referenceLine.tsx@@ -8,7 +8,7 @@*/import type {SeriesDef} from '../types';-import type {ScaleLinear} from 'd3-scale';+import {isBandScale} from '../utils';export interface ReferenceLineOptions {/** Horizontal reference at this y value */@@ -211,11 +211,11 @@ export function referenceLine(options: ReferenceLineOptions): SeriesDef {// Vertical reference line (linear x only — a band scale has no pixel// position for an arbitrary numeric x).- if (options.x != null && !('bandwidth' in xScale)) {+ if (options.x != null && !isBandScale(xScale)) {if (!Number.isFinite(options.x)) {return null;}- const px = (xScale as ScaleLinear<number, number>)(options.x);+ const px = xScale(options.x);if (!Number.isFinite(px)) {return null;}diff --git a/packages/charts/src/types.ts b/packages/charts/src/types.tsindex 990f898c97..f9db666f3a 100644--- a/packages/charts/src/types.ts+++ b/packages/charts/src/types.ts@@ -62,6 +62,12 @@ export interface SeriesContext {xKey: string;xScale: ChartScale;yScale: ScaleLinear<number, number>;+ /**+ * Categorical y band scale for row-based marks (e.g. heatmap). Present only+ * when a series declares `layout.yBandKey`; in that case the y-axis is+ * categorical and the linear `yScale` is unused/degenerate.+ */+ yBandScale?: ScaleBand<string>;/** Width of the plot area */width: number;/** Height of the plot area */@@ -116,6 +122,15 @@ export interface SeriesDef {group?: string;/** Whether this series contributes to y-domain zero inclusion */includeZero?: boolean;+ /**+ * When set, the chart's y-axis is a band scale built from this data key's+ * unique values (categorical rows, e.g. a heatmap's days) rather than a+ * linear value scale. The layout pass exposes it to marks and the axis as+ * `yBandScale`, so a left `<ChartAxis>` renders the categories aligned to+ * each row. A heatmap should also declare `dataKeys: []` so it doesn't feed+ * the (now unused) linear y-domain.+ */+ yBandKey?: string;};/*** Resolve pixel positions for each data point.@@ -155,6 +170,12 @@ export interface ChartContext {xKey: string;xScale: ChartScale;yScale: ScaleLinear<number, number>;+ /**+ * Categorical y band scale (e.g. heatmap rows), present when a series declares+ * `layout.yBandKey`. Chrome that renders the y-axis (`ChartAxis`) should+ * prefer this over the linear `yScale` when it exists.+ */+ yBandScale?: ScaleBand<string>;resolved: Map<string, ResolvedPoint[]>;onPointer: (handler: (e: ChartPointerEvent) => void) => () => void;svgRef: React.RefObject<SVGSVGElement | null>;diff --git a/packages/charts/src/utils.ts b/packages/charts/src/utils.tsindex 4fc86868a8..ac38b13891 100644--- a/packages/charts/src/utils.ts+++ b/packages/charts/src/utils.ts@@ -28,9 +28,11 @@ export function xPixel(return (xScale(String(raw)) ?? 0) + xScale.bandwidth() / 2;}// Not a band scale → the guard narrows `xScale` to the linear scale, so no- // cast is needed. Coerce explicitly: numbers pass through, Date/numeric-string- // map as d3 would, and non-numerics become NaN (an off-canvas point) rather- // than a silently wrong position.+ // cast is needed. Coerce explicitly: finite numbers pass through, Date/+ // numeric-string map as d3 would. Anything that coerces to a non-finite value+ // — a non-numeric (→ NaN) or a raw ±Infinity — collapses to NaN, a single+ // off-canvas sentinel that marks already skip, rather than a silently wrong+ // position (d3 maps ±Infinity to an out-of-range pixel, not off-canvas).const value = typeof raw === 'number' ? raw : Number(raw);- return xScale(value);+ return Number.isFinite(value) ? xScale(value) : NaN;}diff --git a/packages/charts/src/webgl.ts b/packages/charts/src/webgl.tsindex cdeaba0ccf..f3e0ab8f72 100644--- a/packages/charts/src/webgl.ts+++ b/packages/charts/src/webgl.ts@@ -42,15 +42,30 @@ export function createProgram(const vs = compileShader(gl, gl.VERTEX_SHADER, vertSrc);const fs = compileShader(gl, gl.FRAGMENT_SHADER, fragSrc);if (!vs || !fs) {+ // One shader may have compiled while the other failed — free the survivor+ // so the failure path never leaks a shader object.+ if (vs) {+ gl.deleteShader(vs);+ }+ if (fs) {+ gl.deleteShader(fs);+ }return null;}const p = gl.createProgram();if (!p) {+ gl.deleteShader(vs);+ gl.deleteShader(fs);return null;}gl.attachShader(p, vs);gl.attachShader(p, fs);gl.linkProgram(p);+ // The shaders are now linked into the program; flag them for deletion so the+ // GPU frees them once the program is deleted instead of leaving them attached+ // (and allocated) for the program's whole lifetime.+ gl.deleteShader(vs);+ gl.deleteShader(fs);if (!gl.getProgramParameter(p, gl.LINK_STATUS)) {gl.deleteProgram(p);return null;diff --git a/packages/lab/src/Chart/ChartHeatmapGL.tsx b/packages/lab/src/Chart/ChartHeatmapGL.tsxindex 7522868964..517eb21585 100644--- a/packages/lab/src/Chart/ChartHeatmapGL.tsx+++ b/packages/lab/src/Chart/ChartHeatmapGL.tsx@@ -156,6 +156,13 @@ export function ChartHeatmapGL({const gap = cellGap;const xBW = xScale.bandwidth();const yBW = yBandScale.bandwidth();+ // Heatmap cells fill their full slot (step), not just the band width. The+ // shared x-scale carries bar-style padding (~0.2), so sizing cells to the+ // bandwidth leaves gaps between columns while the local y-scale stays tight —+ // an asymmetric, sparse grid. Sizing to the step and centering on the band+ // keeps cells contiguous (a real heatmap); cellGap alone controls spacing.+ const xStep = typeof xScale.step === 'function' ? xScale.step() : xBW;+ const yStep = yBandScale.step();for (const d of data) {const xVal = xScale(String(d[xKey]));@@ -168,10 +175,12 @@ export function ChartHeatmapGL({const t = (v - dMin) / range;const [r, g, b] = sampleRamp(ramp, t);- const x0 = xVal + gap / 2;- const x1 = xVal + xBW - gap / 2;- const y0 = yVal + gap / 2;- const y1 = yVal + yBW - gap / 2;+ const xc = xVal + xBW / 2;+ const yc = yVal + yBW / 2;+ const x0 = xc - xStep / 2 + gap / 2;+ const x1 = xc + xStep / 2 - gap / 2;+ const y0 = yc - yStep / 2 + gap / 2;+ const y1 = yc + yStep / 2 - gap / 2;positions.push(x0, y0, x1, y0, x0, y1, x1, y0, x1, y1, x0, y1);for (let i = 0; i < 6; i++) {