An open source design system that's fully customizable and agent ready
TypeScript
feat(lab): advanced chart components — WebGL, streaming, confidence intervals, candlestick (#1397)
Cindy Zhang21089408a20a
diff --git a/apps/storybook/stories/Chart.stories.tsx b/apps/storybook/stories/Chart.stories.tsxindex a368b98344..22fde51b2f 100644--- a/apps/storybook/stories/Chart.stories.tsx+++ b/apps/storybook/stories/Chart.stories.tsx@@ -6,13 +6,42 @@ import {XDSChartBar,XDSChartLine,XDSChartDot,+ XDSChartArea,+ XDSChartErrorBar,+ XDSChartCandlestick,XDSChartTooltip,XDSChartLegend,- XDSChartColors,+ useXDSChartColors,} from '@xds/lab';-const meta: Meta = {+/**+ * `XDSChart` is the root container for all chart components. It computes+ * scales from data and provides them to children via React context.+ *+ * Colors come from `useXDSChartColors()` — theme-aware, always resolved+ * for the current light/dark mode.+ *+ * ## Composition+ *+ * ```tsx+ * const colors = useXDSChartColors();+ * <XDSChart data={data} xKey="month" yKeys={['revenue']}>+ * <XDSChartGrid horizontal />+ * <XDSChartAxis position="bottom" />+ * <XDSChartAxis position="left" />+ * <XDSChartBar dataKey="revenue" color={colors.categorical(1)[0]} />+ * <XDSChartTooltip />+ * </XDSChart>+ * ```+ */+const meta: Meta<typeof XDSChart> = {title: 'Lab/XDSChart',+ component: XDSChart,+ tags: ['autodocs'],+ argTypes: {+ height: {control: {type: 'number', min: 100, max: 600, step: 50}},+ yBaseline: {control: 'select', options: ['auto', 'zero', 'data']},+ },};export default meta;@@ -26,24 +55,25 @@ const monthlyData = [{month: 'Jun', revenue: 6200, expenses: 3400, trend: 5000},];-const colors = XDSChartColors.categorical(3);--/** Bar chart with axes and grid */-export const BarChart: StoryObj = {- render: () => (+function BarChartDemo() {+ const colors = useXDSChartColors();+ return (<XDSChart data={monthlyData} xKey="month" yKeys={['revenue']} height={300}><XDSChartGrid horizontal /><XDSChartAxis position="bottom" /><XDSChartAxis position="left" />- <XDSChartBar dataKey="revenue" color={colors[0]} />+ <XDSChartBar dataKey="revenue" color={colors.categorical(1)[0]} /><XDSChartTooltip /></XDSChart>- ),-};+ );+}-/** Line chart with dots */-export const LineChart: StoryObj = {- render: () => (+export const BarChart: StoryObj = {render: () => <BarChartDemo />};++function LineChartDemo() {+ const colors = useXDSChartColors();+ const c = colors.categorical(2);+ return (<XDSChartdata={monthlyData}xKey="month"@@ -52,22 +82,25 @@ export const LineChart: StoryObj = {<XDSChartGrid horizontal /><XDSChartAxis position="bottom" /><XDSChartAxis position="left" />- <XDSChartLine dataKey="revenue" color={colors[0]} dots />- <XDSChartLine dataKey="expenses" color={colors[1]} dots />+ <XDSChartLine dataKey="revenue" color={c[0]} dots />+ <XDSChartLine dataKey="expenses" color={c[1]} dots /><XDSChartLegenditems={[- {label: 'Revenue', color: colors[0]},- {label: 'Expenses', color: colors[1]},+ {label: 'Revenue', color: c[0]},+ {label: 'Expenses', color: c[1]},]}/><XDSChartTooltip /></XDSChart>- ),-};+ );+}-/** Mixed bar + line chart */-export const MixedChart: StoryObj = {- render: () => (+export const LineChart: StoryObj = {render: () => <LineChartDemo />};++function MixedChartDemo() {+ const colors = useXDSChartColors();+ const c = colors.categorical(3);+ return (<XDSChartdata={monthlyData}xKey="month"@@ -76,22 +109,25 @@ export const MixedChart: StoryObj = {<XDSChartGrid horizontal /><XDSChartAxis position="bottom" /><XDSChartAxis position="left" />- <XDSChartBar dataKey="revenue" color={colors[0]} />- <XDSChartLine dataKey="trend" color={colors[2]} dots />+ <XDSChartBar dataKey="revenue" color={c[0]} />+ <XDSChartLine dataKey="trend" color={c[2]} dots /><XDSChartLegenditems={[- {label: 'Revenue', color: colors[0]},- {label: 'Trend', color: colors[2]},+ {label: 'Revenue', color: c[0]},+ {label: 'Trend', color: c[2]},]}/><XDSChartTooltip /></XDSChart>- ),-};+ );+}-/** Scatter plot */-export const ScatterPlot: StoryObj = {- render: () => (+export const MixedChart: StoryObj = {render: () => <MixedChartDemo />};++function ScatterPlotDemo() {+ const colors = useXDSChartColors();+ const c = colors.categorical(2);+ return (<XDSChartdata={monthlyData}xKey="month"@@ -100,15 +136,178 @@ export const ScatterPlot: StoryObj = {<XDSChartGrid horizontal vertical /><XDSChartAxis position="bottom" /><XDSChartAxis position="left" />- <XDSChartDot dataKey="revenue" color={colors[0]} radius={5} />- <XDSChartDot dataKey="expenses" color={colors[1]} radius={5} />+ <XDSChartDot dataKey="revenue" color={c[0]} radius={5} />+ <XDSChartDot dataKey="expenses" color={c[1]} radius={5} /><XDSChartLegenditems={[- {label: 'Revenue', color: colors[0]},- {label: 'Expenses', color: colors[1]},+ {label: 'Revenue', color: c[0]},+ {label: 'Expenses', color: c[1]},]}/><XDSChartTooltip /></XDSChart>+ );+}++export const ScatterPlot: StoryObj = {render: () => <ScatterPlotDemo />};++const ciData = [+ {month: 'Jan', mean: 42, upper95: 52, lower95: 32},+ {month: 'Feb', mean: 38, upper95: 50, lower95: 26},+ {month: 'Mar', mean: 51, upper95: 62, lower95: 40},+ {month: 'Apr', mean: 46, upper95: 58, lower95: 34},+ {month: 'May', mean: 54, upper95: 66, lower95: 42},+ {month: 'Jun', mean: 62, upper95: 74, lower95: 50},+];++function ConfidenceBandDemo() {+ const colors = useXDSChartColors();+ const c = colors.categorical(1);+ return (+ <XDSChart+ data={ciData}+ xKey="month"+ yKeys={['upper95', 'lower95']}+ height={300}>+ <XDSChartGrid horizontal />+ <XDSChartAxis position="bottom" />+ <XDSChartAxis position="left" />+ <XDSChartArea+ yUpper="upper95"+ yLower="lower95"+ color={c[0]}+ opacity={0.15}+ />+ <XDSChartLine dataKey="mean" color={c[0]} dots />+ <XDSChartTooltip />+ </XDSChart>+ );+}++export const ConfidenceBand: StoryObj = {render: () => <ConfidenceBandDemo />};++const errorData = [+ {cat: 'A', value: 45, upper: 52, lower: 38},+ {cat: 'B', value: 62, upper: 70, lower: 54},+ {cat: 'C', value: 38, upper: 48, lower: 28},+ {cat: 'D', value: 55, upper: 60, lower: 50},+];++function ErrorBarDemo() {+ const colors = useXDSChartColors();+ return (+ <XDSChart+ data={errorData}+ xKey="cat"+ yKeys={['upper', 'lower']}+ height={300}>+ <XDSChartGrid horizontal />+ <XDSChartAxis position="bottom" />+ <XDSChartAxis position="left" />+ <XDSChartBar dataKey="value" color={colors.categorical(1)[0]} />+ <XDSChartErrorBar yUpper="upper" yLower="lower" />+ </XDSChart>+ );+}++export const WithErrorBars: StoryObj = {render: () => <ErrorBarDemo />};++const ohlcData = [+ {day: 'Mon', open: 100, close: 108, high: 112, low: 98},+ {day: 'Tue', open: 108, close: 103, high: 110, low: 101},+ {day: 'Wed', open: 103, close: 110, high: 115, low: 100},+ {day: 'Thu', open: 110, close: 106, high: 113, low: 104},+ {day: 'Fri', open: 106, close: 114, high: 118, low: 105},+];++export const Candlestick: StoryObj = {+ render: () => (+ <XDSChart+ data={ohlcData}+ xKey="day"+ yKeys={['high', 'low']}+ yBaseline="data"+ height={300}>+ <XDSChartGrid horizontal />+ <XDSChartAxis position="bottom" />+ <XDSChartAxis position="left" />+ <XDSChartCandlestick high="high" low="low" open="open" close="close" />+ </XDSChart>),};++function CandlestickBarDemo() {+ const colors = useXDSChartColors();+ return (+ <XDSChart+ data={ohlcData}+ xKey="day"+ yKeys={['high', 'low']}+ yBaseline="data"+ height={300}>+ <XDSChartGrid horizontal />+ <XDSChartAxis position="bottom" />+ <XDSChartAxis position="left" />+ <XDSChartCandlestick+ variant="bar"+ high="high"+ low="low"+ open="open"+ close="close"+ color={colors.categorical(1)[0]}+ />+ </XDSChart>+ );+}++export const CandlestickBar: StoryObj = {render: () => <CandlestickBarDemo />};++const plData = [+ {month: 'Jan', profit: 12},+ {month: 'Feb', profit: -8},+ {month: 'Mar', profit: 22},+ {month: 'Apr', profit: -15},+ {month: 'May', profit: 5},+ {month: 'Jun', profit: -3},+];++function ZeroCenteredDemo() {+ const colors = useXDSChartColors();+ return (+ <XDSChart+ data={plData}+ xKey="month"+ yKeys={['profit']}+ yBaseline="zero"+ height={300}>+ <XDSChartGrid horizontal />+ <XDSChartAxis position="bottom" />+ <XDSChartAxis position="left" />+ <XDSChartBar dataKey="profit" color={colors.categorical(1)[0]} />+ </XDSChart>+ );+}++export const ZeroCentered: StoryObj = {render: () => <ZeroCenteredDemo />};++function GradientLegendDemo() {+ const colors = useXDSChartColors();+ return (+ <XDSChart+ data={[+ {x: 0, v: 0},+ {x: 1, v: 100},+ ]}+ xKey="x"+ yKeys={['v']}+ height={80}>+ <XDSChartLegend+ gradient={colors.sequential.blue(5)}+ domain={[0, 100]}+ label="Temperature"+ />+ </XDSChart>+ );+}++export const GradientLegend: StoryObj = {render: () => <GradientLegendDemo />};diff --git a/apps/storybook/stories/ChartAdvanced.stories.tsx b/apps/storybook/stories/ChartAdvanced.stories.tsxnew file mode 100644index 0000000000..91d1aa852f--- /dev/null+++ b/apps/storybook/stories/ChartAdvanced.stories.tsx@@ -0,0 +1,273 @@+import type {Meta, StoryObj} from '@storybook/react';+import {+ XDSChart,+ XDSChartAxis,+ XDSChartGrid,+ XDSChartBar,+ XDSChartLine,+ XDSChartArea,+ XDSChartErrorBar,+ XDSChartCandlestick,+ XDSChartLegend,+ useXDSChartColors,+} from '@xds/lab';+import {XDSStack, XDSText} from '@xds/core';+import {XDSHeading} from '@xds/core/Text';++const meta: Meta = {title: 'Lab/XDSChartAdvanced'};+export default meta;++const ciData = [+ {month: 'Jan', mean: 42, upper95: 52, lower95: 32, upper80: 48, lower80: 36},+ {month: 'Feb', mean: 38, upper95: 50, lower95: 26, upper80: 44, lower80: 32},+ {month: 'Mar', mean: 51, upper95: 62, lower95: 40, upper80: 57, lower80: 45},+ {month: 'Apr', mean: 46, upper95: 58, lower95: 34, upper80: 52, lower80: 40},+ {month: 'May', mean: 54, upper95: 66, lower95: 42, upper80: 60, lower80: 48},+ {month: 'Jun', mean: 62, upper95: 74, lower95: 50, upper80: 68, lower80: 56},+];++function ConfidenceIntervalsDemo() {+ const colors = useXDSChartColors();+ const c = colors.categorical(3);+ return (+ <XDSStack direction="vertical" gap={4}>+ <XDSHeading level={3}>Confidence Intervals</XDSHeading>+ <XDSChart+ data={ciData}+ xKey="month"+ yKeys={['upper95', 'lower95']}+ height={300}>+ <XDSChartGrid horizontal />+ <XDSChartAxis position="bottom" />+ <XDSChartAxis position="left" />+ <XDSChartArea+ yUpper="upper95"+ yLower="lower95"+ color={c[0]}+ opacity={0.1}+ />+ <XDSChartArea+ yUpper="upper80"+ yLower="lower80"+ color={c[0]}+ opacity={0.2}+ />+ <XDSChartLine dataKey="mean" color={c[0]} dots />+ <XDSChartLegend+ items={[+ {label: 'Mean', color: c[0]},+ {label: '80% CI', color: colors.alpha(c[0], 0.3)},+ {label: '95% CI', color: colors.alpha(c[0], 0.15)},+ ]}+ />+ </XDSChart>+ </XDSStack>+ );+}+export const ConfidenceIntervals: StoryObj = {+ render: () => <ConfidenceIntervalsDemo />,+};++function UpperConfidenceDemo() {+ const colors = useXDSChartColors();+ const c = colors.categorical(3);+ return (+ <XDSStack direction="vertical" gap={4}>+ <XDSHeading level={3}>Upper Confidence Only</XDSHeading>+ <XDSChart+ data={ciData}+ xKey="month"+ yKeys={['upper95', 'mean']}+ height={300}>+ <XDSChartGrid horizontal />+ <XDSChartAxis position="bottom" />+ <XDSChartAxis position="left" />+ <XDSChartArea+ yUpper="upper95"+ baseline="mean"+ color={c[1]}+ opacity={0.2}+ />+ <XDSChartLine dataKey="mean" color={c[1]} dots />+ </XDSChart>+ </XDSStack>+ );+}+export const UpperConfidence: StoryObj = {+ render: () => <UpperConfidenceDemo />,+};++const errorData = [+ {category: 'A', value: 45, upper: 52, lower: 38},+ {category: 'B', value: 62, upper: 70, lower: 54},+ {category: 'C', value: 38, upper: 48, lower: 28},+ {category: 'D', value: 55, upper: 60, lower: 50},+ {category: 'E', value: 48, upper: 58, lower: 38},+];++function ErrorBarsDemo() {+ const colors = useXDSChartColors();+ return (+ <XDSStack direction="vertical" gap={4}>+ <XDSHeading level={3}>Bar Chart with Error Bars</XDSHeading>+ <XDSChart+ data={errorData}+ xKey="category"+ yKeys={['upper', 'lower']}+ height={300}>+ <XDSChartGrid horizontal />+ <XDSChartAxis position="bottom" />+ <XDSChartAxis position="left" />+ <XDSChartBar dataKey="value" color={colors.categorical(1)[0]} />+ <XDSChartErrorBar yUpper="upper" yLower="lower" />+ </XDSChart>+ </XDSStack>+ );+}+export const ErrorBars: StoryObj = {render: () => <ErrorBarsDemo />};++const ohlcData = [+ {day: 'Mon', open: 100, close: 108, high: 112, low: 98},+ {day: 'Tue', open: 108, close: 103, high: 110, low: 101},+ {day: 'Wed', open: 103, close: 110, high: 115, low: 100},+ {day: 'Thu', open: 110, close: 106, high: 113, low: 104},+ {day: 'Fri', open: 106, close: 114, high: 118, low: 105},+];++export const Candlestick: StoryObj = {+ render: () => (+ <XDSStack direction="vertical" gap={4}>+ <XDSHeading level={3}>Candlestick (OHLC)</XDSHeading>+ <XDSChart+ data={ohlcData}+ xKey="day"+ yKeys={['high', 'low']}+ yBaseline="data"+ height={300}>+ <XDSChartGrid horizontal />+ <XDSChartAxis position="bottom" />+ <XDSChartAxis position="left" />+ <XDSChartCandlestick high="high" low="low" open="open" close="close" />+ </XDSChart>+ </XDSStack>+ ),+};++function CandlestickBarDemo() {+ const colors = useXDSChartColors();+ return (+ <XDSStack direction="vertical" gap={4}>+ <XDSHeading level={3}>OHLC Bar</XDSHeading>+ <XDSText type="supporting" color="secondary">+ Vertical line for range, left tick at open, right tick at close.+ </XDSText>+ <XDSChart+ data={ohlcData}+ xKey="day"+ yKeys={['high', 'low']}+ yBaseline="data"+ height={300}>+ <XDSChartGrid horizontal />+ <XDSChartAxis position="bottom" />+ <XDSChartAxis position="left" />+ <XDSChartCandlestick+ variant="bar"+ high="high"+ low="low"+ open="open"+ close="close"+ color={colors.categorical(1)[0]}+ />+ </XDSChart>+ </XDSStack>+ );+}+export const CandlestickBar: StoryObj = {render: () => <CandlestickBarDemo />};++const plData = [+ {month: 'Jan', profit: 12},+ {month: 'Feb', profit: -8},+ {month: 'Mar', profit: 22},+ {month: 'Apr', profit: -15},+ {month: 'May', profit: 5},+ {month: 'Jun', profit: -3},+];++function ZeroCenteredDemo() {+ const colors = useXDSChartColors();+ return (+ <XDSStack direction="vertical" gap={4}>+ <XDSHeading level={3}>+ Zero-Centered (yBaseline="zero")+ </XDSHeading>+ <XDSChart+ data={plData}+ xKey="month"+ yKeys={['profit']}+ yBaseline="zero"+ height={300}>+ <XDSChartGrid horizontal />+ <XDSChartAxis position="bottom" />+ <XDSChartAxis position="left" />+ <XDSChartBar dataKey="profit" color={colors.categorical(1)[0]} />+ </XDSChart>+ </XDSStack>+ );+}+export const ZeroCentered: StoryObj = {render: () => <ZeroCenteredDemo />};++function GradientLegendDemo() {+ const colors = useXDSChartColors();+ return (+ <XDSStack direction="vertical" gap={6}>+ <XDSHeading level={3}>Gradient Legends</XDSHeading>+ <XDSStack direction="vertical" gap={4}>+ <XDSChart+ data={[+ {x: 0, v: 0},+ {x: 1, v: 100},+ ]}+ xKey="x"+ yKeys={['v']}+ height={80}>+ <XDSChartLegend+ gradient={colors.sequential.blue(5)}+ domain={[0, 100]}+ label="Temperature"+ />+ </XDSChart>+ <XDSChart+ data={[+ {x: 0, v: -50},+ {x: 1, v: 50},+ ]}+ xKey="x"+ yKeys={['v']}+ height={80}>+ <XDSChartLegend+ gradient={colors.diverging.coldHot(7)}+ domain={[-50, 50]}+ label="Change %"+ tickFormat={v => `${v > 0 ? '+' : ''}${v}%`}+ />+ </XDSChart>+ <XDSChart+ data={[+ {x: 0, v: 0},+ {x: 1, v: 1},+ ]}+ xKey="x"+ yKeys={['v']}+ height={80}>+ <XDSChartLegend+ gradient={colors.diverging.positiveNegative(9)}+ domain={[-100, 100]}+ label="Profit/Loss"+ ticks={5}+ />+ </XDSChart>+ </XDSStack>+ </XDSStack>+ );+}+export const GradientLegend: StoryObj = {render: () => <GradientLegendDemo />};diff --git a/apps/storybook/stories/ChartColors.stories.tsx b/apps/storybook/stories/ChartColors.stories.tsxdeleted file mode 100644index ee2a92dde6..0000000000--- a/apps/storybook/stories/ChartColors.stories.tsx+++ /dev/null@@ -1,123 +0,0 @@-import type {Meta, StoryObj} from '@storybook/react';-import {XDSChartColors, type SequentialHue} from '@xds/lab';-import {XDSStack, XDSText} from '@xds/core';-import {XDSHeading} from '@xds/core/Text';--const meta: Meta = {- title: 'Lab/XDSChartColors',-};--export default meta;--function Swatches({colors, label}: {colors: string[]; label: string}) {- return (- <XDSStack direction="vertical" gap={1}>- <XDSText type="label">{label}</XDSText>- <XDSStack direction="horizontal" gap={0.5}>- {colors.map((color, i) => (- <div- key={i}- title={color}- style={{- width: 48,- height: 32,- borderRadius: 4,- backgroundColor: color,- }}- />- ))}- </XDSStack>- </XDSStack>- );-}--export const Categorical: StoryObj = {- render: () => (- <XDSStack direction="vertical" gap={6}>- <XDSHeading level={3}>Categorical Palettes</XDSHeading>- <XDSStack direction="vertical" gap={4}>- <Swatches- colors={XDSChartColors.categorical(5)}- label="categorical(5)"- />- <Swatches- colors={XDSChartColors.categorical(10)}- label="categorical(10)"- />- </XDSStack>- </XDSStack>- ),-};--export const Sequential: StoryObj = {- render: () => {- const hues: SequentialHue[] = [- 'blue',- 'shamrock',- 'orange',- 'pink',- 'purple',- 'red',- 'teal',- 'yellow',- 'gray',- ];- return (- <XDSStack direction="vertical" gap={6}>- <XDSHeading level={3}>Sequential Ramps</XDSHeading>- <XDSStack direction="vertical" gap={4}>- {hues.map(hue => (- <Swatches- key={hue}- colors={XDSChartColors.sequential[hue](5)}- label={`sequential.${hue}(5)`}- />- ))}- </XDSStack>- </XDSStack>- );- },-};--export const Diverging: StoryObj = {- render: () => (- <XDSStack direction="vertical" gap={6}>- <XDSHeading level={3}>Diverging Palettes</XDSHeading>- <XDSStack direction="vertical" gap={4}>- <Swatches- colors={XDSChartColors.diverging.positiveNegative(5)}- label="diverging.positiveNegative(5)"- />- <Swatches- colors={XDSChartColors.diverging.positiveNegative(11)}- label="diverging.positiveNegative(11)"- />- <Swatches- colors={XDSChartColors.diverging.coldHot(7)}- label="diverging.coldHot(7)"- />- <Swatches- colors={XDSChartColors.diverging.custom('blue', 'orange', 7)}- label="diverging.custom('blue', 'orange', 7)"- />- </XDSStack>- </XDSStack>- ),-};--export const Semantic: StoryObj = {- render: () => (- <XDSStack direction="vertical" gap={6}>- <XDSHeading level={3}>Semantic Colors</XDSHeading>- <Swatches- colors={[- XDSChartColors.semantic.positive,- XDSChartColors.semantic.negative,- XDSChartColors.semantic.warning,- XDSChartColors.semantic.neutral,- ]}- label="positive, negative, warning, neutral"- />- </XDSStack>- ),-};diff --git a/apps/storybook/stories/ChartDotGL.stories.tsx b/apps/storybook/stories/ChartDotGL.stories.tsxnew file mode 100644index 0000000000..d68197eac1--- /dev/null+++ b/apps/storybook/stories/ChartDotGL.stories.tsx@@ -0,0 +1,75 @@+import type {Meta, StoryObj} from '@storybook/react';+import {+ XDSChart,+ XDSChartAxis,+ XDSChartGrid,+ XDSChartDot,+ XDSChartDotGL,+ useXDSChartColors,+} from '@xds/lab';+import {XDSStack, XDSText} from '@xds/core';+import {XDSHeading} from '@xds/core/Text';++const meta: Meta = {title: 'Lab/XDSChartDotGL'};+export default meta;++const smallData = Array.from({length: 30}, (_, i) => ({+ x: i,+ y: Math.sin(i * 0.3) * 40 + 50 + Math.random() * 20,+}));+const largeData = Array.from({length: 5000}, () => ({+ x: Math.random() * 100,+ y: Math.random() * 100,+}));++function SVGvsWebGLDemo() {+ const colors = useXDSChartColors();+ const c = colors.categorical(2);+ return (+ <XDSStack direction="vertical" gap={6}>+ <XDSHeading level={3}>SVG vs WebGL</XDSHeading>+ <XDSStack direction="horizontal" gap={6}>+ <XDSStack direction="vertical" gap={1}>+ <XDSText type="label">SVG (XDSChartDot)</XDSText>+ <XDSChart data={smallData} xKey="x" yKeys={['y']} height={250}>+ <XDSChartGrid horizontal />+ <XDSChartAxis position="bottom" />+ <XDSChartAxis position="left" />+ <XDSChartDot dataKey="y" color={c[0]} radius={4} />+ </XDSChart>+ </XDSStack>+ <XDSStack direction="vertical" gap={1}>+ <XDSText type="label">WebGL (XDSChartDotGL)</XDSText>+ <XDSChart data={smallData} xKey="x" yKeys={['y']} height={250}>+ <XDSChartGrid horizontal />+ <XDSChartAxis position="bottom" />+ <XDSChartAxis position="left" />+ <XDSChartDotGL dataKey="y" color={c[0]} size={8} />+ </XDSChart>+ </XDSStack>+ </XDSStack>+ </XDSStack>+ );+}+export const SVGvsWebGL: StoryObj = {render: () => <SVGvsWebGLDemo />};++function LargeDatasetDemo() {+ const colors = useXDSChartColors();+ return (+ <XDSStack direction="vertical" gap={4}>+ <XDSHeading level={3}>WebGL \u2014 5,000 points</XDSHeading>+ <XDSChart data={largeData} xKey="x" yKeys={['y']} height={400}>+ <XDSChartGrid horizontal vertical />+ <XDSChartAxis position="bottom" />+ <XDSChartAxis position="left" />+ <XDSChartDotGL+ dataKey="y"+ color={colors.categorical(1)[0]}+ size={4}+ opacity={0.5}+ />+ </XDSChart>+ </XDSStack>+ );+}+export const LargeDataset: StoryObj = {render: () => <LargeDatasetDemo />};diff --git a/apps/storybook/stories/ChartDotGLInteractive.stories.tsx b/apps/storybook/stories/ChartDotGLInteractive.stories.tsxnew file mode 100644index 0000000000..8457c247de--- /dev/null+++ b/apps/storybook/stories/ChartDotGLInteractive.stories.tsx@@ -0,0 +1,74 @@+import type {Meta, StoryObj} from '@storybook/react';+import {+ XDSChart,+ XDSChartAxis,+ XDSChartGrid,+ XDSChartDotGLInteractive,+ useXDSChartColors,+} from '@xds/lab';+import {XDSStack, XDSText} from '@xds/core';+import {XDSHeading} from '@xds/core/Text';++const meta: Meta = {title: 'Lab/XDSChartDotGLInteractive'};+export default meta;++const scatterData = Array.from({length: 5000}, () => ({+ x: Math.random() * 100,+ y: Math.random() * 100,+}));+const bigScatter = Array.from({length: 50000}, (_, i) => ({+ x: Math.random() * 1000,+ y: Math.sin(i * 0.001) * 40 + Math.random() * 60,+}));++function GPUPicking5kDemo() {+ const colors = useXDSChartColors();+ return (+ <XDSStack direction="vertical" gap={4}>+ <XDSHeading level={3}>GPU Color-Picking \u2014 5,000 points</XDSHeading>+ <XDSText type="supporting" color="secondary">+ Hover any point. O(1) via readPixels.+ </XDSText>+ <XDSChart data={scatterData} xKey="x" yKeys={['y']} height={400}>+ <XDSChartGrid horizontal vertical />+ <XDSChartAxis position="bottom" />+ <XDSChartAxis position="left" />+ <XDSChartDotGLInteractive+ dataKey="y"+ color={colors.categorical(1)[0]}+ size={6}+ opacity={0.6}+ />+ </XDSChart>+ </XDSStack>+ );+}+export const GPUPicking5k: StoryObj = {render: () => <GPUPicking5kDemo />};++function GPUPicking50kDemo() {+ const colors = useXDSChartColors();+ return (+ <XDSStack direction="vertical" gap={4}>+ <XDSHeading level={3}>GPU Color-Picking \u2014 50,000 points</XDSHeading>+ <XDSChart data={bigScatter} xKey="x" yKeys={['y']} height={400}>+ <XDSChartGrid horizontal />+ <XDSChartAxis position="bottom" />+ <XDSChartAxis position="left" />+ <XDSChartDotGLInteractive+ dataKey="y"+ color={colors.categorical(2)[1]}+ size={3}+ opacity={0.4}+ renderTooltip={(d, i) => (+ <div style={{fontSize: 12}}>+ <div style={{fontWeight: 600}}>#{i.toLocaleString()}</div>+ <div>x: {Number(d.x).toFixed(1)}</div>+ <div>y: {Number(d.y).toFixed(1)}</div>+ </div>+ )}+ />+ </XDSChart>+ </XDSStack>+ );+}+export const GPUPicking50k: StoryObj = {render: () => <GPUPicking50kDemo />};diff --git a/apps/storybook/stories/ChartHeatmapGL.stories.tsx b/apps/storybook/stories/ChartHeatmapGL.stories.tsxnew file mode 100644index 0000000000..2db6a69143--- /dev/null+++ b/apps/storybook/stories/ChartHeatmapGL.stories.tsx@@ -0,0 +1,125 @@+import type {Meta, StoryObj} from '@storybook/react';+import {+ XDSChart,+ XDSChartAxis,+ XDSChartHeatmapGL,+ XDSChartLegend,+ useXDSChartColors,+ type SequentialHue,+} from '@xds/lab';+import {XDSStack, XDSText} from '@xds/core';+import {XDSHeading} from '@xds/core/Text';++const meta: Meta = {title: 'Lab/XDSChartHeatmapGL'};+export default meta;++const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];+const hours = [+ '6am',+ '8am',+ '10am',+ '12pm',+ '2pm',+ '4pm',+ '6pm',+ '8pm',+ '10pm',+];+const gridData = days.flatMap((day, di) =>+ hours.map((hour, hi) => ({+ hour,+ day,+ activity: Math.round(+ Math.sin((di + hi) * 0.5) * 30 + 50 + Math.random() * 20,+ ),+ })),+);++function ActivityGridDemo() {+ const colors = useXDSChartColors();+ return (+ <XDSStack direction="vertical" gap={4}>+ <XDSHeading level={3}>Heatmap \u2014 Activity by Day x Hour</XDSHeading>+ <XDSChart data={gridData} xKey="hour" yKeys={['activity']} height={280}>+ <XDSChartAxis position="bottom" />+ <XDSChartHeatmapGL+ xKey="hour"+ yKey="day"+ valueKey="activity"+ colorRange={colors.sequential.blue(5)}+ />+ <XDSChartLegend+ gradient={colors.sequential.blue(5)}+ domain={[0, 100]}+ label="Activity"+ />+ </XDSChart>+ </XDSStack>+ );+}+export const ActivityGrid: StoryObj = {render: () => <ActivityGridDemo />};++function ColorRampsDemo() {+ const colors = useXDSChartColors();+ const hues: SequentialHue[] = ['blue', 'shamrock', 'orange', 'purple', 'red'];+ return (+ <XDSStack direction="vertical" gap={6}>+ <XDSHeading level={3}>Heatmap Color Ramps</XDSHeading>+ {hues.map(hue => (+ <XDSStack key={hue} direction="vertical" gap={1}>+ <XDSText type="label">sequential.{hue}(5)</XDSText>+ <XDSChart+ data={gridData}+ xKey="hour"+ yKeys={['activity']}+ height={200}>+ <XDSChartAxis position="bottom" />+ <XDSChartHeatmapGL+ xKey="hour"+ yKey="day"+ valueKey="activity"+ colorRange={colors.sequential[hue](5)}+ />+ </XDSChart>+ </XDSStack>+ ))}+ </XDSStack>+ );+}+export const ColorRamps: StoryObj = {render: () => <ColorRampsDemo />};++const bigRows = Array.from({length: 50}, (_, i) => String(i));+const bigCols = Array.from({length: 50}, (_, i) => String(i));+const bigGrid = bigRows.flatMap(row =>+ bigCols.map(col => ({+ col,+ row,+ value: Math.round(+ Math.sin(Number(row) * 0.2) * Math.cos(Number(col) * 0.15) * 50 + 50,+ ),+ })),+);++function LargeGridDemo() {+ const colors = useXDSChartColors();+ return (+ <XDSStack direction="vertical" gap={4}>+ <XDSHeading level={3}>Heatmap \u2014 50x50 Grid</XDSHeading>+ <XDSChart data={bigGrid} xKey="col" yKeys={['value']} height={400}>+ <XDSChartHeatmapGL+ xKey="col"+ yKey="row"+ valueKey="value"+ colorRange={colors.sequential.red(5)}+ cellGap={0}+ />+ <XDSChartLegend+ gradient={colors.sequential.red(5)}+ domain={[0, 100]}+ label="Intensity"+ />+ </XDSChart>+ </XDSStack>+ );+}+export const LargeGrid: StoryObj = {render: () => <LargeGridDemo />};diff --git a/apps/storybook/stories/ChartStreamGL.stories.tsx b/apps/storybook/stories/ChartStreamGL.stories.tsxnew file mode 100644index 0000000000..76c1e12fbc--- /dev/null+++ b/apps/storybook/stories/ChartStreamGL.stories.tsx@@ -0,0 +1,374 @@+import type {Meta, StoryObj} from '@storybook/react';+import {useRef, useEffect, useState} 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',+};++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);++ 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);+ }, []);++ 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>+ </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+// =============================================================================++function useMetricStream(+ ref: React.RefObject<XDSChartStreamGLHandle | null>,+ config: {+ base: number;+ amplitude: number;+ frequency: number;+ noise: number;+ spikeProbability: number;+ spikeSize: number;+ },+) {+ const tRef = useRef(0);+ useEffect(() => {+ const {base, amplitude, frequency, noise, spikeProbability, spikeSize} =+ config;+ const id = setInterval(() => {+ tRef.current += 1;+ let value =+ base ++ Math.sin(tRef.current * frequency) * amplitude ++ Math.sin(tRef.current * frequency * 2.7) * amplitude * 0.3 ++ (Math.random() - 0.5) * noise;+ if (Math.random() < spikeProbability) {+ value += spikeSize * (0.5 + Math.random() * 0.5);+ }+ value = Math.max(0, Math.min(100, value));+ ref.current?.push(tRef.current, value);+ }, 33);+ return () => clearInterval(id);+ }, [ref, config]);+}++function ServerMetrics() {+ const colors = useXDSChartColors().categorical(5);+ const cpuRef = useRef<XDSChartStreamGLHandle>(null);+ const memRef = useRef<XDSChartStreamGLHandle>(null);+ const netRef = useRef<XDSChartStreamGLHandle>(null);++ 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,+ });++ 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>+ </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+// =============================================================================++function Seismograph() {+ const colors = useXDSChartColors().categorical(5);+ const streamRef = useRef<XDSChartStreamGLHandle>(null);+ const tRef = useRef(0);+ const quakeRef = useRef(0);++ 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);+ raf = requestAnimationFrame(tick);+ };+ raf = requestAnimationFrame(tick);+ 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="zero" anchors 0 to center. yDomain=[-80, 80] keeps+ axis stable.+ </XDSText>+ <Seismograph />+ </XDSStack>+ ),+};++// =============================================================================+// Multi-sensor overlay — same chart, same yDomain+// =============================================================================++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);+ }, []);++ 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>+ );+}++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>+ ),+};diff --git a/packages/lab/src/Chart/XDSChart.tsx b/packages/lab/src/Chart/XDSChart.tsxindex 2b0ed786d1..e70ce1eb4c 100644--- a/packages/lab/src/Chart/XDSChart.tsx+++ b/packages/lab/src/Chart/XDSChart.tsx@@ -19,6 +19,14 @@ import type {ScaleLinear} from 'd3-scale';import {ChartProvider} from './ChartContext';import type {ChartMargin, ChartScale} from './types';+/**+ * Controls how the y-axis domain is computed:+ * - `'auto'` — includes 0 when all values are positive (default, bar-friendly)+ * - `'zero'` — symmetric range centered on 0 (good for +/- data)+ * - `'data'` — tight fit to data extent only (no forced zero)+ */+export type YBaseline = 'auto' | 'zero' | 'data';+export interface XDSChartProps {/** The dataset — array of objects with consistent keys */data: Record<string, unknown>[];@@ -36,6 +44,19 @@ export interface XDSChartProps {height?: number;/** Override default margins */margin?: Partial<ChartMargin>;+ /**+ * How the y-axis domain is computed.+ * - `'auto'` — includes 0 when all values are positive (default)+ * - `'zero'` — symmetric around 0 (use for profit/loss, sentiment, etc.)+ * - `'data'` — tight fit to data extent+ */+ 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.+ */+ yDomain?: [number, number];/** Chart contents — axes, marks, tooltips */children: ReactNode;}@@ -50,7 +71,7 @@ const DEFAULT_MARGIN: ChartMargin = {top: 16, right: 16, bottom: 32, left: 48};* <XDSChart data={data} xKey="month" yKeys={['revenue']} height={300}>* <XDSChartAxis position="bottom" />* <XDSChartAxis position="left" />- * <XDSChartBar dataKey="revenue" color={XDSChartColors.categorical(1)[0]} />+ * <XDSChartBar dataKey="revenue" color={useXDSChartColors().categorical(1)[0]} />* </XDSChart>* ```*/@@ -60,6 +81,8 @@ export function XDSChart({yKeys,height = 300,margin: marginOverride,+ yBaseline = 'auto',+ yDomain: yDomainProp,children,}: XDSChartProps) {const containerRef = useRef<HTMLDivElement>(null);@@ -95,7 +118,6 @@ export function XDSChart({.nice();}- // Categorical / stringreturn scaleBand<string>().domain(xValues.map(String)).range([0, innerWidth])@@ -103,8 +125,11 @@ export function XDSChart({}, [data, xKey, innerWidth]);const yScale = useMemo((): ScaleLinear<number, number> => {- let min = Infinity;- let max = -Infinity;+ // Start from explicit domain or compute from data+ let min = yDomainProp ? yDomainProp[0] : Infinity;+ let max = yDomainProp ? yDomainProp[1] : -Infinity;++ // Always scan data — expand beyond yDomainProp if data exceeds itfor (const d of data) {for (const key of yKeys) {const v = d[key];@@ -114,10 +139,18 @@ export function XDSChart({}}}- // Always include 0 in bar-friendly charts- if (min > 0) min = 0;++ 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();- }, [data, yKeys, innerHeight]);+ }, [data, yKeys, innerHeight, yBaseline, yDomainProp]);const ctx = useMemo(() => ({diff --git a/packages/lab/src/Chart/XDSChartArea.tsx b/packages/lab/src/Chart/XDSChartArea.tsxnew file mode 100644index 0000000000..dc11e77983--- /dev/null+++ b/packages/lab/src/Chart/XDSChartArea.tsx@@ -0,0 +1,109 @@+/**+ * @file XDSChartArea.tsx+ * @output Renders a filled area between two y-bounds — confidence intervals, bands, ranges+ * @position Child of XDSChart; reads scales from context+ */++import {useMemo} from 'react';+import {area, curveMonotoneX} from 'd3-shape';+import {useChart} from './ChartContext';+import type {ScaleBand} from 'd3-scale';++export interface XDSChartAreaProps {+ /** Data key for the upper bound. If omitted, uses `baseline`. */+ yUpper?: string;+ /** Data key for the lower bound. If omitted, uses `baseline`. */+ yLower?: string;+ /**+ * Fallback data key when only one bound is specified.+ * Acts as the other edge of the band.+ */+ baseline?: string;+ /** Fill color */+ color: string;+ /** Fill opacity (default: 0.2) */+ opacity?: number;+ /** Optional stroke on the band edges */+ stroke?: boolean;+ /** Stroke width when stroke is enabled */+ strokeWidth?: number;+}++function isBandScale(scale: unknown): scale is ScaleBand<string> {+ return typeof scale === 'function' && 'bandwidth' in scale;+}++/**+ * Area band between two y-values. Use for confidence intervals, error ranges,+ * or any min/max band around a line.+ *+ * Supports full band (both bounds), upper-only, or lower-only:+ *+ * @example+ * ```+ * // Full band+ * <XDSChartArea yUpper="upper95" yLower="lower95" color={colors[0]} />+ *+ * // Upper confidence only — shades from mean up to upper bound+ * <XDSChartArea yUpper="upper95" baseline="mean" color={colors[0]} />+ *+ * // Lower confidence only — shades from lower bound up to mean+ * <XDSChartArea yLower="lower95" baseline="mean" color={colors[0]} />+ * ```+ */+export function XDSChartArea({+ yUpper,+ yLower,+ baseline,+ color,+ opacity = 0.2,+ stroke = false,+ strokeWidth = 1,+}: XDSChartAreaProps) {+ const {data, xScale, yScale} = useChart();++ // Resolve which keys to use for upper and lower edges+ const upperKey = yUpper ?? baseline;+ const lowerKey = yLower ?? baseline;++ const pathD = useMemo(() => {+ if (!upperKey || !lowerKey) return '';++ const generator = area<Record<string, unknown>>()+ .x(d => {+ if (isBandScale(xScale)) {+ return (+ (xScale(String(Object.values(d)[0])) ?? 0) + xScale.bandwidth() / 2+ );+ }+ return (xScale as (v: number) => number)(Object.values(d)[0] as number);+ })+ .y0(d => {+ const v = typeof d[lowerKey] === 'number' ? (d[lowerKey] as number) : 0;+ return yScale(v);+ })+ .y1(d => {+ const v = typeof d[upperKey] === 'number' ? (d[upperKey] as number) : 0;+ return yScale(v);+ })+ .curve(curveMonotoneX);+ return generator(data) ?? '';+ }, [data, xScale, yScale, upperKey, lowerKey]);++ if (!pathD) return null;++ return (+ <g>+ <path d={pathD} fill={color} fillOpacity={opacity} stroke="none" />+ {stroke && (+ <path+ d={pathD}+ fill="none"+ stroke={color}+ strokeWidth={strokeWidth}+ strokeOpacity={opacity * 2}+ />+ )}+ </g>+ );+}diff --git a/packages/lab/src/Chart/XDSChartBar.tsx b/packages/lab/src/Chart/XDSChartBar.tsxindex b9e5b6e56a..fc435919f2 100644--- a/packages/lab/src/Chart/XDSChartBar.tsx+++ b/packages/lab/src/Chart/XDSChartBar.tsx@@ -25,7 +25,7 @@ function isBandScale(scale: unknown): scale is ScaleBand<string> {** @example* ```- * <XDSChartBar dataKey="revenue" color={XDSChartColors.categorical(1)[0]} />+ * <XDSChartBar dataKey="revenue" color={useXDSChartColors().categorical(1)[0]} />* ```*/export function XDSChartBar({dataKey, color, radius = 4}: XDSChartBarProps) {diff --git a/packages/lab/src/Chart/XDSChartCandlestick.tsx b/packages/lab/src/Chart/XDSChartCandlestick.tsxnew file mode 100644index 0000000000..207d4c86ad--- /dev/null+++ b/packages/lab/src/Chart/XDSChartCandlestick.tsx@@ -0,0 +1,183 @@+/**+ * @file XDSChartCandlestick.tsx+ * @output Renders candlestick/box-whisker marks for OHLC or statistical data+ * @position Child of XDSChart; reads scales from context+ *+ * Two variants:+ * - `'default'` — filled body with whiskers (traditional candlestick/box plot)+ * - `'bar'` — OHLC bar — vertical line with open/close ticks+ */++import {useChart} from './ChartContext';+import type {ScaleBand} from 'd3-scale';++export interface XDSChartCandlestickProps {+ /** Data key for the high/max value (top of whisker) */+ high: string;+ /** Data key for the low/min value (bottom of whisker) */+ low: string;+ /** Data key for the open/Q1 value (bottom of body) */+ open: string;+ /** Data key for the close/Q3 value (top of body) */+ close: string;+ /**+ * Visual variant:+ * - `'default'` — filled body with whiskers+ * - `'bar'` — OHLC bar — vertical range line, left tick at open, right tick at close+ */+ variant?: 'default' | 'bar';+ /** Color when close >= open (bullish / positive) */+ upColor?: string;+ /** Color when close < open (bearish / negative) */+ downColor?: string;+ /** Fixed color — overrides up/down logic. Use for box plots. */+ color?: string;+ /** Body width as fraction of band width (default: 0.6) */+ bodyWidth?: number;+ /** Stroke width for whiskers and bar lines */+ strokeWidth?: number;+ /** Corner radius on body (default variant only) */+ radius?: number;+ /** Dot radius (unused in bar variant, kept for future variants) */+ dotRadius?: number;+}++function isBandScale(scale: unknown): scale is ScaleBand<string> {+ return typeof scale === 'function' && 'bandwidth' in scale;+}++/**+ * Candlestick / box-whisker marks with optional Tufte variant.+ *+ * @example+ * ```+ * // Financial OHLC+ * <XDSChartCandlestick+ * high="high" low="low" open="open" close="close"+ * upColor={useXDSChartColors().semantic.positive}+ * downColor={useXDSChartColors().semantic.negative}+ * />+ *+ * // Tufte range-bar+ * <XDSChartCandlestick+ * variant="bar"+ * high="max" low="min" open="q1" close="median"+ * color={useXDSChartColors().categorical(1)[0]}+ * />+ * ```+ */+export function XDSChartCandlestick({+ high,+ low,+ open,+ close,+ variant = 'default',+ upColor = '#0B991F',+ downColor = '#F5394F',+ color,+ bodyWidth = 0.6,+ strokeWidth = 1.5,+ radius = 2,+ dotRadius = 3,+}: XDSChartCandlestickProps) {+ const {data, xScale, yScale} = useChart();++ if (!isBandScale(xScale)) return null;+ const bw = xScale.bandwidth();++ return (+ <g>+ {data.map((d, i) => {+ const xVal = xScale(String(Object.values(d)[0]));+ if (xVal == null) return null;++ const hVal = typeof d[high] === 'number' ? (d[high] as number) : 0;+ const lVal = typeof d[low] === 'number' ? (d[low] as number) : 0;+ const oVal = typeof d[open] === 'number' ? (d[open] as number) : 0;+ const cVal = typeof d[close] === 'number' ? (d[close] as number) : 0;++ const isUp = cVal >= oVal;+ const fill = color ?? (isUp ? upColor : downColor);+ const centerX = xVal + bw / 2;++ const yHigh = yScale(hVal);+ const yLow = yScale(lVal);+ const yOpen = yScale(oVal);+ const yClose = yScale(cVal);+ const bodyTop = Math.min(yOpen, yClose);+ const bodyBot = Math.max(yOpen, yClose);++ if (variant === 'bar') {+ // OHLC bar: vertical line (high→low), left tick at open, right tick at close+ const tickLen = bw * bodyWidth * 0.4;+ return (+ <g key={i}>+ {/* Vertical range line: high to low */}+ <line+ x1={centerX}+ x2={centerX}+ y1={yHigh}+ y2={yLow}+ stroke={fill}+ strokeWidth={strokeWidth}+ />+ {/* Open tick — extends left */}+ <line+ x1={centerX - tickLen}+ x2={centerX}+ y1={yOpen}+ y2={yOpen}+ stroke={fill}+ strokeWidth={strokeWidth}+ />+ {/* Close tick — extends right */}+ <line+ x1={centerX}+ x2={centerX + tickLen}+ y1={yClose}+ y2={yClose}+ stroke={fill}+ strokeWidth={strokeWidth}+ />+ </g>+ );+ }++ // Default variant: filled body with whiskers+ const bodyW = bw * bodyWidth;+ const bodyX = centerX - bodyW / 2;+ const bodyH = Math.max(1, bodyBot - bodyTop);++ return (+ <g key={i}>+ <line+ x1={centerX}+ x2={centerX}+ y1={yHigh}+ y2={bodyTop}+ stroke={fill}+ strokeWidth={strokeWidth}+ />+ <line+ x1={centerX}+ x2={centerX}+ y1={bodyBot}+ y2={yLow}+ stroke={fill}+ strokeWidth={strokeWidth}+ />+ <rect+ x={bodyX}+ y={bodyTop}+ width={bodyW}+ height={bodyH}+ fill={fill}+ rx={radius}+ ry={radius}+ />+ </g>+ );+ })}+ </g>+ );+}diff --git a/packages/lab/src/Chart/XDSChartDot.tsx b/packages/lab/src/Chart/XDSChartDot.tsxindex 5bd81b3d6c..8c932ac47a 100644--- a/packages/lab/src/Chart/XDSChartDot.tsx+++ b/packages/lab/src/Chart/XDSChartDot.tsx@@ -25,7 +25,7 @@ function isBandScale(scale: unknown): scale is ScaleBand<string> {** @example* ```- * <XDSChartDot dataKey="outliers" color={XDSChartColors.categorical(3)[2]} />+ * <XDSChartDot dataKey="outliers" color={useXDSChartColors().categorical(3)[2]} />* ```*/export function XDSChartDot({dataKey, color, radius = 4}: XDSChartDotProps) {diff --git a/packages/lab/src/Chart/XDSChartDotGL.tsx b/packages/lab/src/Chart/XDSChartDotGL.tsxnew file mode 100644index 0000000000..0e1e50e72e--- /dev/null+++ b/packages/lab/src/Chart/XDSChartDotGL.tsx@@ -0,0 +1,204 @@+/**+ * @file XDSChartDotGL.tsx+ * @output WebGL scatter renderer — canvas overlay aligned with SVG chart space+ * @position Child of XDSChart; reads scales from context, renders to a canvas via foreignObject+ */++import {useRef, useEffect, useCallback} from 'react';+import {useChart} from './ChartContext';+import type {ScaleBand} from 'd3-scale';++export interface XDSChartDotGLProps {+ /** Which data key for the y values */+ dataKey: string;+ /** Dot fill color (hex string) */+ color: string;+ /** Point size in pixels */+ size?: number;+ /** Opacity 0-1 */+ opacity?: number;+}++function isBandScale(scale: unknown): scale is ScaleBand<string> {+ return typeof scale === 'function' && 'bandwidth' in scale;+}++/** Parse hex color to [r, g, b] floats 0-1 */+function hexToGL(hex: string): [number, number, number] {+ const n = parseInt(hex.replace('#', ''), 16);+ return [(n >> 16) / 255, ((n >> 8) & 0xff) / 255, (n & 0xff) / 255];+}++const VERT = `+ attribute vec2 a_position;+ uniform vec2 u_resolution;+ uniform float u_size;+ void main() {+ // Convert pixel coords to clip space (-1 to 1)+ vec2 clip = (a_position / u_resolution) * 2.0 - 1.0;+ // Flip y — canvas y goes down, clip y goes up+ gl_Position = vec4(clip.x, -clip.y, 0.0, 1.0);+ gl_PointSize = u_size;+ }+`;++const FRAG = `+ precision mediump float;+ uniform vec3 u_color;+ uniform float u_opacity;+ void main() {+ // Circle mask — discard outside radius+ vec2 coord = gl_PointCoord - vec2(0.5);+ if (dot(coord, coord) > 0.25) discard;+ gl_FragColor = vec4(u_color, u_opacity);+ }+`;++function compileShader(+ gl: WebGLRenderingContext,+ type: number,+ source: string,+): WebGLShader | null {+ const shader = gl.createShader(type);+ if (!shader) return null;+ gl.shaderSource(shader, source);+ gl.compileShader(shader);+ if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {+ gl.deleteShader(shader);+ return null;+ }+ return shader;+}++function createProgram(gl: WebGLRenderingContext): WebGLProgram | null {+ const vert = compileShader(gl, gl.VERTEX_SHADER, VERT);+ const frag = compileShader(gl, gl.FRAGMENT_SHADER, FRAG);+ if (!vert || !frag) return null;+ const program = gl.createProgram();+ if (!program) return null;+ gl.attachShader(program, vert);+ gl.attachShader(program, frag);+ gl.linkProgram(program);+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {+ gl.deleteProgram(program);+ return null;+ }+ return program;+}++/**+ * WebGL scatter plot. Renders points on a canvas overlay aligned with the SVG chart.+ * Use for large datasets (1k+ points) where SVG circles would be slow.+ *+ * @example+ * ```+ * <XDSChartDotGL dataKey="value" color={useXDSChartColors().categorical(1)[0]} />+ * <XDSChartDotGL dataKey="value" color="#0171E3" size={4} opacity={0.6} />+ * ```+ */+export function XDSChartDotGL({+ dataKey,+ color,+ size = 6,+ opacity = 0.8,+}: XDSChartDotGLProps) {+ const {data, xScale, yScale, width, height} = useChart();+ const canvasRef = useRef<HTMLCanvasElement>(null);+ const glRef = useRef<WebGLRenderingContext | null>(null);+ const programRef = useRef<WebGLProgram | null>(null);++ // Compute pixel positions from scales+ const getPositions = useCallback((): Float32Array => {+ const positions: number[] = [];+ for (const d of data) {+ let x: number;+ if (isBandScale(xScale)) {+ x = (xScale(String(Object.values(d)[0])) ?? 0) + xScale.bandwidth() / 2;+ } else {+ const xVal = Object.values(d)[0];+ x = (xScale as (v: number) => number)(xVal as number);+ }+ const yVal = typeof d[dataKey] === 'number' ? (d[dataKey] as number) : 0;+ positions.push(x, yScale(yVal));+ }+ return new Float32Array(positions);+ }, [data, dataKey, xScale, yScale]);++ useEffect(() => {+ const canvas = canvasRef.current;+ if (!canvas || width <= 0 || height <= 0) return;++ // Set canvas size (account for device pixel ratio for sharp rendering)+ const dpr = window.devicePixelRatio || 1;+ canvas.width = width * dpr;+ canvas.height = height * dpr;+ canvas.style.width = `${width}px`;+ canvas.style.height = `${height}px`;++ // Init WebGL+ let gl = glRef.current;+ if (!gl) {+ gl = canvas.getContext('webgl', {+ alpha: true,+ premultipliedAlpha: false,+ antialias: true,+ });+ if (!gl) return;+ glRef.current = gl;+ }++ // Init program+ let program = programRef.current;+ if (!program) {+ program = createProgram(gl);+ if (!program) return;+ programRef.current = program;+ }++ gl.viewport(0, 0, canvas.width, canvas.height);+ gl.clearColor(0, 0, 0, 0);+ gl.clear(gl.COLOR_BUFFER_BIT);+ gl.enable(gl.BLEND);+ gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);++ gl.useProgram(program);++ // Upload positions+ const positions = getPositions();+ const posBuffer = gl.createBuffer();+ gl.bindBuffer(gl.ARRAY_BUFFER, posBuffer);+ gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW);++ const aPos = gl.getAttribLocation(program, 'a_position');+ gl.enableVertexAttribArray(aPos);+ gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0);++ // Uniforms+ const [r, g, b] = hexToGL(color);+ 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);+ gl.uniform1f(gl.getUniformLocation(program, 'u_opacity'), opacity);++ // Draw+ gl.drawArrays(gl.POINTS, 0, positions.length / 2);++ // Cleanup buffer+ gl.deleteBuffer(posBuffer);+ }, [width, height, color, size, opacity, getPositions]);++ if (width <= 0 || height <= 0) return null;++ return (+ <foreignObject x={0} y={0} width={width} height={height}>+ <canvas+ ref={canvasRef}+ style={{+ width,+ height,+ pointerEvents: 'none',+ }}+ />+ </foreignObject>+ );+}diff --git a/packages/lab/src/Chart/XDSChartDotGLInteractive.tsx b/packages/lab/src/Chart/XDSChartDotGLInteractive.tsxnew file mode 100644index 0000000000..c1ac2caeea--- /dev/null+++ b/packages/lab/src/Chart/XDSChartDotGLInteractive.tsx@@ -0,0 +1,502 @@+/**+ * @file XDSChartDotGLInteractive.tsx+ * @output WebGL scatter with GPU color-picking for O(1) nearest-point hover detection+ * @position Child of XDSChart; renders to two canvases — one visible, one offscreen pick buffer+ *+ * Technique: Each point is assigned a unique color encoding its index.+ * On hover, we readPixels from the offscreen framebuffer at the cursor position+ * and decode the index. No JS iteration over data points — hover is O(1).+ */++import {+ useRef,+ useEffect,+ useCallback,+ useState,+ useMemo,+ type ReactNode,+} from 'react';+import {useChart} from './ChartContext';+import type {ScaleBand} from 'd3-scale';++export interface XDSChartDotGLInteractiveProps {+ /** Which data key for the y values */+ dataKey: string;+ /** Dot fill color (hex string) */+ color: string;+ /** Point size in pixels */+ size?: number;+ /** Opacity 0-1 */+ opacity?: number;+ /**+ * Tooltip render function. Receives the hovered data point and its index.+ * If omitted, a default tooltip is rendered.+ */+ renderTooltip?: (datum: Record<string, unknown>, index: number) => ReactNode;+}++function isBandScale(scale: unknown): scale is ScaleBand<string> {+ return typeof scale === 'function' && 'bandwidth' in scale;+}++function hexToGL(hex: string): [number, number, number] {+ const n = parseInt(hex.replace('#', ''), 16);+ return [(n >> 16) / 255, ((n >> 8) & 0xff) / 255, (n & 0xff) / 255];+}++/** Encode a point index as an RGB color (supports up to 16.7M points) */+function indexToColor(i: number): [number, number, number] {+ // Add 1 so index 0 isn't black (which is our clear color)+ const id = i + 1;+ return [+ ((id >> 16) & 0xff) / 255,+ ((id >> 8) & 0xff) / 255,+ (id & 0xff) / 255,+ ];+}++/** Decode an RGB pixel back to a point index. Returns -1 for background. */+function colorToIndex(r: number, g: number, b: number): number {+ if (r === 0 && g === 0 && b === 0) return -1;+ return ((r << 16) | (g << 8) | b) - 1;+}++// Visible pass — normal rendering+const VERT_VIS = `+ attribute vec2 a_position;+ uniform vec2 u_resolution;+ uniform float u_size;+ void main() {+ vec2 clip = (a_position / u_resolution) * 2.0 - 1.0;+ gl_Position = vec4(clip.x, -clip.y, 0.0, 1.0);+ gl_PointSize = u_size;+ }+`;++const FRAG_VIS = `+ precision mediump float;+ uniform vec3 u_color;+ uniform float u_opacity;+ void main() {+ vec2 coord = gl_PointCoord - vec2(0.5);+ if (dot(coord, coord) > 0.25) discard;+ gl_FragColor = vec4(u_color, u_opacity);+ }+`;++// Pick pass — encode index as color+const VERT_PICK = `+ attribute vec2 a_position;+ attribute vec3 a_pickColor;+ uniform vec2 u_resolution;+ uniform float u_size;+ varying vec3 v_pickColor;+ void main() {+ vec2 clip = (a_position / u_resolution) * 2.0 - 1.0;+ gl_Position = vec4(clip.x, -clip.y, 0.0, 1.0);+ gl_PointSize = u_size + 4.0; // slightly larger hit area+ v_pickColor = a_pickColor;+ }+`;++const FRAG_PICK = `+ precision mediump float;+ varying vec3 v_pickColor;+ void main() {+ vec2 coord = gl_PointCoord - vec2(0.5);+ if (dot(coord, coord) > 0.25) discard;+ gl_FragColor = vec4(v_pickColor, 1.0);+ }+`;++function compileShader(+ gl: WebGLRenderingContext,+ type: number,+ src: string,+): WebGLShader | null {+ const s = gl.createShader(type);+ if (!s) return null;+ gl.shaderSource(s, src);+ gl.compileShader(s);+ if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) {+ gl.deleteShader(s);+ return null;+ }+ return s;+}++function linkProgram(+ gl: WebGLRenderingContext,+ vert: string,+ frag: string,+): WebGLProgram | null {+ const vs = compileShader(gl, gl.VERTEX_SHADER, vert);+ const fs = compileShader(gl, gl.FRAGMENT_SHADER, frag);+ if (!vs || !fs) return null;+ const p = gl.createProgram();+ if (!p) return null;+ gl.attachShader(p, vs);+ gl.attachShader(p, fs);+ gl.linkProgram(p);+ if (!gl.getProgramParameter(p, gl.LINK_STATUS)) {+ gl.deleteProgram(p);+ return null;+ }+ return p;+}++/**+ * WebGL scatter with built-in GPU hover detection.+ * Uses color-picking on an offscreen framebuffer — readPixels at cursor+ * gives the hovered point index in O(1), no matter how many points.+ *+ * @example+ * ```+ * <XDSChartDotGLInteractive+ * dataKey="value"+ * color={useXDSChartColors().categorical(1)[0]}+ * renderTooltip={(d, i) => <span>Point {i}: {d.value}</span>}+ * />+ * ```+ */+export function XDSChartDotGLInteractive({+ dataKey,+ color,+ size = 6,+ opacity = 0.8,+ renderTooltip,+}: XDSChartDotGLInteractiveProps) {+ const {data, xScale, yScale, width, height} = useChart();+ const visCanvasRef = useRef<HTMLCanvasElement>(null);+ const pickCanvasRef = useRef<HTMLCanvasElement>(null);+ const [hoverIndex, setHoverIndex] = useState<number>(-1);+ const [mousePos, setMousePos] = useState<{x: number; y: number} | null>(null);++ // Refs for WebGL state+ const visGLRef = useRef<{+ gl: WebGLRenderingContext;+ prog: WebGLProgram;+ } | null>(null);+ const pickGLRef = useRef<{+ gl: WebGLRenderingContext;+ prog: WebGLProgram;+ fb: WebGLFramebuffer;+ tex: WebGLTexture;+ } | null>(null);++ // Compute positions+ const positions = useMemo(() => {+ const pos: number[] = [];+ for (const d of data) {+ let x: number;+ if (isBandScale(xScale)) {+ x = (xScale(String(Object.values(d)[0])) ?? 0) + xScale.bandwidth() / 2;+ } else {+ x = (xScale as (v: number) => number)(Object.values(d)[0] as number);+ }+ const yVal = typeof d[dataKey] === 'number' ? (d[dataKey] as number) : 0;+ pos.push(x, yScale(yVal));+ }+ return new Float32Array(pos);+ }, [data, dataKey, xScale, yScale]);++ // Pick colors — one unique color per point+ const pickColors = useMemo(() => {+ const colors: number[] = [];+ for (let i = 0; i < data.length; i++) {+ const [r, g, b] = indexToColor(i);+ colors.push(r, g, b);+ }+ return new Float32Array(colors);+ }, [data.length]);++ // Render both passes+ useEffect(() => {+ if (width <= 0 || height <= 0) return;+ const dpr = window.devicePixelRatio || 1;++ // --- Visible canvas ---+ const visCanvas = visCanvasRef.current;+ if (visCanvas) {+ visCanvas.width = width * dpr;+ visCanvas.height = height * dpr;++ if (!visGLRef.current) {+ const gl = visCanvas.getContext('webgl', {+ alpha: true,+ premultipliedAlpha: false,+ antialias: true,+ });+ const prog = gl ? linkProgram(gl, VERT_VIS, FRAG_VIS) : null;+ if (gl && prog) visGLRef.current = {gl, prog};+ }++ const vis = visGLRef.current;+ if (vis) {+ const {gl, prog} = vis;+ gl.viewport(0, 0, visCanvas.width, visCanvas.height);+ gl.clearColor(0, 0, 0, 0);+ gl.clear(gl.COLOR_BUFFER_BIT);+ gl.enable(gl.BLEND);+ gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);+ gl.useProgram(prog);++ const buf = gl.createBuffer();+ gl.bindBuffer(gl.ARRAY_BUFFER, buf);+ gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW);+ const aPos = gl.getAttribLocation(prog, 'a_position');+ gl.enableVertexAttribArray(aPos);+ gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0);++ const [r, g, b] = hexToGL(color);+ gl.uniform2f(+ gl.getUniformLocation(prog, 'u_resolution'),+ width,+ height,+ );+ gl.uniform3f(gl.getUniformLocation(prog, 'u_color'), r, g, b);+ gl.uniform1f(gl.getUniformLocation(prog, 'u_size'), size * dpr);+ gl.uniform1f(gl.getUniformLocation(prog, 'u_opacity'), opacity);++ gl.drawArrays(gl.POINTS, 0, positions.length / 2);+ gl.deleteBuffer(buf);+ }+ }++ // --- Pick canvas (offscreen) ---+ const pickCanvas = pickCanvasRef.current;+ if (pickCanvas) {+ pickCanvas.width = width * dpr;+ pickCanvas.height = height * dpr;++ if (!pickGLRef.current) {+ const gl = pickCanvas.getContext('webgl', {+ alpha: false,+ premultipliedAlpha: false,+ antialias: false, // no AA for clean color IDs+ preserveDrawingBuffer: true,+ });+ if (gl) {+ const prog = linkProgram(gl, VERT_PICK, FRAG_PICK);+ const fb = gl.createFramebuffer();+ const tex = gl.createTexture();+ if (prog && fb && tex) {+ // Set up framebuffer with texture+ gl.bindTexture(gl.TEXTURE_2D, tex);+ gl.texImage2D(+ gl.TEXTURE_2D,+ 0,+ gl.RGBA,+ pickCanvas.width,+ pickCanvas.height,+ 0,+ gl.RGBA,+ gl.UNSIGNED_BYTE,+ null,+ );+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);+ gl.bindFramebuffer(gl.FRAMEBUFFER, fb);+ gl.framebufferTexture2D(+ gl.FRAMEBUFFER,+ gl.COLOR_ATTACHMENT0,+ gl.TEXTURE_2D,+ tex,+ 0,+ );+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);+ pickGLRef.current = {gl, prog, fb, tex};+ }+ }+ }++ const pick = pickGLRef.current;+ if (pick) {+ const {gl, prog, fb, tex} = pick;++ // Resize texture if needed+ gl.bindTexture(gl.TEXTURE_2D, tex);+ gl.texImage2D(+ gl.TEXTURE_2D,+ 0,+ gl.RGBA,+ pickCanvas.width,+ pickCanvas.height,+ 0,+ gl.RGBA,+ gl.UNSIGNED_BYTE,+ null,+ );++ gl.bindFramebuffer(gl.FRAMEBUFFER, fb);+ gl.viewport(0, 0, pickCanvas.width, pickCanvas.height);+ gl.clearColor(0, 0, 0, 1);+ gl.clear(gl.COLOR_BUFFER_BIT);+ gl.disable(gl.BLEND); // no blending for pick IDs+ gl.useProgram(prog);++ // Positions+ const posBuf = gl.createBuffer();+ gl.bindBuffer(gl.ARRAY_BUFFER, posBuf);+ gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW);+ const aPos = gl.getAttribLocation(prog, 'a_position');+ gl.enableVertexAttribArray(aPos);+ gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0);++ // Pick colors+ const colBuf = gl.createBuffer();+ gl.bindBuffer(gl.ARRAY_BUFFER, colBuf);+ gl.bufferData(gl.ARRAY_BUFFER, pickColors, gl.STATIC_DRAW);+ const aCol = gl.getAttribLocation(prog, 'a_pickColor');+ gl.enableVertexAttribArray(aCol);+ gl.vertexAttribPointer(aCol, 3, gl.FLOAT, false, 0, 0);++ gl.uniform2f(+ gl.getUniformLocation(prog, 'u_resolution'),+ width,+ height,+ );+ gl.uniform1f(gl.getUniformLocation(prog, 'u_size'), (size + 4) * dpr);++ gl.drawArrays(gl.POINTS, 0, positions.length / 2);++ gl.deleteBuffer(posBuf);+ gl.deleteBuffer(colBuf);+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);+ }+ }+ }, [width, height, positions, pickColors, color, size, opacity]);++ // Mouse handler — read pick buffer+ const handleMouseMove = useCallback((e: React.MouseEvent<SVGRectElement>) => {+ const pick = pickGLRef.current;+ if (!pick) return;++ const svg = e.currentTarget.ownerSVGElement;+ if (!svg) return;+ const pt = svg.createSVGPoint();+ pt.x = e.clientX;+ pt.y = e.clientY;+ const local = pt.matrixTransform(e.currentTarget.getScreenCTM()?.inverse());++ const dpr = window.devicePixelRatio || 1;+ const px = Math.floor(local.x * dpr);+ const py = Math.floor(local.y * dpr);++ const {gl, fb} = pick;+ gl.bindFramebuffer(gl.FRAMEBUFFER, fb);+ const pixel = new Uint8Array(4);+ gl.readPixels(+ px,+ gl.canvas.height - py,+ 1,+ 1,+ gl.RGBA,+ gl.UNSIGNED_BYTE,+ pixel,+ );+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);++ const idx = colorToIndex(pixel[0], pixel[1], pixel[2]);+ setHoverIndex(idx);+ setMousePos(idx >= 0 ? {x: local.x, y: local.y} : null);+ }, []);++ const handleMouseLeave = useCallback(() => {+ setHoverIndex(-1);+ setMousePos(null);+ }, []);++ const datum =+ hoverIndex >= 0 && hoverIndex < data.length ? data[hoverIndex] : null;++ const defaultTooltip = (d: Record<string, unknown>, i: number) => (+ <div+ style={{display: 'flex', flexDirection: 'column', gap: 2, fontSize: 12}}>+ <div style={{fontWeight: 600, color: 'var(--color-text-primary)'}}>+ Point {i}+ </div>+ {Object.entries(d).map(([k, v]) => (+ <div key={k}>+ <span style={{color: 'var(--color-text-secondary)'}}>{k}:</span>{' '}+ <span style={{fontWeight: 500}}>{String(v)}</span>+ </div>+ ))}+ </div>+ );++ if (width <= 0 || height <= 0) return null;++ return (+ <g>+ {/* Visible WebGL canvas */}+ <foreignObject x={0} y={0} width={width} height={height}>+ <canvas+ ref={visCanvasRef}+ style={{width, height, pointerEvents: 'none'}}+ />+ </foreignObject>++ {/* Hidden pick canvas — offscreen, not displayed */}+ <foreignObject+ x={0}+ y={0}+ width={0}+ height={0}+ style={{overflow: 'hidden'}}>+ <canvas ref={pickCanvasRef} style={{display: 'none'}} />+ </foreignObject>++ {/* Invisible mouse capture overlay */}+ <rect+ x={0}+ y={0}+ width={width}+ height={height}+ fill="transparent"+ onMouseMove={handleMouseMove}+ onMouseLeave={handleMouseLeave}+ />++ {/* Hover highlight */}+ {datum && hoverIndex >= 0 && (+ <circle+ cx={positions[hoverIndex * 2]}+ cy={positions[hoverIndex * 2 + 1]}+ r={size / 2 + 3}+ fill="none"+ stroke={color}+ strokeWidth={2}+ strokeOpacity={0.8}+ pointerEvents="none"+ />+ )}++ {/* Tooltip */}+ {datum && mousePos && (+ <foreignObject+ x={mousePos.x + 12}+ y={Math.max(0, mousePos.y - 40)}+ width={200}+ height={120}+ pointerEvents="none"+ style={{overflow: 'visible'}}>+ <div+ style={{+ background: 'var(--color-background-popover)',+ border: '1px solid var(--color-border)',+ borderRadius: 8,+ padding: '8px 12px',+ boxShadow: 'var(--shadow-med)',+ whiteSpace: 'nowrap',+ width: 'fit-content',+ }}>+ {renderTooltip+ ? renderTooltip(datum, hoverIndex)+ : defaultTooltip(datum, hoverIndex)}+ </div>+ </foreignObject>+ )}+ </g>+ );+}diff --git a/packages/lab/src/Chart/XDSChartErrorBar.tsx b/packages/lab/src/Chart/XDSChartErrorBar.tsxnew file mode 100644index 0000000000..753090a38e--- /dev/null+++ b/packages/lab/src/Chart/XDSChartErrorBar.tsx@@ -0,0 +1,96 @@+/**+ * @file XDSChartErrorBar.tsx+ * @output Renders error bars (whiskers) at each data point+ * @position Child of XDSChart; reads scales from context+ */++import {useChart} from './ChartContext';+import type {ScaleBand} from 'd3-scale';++export interface XDSChartErrorBarProps {+ /** Data key for the upper bound */+ yUpper: string;+ /** Data key for the lower bound */+ yLower: string;+ /** Stroke color */+ color?: string;+ /** Stroke width */+ strokeWidth?: number;+ /** Width of the whisker caps in pixels */+ capWidth?: number;+}++function isBandScale(scale: unknown): scale is ScaleBand<string> {+ return typeof scale === 'function' && 'bandwidth' in scale;+}++/**+ * Error bars with whisker caps. Pair with XDSChartBar or XDSChartDot.+ *+ * @example+ * ```+ * <XDSChartBar dataKey="mean" color={colors[0]} />+ * <XDSChartErrorBar yUpper="upper95" yLower="lower95" />+ * ```+ */+export function XDSChartErrorBar({+ yUpper,+ yLower,+ color = 'var(--color-text-primary)',+ strokeWidth = 1.5,+ capWidth = 8,+}: XDSChartErrorBarProps) {+ const {data, xScale, yScale} = useChart();++ return (+ <g>+ {data.map((d, i) => {+ let x: number;+ if (isBandScale(xScale)) {+ x =+ (xScale(String(Object.values(d)[0])) ?? 0) + xScale.bandwidth() / 2;+ } else {+ x = (xScale as (v: number) => number)(Object.values(d)[0] as number);+ }++ const upper = typeof d[yUpper] === 'number' ? (d[yUpper] as number) : 0;+ const lower = typeof d[yLower] === 'number' ? (d[yLower] as number) : 0;+ const yTop = yScale(upper);+ const yBot = yScale(lower);+ const half = capWidth / 2;++ return (+ <g key={i}>+ {/* Vertical stem */}+ <line+ x1={x}+ x2={x}+ y1={yTop}+ y2={yBot}+ stroke={color}+ strokeWidth={strokeWidth}+ />+ {/* Top cap */}+ <line+ x1={x - half}+ x2={x + half}+ y1={yTop}+ y2={yTop}+ stroke={color}+ strokeWidth={strokeWidth}+ />+ {/* Bottom cap */}+ <line+ x1={x - half}+ x2={x + half}+ y1={yBot}+ y2={yBot}+ stroke={color}+ strokeWidth={strokeWidth}+ />+ </g>+ );+ })}+ </g>+ );+}diff --git a/packages/lab/src/Chart/XDSChartHeatmapGL.tsx b/packages/lab/src/Chart/XDSChartHeatmapGL.tsxnew file mode 100644index 0000000000..031790699a--- /dev/null+++ b/packages/lab/src/Chart/XDSChartHeatmapGL.tsx@@ -0,0 +1,266 @@+/**+ * @file XDSChartHeatmapGL.tsx+ * @output WebGL heatmap — 2D grid of color-mapped cells+ * @position Child of XDSChart; manages its own row (y) band scale+ *+ * Renders a grid where x positions come from the chart's xScale (band)+ * and y positions come from a second categorical key. Each cell is colored+ * by interpolating a sequential palette based on the value key.+ */++import {useRef, useEffect, useMemo} from 'react';+import {scaleBand} from 'd3-scale';+import {useChart} from './ChartContext';+import type {ScaleBand} from 'd3-scale';++export interface XDSChartHeatmapGLProps {+ /** Data key for x-axis categories (columns) */+ xKey: string;+ /** Data key for y-axis categories (rows) */+ yKey: string;+ /** Data key containing the numeric intensity value */+ valueKey: string;+ /**+ * Color ramp — array of hex colors from low to high intensity.+ * Use useXDSChartColors().sequential.blue(5) or similar.+ */+ colorRange: string[];+ /** Explicit domain [min, max]. If omitted, computed from data. */+ domain?: [number, number];+ /** Gap between cells in pixels (default: 1) */+ cellGap?: number;+}++function isBandScale(scale: unknown): scale is ScaleBand<string> {+ return typeof scale === 'function' && 'bandwidth' in scale;+}++function hexToGL(hex: string): [number, number, number] {+ const n = parseInt(hex.replace('#', ''), 16);+ return [(n >> 16) / 255, ((n >> 8) & 0xff) / 255, (n & 0xff) / 255];+}++const VERT = `+ attribute vec2 a_position;+ attribute vec3 a_color;+ uniform vec2 u_resolution;+ varying vec3 v_color;+ void main() {+ vec2 clip = (a_position / u_resolution) * 2.0 - 1.0;+ gl_Position = vec4(clip.x, -clip.y, 0.0, 1.0);+ v_color = a_color;+ }+`;++const FRAG = `+ precision mediump float;+ varying vec3 v_color;+ void main() {+ gl_FragColor = vec4(v_color, 1.0);+ }+`;++function compileShader(+ gl: WebGLRenderingContext,+ type: number,+ source: string,+): WebGLShader | null {+ const shader = gl.createShader(type);+ if (!shader) return null;+ gl.shaderSource(shader, source);+ gl.compileShader(shader);+ if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {+ gl.deleteShader(shader);+ return null;+ }+ return shader;+}++function createProgram(gl: WebGLRenderingContext): WebGLProgram | null {+ const vert = compileShader(gl, gl.VERTEX_SHADER, VERT);+ const frag = compileShader(gl, gl.FRAGMENT_SHADER, FRAG);+ if (!vert || !frag) return null;+ const program = gl.createProgram();+ if (!program) return null;+ gl.attachShader(program, vert);+ gl.attachShader(program, frag);+ gl.linkProgram(program);+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {+ gl.deleteProgram(program);+ return null;+ }+ return program;+}++function sampleRamp(+ ramp: [number, number, number][],+ t: number,+): [number, number, number] {+ const clamped = Math.max(0, Math.min(1, t));+ if (ramp.length === 1) return ramp[0];+ const scaled = clamped * (ramp.length - 1);+ const lo = Math.floor(scaled);+ const hi = Math.min(lo + 1, ramp.length - 1);+ const frac = scaled - lo;+ return [+ ramp[lo][0] + frac * (ramp[hi][0] - ramp[lo][0]),+ ramp[lo][1] + frac * (ramp[hi][1] - ramp[lo][1]),+ ramp[lo][2] + frac * (ramp[hi][2] - ramp[lo][2]),+ ];+}++/**+ * WebGL heatmap grid. Two categorical axes (xKey × yKey) with cells colored by valueKey.+ *+ * @example+ * ```+ * <XDSChartHeatmapGL+ * xKey="hour"+ * yKey="day"+ * valueKey="activity"+ * colorRange={useXDSChartColors().sequential.blue(5)}+ * />+ * ```+ */+export function XDSChartHeatmapGL({+ xKey,+ yKey,+ valueKey,+ colorRange,+ domain: domainProp,+ cellGap = 1,+}: XDSChartHeatmapGLProps) {+ const {data, xScale, width, height} = useChart();+ const canvasRef = useRef<HTMLCanvasElement>(null);+ const glRef = useRef<WebGLRenderingContext | null>(null);+ const programRef = useRef<WebGLProgram | null>(null);++ const ramp = useMemo(() => colorRange.map(hexToGL), [colorRange]);++ // Build row (y) band scale from unique yKey values+ const yBandScale = useMemo(() => {+ const yCategories = [...new Set(data.map(d => String(d[yKey])))];+ return scaleBand<string>()+ .domain(yCategories)+ .range([0, height])+ .padding(0.05);+ }, [data, yKey, height]);++ // Value domain+ const domain = useMemo((): [number, number] => {+ if (domainProp) return domainProp;+ let min = Infinity;+ let max = -Infinity;+ for (const d of data) {+ const v = d[valueKey];+ if (typeof v === 'number') {+ if (v < min) min = v;+ if (v > max) max = v;+ }+ }+ return [min, max];+ }, [data, valueKey, domainProp]);++ useEffect(() => {+ const canvas = canvasRef.current;+ if (!canvas || width <= 0 || height <= 0 || !isBandScale(xScale)) return;++ const dpr = window.devicePixelRatio || 1;+ canvas.width = width * dpr;+ canvas.height = height * dpr;+ canvas.style.width = `${width}px`;+ canvas.style.height = `${height}px`;++ let gl = glRef.current;+ if (!gl) {+ gl = canvas.getContext('webgl', {+ alpha: true,+ premultipliedAlpha: false,+ antialias: false,+ });+ if (!gl) return;+ glRef.current = gl;+ }++ let program = programRef.current;+ if (!program) {+ program = createProgram(gl);+ if (!program) return;+ programRef.current = program;+ }++ gl.viewport(0, 0, canvas.width, canvas.height);+ gl.clearColor(0, 0, 0, 0);+ gl.clear(gl.COLOR_BUFFER_BIT);+ gl.useProgram(program);++ const positions: number[] = [];+ const colors: number[] = [];+ const [dMin, dMax] = domain;+ const range = dMax - dMin || 1;+ const gap = cellGap;++ const xBW = xScale.bandwidth();+ const yBW = yBandScale.bandwidth();++ for (const d of data) {+ const xVal = xScale(String(d[xKey]));+ const yVal = yBandScale(String(d[yKey]));+ if (xVal == null || yVal == null) continue;++ const v = typeof d[valueKey] === 'number' ? (d[valueKey] as number) : 0;+ 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;++ // Two triangles per cell+ positions.push(x0, y0, x1, y0, x0, y1);+ positions.push(x1, y0, x1, y1, x0, y1);+ for (let i = 0; i < 6; i++) colors.push(r, g, b);+ }++ const posBuf = gl.createBuffer();+ gl.bindBuffer(gl.ARRAY_BUFFER, posBuf);+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);+ const aPos = gl.getAttribLocation(program, 'a_position');+ gl.enableVertexAttribArray(aPos);+ gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0);++ const colBuf = gl.createBuffer();+ gl.bindBuffer(gl.ARRAY_BUFFER, colBuf);+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);+ const aCol = gl.getAttribLocation(program, 'a_color');+ gl.enableVertexAttribArray(aCol);+ gl.vertexAttribPointer(aCol, 3, gl.FLOAT, false, 0, 0);++ gl.uniform2f(gl.getUniformLocation(program, 'u_resolution'), width, height);+ gl.drawArrays(gl.TRIANGLES, 0, positions.length / 2);++ gl.deleteBuffer(posBuf);+ gl.deleteBuffer(colBuf);+ }, [+ data,+ xKey,+ yKey,+ valueKey,+ xScale,+ yBandScale,+ width,+ height,+ domain,+ ramp,+ cellGap,+ ]);++ if (width <= 0 || height <= 0) return null;++ return (+ <foreignObject x={0} y={0} width={width} height={height}>+ <canvas ref={canvasRef} style={{width, height, pointerEvents: 'none'}} />+ </foreignObject>+ );+}diff --git a/packages/lab/src/Chart/XDSChartLegend.tsx b/packages/lab/src/Chart/XDSChartLegend.tsxindex 7202ef81cd..e84db99e0a 100644--- a/packages/lab/src/Chart/XDSChartLegend.tsx+++ b/packages/lab/src/Chart/XDSChartLegend.tsx@@ -1,7 +1,13 @@/*** @file XDSChartLegend.tsx- * @output Renders a legend with color swatches and labels+ * @output Renders a legend — discrete swatches or continuous gradient bar* @position Child of XDSChart or standalone+ *+ * Two modes:+ * - Discrete: pass `items` — renders color swatches with labels+ * - Gradient: pass `gradient` + `domain` — renders a continuous color bar with tick labels+ *+ * The `gradient` prop accepts the output of useXDSChartColors().sequential/diverging directly.*/export interface XDSChartLegendItem {@@ -10,23 +16,126 @@ export interface XDSChartLegendItem {}export interface XDSChartLegendProps {- items: XDSChartLegendItem[];- /** Position relative to chart (default: bottom) */- position?: 'top' | 'bottom';+ /** Discrete legend items — color swatches with labels */+ items?: XDSChartLegendItem[];+ /**+ * Continuous gradient — array of hex colors from low to high.+ * Pass the output of useXDSChartColors().sequential.blue(5) or diverging directly.+ */+ gradient?: string[];+ /** Numeric domain for the gradient [min, max]. Required when gradient is set. */+ domain?: [number, number];+ /** Label for the gradient legend */+ label?: string;+ /** Number of tick labels on the gradient bar (default: 3) */+ ticks?: number;+ /** Custom tick formatter */+ tickFormat?: (value: number) => string;+}++/** Build a CSS linear-gradient from an array of color stops */+function toGradientCSS(colors: string[]): string {+ if (colors.length === 0) return 'transparent';+ if (colors.length === 1) return colors[0];+ const stops = colors.map(+ (c, i) => `${c} ${(i / (colors.length - 1)) * 100}%`,+ );+ return `linear-gradient(to right, ${stops.join(', ')})`;}/**- * Chart legend. Renders a row of color swatches with labels.+ * Chart legend — discrete swatches or continuous gradient.** @example* ```+ * // Discrete* <XDSChartLegend items={[- * { label: 'Revenue', color: XDSChartColors.categorical(2)[0] },- * { label: 'Expenses', color: XDSChartColors.categorical(2)[1] },+ * {label: 'Revenue', color: colors[0]},+ * {label: 'Expenses', color: colors[1]},* ]} />+ *+ * // Continuous — pipe useXDSChartColors() directly+ * <XDSChartLegend+ * gradient={useXDSChartColors().sequential.blue(5)}+ * domain={[0, 100]}+ * label="Temperature"+ * />+ *+ * // Diverging+ * <XDSChartLegend+ * gradient={useXDSChartColors().diverging.coldHot(7)}+ * domain={[-50, 50]}+ * label="Change %"+ * />* ```*/-export function XDSChartLegend({items}: XDSChartLegendProps) {+export function XDSChartLegend({+ items,+ gradient,+ domain,+ label,+ ticks = 3,+ tickFormat = String,+}: XDSChartLegendProps) {+ // Gradient mode+ if (gradient && gradient.length > 0 && domain) {+ const [min, max] = domain;+ const tickValues = Array.from(+ {length: ticks},+ (_, i) => min + (i / (ticks - 1)) * (max - min),+ );++ return (+ <foreignObject+ x={0}+ y={-4}+ width="100%"+ height={48}+ style={{overflow: 'visible'}}>+ <div+ style={{+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ gap: 4,+ fontSize: 12,+ color: 'var(--color-text-secondary)',+ }}>+ {label && (+ <span style={{fontWeight: 500, color: 'var(--color-text-primary)'}}>+ {label}+ </span>+ )}+ <div+ style={{+ display: 'flex',+ flexDirection: 'column',+ gap: 2,+ width: 200,+ }}>+ <div+ style={{+ height: 10,+ borderRadius: 4,+ background: toGradientCSS(gradient),+ }}+ />+ <div style={{display: 'flex', justifyContent: 'space-between'}}>+ {tickValues.map(v => (+ <span key={v} style={{fontSize: 10}}>+ {tickFormat(v)}+ </span>+ ))}+ </div>+ </div>+ </div>+ </foreignObject>+ );+ }++ // Discrete mode+ if (!items || items.length === 0) return null;+return (<foreignObjectx={0}diff --git a/packages/lab/src/Chart/XDSChartLine.tsx b/packages/lab/src/Chart/XDSChartLine.tsxindex c8fd81f8fb..1a8c01503e 100644--- a/packages/lab/src/Chart/XDSChartLine.tsx+++ b/packages/lab/src/Chart/XDSChartLine.tsx@@ -31,7 +31,7 @@ function isBandScale(scale: unknown): scale is ScaleBand<string> {** @example* ```- * <XDSChartLine dataKey="trend" color={XDSChartColors.categorical(2)[1]} />+ * <XDSChartLine dataKey="trend" color={useXDSChartColors().categorical(2)[1]} />* <XDSChartLine dataKey="trend" color="#0171E3" dots />* ```*/diff --git a/packages/lab/src/Chart/XDSChartStreamGL.tsx b/packages/lab/src/Chart/XDSChartStreamGL.tsxnew file mode 100644index 0000000000..b26d639679--- /dev/null+++ b/packages/lab/src/Chart/XDSChartStreamGL.tsx@@ -0,0 +1,238 @@+/**+ * @file XDSChartStreamGL.tsx+ * @output WebGL streaming time-series renderer — ring buffer drawn as a line strip+ * @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).+ */++import {+ useRef,+ useEffect,+ useImperativeHandle,+ forwardRef,+ useCallback,+} from 'react';+import {useChart} from './ChartContext';++export interface XDSChartStreamGLProps {+ /** Line stroke color (hex) */+ color: string;+ /** Max number of points in the buffer (default: 500) */+ bufferSize?: number;+ /** Line width in pixels (default: 2) */+ lineWidth?: number;+ /** Opacity 0-1 */+ opacity?: number;+}++export interface XDSChartStreamGLHandle {+ /** Push a new [x, y] point into the ring buffer and redraw */+ push(x: number, y: number): void;+ /** Clear the buffer */+ clear(): void;+}++function hexToGL(hex: string): [number, number, number] {+ const n = parseInt(hex.replace('#', ''), 16);+ return [(n >> 16) / 255, ((n >> 8) & 0xff) / 255, (n & 0xff) / 255];+}++const VERT = `+ attribute vec2 a_position;+ uniform vec2 u_resolution;+ void main() {+ vec2 clip = (a_position / u_resolution) * 2.0 - 1.0;+ gl_Position = vec4(clip.x, -clip.y, 0.0, 1.0);+ }+`;++const FRAG = `+ precision mediump float;+ uniform vec3 u_color;+ uniform float u_opacity;+ void main() {+ gl_FragColor = vec4(u_color, u_opacity);+ }+`;++function compileShader(+ gl: WebGLRenderingContext,+ type: number,+ source: string,+): WebGLShader | null {+ const shader = gl.createShader(type);+ if (!shader) return null;+ gl.shaderSource(shader, source);+ gl.compileShader(shader);+ if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {+ gl.deleteShader(shader);+ return null;+ }+ return shader;+}++function createProgram(gl: WebGLRenderingContext): WebGLProgram | null {+ const vert = compileShader(gl, gl.VERTEX_SHADER, VERT);+ const frag = compileShader(gl, gl.FRAGMENT_SHADER, FRAG);+ if (!vert || !frag) return null;+ const program = gl.createProgram();+ if (!program) return null;+ gl.attachShader(program, vert);+ gl.attachShader(program, frag);+ gl.linkProgram(program);+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {+ gl.deleteProgram(program);+ return null;+ }+ return program;+}++/**+ * WebGL streaming time-series line. Ring buffer — push new points without+ * React re-renders.+ *+ * Y-axis is controlled by the parent XDSChart's yDomain/yBaseline.+ * X-axis is a sliding window (oldest point at left, newest at right).+ *+ * @example+ * ```+ * <XDSChart data={[]} xKey="t" yKeys={[]} yDomain={[0, 100]} height={200}>+ * <XDSChartGrid horizontal />+ * <XDSChartAxis position="left" />+ * <XDSChartStreamGL ref={streamRef} color="#0171E3" />+ * </XDSChart>+ * ```+ */+export const XDSChartStreamGL = forwardRef<+ XDSChartStreamGLHandle,+ XDSChartStreamGLProps+>(function XDSChartStreamGL(+ {color, bufferSize = 500, lineWidth = 2, opacity = 1},+ ref,+) {+ const {width, height, yScale} = useChart();+ const canvasRef = useRef<HTMLCanvasElement>(null);+ const glRef = useRef<WebGLRenderingContext | null>(null);+ const programRef = useRef<WebGLProgram | null>(null);+ const bufRef = useRef<WebGLBuffer | null>(null);++ // Ring buffer — raw data only, no domain tracking+ const ring = useRef({+ data: new Float32Array(bufferSize * 2),+ head: 0,+ count: 0,+ });++ const draw = useCallback(() => {+ const gl = glRef.current;+ const program = programRef.current;+ const buffer = bufRef.current;+ if (!gl || !program || !buffer) return;++ 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+ 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 + 1] = yScale(ringData[idx + 1]);+ }++ gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);+ gl.clearColor(0, 0, 0, 0);+ gl.clear(gl.COLOR_BUFFER_BIT);+ gl.enable(gl.BLEND);+ gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);++ gl.useProgram(program);++ gl.bindBuffer(gl.ARRAY_BUFFER, buffer);+ gl.bufferData(gl.ARRAY_BUFFER, drawBuf, gl.DYNAMIC_DRAW);++ const aPos = gl.getAttribLocation(program, 'a_position');+ gl.enableVertexAttribArray(aPos);+ gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0);++ const [r, g, b] = hexToGL(color);+ 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]);++ useImperativeHandle(+ ref,+ () => ({+ push(x: number, y: number) {+ const r = ring.current;+ const idx = r.head * 2;+ r.data[idx] = x;+ r.data[idx + 1] = y;+ r.head = (r.head + 1) % bufferSize;+ r.count = Math.min(r.count + 1, bufferSize);+ draw();+ },+ clear() {+ ring.current.head = 0;+ ring.current.count = 0;+ const gl = glRef.current;+ if (gl) {+ gl.clearColor(0, 0, 0, 0);+ gl.clear(gl.COLOR_BUFFER_BIT);+ }+ },+ }),+ [bufferSize, draw],+ );++ useEffect(() => {+ const canvas = canvasRef.current;+ if (!canvas || width <= 0 || height <= 0) return;++ const dpr = window.devicePixelRatio || 1;+ canvas.width = width * dpr;+ canvas.height = height * dpr;+ canvas.style.width = `${width}px`;+ canvas.style.height = `${height}px`;++ if (!glRef.current) {+ const gl = canvas.getContext('webgl', {+ alpha: true,+ premultipliedAlpha: false,+ antialias: true,+ });+ if (!gl) return;+ glRef.current = gl;+ }++ if (!programRef.current) {+ programRef.current = createProgram(glRef.current);+ }++ if (!bufRef.current) {+ bufRef.current = glRef.current.createBuffer();+ }+ }, [width, height]);++ if (width <= 0 || height <= 0) return null;++ return (+ <foreignObject x={0} y={0} width={width} height={height}>+ <canvas ref={canvasRef} style={{width, height, pointerEvents: 'none'}} />+ </foreignObject>+ );+});diff --git a/packages/lab/src/Chart/getXDSChartColors.ts b/packages/lab/src/Chart/getXDSChartColors.tsnew file mode 100644index 0000000000..7eb782f7b5--- /dev/null+++ b/packages/lab/src/Chart/getXDSChartColors.ts@@ -0,0 +1,213 @@+/**+ * @file getXDSChartColors.ts+ * @output Pure function to resolve chart colors from a theme — no React required+ * @position Foundation utility; consumed by useXDSChartColors and non-React contexts+ *+ * Takes a token resolver function (or a defined theme + mode) and returns+ * the full chart colors API. The useXDSChartColors hook wraps this.+ */++import type {XDSDefinedTheme} from '@xds/core/theme';++// =============================================================================+// Types+// =============================================================================++/** Hue names available in the sequential ramps */+export type SequentialHue =+ | 'blue'+ | 'shamrock'+ | 'orange'+ | 'pink'+ | 'purple'+ | 'red'+ | 'teal'+ | 'yellow'+ | 'gray';++/** The chart colors API returned by both getXDSChartColors and useXDSChartColors */+export interface XDSChartColorsAPI {+ categorical(n: number): string[];+ sequential: Record<SequentialHue, (n: number) => string[]>;+ diverging: {+ positiveNegative(n: number): string[];+ coldHot(n: number): string[];+ custom(+ neg: SequentialHue,+ pos: SequentialHue,+ n: number,+ midpoint?: string,+ ): string[];+ };+ semantic: {+ positive: string;+ negative: string;+ warning: string;+ neutral: string;+ };+ alpha(hex: string, opacity: number): string;+}++/** A function that resolves a token name to its current value */+export type TokenResolver = (name: string) => string;++// =============================================================================+// Internals+// =============================================================================++const CATEGORICAL_TOKENS = [+ '--color-data-categorical-blue',+ '--color-data-categorical-orange',+ '--color-data-categorical-purple',+ '--color-data-categorical-green',+ '--color-data-categorical-pink',+ '--color-data-categorical-cyan',+ '--color-data-categorical-red',+ '--color-data-categorical-teal',+ '--color-data-categorical-brown',+ '--color-data-categorical-indigo',+] as const;++const SEQUENTIAL_HUES: SequentialHue[] = [+ 'blue',+ 'shamrock',+ 'orange',+ 'pink',+ 'purple',+ 'red',+ 'teal',+ 'yellow',+ 'gray',+];++function pickFromRamp(stops: string[], n: number): string[] {+ if (n <= 0) return [];+ if (n >= 5) return stops;+ if (n === 1) return [stops[2]];+ return Array.from(+ {length: n},+ (_, i) => stops[Math.round((i * 4) / (n - 1))],+ );+}++function hexAlpha(hex: string, opacity: number): string {+ const match = hex.match(+ /^#?([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/,+ );+ if (!match) return hex;+ const r = parseInt(match[1], 16);+ const g = parseInt(match[2], 16);+ const b = parseInt(match[3], 16);+ return `rgba(${r},${g},${b},${Math.max(0, Math.min(1, opacity))})`;+}++// =============================================================================+// Public API+// =============================================================================++/**+ * Build chart colors from a token resolver function.+ * This is the lowest-level API — pass any function that maps token names to values.+ */+export function getXDSChartColorsFromResolver(+ resolve: TokenResolver,+): XDSChartColorsAPI {+ const categorical = CATEGORICAL_TOKENS.map(t => resolve(t));++ const ramp = (hue: SequentialHue): string[] =>+ [5, 4, 3, 2, 1].map(step => resolve(`--color-data-${hue}-${step}`));++ const gray1 = resolve('--color-data-gray-1');++ function buildDiverging(+ negHue: SequentialHue,+ posHue: SequentialHue,+ n: number,+ midpoint: string = gray1,+ ): string[] {+ if (n <= 0) return [];+ if (n === 1) return [midpoint];+ const neg = ramp(negHue);+ const pos = ramp(posHue);+ const half = Math.floor(n / 2);+ const hasCenter = n % 2 === 1;+ const negSide = pickFromRamp(neg, half);+ const posSide = pickFromRamp(pos, half).reverse();+ if (hasCenter) return [...negSide, midpoint, ...posSide];+ return [...negSide, ...posSide];+ }++ return {+ categorical(n: number): string[] {+ if (n <= 0) return [];+ return categorical.slice(0, Math.min(n, categorical.length));+ },++ sequential: Object.fromEntries(+ SEQUENTIAL_HUES.map(hue => [+ hue,+ (n: number): string[] => {+ if (n <= 0) return [];+ return pickFromRamp(ramp(hue), n);+ },+ ]),+ ) as Record<SequentialHue, (n: number) => string[]>,++ diverging: {+ positiveNegative: (n: number) => buildDiverging('shamrock', 'red', n),+ coldHot: (n: number) => buildDiverging('blue', 'red', n),+ custom: (+ neg: SequentialHue,+ pos: SequentialHue,+ n: number,+ mid?: string,+ ) => buildDiverging(neg, pos, n, mid),+ },++ semantic: {+ positive: resolve('--color-data-categorical-green'),+ negative: resolve('--color-data-categorical-red'),+ warning: resolve('--color-data-categorical-orange'),+ neutral: resolve('--color-data-neutral'),+ },++ alpha: hexAlpha,+ };+}++/**+ * Build chart colors from a defined theme and color mode.+ *+ * Use this in non-React contexts — WebGL setup, SSR, tests, Node scripts.+ *+ * @example+ * ```+ * import { defaultTheme } from '@xds/theme-default';+ * const colors = getXDSChartColors(defaultTheme, 'light');+ * colors.categorical(5)+ * ```+ */+export function getXDSChartColors(+ theme: XDSDefinedTheme,+ mode: 'light' | 'dark' = 'light',+): XDSChartColorsAPI {+ // Build a resolver from the theme's token map+ const resolve: TokenResolver = (name: string) => {+ // Check theme token overrides first, then fall back to defaults+ const raw = theme.tokens?.[name] ?? '';+ if (!raw) return '';+ // Resolve light-dark() for the given mode+ if (raw.startsWith('light-dark(') && raw.endsWith(')')) {+ const inner = raw.slice(11, -1);+ const commaIdx = inner.indexOf(',');+ if (commaIdx !== -1) {+ const light = inner.slice(0, commaIdx).trim();+ const dark = inner.slice(commaIdx + 1).trim();+ return mode === 'light' ? light : dark;+ }+ }+ return raw;+ };++ return getXDSChartColorsFromResolver(resolve);+}diff --git a/packages/lab/src/Chart/index.ts b/packages/lab/src/Chart/index.tsindex 714659584f..9b7f61c375 100644--- a/packages/lab/src/Chart/index.ts+++ b/packages/lab/src/Chart/index.ts@@ -1,9 +1,29 @@-export {XDSChart, type XDSChartProps} from './XDSChart';+export {XDSChart, type XDSChartProps, type YBaseline} from './XDSChart';export {XDSChartAxis, type XDSChartAxisProps} from './XDSChartAxis';export {XDSChartGrid, type XDSChartGridProps} from './XDSChartGrid';export {XDSChartBar, type XDSChartBarProps} from './XDSChartBar';export {XDSChartLine, type XDSChartLineProps} from './XDSChartLine';+export {XDSChartArea, type XDSChartAreaProps} from './XDSChartArea';+export {XDSChartErrorBar, type XDSChartErrorBarProps} from './XDSChartErrorBar';+export {+ XDSChartCandlestick,+ type XDSChartCandlestickProps,+} from './XDSChartCandlestick';export {XDSChartDot, type XDSChartDotProps} from './XDSChartDot';+export {XDSChartDotGL, type XDSChartDotGLProps} from './XDSChartDotGL';+export {+ XDSChartDotGLInteractive,+ type XDSChartDotGLInteractiveProps,+} from './XDSChartDotGLInteractive';+export {+ XDSChartHeatmapGL,+ type XDSChartHeatmapGLProps,+} from './XDSChartHeatmapGL';+export {+ XDSChartStreamGL,+ type XDSChartStreamGLProps,+ type XDSChartStreamGLHandle,+} from './XDSChartStreamGL';export {XDSChartTooltip, type XDSChartTooltipProps} from './XDSChartTooltip';export {XDSChartLegend,@@ -12,3 +32,12 @@ export {} from './XDSChartLegend';export {useChart} from './ChartContext';export type {ChartContext, ChartMargin, ChartScale} from './types';+export {m4Reduce, type M4Point} from './m4';+export {useXDSChartColors} from './useXDSChartColors';+export {+ getXDSChartColors,+ getXDSChartColorsFromResolver,+ type XDSChartColorsAPI,+ type SequentialHue,+ type TokenResolver,+} from './getXDSChartColors';diff --git a/packages/lab/src/Chart/m4.test.ts b/packages/lab/src/Chart/m4.test.tsnew file mode 100644index 0000000000..9c869182ab--- /dev/null+++ b/packages/lab/src/Chart/m4.test.ts@@ -0,0 +1,64 @@+import {describe, it, expect} from 'vitest';+import {m4Reduce, type M4Point} from './m4';++describe('m4Reduce', () => {+ it('returns empty for empty input', () => {+ expect(m4Reduce([], 100)).toEqual([]);+ });++ it('returns data as-is when small enough', () => {+ const data: M4Point[] = [+ {x: 0, y: 1},+ {x: 1, y: 2},+ {x: 2, y: 3},+ ];+ expect(m4Reduce(data, 100)).toEqual(data);+ });++ it('reduces large dataset', () => {+ // 10k points into 100px width = at most 400 output points+ const data: M4Point[] = Array.from({length: 10000}, (_, i) => ({+ x: i,+ y: Math.sin(i * 0.01) * 100,+ }));+ const reduced = m4Reduce(data, 100);+ expect(reduced.length).toBeLessThanOrEqual(400);+ expect(reduced.length).toBeGreaterThan(0);+ });++ it('preserves min and max values', () => {+ // Create data with a known spike+ const data: M4Point[] = Array.from({length: 1000}, (_, i) => ({+ x: i,+ y: i === 500 ? 999 : 0,+ }));+ const reduced = m4Reduce(data, 10);+ const maxY = Math.max(...reduced.map(p => p.y));+ expect(maxY).toBe(999); // spike must be preserved+ });++ it('preserves first and last points', () => {+ const data: M4Point[] = Array.from({length: 1000}, (_, i) => ({+ x: i,+ y: i,+ }));+ const reduced = m4Reduce(data, 10);+ expect(reduced[0].x).toBe(0);+ expect(reduced[reduced.length - 1].x).toBe(999);+ });++ it('handles single point', () => {+ const data: M4Point[] = [{x: 5, y: 10}];+ expect(m4Reduce(data, 100)).toEqual([{x: 5, y: 10}]);+ });++ it('respects custom xDomain', () => {+ const data: M4Point[] = Array.from({length: 1000}, (_, i) => ({+ x: i + 500,+ y: i,+ }));+ const reduced = m4Reduce(data, 10, [500, 1499]);+ expect(reduced.length).toBeLessThanOrEqual(40);+ expect(reduced.length).toBeGreaterThan(0);+ });+});diff --git a/packages/lab/src/Chart/m4.ts b/packages/lab/src/Chart/m4.tsnew file mode 100644index 0000000000..253375ca99--- /dev/null+++ b/packages/lab/src/Chart/m4.ts@@ -0,0 +1,114 @@+/**+ * @file m4.ts+ * @output m4Reduce — pixel-aware time series data reduction+ * @position Utility consumed by chart line/stream components for large datasets+ *+ * Implements the M4 algorithm from "M4: A Visualization-Oriented Time Series+ * Data Aggregation" (Jugel et al., VLDB 2014).+ *+ * For each pixel column, retains 4 values: first, last, min, max.+ * This is the minimum set needed to visually reproduce a line chart at the+ * target resolution. A 1M-point dataset becomes ~4×width points.+ */++export interface M4Point {+ x: number;+ y: number;+}++/**+ * Reduce a time-series dataset to at most 4 points per pixel column.+ *+ * The output preserves all visual features (peaks, troughs, trends) that+ * are distinguishable at the given pixel width. Points within the same+ * pixel column are collapsed to first/min/max/last.+ *+ * @param data — input points, must be sorted by x ascending+ * @param width — chart width in pixels (determines bucket count)+ * @param xDomain — [min, max] of the x-axis. If omitted, derived from data.+ * @returns reduced points (at most 4 × width, typically much fewer)+ *+ * @example+ * ```+ * // Reduce 100k points to fit a 600px chart+ * const reduced = m4Reduce(rawData, 600);+ * ```+ */+export function m4Reduce(+ data: M4Point[],+ width: number,+ xDomain?: [number, number],+): M4Point[] {+ if (data.length === 0 || width <= 0) return [];++ // If data fits without reduction, return as-is+ if (data.length <= width * 4) return data;++ const xMin = xDomain ? xDomain[0] : data[0].x;+ const xMax = xDomain ? xDomain[1] : data[data.length - 1].x;+ const xRange = xMax - xMin;+ if (xRange <= 0) return [data[0]];++ const bucketCount = Math.ceil(width);++ // Each bucket tracks: first, last, min, max+ interface Bucket {+ first: M4Point | null;+ last: M4Point | null;+ min: M4Point | null;+ max: M4Point | null;+ }++ const buckets: Bucket[] = Array.from({length: bucketCount}, () => ({+ first: null,+ last: null,+ min: null,+ max: null,+ }));++ // Single pass through the data+ for (const point of data) {+ const bucketIdx = Math.min(+ bucketCount - 1,+ Math.floor(((point.x - xMin) / xRange) * bucketCount),+ );+ const bucket = buckets[bucketIdx];++ if (!bucket.first) {+ bucket.first = point;+ bucket.last = point;+ bucket.min = point;+ bucket.max = point;+ } else {+ bucket.last = point;+ if (point.y < bucket.min!.y) bucket.min = point;+ if (point.y > bucket.max!.y) bucket.max = point;+ }+ }++ // Emit points in order: first, min, max, last per bucket+ // Sort min/max by x within bucket to maintain temporal order+ const result: M4Point[] = [];++ for (const bucket of buckets) {+ if (!bucket.first) continue;++ const points = [bucket.first, bucket.min!, bucket.max!, bucket.last!];++ // Deduplicate (some may be the same point)+ const seen = new Set<M4Point>();+ const unique: M4Point[] = [];+ for (const p of points) {+ if (!seen.has(p)) {+ seen.add(p);+ unique.push(p);+ }+ }++ // Sort by x to maintain line continuity+ unique.sort((a, b) => a.x - b.x);+ result.push(...unique);+ }++ return result;+}diff --git a/packages/lab/src/Chart/useXDSChartColors.ts b/packages/lab/src/Chart/useXDSChartColors.tsnew file mode 100644index 0000000000..54e4a90736--- /dev/null+++ b/packages/lab/src/Chart/useXDSChartColors.ts@@ -0,0 +1,32 @@+/**+ * @file useXDSChartColors.ts+ * @output Theme-aware chart color palette hook+ * @position React hook wrapping getXDSChartColors — resolves from live theme context+ */++import {useMemo} from 'react';+import {useXDSTheme} from '@xds/core/theme';+import {getXDSChartColorsFromResolver} from './getXDSChartColors';+import type {XDSChartColorsAPI} from './getXDSChartColors';++/**+ * Theme-aware chart colors. Resolves data-viz tokens from the current+ * theme context — respects light/dark mode and custom themes.+ *+ * @example+ * ```+ * const colors = useXDSChartColors();+ * colors.categorical(5)+ * colors.sequential.blue(3)+ * colors.diverging.positiveNegative(5)+ * colors.alpha('#0171E3', 0.5)+ * ```+ */+export function useXDSChartColors(): XDSChartColorsAPI {+ const {token} = useXDSTheme();++ return useMemo(+ () => getXDSChartColorsFromResolver(name => token(name) || ''),+ [token],+ );+}diff --git a/packages/lab/src/ChartColors/XDSChartColors.test.ts b/packages/lab/src/ChartColors/XDSChartColors.test.tsdeleted file mode 100644index 8a1a60b327..0000000000--- a/packages/lab/src/ChartColors/XDSChartColors.test.ts+++ /dev/null@@ -1,126 +0,0 @@-import {describe, it, expect} from 'vitest';-import {XDSChartColors} from './XDSChartColors';--describe('XDSChartColors', () => {- describe('categorical', () => {- it('returns empty for n=0', () => {- expect(XDSChartColors.categorical(0)).toEqual([]);- });-- it('returns curated colors for small n', () => {- const colors = XDSChartColors.categorical(3);- expect(colors).toHaveLength(3);- expect(colors[0]).toBe('#0171E3');- expect(colors[1]).toBe('#EB6E00');- expect(colors[2]).toBe('#6B1EFD');- });-- it('returns all 10 curated colors', () => {- const colors = XDSChartColors.categorical(10);- expect(colors).toHaveLength(10);- colors.forEach(c => expect(c).toMatch(/^#[0-9A-Fa-f]{6}$/));- });-- it('caps at 10', () => {- expect(XDSChartColors.categorical(20)).toHaveLength(10);- });- });-- describe('sequential', () => {- it('returns single midpoint for n=1', () => {- const colors = XDSChartColors.sequential.blue(1);- expect(colors).toHaveLength(1);- expect(colors[0]).toBe('#2694FE'); // blue-3- });-- it('returns 2-stop ramp (darkest + lightest)', () => {- const colors = XDSChartColors.sequential.blue(2);- expect(colors).toHaveLength(2);- expect(colors[0]).toBe('#02165E');- expect(colors[1]).toBe('#DBECFF');- });-- it('returns full 5-step ramp', () => {- const colors = XDSChartColors.sequential.blue(5);- expect(colors).toHaveLength(5);- expect(colors[0]).toBe('#02165E');- expect(colors[4]).toBe('#DBECFF');- });-- it('caps at 5', () => {- expect(XDSChartColors.sequential.blue(10)).toHaveLength(5);- });-- it('all hues are available', () => {- const hues = [- 'blue',- 'shamrock',- 'orange',- 'pink',- 'purple',- 'red',- 'teal',- 'yellow',- 'gray',- ] as const;- hues.forEach(hue => {- const colors = XDSChartColors.sequential[hue](3);- expect(colors).toHaveLength(3);- colors.forEach(c => expect(c).toMatch(/^#[0-9A-Fa-f]{6}$/));- });- });- });-- describe('diverging', () => {- it('positiveNegative returns correct size', () => {- const colors = XDSChartColors.diverging.positiveNegative(5);- expect(colors).toHaveLength(5);- // Center is gray-1- expect(colors[2]).toBe('#F1F4F7');- });-- it('coldHot returns correct size', () => {- const colors = XDSChartColors.diverging.coldHot(7);- expect(colors).toHaveLength(7);- expect(colors[3]).toBe('#F1F4F7');- });-- it('custom allows different hues', () => {- const colors = XDSChartColors.diverging.custom('blue', 'orange', 5);- expect(colors).toHaveLength(5);- expect(colors[2]).toBe('#F1F4F7');- });-- it('custom allows custom midpoint', () => {- const colors = XDSChartColors.diverging.custom(- 'blue',- 'orange',- 5,- '#ffffff',- );- expect(colors).toHaveLength(5);- expect(colors[2]).toBe('#ffffff');- });-- it('returns midpoint for n=1', () => {- const colors = XDSChartColors.diverging.positiveNegative(1);- expect(colors).toEqual(['#F1F4F7']);- });-- it('even n has no center', () => {- const colors = XDSChartColors.diverging.positiveNegative(4);- expect(colors).toHaveLength(4);- // No gray-1 in the middle- expect(colors).not.toContain('#F1F4F7');- });- });-- describe('semantic', () => {- it('has all four semantic colors', () => {- expect(XDSChartColors.semantic.positive).toMatch(/^#[0-9A-Fa-f]{6}$/);- expect(XDSChartColors.semantic.negative).toMatch(/^#[0-9A-Fa-f]{6}$/);- expect(XDSChartColors.semantic.warning).toMatch(/^#[0-9A-Fa-f]{6}$/);- expect(XDSChartColors.semantic.neutral).toMatch(/^#[0-9A-Fa-f]{6}$/);- });- });-});diff --git a/packages/lab/src/ChartColors/XDSChartColors.ts b/packages/lab/src/ChartColors/XDSChartColors.tsdeleted file mode 100644index c178f69494..0000000000--- a/packages/lab/src/ChartColors/XDSChartColors.ts+++ /dev/null@@ -1,224 +0,0 @@-/**- * @file XDSChartColors.ts- * @input dataTokenDefaults from core theme tokens- * @output XDSChartColors — palette accessor for categorical, sequential, and diverging colors- * @position Lab utility; consumed by chart components and any data-visualization surface- *- * Provides a typed, discoverable API over the raw --color-data-* CSS custom properties.- * Returns curated token values from the XDS data visualization palette.- */--import {dataTokenDefaults} from '@xds/core/theme';--// =============================================================================-// Types-// =============================================================================--/** Hue names available in the sequential ramps */-export type SequentialHue =- | 'blue'- | 'shamrock'- | 'orange'- | 'pink'- | 'purple'- | 'red'- | 'teal'- | 'yellow'- | 'gray';--// =============================================================================-// Internals-// =============================================================================--/**- * Resolve a token default to its light-mode hex value.- * dataTokenDefaults stores values as 'light-dark(#hex, #hex)'.- */-function resolve(token: string): string {- const match = token.match(/#[0-9A-Fa-f]{6}/);- return match ? match[0] : token;-}--/** The 10 curated categorical colors in token order */-const CATEGORICAL = [- 'blue',- 'orange',- 'purple',- 'green',- 'pink',- 'cyan',- 'red',- 'teal',- 'brown',- 'indigo',-].map(name =>- resolve(- dataTokenDefaults[- `--color-data-categorical-${name}` as keyof typeof dataTokenDefaults- ],- ),-);--const SEQUENTIAL_HUES: SequentialHue[] = [- 'blue',- 'shamrock',- 'orange',- 'pink',- 'purple',- 'red',- 'teal',- 'yellow',- 'gray',-];--/** Default diverging midpoint — gray-1 per design specs */-const GRAY_1 = resolve(dataTokenDefaults['--color-data-gray-1']);--/** 5-step ramp for a hue: darkest (5) → lightest (1) */-function ramp(hue: SequentialHue): string[] {- return [5, 4, 3, 2, 1].map(step =>- resolve(- dataTokenDefaults[- `--color-data-${hue}-${step}` as keyof typeof dataTokenDefaults- ],- ),- );-}--/** Pick n evenly spaced items from a 5-stop ramp */-function pickFromRamp(stops: string[], n: number): string[] {- if (n >= 5) return stops;- if (n === 1) return [stops[2]]; // midpoint- return Array.from(- {length: n},- (_, i) => stops[Math.round((i * 4) / (n - 1))],- );-}--/**- * Build a diverging palette from two hues and a midpoint.- * Picks stops from each hue's ramp (darkest → lightest) with midpoint between.- * Max meaningful size is 11 (5 negative + midpoint + 5 positive).- */-function buildDiverging(- negativeHue: SequentialHue,- positiveHue: SequentialHue,- n: number,- midpoint: string = GRAY_1,-): string[] {- if (n <= 0) return [];- if (n === 1) return [midpoint];-- const neg = ramp(negativeHue);- const pos = ramp(positiveHue);-- const half = Math.floor(n / 2);- const hasCenter = n % 2 === 1;-- const negSide = pickFromRamp(neg, half);- const posSide = pickFromRamp(pos, half).reverse(); // lightest → darkest-- if (hasCenter) {- return [...negSide, midpoint, ...posSide];- }- return [...negSide, ...posSide];-}--// =============================================================================-// Public API-// =============================================================================--/**- * XDS Chart Colors — typed palette accessor for data visualization.- *- * All methods return resolved hex strings usable in SVG fill/stroke,- * CSS, canvas, or any rendering context.- *- * @example- * ```- * XDSChartColors.categorical(5)- * XDSChartColors.sequential.blue(3)- * XDSChartColors.diverging.positiveNegative(5)- * XDSChartColors.diverging.coldHot(7)- * XDSChartColors.diverging.custom('blue', 'orange', 7)- * XDSChartColors.semantic.positive- * ```- */-export const XDSChartColors = {- /**- * Categorical palette — distinct colors for unrelated series.- * Returns up to 10 curated colors from the XDS data token palette.- */- categorical(n: number): string[] {- if (n <= 0) return [];- return CATEGORICAL.slice(0, Math.min(n, CATEGORICAL.length));- },-- /**- * Sequential ramps — ordered colors within a single hue.- * Returns up to 5 curated stops (darkest → lightest).- */- sequential: Object.fromEntries(- SEQUENTIAL_HUES.map(hue => [- hue,- (n: number): string[] => {- if (n <= 0) return [];- return pickFromRamp(ramp(hue), n);- },- ]),- ) as Record<SequentialHue, (n: number) => string[]>,-- /**- * Diverging palettes — two sequential hues meeting at a neutral midpoint.- *- * Presets match design specs (gray-1 midpoint):- * - `positiveNegative` — shamrock → gray-1 → red- * - `coldHot` — blue → gray-1 → red- *- * Use `custom` for any hue combination or a custom midpoint.- */- diverging: {- /** shamrock → gray-1 → red (gain/loss, positive/negative) */- positiveNegative(n: number): string[] {- return buildDiverging('shamrock', 'red', n);- },-- /** blue → gray-1 → red (cold/hot, low/high) */- coldHot(n: number): string[] {- return buildDiverging('blue', 'red', n);- },-- /**- * Custom diverging palette from any two hues.- * Default midpoint is gray-1; pass a hex string to override.- */- custom(- negativeHue: SequentialHue,- positiveHue: SequentialHue,- n: number,- midpoint?: string,- ): string[] {- return buildDiverging(negativeHue, positiveHue, n, midpoint);- },- },-- /** Semantic colors — fixed-meaning data values */- semantic: {- positive: resolve(- dataTokenDefaults[- '--color-data-categorical-green' as keyof typeof dataTokenDefaults- ],- ),- negative: resolve(- dataTokenDefaults[- '--color-data-categorical-red' as keyof typeof dataTokenDefaults- ],- ),- warning: resolve(- dataTokenDefaults[- '--color-data-categorical-orange' as keyof typeof dataTokenDefaults- ],- ),- neutral: resolve(dataTokenDefaults['--color-data-neutral']),- },-} as const;diff --git a/packages/lab/src/ChartColors/index.ts b/packages/lab/src/ChartColors/index.tsdeleted file mode 100644index cc3ee8f542..0000000000--- a/packages/lab/src/ChartColors/index.ts+++ /dev/null@@ -1 +0,0 @@-export {XDSChartColors, type SequentialHue} from './XDSChartColors';diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.tsindex 455bea16c1..9a27d6ce6a 100644--- a/packages/lab/src/index.ts+++ b/packages/lab/src/index.ts@@ -55,13 +55,11 @@ export {starterIcons,} from './SVGIcon';-// Chart colors — palette accessor for data visualization-export {XDSChartColors, type SequentialHue} from './ChartColors';-// Chart components — composable d3-based data visualizationexport {XDSChart,type XDSChartProps,+ type YBaseline,XDSChartAxis,type XDSChartAxisProps,XDSChartGrid,@@ -70,8 +68,23 @@ export {type XDSChartBarProps,XDSChartLine,type XDSChartLineProps,+ XDSChartArea,+ type XDSChartAreaProps,+ XDSChartErrorBar,+ type XDSChartErrorBarProps,+ XDSChartCandlestick,+ type XDSChartCandlestickProps,XDSChartDot,type XDSChartDotProps,+ XDSChartDotGL,+ type XDSChartDotGLProps,+ XDSChartDotGLInteractive,+ type XDSChartDotGLInteractiveProps,+ XDSChartHeatmapGL,+ type XDSChartHeatmapGLProps,+ XDSChartStreamGL,+ type XDSChartStreamGLProps,+ type XDSChartStreamGLHandle,XDSChartTooltip,type XDSChartTooltipProps,XDSChartLegend,@@ -81,4 +94,12 @@ export {type ChartContext,type ChartMargin,type ChartScale,+ m4Reduce,+ type M4Point,+ useXDSChartColors,+ getXDSChartColors,+ getXDSChartColorsFromResolver,+ type XDSChartColorsAPI,+ type SequentialHue,+ type TokenResolver,} from './Chart';