Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix: chart Tier 2 — remove hardcoded colors, document DPR contract, clean up dead props (#1424)

Cindy Zhang1e1fa4d8311a
diff --git a/apps/storybook/stories/ChartStreamGL.stories.tsx b/apps/storybook/stories/ChartStreamGL.stories.tsx
index 76c1e12fbc..9b080b236d 100644
--- a/apps/storybook/stories/ChartStreamGL.stories.tsx
+++ b/apps/storybook/stories/ChartStreamGL.stories.tsx
@@ -1,5 +1,5 @@
import type {Meta, StoryObj} from '@storybook/react';
-import {useRef, useEffect, useState} from 'react';
+import {useRef, useEffect, useState, useCallback} from 'react';
import {
XDSChart,
XDSChartAxis,
@@ -21,78 +21,74 @@ export default meta;
// Simulated Stock Ticker
// =============================================================================
-function StockTicker() {
- const colors = useXDSChartColors().categorical(5);
- const streamRef = useRef<XDSChartStreamGLHandle>(null);
- const priceRef = useRef(150);
- const tRef = useRef(0);
- const [price, setPrice] = useState(150);
+/** Simulated stock price — GBM with drift and volatility */
+export const StockPrice: StoryObj = {
+ render: () => {
+ const colors = useXDSChartColors();
+ const streamRef = useRef<XDSChartStreamGLHandle>(null);
+ const priceRef = useRef(150);
+ const tRef = useRef(0);
+ const [price, setPrice] = useState(150);
+ const [xDomain, setXDomain] = useState<[number, number]>([0, 400]);
- useEffect(() => {
- const mu = 0.0001;
- const sigma = 0.008;
- const id = setInterval(() => {
- tRef.current += 1;
- const z = (Math.random() + Math.random() + Math.random() - 1.5) * 2;
- const logReturn = mu - (sigma * sigma) / 2 + sigma * z;
- priceRef.current *= Math.exp(logReturn);
- if (Math.random() < 0.002) {
- priceRef.current *= 1 + (Math.random() - 0.5) * 0.03;
- }
- setPrice(priceRef.current);
- streamRef.current?.push(tRef.current, priceRef.current);
- }, 50);
- return () => clearInterval(id);
- }, []);
+ useEffect(() => {
+ const mu = 0.0001;
+ const sigma = 0.008;
+ const id = setInterval(() => {
+ tRef.current += 1;
+ const z = (Math.random() + Math.random() + Math.random() - 1.5) * 2;
+ const logReturn = mu - (sigma * sigma) / 2 + sigma * z;
+ priceRef.current *= Math.exp(logReturn);
+ setPrice(priceRef.current);
+ streamRef.current?.push(tRef.current, priceRef.current);
+ // Slide the x window
+ {
+ setXDomain([Math.max(0, tRef.current - 400), tRef.current]);
+ }
+ }, 50);
+ return () => clearInterval(id);
+ }, []);
- return (
- <XDSStack direction="vertical" gap={2}>
- <XDSStack direction="horizontal" gap={3} vAlign="center">
- <XDSText type="label">ACME Corp</XDSText>
- <XDSText type="body">${price.toFixed(2)}</XDSText>
+ return (
+ <XDSStack direction="vertical" gap={4}>
+ <XDSHeading level={3}>Simulated Stock Ticker</XDSHeading>
+ <XDSStack direction="horizontal" gap={3} vAlign="center">
+ <XDSText type="label">ACME Corp</XDSText>
+ <XDSText type="body">${price.toFixed(2)}</XDSText>
+ </XDSStack>
+ <XDSChart
+ data={[
+ {t: 0, v: 130},
+ {t: 1, v: 170},
+ ]}
+ xKey="t"
+ yKeys={['v']}
+ yDomain={[130, 170]}
+ xDomain={xDomain}
+ yBaseline="data"
+ height={220}>
+ <XDSChartGrid horizontal />
+ <XDSChartAxis position="bottom" />
+ <XDSChartAxis position="left" />
+ <XDSChartStreamGL
+ ref={streamRef}
+ color={colors.categorical(1)[0]}
+ bufferSize={400}
+ lineWidth={1.5}
+ />
+ </XDSChart>
</XDSStack>
- <XDSChart
- data={[
- {t: 0, v: 130},
- {t: 1, v: 170},
- ]}
- xKey="t"
- yKeys={['v']}
- yDomain={[130, 170]}
- yBaseline="data"
- height={200}>
- <XDSChartGrid horizontal />
- <XDSChartAxis position="left" />
- <XDSChartStreamGL
- ref={streamRef}
- color={colors[0]}
- bufferSize={400}
- lineWidth={1.5}
- />
- </XDSChart>
- </XDSStack>
- );
-}
-
-export const StockPrice: StoryObj = {
- render: () => (
- <XDSStack direction="vertical" gap={4}>
- <XDSHeading level={3}>Simulated Stock Ticker</XDSHeading>
- <XDSText type="supporting" color="secondary">
- GBM with drift and volatility. Y-axis locked to $130\u2013$170 via
- yDomain.
- </XDSText>
- <StockTicker />
- </XDSStack>
- ),
+ );
+ },
};
// =============================================================================
-// Server Metrics — shared yDomain [0, 100] for all three
+// Server Metrics — shared yDomain [0, 100]
// =============================================================================
function useMetricStream(
ref: React.RefObject<XDSChartStreamGLHandle | null>,
+ setXDomain: (d: [number, number]) => void,
config: {
base: number;
amplitude: number;
@@ -100,12 +96,20 @@ function useMetricStream(
noise: number;
spikeProbability: number;
spikeSize: number;
+ windowSize: number;
},
) {
const tRef = useRef(0);
useEffect(() => {
- const {base, amplitude, frequency, noise, spikeProbability, spikeSize} =
- config;
+ const {
+ base,
+ amplitude,
+ frequency,
+ noise,
+ spikeProbability,
+ spikeSize,
+ windowSize,
+ } = config;
const id = setInterval(() => {
tRef.current += 1;
let value =
@@ -118,257 +122,272 @@ function useMetricStream(
}
value = Math.max(0, Math.min(100, value));
ref.current?.push(tRef.current, value);
+ {
+ setXDomain([Math.max(0, tRef.current - windowSize), tRef.current]);
+ }
}, 33);
return () => clearInterval(id);
- }, [ref, config]);
+ }, [ref, setXDomain, config]);
}
-function ServerMetrics() {
- const colors = useXDSChartColors().categorical(5);
- const cpuRef = useRef<XDSChartStreamGLHandle>(null);
- const memRef = useRef<XDSChartStreamGLHandle>(null);
- const netRef = useRef<XDSChartStreamGLHandle>(null);
+/** Server dashboard — CPU, Memory, and Network at 30fps */
+export const ServerDashboard: StoryObj = {
+ render: () => {
+ const colors = useXDSChartColors();
+ const cpuRef = useRef<XDSChartStreamGLHandle>(null);
+ const memRef = useRef<XDSChartStreamGLHandle>(null);
+ const netRef = useRef<XDSChartStreamGLHandle>(null);
+ const [cpuX, setCpuX] = useState<[number, number]>([0, 300]);
+ const [memX, setMemX] = useState<[number, number]>([0, 300]);
+ const [netX, setNetX] = useState<[number, number]>([0, 300]);
- useMetricStream(cpuRef, {
- base: 35,
- amplitude: 15,
- frequency: 0.04,
- noise: 8,
- spikeProbability: 0.01,
- spikeSize: 40,
- });
- useMetricStream(memRef, {
- base: 62,
- amplitude: 5,
- frequency: 0.008,
- noise: 2,
- spikeProbability: 0.005,
- spikeSize: 15,
- });
- useMetricStream(netRef, {
- base: 20,
- amplitude: 12,
- frequency: 0.06,
- noise: 10,
- spikeProbability: 0.02,
- spikeSize: 30,
- });
+ useMetricStream(cpuRef, setCpuX, {
+ base: 35,
+ amplitude: 15,
+ frequency: 0.04,
+ noise: 8,
+ spikeProbability: 0.01,
+ spikeSize: 40,
+ windowSize: 300,
+ });
+ useMetricStream(memRef, setMemX, {
+ base: 62,
+ amplitude: 5,
+ frequency: 0.008,
+ noise: 2,
+ spikeProbability: 0.005,
+ spikeSize: 15,
+ windowSize: 300,
+ });
+ useMetricStream(netRef, setNetX, {
+ base: 20,
+ amplitude: 12,
+ frequency: 0.06,
+ noise: 10,
+ spikeProbability: 0.02,
+ spikeSize: 30,
+ windowSize: 300,
+ });
- const chartProps = {
- data: [
- {t: 0, v: 0},
- {t: 1, v: 100},
- ] as Record<string, unknown>[],
- xKey: 't',
- yKeys: ['v'] as string[],
- yDomain: [0, 100] as [number, number],
- height: 150,
- };
+ const chartProps = {
+ data: [
+ {t: 0, v: 0},
+ {t: 1, v: 100},
+ ] as Record<string, unknown>[],
+ xKey: 't',
+ yKeys: ['v'] as string[],
+ yDomain: [0, 100] as [number, number],
+ height: 150,
+ };
- return (
- <XDSStack direction="vertical" gap={4}>
- <XDSStack direction="vertical" gap={1}>
- <XDSText type="label">CPU Usage (%)</XDSText>
- <XDSChart {...chartProps}>
- <XDSChartGrid horizontal />
- <XDSChartAxis position="left" />
- <XDSChartStreamGL
- ref={cpuRef}
- color={colors[0]}
- bufferSize={300}
- lineWidth={1.5}
- />
- </XDSChart>
- </XDSStack>
- <XDSStack direction="vertical" gap={1}>
- <XDSText type="label">Memory Usage (%)</XDSText>
- <XDSChart {...chartProps}>
- <XDSChartGrid horizontal />
- <XDSChartAxis position="left" />
- <XDSChartStreamGL
- ref={memRef}
- color={colors[1]}
- bufferSize={300}
- lineWidth={1.5}
- />
- </XDSChart>
+ return (
+ <XDSStack direction="vertical" gap={4}>
+ <XDSHeading level={3}>Server Metrics Dashboard</XDSHeading>
+ <XDSStack direction="vertical" gap={1}>
+ <XDSText type="label">CPU Usage (%)</XDSText>
+ <XDSChart {...chartProps} xDomain={cpuX}>
+ <XDSChartGrid horizontal />
+ <XDSChartAxis position="bottom" />
+ <XDSChartAxis position="left" />
+ <XDSChartStreamGL
+ ref={cpuRef}
+ color={colors.categorical(3)[0]}
+ bufferSize={300}
+ lineWidth={1.5}
+ />
+ </XDSChart>
+ </XDSStack>
+ <XDSStack direction="vertical" gap={1}>
+ <XDSText type="label">Memory Usage (%)</XDSText>
+ <XDSChart {...chartProps} xDomain={memX}>
+ <XDSChartGrid horizontal />
+ <XDSChartAxis position="bottom" />
+ <XDSChartAxis position="left" />
+ <XDSChartStreamGL
+ ref={memRef}
+ color={colors.categorical(3)[1]}
+ bufferSize={300}
+ lineWidth={1.5}
+ />
+ </XDSChart>
+ </XDSStack>
+ <XDSStack direction="vertical" gap={1}>
+ <XDSText type="label">Network I/O (Mbps)</XDSText>
+ <XDSChart {...chartProps} xDomain={netX}>
+ <XDSChartGrid horizontal />
+ <XDSChartAxis position="bottom" />
+ <XDSChartAxis position="left" />
+ <XDSChartStreamGL
+ ref={netRef}
+ color={colors.categorical(3)[2]}
+ bufferSize={300}
+ lineWidth={1.5}
+ />
+ </XDSChart>
+ </XDSStack>
</XDSStack>
- <XDSStack direction="vertical" gap={1}>
- <XDSText type="label">Network I/O (Mbps)</XDSText>
- <XDSChart {...chartProps}>
- <XDSChartGrid horizontal />
- <XDSChartAxis position="left" />
- <XDSChartStreamGL
- ref={netRef}
- color={colors[2]}
- bufferSize={300}
- lineWidth={1.5}
- />
- </XDSChart>
- </XDSStack>
- </XDSStack>
- );
-}
-
-export const ServerDashboard: StoryObj = {
- render: () => (
- <XDSStack direction="vertical" gap={4}>
- <XDSHeading level={3}>Server Metrics Dashboard</XDSHeading>
- <XDSText type="supporting" color="secondary">
- All three charts share yDomain=[0, 100]. Grid and axes stay locked.
- </XDSText>
- <ServerMetrics />
- </XDSStack>
- ),
+ );
+ },
};
// =============================================================================
-// Seismograph — centered on 0
+// Seismograph — zero-centered
// =============================================================================
-function Seismograph() {
- const colors = useXDSChartColors().categorical(5);
- const streamRef = useRef<XDSChartStreamGLHandle>(null);
- const tRef = useRef(0);
- const quakeRef = useRef(0);
+/** Seismograph — zero-centered with x-axis */
+export const SeismographDemo: StoryObj = {
+ render: () => {
+ const colors = useXDSChartColors();
+ const streamRef = useRef<XDSChartStreamGLHandle>(null);
+ const tRef = useRef(0);
+ const quakeRef = useRef(0);
+ const [xDomain, setXDomain] = useState<[number, number]>([0, 600]);
- useEffect(() => {
- let raf: number;
- const tick = () => {
- tRef.current += 1;
- if (Math.random() < 0.003) {
- quakeRef.current = 30 + Math.random() * 50;
- }
- quakeRef.current *= 0.97;
- const microTremor = (Math.random() - 0.5) * 2;
- const quakeSignal =
- quakeRef.current > 0.5
- ? Math.sin(tRef.current * 0.5) *
- quakeRef.current *
- (0.5 + Math.random() * 0.5)
- : 0;
- streamRef.current?.push(tRef.current, microTremor + quakeSignal);
+ useEffect(() => {
+ let raf: number;
+ const tick = () => {
+ tRef.current += 1;
+ if (Math.random() < 0.003) {
+ quakeRef.current = 30 + Math.random() * 50;
+ }
+ quakeRef.current *= 0.97;
+ const microTremor = (Math.random() - 0.5) * 2;
+ const quakeSignal =
+ quakeRef.current > 0.5
+ ? Math.sin(tRef.current * 0.5) *
+ quakeRef.current *
+ (0.5 + Math.random() * 0.5)
+ : 0;
+ streamRef.current?.push(tRef.current, microTremor + quakeSignal);
+ {
+ setXDomain([Math.max(0, tRef.current - 600), tRef.current]);
+ }
+ raf = requestAnimationFrame(tick);
+ };
raf = requestAnimationFrame(tick);
- };
- raf = requestAnimationFrame(tick);
- return () => cancelAnimationFrame(raf);
- }, []);
+ return () => cancelAnimationFrame(raf);
+ }, []);
- return (
- <XDSChart
- data={[
- {t: 0, v: -80},
- {t: 1, v: 80},
- ]}
- xKey="t"
- yKeys={['v']}
- yDomain={[-80, 80]}
- yBaseline="zero"
- height={200}>
- <XDSChartGrid horizontal />
- <XDSChartAxis position="left" />
- <XDSChartStreamGL
- ref={streamRef}
- color={colors[3]}
- bufferSize={600}
- lineWidth={1}
- opacity={0.9}
- />
- </XDSChart>
- );
-}
-
-export const SeismographDemo: StoryObj = {
- render: () => (
- <XDSStack direction="vertical" gap={4}>
- <XDSHeading level={3}>Seismograph</XDSHeading>
- <XDSText type="supporting" color="secondary">
- yBaseline=&quot;zero&quot; anchors 0 to center. yDomain=[-80, 80] keeps
- axis stable.
- </XDSText>
- <Seismograph />
- </XDSStack>
- ),
+ return (
+ <XDSStack direction="vertical" gap={4}>
+ <XDSHeading level={3}>Seismograph</XDSHeading>
+ <XDSText type="supporting" color="secondary">
+ yBaseline=&quot;zero&quot; anchors 0 to center. Both axes from chart
+ context.
+ </XDSText>
+ <XDSChart
+ data={[
+ {t: 0, v: -80},
+ {t: 1, v: 80},
+ ]}
+ xKey="t"
+ yKeys={['v']}
+ yDomain={[-80, 80]}
+ xDomain={xDomain}
+ yBaseline="zero"
+ height={220}>
+ <XDSChartGrid horizontal />
+ <XDSChartAxis position="bottom" />
+ <XDSChartAxis position="left" />
+ <XDSChartStreamGL
+ ref={streamRef}
+ color={colors.categorical(5)[3]}
+ bufferSize={600}
+ lineWidth={1}
+ opacity={0.9}
+ />
+ </XDSChart>
+ </XDSStack>
+ );
+ },
};
// =============================================================================
-// Multi-sensor overlay — same chart, same yDomain
+// Multi-sensor overlay — same chart, same domains
// =============================================================================
-function MultiSensor() {
- const colors = useXDSChartColors().categorical(5);
- const s1Ref = useRef<XDSChartStreamGLHandle>(null);
- const s2Ref = useRef<XDSChartStreamGLHandle>(null);
- const s3Ref = useRef<XDSChartStreamGLHandle>(null);
- const tRef = useRef(0);
-
- useEffect(() => {
- const id = setInterval(() => {
- tRef.current += 1;
- const t = tRef.current;
- const shared = Math.sin(t * 0.02) * 20;
- s1Ref.current?.push(
- t,
- 50 + shared + Math.sin(t * 0.07) * 10 + (Math.random() - 0.5) * 4,
- );
- s2Ref.current?.push(
- t,
- 50 + shared * 0.6 + Math.cos(t * 0.05) * 15 + (Math.random() - 0.5) * 6,
- );
- s3Ref.current?.push(
- t,
- 50 + shared * 0.3 + Math.sin(t * 0.11) * 8 + (Math.random() - 0.5) * 3,
- );
- }, 33);
- return () => clearInterval(id);
- }, []);
+/** Three streams on one chart sharing xDomain and yDomain */
+export const MultiSensorOverlay: StoryObj = {
+ render: () => {
+ const colors = useXDSChartColors();
+ const s1Ref = useRef<XDSChartStreamGLHandle>(null);
+ const s2Ref = useRef<XDSChartStreamGLHandle>(null);
+ const s3Ref = useRef<XDSChartStreamGLHandle>(null);
+ const tRef = useRef(0);
+ const [xDomain, setXDomain] = useState<[number, number]>([0, 400]);
- return (
- <XDSChart
- data={[
- {t: 0, v: 0},
- {t: 1, v: 100},
- ]}
- xKey="t"
- yKeys={['v']}
- yDomain={[0, 100]}
- height={250}>
- <XDSChartGrid horizontal />
- <XDSChartAxis position="left" />
- <XDSChartStreamGL
- ref={s1Ref}
- color={colors[0]}
- bufferSize={400}
- lineWidth={1.5}
- opacity={0.8}
- />
- <XDSChartStreamGL
- ref={s2Ref}
- color={colors[1]}
- bufferSize={400}
- lineWidth={1.5}
- opacity={0.8}
- />
- <XDSChartStreamGL
- ref={s3Ref}
- color={colors[2]}
- bufferSize={400}
- lineWidth={1.5}
- opacity={0.8}
- />
- </XDSChart>
- );
-}
+ useEffect(() => {
+ const id = setInterval(() => {
+ tRef.current += 1;
+ const t = tRef.current;
+ const shared = Math.sin(t * 0.02) * 20;
+ s1Ref.current?.push(
+ t,
+ 50 + shared + Math.sin(t * 0.07) * 10 + (Math.random() - 0.5) * 4,
+ );
+ s2Ref.current?.push(
+ t,
+ 50 +
+ shared * 0.6 +
+ Math.cos(t * 0.05) * 15 +
+ (Math.random() - 0.5) * 6,
+ );
+ s3Ref.current?.push(
+ t,
+ 50 +
+ shared * 0.3 +
+ Math.sin(t * 0.11) * 8 +
+ (Math.random() - 0.5) * 3,
+ );
+ if (t > 400) {
+ setXDomain([Math.max(0, t - 400), t]);
+ }
+ }, 33);
+ return () => clearInterval(id);
+ }, []);
-export const MultiSensorOverlay: StoryObj = {
- render: () => (
- <XDSStack direction="vertical" gap={4}>
- <XDSHeading level={3}>Multi-Sensor Overlay</XDSHeading>
- <XDSText type="supporting" color="secondary">
- Three streams on one chart sharing yDomain=[0, 100]. Lines are properly
- comparable because they all map through the same yScale.
- </XDSText>
- <MultiSensor />
- </XDSStack>
- ),
+ return (
+ <XDSStack direction="vertical" gap={4}>
+ <XDSHeading level={3}>Multi-Sensor Overlay</XDSHeading>
+ <XDSText type="supporting" color="secondary">
+ Three streams sharing one chart — same xDomain, same yDomain=[0, 100].
+ </XDSText>
+ <XDSChart
+ data={[
+ {t: 0, v: 0},
+ {t: 1, v: 100},
+ ]}
+ xKey="t"
+ yKeys={['v']}
+ yDomain={[0, 100]}
+ xDomain={xDomain}
+ height={280}>
+ <XDSChartGrid horizontal />
+ <XDSChartAxis position="bottom" />
+ <XDSChartAxis position="left" />
+ <XDSChartStreamGL
+ ref={s1Ref}
+ color={colors.categorical(3)[0]}
+ bufferSize={400}
+ lineWidth={1.5}
+ opacity={0.8}
+ />
+ <XDSChartStreamGL
+ ref={s2Ref}
+ color={colors.categorical(3)[1]}
+ bufferSize={400}
+ lineWidth={1.5}
+ opacity={0.8}
+ />
+ <XDSChartStreamGL
+ ref={s3Ref}
+ color={colors.categorical(3)[2]}
+ bufferSize={400}
+ lineWidth={1.5}
+ opacity={0.8}
+ />
+ </XDSChart>
+ </XDSStack>
+ );
+ },
};
diff --git a/apps/storybook/stories/ChartStreamPerf.stories.tsx b/apps/storybook/stories/ChartStreamPerf.stories.tsx
new file mode 100644
index 0000000000..e00b0be9a8
--- /dev/null
+++ b/apps/storybook/stories/ChartStreamPerf.stories.tsx
@@ -0,0 +1,296 @@
+import type {Meta, StoryObj} from '@storybook/react';
+import {useRef, useEffect, useState, useCallback} from 'react';
+import {
+ XDSChart,
+ XDSChartAxis,
+ XDSChartGrid,
+ XDSChartStreamGL,
+ useXDSChartColors,
+ type XDSChartStreamGLHandle,
+} from '@xds/lab';
+import {XDSStack, XDSText} from '@xds/core';
+import {XDSHeading} from '@xds/core/Text';
+
+const meta: Meta = {
+ title: 'Lab/XDSChartStreamGL/Performance',
+};
+
+export default meta;
+
+/**
+ * Measures frame timing when xDomain updates on every push.
+ * Shows: fps, render time per frame, and dropped frames.
+ */
+export const XDomainUpdateCost: StoryObj = {
+ render: () => {
+ const colors = useXDSChartColors();
+ const streamRef = useRef<XDSChartStreamGLHandle>(null);
+ const tRef = useRef(0);
+ const [xDomain, setXDomain] = useState<[number, number]>([0, 300]);
+ const [fps, setFps] = useState(0);
+ const [renderMs, setRenderMs] = useState(0);
+ const frameTimesRef = useRef<number[]>([]);
+ const lastFrameRef = useRef(performance.now());
+
+ useEffect(() => {
+ let raf: number;
+ const tick = () => {
+ const now = performance.now();
+ const dt = now - lastFrameRef.current;
+ lastFrameRef.current = now;
+
+ frameTimesRef.current.push(dt);
+ if (frameTimesRef.current.length > 60) frameTimesRef.current.shift();
+
+ // Update stats every 30 frames
+ if (tRef.current % 30 === 0 && frameTimesRef.current.length > 0) {
+ const avg =
+ frameTimesRef.current.reduce((a, b) => a + b, 0) /
+ frameTimesRef.current.length;
+ setFps(Math.round(1000 / avg));
+ setRenderMs(Math.round(avg * 100) / 100);
+ }
+
+ tRef.current += 1;
+ const y =
+ Math.sin(tRef.current * 0.05) * 40 + 50 + (Math.random() - 0.5) * 10;
+ streamRef.current?.push(tRef.current, y);
+
+ {
+ setXDomain([Math.max(0, tRef.current - 300), tRef.current]);
+ }
+
+ raf = requestAnimationFrame(tick);
+ };
+ raf = requestAnimationFrame(tick);
+ return () => cancelAnimationFrame(raf);
+ }, []);
+
+ return (
+ <XDSStack direction="vertical" gap={4}>
+ <XDSHeading level={3}>Performance: xDomain on every frame</XDSHeading>
+ <XDSStack direction="horizontal" gap={6}>
+ <XDSText type="label">FPS: {fps}</XDSText>
+ <XDSText type="label">Frame: {renderMs}ms</XDSText>
+ <XDSText type="supporting" color="secondary">
+ xDomain updates via setState on every requestAnimationFrame
+ </XDSText>
+ </XDSStack>
+ <XDSChart
+ data={[
+ {t: 0, v: 0},
+ {t: 1, v: 100},
+ ]}
+ xKey="t"
+ yKeys={['v']}
+ yDomain={[0, 100]}
+ xDomain={xDomain}
+ height={250}>
+ <XDSChartGrid horizontal />
+ <XDSChartAxis position="bottom" />
+ <XDSChartAxis position="left" />
+ <XDSChartStreamGL
+ ref={streamRef}
+ color={colors.categorical(1)[0]}
+ bufferSize={300}
+ lineWidth={1.5}
+ />
+ </XDSChart>
+ </XDSStack>
+ );
+ },
+};
+
+/**
+ * Throttled xDomain — updates every 500ms instead of every frame.
+ * Axis slides in steps; stream still renders every frame via WebGL.
+ */
+export const ThrottledXDomain: StoryObj = {
+ render: () => {
+ const colors = useXDSChartColors();
+ const streamRef = useRef<XDSChartStreamGLHandle>(null);
+ const tRef = useRef(0);
+ const [xDomain, setXDomain] = useState<[number, number]>([0, 300]);
+ const [fps, setFps] = useState(0);
+ const [renderMs, setRenderMs] = useState(0);
+ const frameTimesRef = useRef<number[]>([]);
+ const lastFrameRef = useRef(performance.now());
+ const lastDomainUpdateRef = useRef(0);
+
+ useEffect(() => {
+ let raf: number;
+ const tick = () => {
+ const now = performance.now();
+ const dt = now - lastFrameRef.current;
+ lastFrameRef.current = now;
+
+ frameTimesRef.current.push(dt);
+ if (frameTimesRef.current.length > 60) frameTimesRef.current.shift();
+
+ if (tRef.current % 30 === 0 && frameTimesRef.current.length > 0) {
+ const avg =
+ frameTimesRef.current.reduce((a, b) => a + b, 0) /
+ frameTimesRef.current.length;
+ setFps(Math.round(1000 / avg));
+ setRenderMs(Math.round(avg * 100) / 100);
+ }
+
+ tRef.current += 1;
+ const y =
+ Math.sin(tRef.current * 0.05) * 40 + 50 + (Math.random() - 0.5) * 10;
+ streamRef.current?.push(tRef.current, y);
+
+ // Throttle xDomain updates to every 500ms
+ if (now - lastDomainUpdateRef.current > 500) {
+ setXDomain([Math.max(0, tRef.current - 300), tRef.current]);
+ lastDomainUpdateRef.current = now;
+ }
+
+ raf = requestAnimationFrame(tick);
+ };
+ raf = requestAnimationFrame(tick);
+ return () => cancelAnimationFrame(raf);
+ }, []);
+
+ return (
+ <XDSStack direction="vertical" gap={4}>
+ <XDSHeading level={3}>
+ Performance: throttled xDomain (500ms)
+ </XDSHeading>
+ <XDSStack direction="horizontal" gap={6}>
+ <XDSText type="label">FPS: {fps}</XDSText>
+ <XDSText type="label">Frame: {renderMs}ms</XDSText>
+ <XDSText type="supporting" color="secondary">
+ xDomain updates every 500ms; WebGL draws every frame
+ </XDSText>
+ </XDSStack>
+ <XDSChart
+ data={[
+ {t: 0, v: 0},
+ {t: 1, v: 100},
+ ]}
+ xKey="t"
+ yKeys={['v']}
+ yDomain={[0, 100]}
+ xDomain={xDomain}
+ height={250}>
+ <XDSChartGrid horizontal />
+ <XDSChartAxis position="bottom" />
+ <XDSChartAxis position="left" />
+ <XDSChartStreamGL
+ ref={streamRef}
+ color={colors.categorical(1)[0]}
+ bufferSize={300}
+ lineWidth={1.5}
+ />
+ </XDSChart>
+ </XDSStack>
+ );
+ },
+};
+
+/**
+ * Stress test: 3 streams + both axes + grid, xDomain every frame.
+ */
+export const StressTest: StoryObj = {
+ render: () => {
+ const colors = useXDSChartColors();
+ const s1 = useRef<XDSChartStreamGLHandle>(null);
+ const s2 = useRef<XDSChartStreamGLHandle>(null);
+ const s3 = useRef<XDSChartStreamGLHandle>(null);
+ const tRef = useRef(0);
+ const [xDomain, setXDomain] = useState<[number, number]>([0, 400]);
+ const [fps, setFps] = useState(0);
+ const frameTimesRef = useRef<number[]>([]);
+ const lastFrameRef = useRef(performance.now());
+
+ useEffect(() => {
+ let raf: number;
+ const tick = () => {
+ const now = performance.now();
+ const dt = now - lastFrameRef.current;
+ lastFrameRef.current = now;
+ frameTimesRef.current.push(dt);
+ if (frameTimesRef.current.length > 60) frameTimesRef.current.shift();
+ if (tRef.current % 30 === 0 && frameTimesRef.current.length > 0) {
+ const avg =
+ frameTimesRef.current.reduce((a, b) => a + b, 0) /
+ frameTimesRef.current.length;
+ setFps(Math.round(1000 / avg));
+ }
+
+ tRef.current += 1;
+ const t = tRef.current;
+ const shared = Math.sin(t * 0.02) * 20;
+ s1.current?.push(
+ t,
+ 50 + shared + Math.sin(t * 0.07) * 10 + (Math.random() - 0.5) * 4,
+ );
+ s2.current?.push(
+ t,
+ 50 +
+ shared * 0.6 +
+ Math.cos(t * 0.05) * 15 +
+ (Math.random() - 0.5) * 6,
+ );
+ s3.current?.push(
+ t,
+ 50 +
+ shared * 0.3 +
+ Math.sin(t * 0.11) * 8 +
+ (Math.random() - 0.5) * 3,
+ );
+
+ setXDomain([Math.max(0, t - 400), t]);
+ raf = requestAnimationFrame(tick);
+ };
+ raf = requestAnimationFrame(tick);
+ return () => cancelAnimationFrame(raf);
+ }, []);
+
+ const c = colors.categorical(3);
+ return (
+ <XDSStack direction="vertical" gap={4}>
+ <XDSHeading level={3}>
+ Stress: 3 streams + axes + grid @ 60fps
+ </XDSHeading>
+ <XDSText type="label">FPS: {fps}</XDSText>
+ <XDSChart
+ data={[
+ {t: 0, v: 0},
+ {t: 1, v: 100},
+ ]}
+ xKey="t"
+ yKeys={['v']}
+ yDomain={[0, 100]}
+ xDomain={xDomain}
+ height={300}>
+ <XDSChartGrid horizontal />
+ <XDSChartAxis position="bottom" />
+ <XDSChartAxis position="left" />
+ <XDSChartStreamGL
+ ref={s1}
+ color={c[0]}
+ bufferSize={400}
+ lineWidth={1.5}
+ opacity={0.8}
+ />
+ <XDSChartStreamGL
+ ref={s2}
+ color={c[1]}
+ bufferSize={400}
+ lineWidth={1.5}
+ opacity={0.8}
+ />
+ <XDSChartStreamGL
+ ref={s3}
+ color={c[2]}
+ bufferSize={400}
+ lineWidth={1.5}
+ opacity={0.8}
+ />
+ </XDSChart>
+ </XDSStack>
+ );
+ },
+};
diff --git a/packages/lab/src/Chart/XDSChart.tsx b/packages/lab/src/Chart/XDSChart.tsx
index 3b8aa969f1..19190ddf45 100644
--- a/packages/lab/src/Chart/XDSChart.tsx
+++ b/packages/lab/src/Chart/XDSChart.tsx
@@ -52,11 +52,18 @@ export interface XDSChartProps {
*/
yBaseline?: YBaseline;
/**
- * Explicit y-axis domain [min, max]. Overrides auto-computation from data.
- * Use for streaming charts where you want a stable axis range.
- * Data that exceeds this range will still expand the domain.
+ * Explicit y-axis domain [min, max].
+ * When provided, this is the y-axis range. Data outside it is not clipped
+ * visually but will extend beyond the chart area.
*/
yDomain?: [number, number];
+ /**
+ * Explicit x-axis domain [min, max] for linear/time scales.
+ * When provided, this is the x-axis range — the chart renders exactly
+ * this window. Use for streaming charts where the range shifts over time.
+ * Ignored for band (categorical) scales.
+ */
+ xDomain?: [number, number];
/** Chart contents — axes, marks, tooltips */
children: ReactNode;
}
@@ -83,6 +90,7 @@ export function XDSChart({
margin: marginOverride,
yBaseline = 'auto',
yDomain: yDomainProp,
+ xDomain: xDomainProp,
children,
}: XDSChartProps) {
const containerRef = useRef<HTMLDivElement>(null);
@@ -111,25 +119,46 @@ export function XDSChart({
const isNumeric = xValues.every(v => typeof v === 'number');
if (isNumeric) {
+ if (xDomainProp) {
+ // Explicit domain is authoritative — use as-is
+ return scaleLinear().domain(xDomainProp).range([0, innerWidth]);
+ }
+ // Auto-compute from data
const nums = xValues as number[];
- return scaleLinear()
- .domain([Math.min(...nums), Math.max(...nums)])
- .range([0, innerWidth])
- .nice();
+ let min = Infinity;
+ let max = -Infinity;
+ for (const n of nums) {
+ if (n < min) min = n;
+ if (n > max) max = n;
+ }
+ return scaleLinear().domain([min, max]).range([0, innerWidth]).nice();
}
+ // Categorical — xDomain doesn't apply to band scales
return scaleBand<string>()
.domain(xValues.map(String))
.range([0, innerWidth])
.padding(0.2);
- }, [data, xKey, innerWidth]);
+ }, [data, xKey, innerWidth, xDomainProp]);
const yScale = useMemo((): ScaleLinear<number, number> => {
- // Start from explicit domain or compute from data
- let min = yDomainProp ? yDomainProp[0] : Infinity;
- let max = yDomainProp ? yDomainProp[1] : -Infinity;
+ if (yDomainProp) {
+ // Explicit domain is authoritative — apply baseline logic but don't expand from data
+ let [min, max] = yDomainProp;
+ if (yBaseline === 'zero') {
+ const abs = Math.max(Math.abs(min), Math.abs(max));
+ min = -abs;
+ max = abs;
+ } else if (yBaseline === 'auto') {
+ if (min > 0) min = 0;
+ if (max < 0) max = 0;
+ }
+ return scaleLinear().domain([min, max]).range([innerHeight, 0]).nice();
+ }
- // Always scan data — expand beyond yDomainProp if data exceeds it
+ // Auto-compute from data
+ let min = Infinity;
+ let max = -Infinity;
for (const d of data) {
for (const key of yKeys) {
const v = d[key];
diff --git a/packages/lab/src/Chart/XDSChartAxis.tsx b/packages/lab/src/Chart/XDSChartAxis.tsx
index 08494f894b..16fa9936d4 100644
--- a/packages/lab/src/Chart/XDSChartAxis.tsx
+++ b/packages/lab/src/Chart/XDSChartAxis.tsx
@@ -2,6 +2,8 @@
* @file XDSChartAxis.tsx
* @output Renders an axis (top, right, bottom, left) using the chart's scales
* @position Child of XDSChart; reads scales from context
+ *
+ * Ticks use CSS transitions for smooth sliding during streaming updates.
*/
import {useMemo} from 'react';
@@ -16,10 +18,13 @@ export interface XDSChartAxisProps {
tickCount?: number;
/** Custom tick formatter */
tickFormat?: (value: unknown) => string;
+ /** Enable smooth transitions for streaming (default: true) */
+ animated?: boolean;
}
/**
* Chart axis. Renders tick marks and labels for the x or y dimension.
+ * Ticks transition smoothly when the scale domain shifts (e.g. streaming).
*
* @example
* ```
@@ -31,6 +36,7 @@ export function XDSChartAxis({
position,
tickCount = 5,
tickFormat,
+ animated = true,
}: XDSChartAxisProps) {
const {width, height, xScale, yScale} = useChart();
@@ -57,12 +63,17 @@ export function XDSChartAxis({
position === 'bottom'
? `translate(0,${height})`
: position === 'right'
- ? `translate(${width},0)`
- : undefined;
+ ? `translate(${width},0)`
+ : undefined;
const format = tickFormat ?? String;
const tickSize = 6;
+ // Transition style for smooth tick movement during streaming
+ const tickTransition = animated
+ ? 'transform 150ms linear, opacity 150ms ease'
+ : undefined;
+
return (
<g transform={transform}>
{/* Axis line */}
@@ -76,10 +87,21 @@ export function XDSChartAxis({
/>
{ticks.map(({value, offset}) => {
const label = format(value);
+ // Clip ticks that are outside the visible area
+ const isVisible = isHorizontal
+ ? offset >= -10 && offset <= width + 10
+ : offset >= -10 && offset <= height + 10;
+
if (isHorizontal) {
const y = position === 'bottom' ? tickSize : -tickSize;
return (
- <g key={label} transform={`translate(${offset},0)`}>
+ <g
+ key={label}
+ style={{
+ transform: `translateX(${offset}px)`,
+ transition: tickTransition,
+ opacity: isVisible ? 1 : 0,
+ }}>
<line y2={y} stroke="var(--color-border)" strokeWidth={1} />
<text
y={position === 'bottom' ? tickSize + 12 : -(tickSize + 4)}
@@ -94,7 +116,13 @@ export function XDSChartAxis({
// Vertical axis
const x = position === 'left' ? -tickSize : tickSize;
return (
- <g key={label} transform={`translate(0,${offset})`}>
+ <g
+ key={label}
+ style={{
+ transform: `translateY(${offset}px)`,
+ transition: tickTransition,
+ opacity: isVisible ? 1 : 0,
+ }}>
<line x2={x} stroke="var(--color-border)" strokeWidth={1} />
<text
x={position === 'left' ? -(tickSize + 4) : tickSize + 4}
diff --git a/packages/lab/src/Chart/XDSChartCandlestick.tsx b/packages/lab/src/Chart/XDSChartCandlestick.tsx
index 38dd854813..fe87192979 100644
--- a/packages/lab/src/Chart/XDSChartCandlestick.tsx
+++ b/packages/lab/src/Chart/XDSChartCandlestick.tsx
@@ -38,12 +38,10 @@ export interface XDSChartCandlestickProps {
strokeWidth?: number;
/** Corner radius on body (default variant only) */
radius?: number;
- /** Dot radius (unused in bar variant, kept for future variants) */
- dotRadius?: number;
}
/**
- * Candlestick / box-whisker marks with optional Tufte variant.
+ * Candlestick / box-whisker marks.
*
* @example
* ```
@@ -54,7 +52,7 @@ export interface XDSChartCandlestickProps {
* downColor={useXDSChartColors().semantic.negative}
* />
*
- * // Tufte range-bar
+ * // OHLC bar
* <XDSChartCandlestick
* variant="bar"
* high="max" low="min" open="q1" close="median"
@@ -68,13 +66,12 @@ export function XDSChartCandlestick({
open,
close,
variant = 'default',
- upColor = '#0B991F',
- downColor = '#F5394F',
+ upColor,
+ downColor,
color,
bodyWidth = 0.6,
strokeWidth = 1.5,
radius = 2,
- dotRadius = 3,
}: XDSChartCandlestickProps) {
const {data, xKey, xScale, yScale} = useChart();
@@ -93,7 +90,11 @@ export function XDSChartCandlestick({
const cVal = typeof d[close] === 'number' ? (d[close] as number) : 0;
const isUp = cVal >= oVal;
- const fill = color ?? (isUp ? upColor : downColor);
+ const fill =
+ color ??
+ (isUp
+ ? (upColor ?? 'var(--color-data-categorical-green)')
+ : (downColor ?? 'var(--color-data-categorical-red)'));
const centerX = xVal + bw / 2;
const yHigh = yScale(hVal);
diff --git a/packages/lab/src/Chart/XDSChartDotGL.tsx b/packages/lab/src/Chart/XDSChartDotGL.tsx
index 5dfbf72186..cf12dfbacf 100644
--- a/packages/lab/src/Chart/XDSChartDotGL.tsx
+++ b/packages/lab/src/Chart/XDSChartDotGL.tsx
@@ -165,6 +165,9 @@ export function XDSChartDotGL({
// Uniforms
const [r, g, b] = hexToGL(color);
+ // Resolution in logical pixels — positions from xPixel/yScale are logical.
+ // The viewport is set to physical pixels (width*dpr) for sharp rendering,
+ // but the shader maps logical positions → clip space via u_resolution.
gl.uniform2f(gl.getUniformLocation(program, 'u_resolution'), width, height);
gl.uniform3f(gl.getUniformLocation(program, 'u_color'), r, g, b);
gl.uniform1f(gl.getUniformLocation(program, 'u_size'), size * dpr);
diff --git a/packages/lab/src/Chart/XDSChartDotGLInteractive.tsx b/packages/lab/src/Chart/XDSChartDotGLInteractive.tsx
index 52eb53ea05..5fa8f9213b 100644
--- a/packages/lab/src/Chart/XDSChartDotGLInteractive.tsx
+++ b/packages/lab/src/Chart/XDSChartDotGLInteractive.tsx
@@ -240,6 +240,7 @@ export function XDSChartDotGLInteractive({
gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0);
const [r, g, b] = hexToGL(color);
+ // Logical pixels — positions from xPixel/yScale are logical
gl.uniform2f(
gl.getUniformLocation(prog, 'u_resolution'),
width,
diff --git a/packages/lab/src/Chart/XDSChartHeatmapGL.tsx b/packages/lab/src/Chart/XDSChartHeatmapGL.tsx
index b2a7d6b2b7..20835644e6 100644
--- a/packages/lab/src/Chart/XDSChartHeatmapGL.tsx
+++ b/packages/lab/src/Chart/XDSChartHeatmapGL.tsx
@@ -234,6 +234,7 @@ export function XDSChartHeatmapGL({
gl.enableVertexAttribArray(aCol);
gl.vertexAttribPointer(aCol, 3, gl.FLOAT, false, 0, 0);
+ // Logical pixels — positions are in logical space, viewport handles DPR
gl.uniform2f(gl.getUniformLocation(program, 'u_resolution'), width, height);
gl.drawArrays(gl.TRIANGLES, 0, positions.length / 2);
diff --git a/packages/lab/src/Chart/XDSChartStreamGL.tsx b/packages/lab/src/Chart/XDSChartStreamGL.tsx
index b26d639679..82af8544ff 100644
--- a/packages/lab/src/Chart/XDSChartStreamGL.tsx
+++ b/packages/lab/src/Chart/XDSChartStreamGL.tsx
@@ -4,8 +4,9 @@
* @position Child of XDSChart; uses the chart's yScale for y-mapping
*
* The y-axis domain is controlled by XDSChart (via yDomain/yBaseline).
- * The x-axis is a sliding time window managed internally (newest point
- * at the right edge, oldest at the left).
+ * The x-axis domain is controlled by XDSChart (via xDomain).
+ * Both axes, grid, and stream data map through the same scales.
+ * For streaming, the parent should update xDomain as new data arrives.
*/
import {
@@ -99,8 +100,11 @@ function createProgram(gl: WebGLRenderingContext): WebGLProgram | null {
*
* @example
* ```
- * <XDSChart data={[]} xKey="t" yKeys={[]} yDomain={[0, 100]} height={200}>
+ * const [xDomain, setXDomain] = useState<[number, number]>([0, 100]);
+ *
+ * <XDSChart data={[]} xKey="t" yKeys={[]} yDomain={[0, 100]} xDomain={xDomain} height={200}>
* <XDSChartGrid horizontal />
+ * <XDSChartAxis position="bottom" />
* <XDSChartAxis position="left" />
* <XDSChartStreamGL ref={streamRef} color="#0171E3" />
* </XDSChart>
@@ -113,7 +117,7 @@ export const XDSChartStreamGL = forwardRef<
{color, bufferSize = 500, lineWidth = 2, opacity = 1},
ref,
) {
- const {width, height, yScale} = useChart();
+ const {width, height, xScale, yScale} = useChart();
const canvasRef = useRef<HTMLCanvasElement>(null);
const glRef = useRef<WebGLRenderingContext | null>(null);
const programRef = useRef<WebGLProgram | null>(null);
@@ -135,18 +139,12 @@ export const XDSChartStreamGL = forwardRef<
const {data: ringData, head, count} = ring.current;
if (count < 2) return;
- // X domain: sliding window from oldest to newest visible point
- const oldestIdx = ((head - count + bufferSize) % bufferSize) * 2;
- const newestIdx = ((head - 1 + bufferSize) % bufferSize) * 2;
- const xMin = ringData[oldestIdx];
- const xMax = ringData[newestIdx];
- const xRange = xMax - xMin || 1;
-
- // Map to pixel space: x from sliding window, y from chart's yScale
+ // Map to pixel space: both x and y from chart's scales
+ const linearX = xScale as (v: number) => number;
const drawBuf = new Float32Array(count * 2);
for (let i = 0; i < count; i++) {
const idx = ((head - count + i + bufferSize) % bufferSize) * 2;
- drawBuf[i * 2] = ((ringData[idx] - xMin) / xRange) * width;
+ drawBuf[i * 2] = linearX(ringData[idx]);
drawBuf[i * 2 + 1] = yScale(ringData[idx + 1]);
}
@@ -166,13 +164,14 @@ export const XDSChartStreamGL = forwardRef<
gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0);
const [r, g, b] = hexToGL(color);
+ // Logical pixels — positions are in logical space, viewport handles DPR
gl.uniform2f(gl.getUniformLocation(program, 'u_resolution'), width, height);
gl.uniform3f(gl.getUniformLocation(program, 'u_color'), r, g, b);
gl.uniform1f(gl.getUniformLocation(program, 'u_opacity'), opacity);
gl.lineWidth(lineWidth);
gl.drawArrays(gl.LINE_STRIP, 0, count);
- }, [width, height, color, lineWidth, opacity, bufferSize, yScale]);
+ }, [width, height, color, lineWidth, opacity, bufferSize, xScale, yScale]);
useImperativeHandle(
ref,