An open source design system that's fully customizable and agent ready
TypeScript
feat(charts): port remaining v1 marks to v2 config model (#1730)
Cindy Zhang0a1753a041a9
diff --git a/apps/storybook/stories/ChartV2Advanced.stories.tsx b/apps/storybook/stories/ChartV2Advanced.stories.tsxnew file mode 100644index 0000000000..f25bb5c2ed--- /dev/null+++ b/apps/storybook/stories/ChartV2Advanced.stories.tsx@@ -0,0 +1,253 @@+import type {Meta, StoryObj} from '@storybook/react';+import {useMemo, useRef, useEffect} from 'react';+import {+ XDSChartV2 as XDSChart,+ bar,+ line,+ dot,+ area,+ band,+ candlestick,+ errorBar,+ referenceLine,+ dotGL,+ heatmapGL,+ streamGL,+} from '@xds/lab';+import {XDSChartGrid, XDSChartAxis} from '@xds/lab';+import {XDSText} from '@xds/core';++const meta: Meta<typeof XDSChart> = {+ title: 'Lab/XDSChart v2/Advanced',+ component: XDSChart,+};+export default meta;++// ─── Data ──────────────────────────────────────────────────────────────────++const stockData = Array.from({length: 30}, (_, i) => {+ const base = 100 + Math.sin(i / 5) * 20 + i * 0.5;+ const open = base + (Math.random() - 0.5) * 8;+ const close = base + (Math.random() - 0.5) * 8;+ return {+ day: `Day ${i + 1}`,+ open: Math.round(open * 10) / 10,+ close: Math.round(close * 10) / 10,+ high: Math.round(Math.max(open, close, base + Math.random() * 10) * 10) / 10,+ low: Math.round(Math.min(open, close, base - Math.random() * 10) * 10) / 10,+ volume: Math.round(500 + Math.random() * 1000),+ };+});++const predictionData = Array.from({length: 20}, (_, i) => {+ const x = i;+ const mean = 30 + i * 2 + Math.sin(i / 3) * 5;+ return {+ x,+ mean: Math.round(mean * 10) / 10,+ upper95: Math.round((mean + 8 + i * 0.3) * 10) / 10,+ lower95: Math.round((mean - 8 - i * 0.3) * 10) / 10,+ upper80: Math.round((mean + 4 + i * 0.15) * 10) / 10,+ lower80: Math.round((mean - 4 - i * 0.15) * 10) / 10,+ };+});++const salesData = [+ {month: 'Jan', sales: 45, target: 50, errorHigh: 48, errorLow: 42},+ {month: 'Feb', sales: 52, target: 50, errorHigh: 56, errorLow: 48},+ {month: 'Mar', sales: 48, target: 50, errorHigh: 52, errorLow: 44},+ {month: 'Apr', sales: 61, target: 50, errorHigh: 66, errorLow: 56},+ {month: 'May', sales: 55, target: 50, errorHigh: 59, errorLow: 51},+ {month: 'Jun', sales: 70, target: 50, errorHigh: 76, errorLow: 64},+];++const scatterData = Array.from({length: 200}, (_, i) => ({+ x: Math.random() * 100,+ y: Math.random() * 100,+}));++const heatmapData: Record<string, unknown>[] = [];+const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];+for (const day of days) {+ for (let hour = 0; hour < 24; hour++) {+ heatmapData.push({+ hour: `${hour}`,+ day,+ traffic: Math.round(+ 50 + Math.sin(hour / 4) * 30 + (day === 'Sat' || day === 'Sun' ? -20 : 10) + Math.random() * 20,+ ),+ });+ }+}++// ─── Stories ───────────────────────────────────────────────────────────────++/** Candlestick chart */+export const Candlestick: StoryObj = {+ render: () => (+ <XDSChart+ data={stockData}+ xKey="day"+ series={[+ candlestick({open: 'open', high: 'high', low: 'low', close: 'close', upColor: '#22c55e', downColor: '#ef4444'}),+ ]}+ grid={<XDSChartGrid horizontal />}+ axes={<><XDSChartAxis position="bottom" /><XDSChartAxis position="left" /></>}+ height={350}+ />+ ),+};++/** Candlestick + MA line + volume bars */+export const FinancialComposite: StoryObj = {+ name: 'Financial (Candlestick + MA + Volume)',+ render: () => {+ const data = useMemo(() => {+ let sum = 0;+ return stockData.map((d, i) => {+ sum += d.close;+ return {...d, ma5: i >= 4 ? Math.round((sum - stockData.slice(0, i - 4).reduce((s, v) => s + v.close, 0)) / 5 * 10) / 10 : undefined};+ });+ }, []);+ return (+ <XDSChart+ data={data}+ xKey="day"+ series={[+ candlestick({open: 'open', high: 'high', low: 'low', close: 'close', upColor: '#22c55e', downColor: '#ef4444'}),+ line('ma5', {color: '#f59e0b', strokeWidth: 1.5}),+ bar('volume', {color: '#94a3b8', opacity: 0.3}),+ ]}+ grid={<XDSChartGrid horizontal />}+ axes={<><XDSChartAxis position="bottom" /><XDSChartAxis position="left" /></>}+ height={400}+ />+ );+ },+};++/** Confidence bands (80% + 95%) */+export const ConfidenceBands: StoryObj = {+ render: () => (+ <XDSChart+ data={predictionData}+ xKey="x"+ series={[+ band({upper: 'upper95', lower: 'lower95', color: '#3b82f6', opacity: 0.1}),+ band({upper: 'upper80', lower: 'lower80', color: '#3b82f6', opacity: 0.2}),+ line('mean', {color: '#3b82f6', strokeWidth: 2}),+ ]}+ grid={<XDSChartGrid horizontal />}+ axes={<><XDSChartAxis position="bottom" /><XDSChartAxis position="left" /></>}+ height={300}+ />+ ),+};++/** Error bars on bar chart + reference line */+export const ErrorBarsWithTarget: StoryObj = {+ name: 'Error Bars + Reference Line',+ render: () => (+ <XDSChart+ data={salesData}+ xKey="month"+ series={[+ bar('sales', {color: '#3b82f6'}),+ errorBar({high: 'errorHigh', low: 'errorLow', color: '#1e3a5f'}),+ referenceLine({y: 50, label: 'Target', color: '#ef4444'}),+ referenceLine({y: 40, y2: 60, label: 'Acceptable', color: '#22c55e', opacity: 0.1}),+ ]}+ grid={<XDSChartGrid horizontal />}+ axes={<><XDSChartAxis position="bottom" /><XDSChartAxis position="left" /></>}+ height={300}+ />+ ),+};++/** WebGL scatter — 200 points */+export const WebGLScatter: StoryObj = {+ name: 'WebGL Scatter (dotGL)',+ render: () => (+ <XDSChart+ data={scatterData}+ xKey="x"+ series={[dotGL('y', {color: '#3b82f6', size: 4})]}+ grid={<XDSChartGrid horizontal vertical />}+ axes={<><XDSChartAxis position="bottom" /><XDSChartAxis position="left" /></>}+ height={400}+ />+ ),+};++/** WebGL heatmap — traffic by hour × day */+export const WebGLHeatmap: StoryObj = {+ name: 'WebGL Heatmap',+ render: () => (+ <XDSChart+ data={heatmapData}+ xKey="hour"+ series={[+ heatmapGL({xKey: 'hour', yKey: 'day', valueKey: 'traffic', colorRange: ['#eff6ff', '#1e40af']}),+ ]}+ axes={<><XDSChartAxis position="bottom" /><XDSChartAxis position="left" /></>}+ height={280}+ />+ ),+};++/** Streaming line — real-time data */+export const StreamingLine: StoryObj = {+ name: 'Streaming (streamGL)',+ render: () => {+ const handleRef = useRef<{push: (point: {x: number; y: number}) => void}>(null);+ useEffect(() => {+ let t = 0;+ const interval = setInterval(() => {+ handleRef.current?.push({x: t, y: 50 + Math.sin(t / 10) * 30 + Math.random() * 10});+ t++;+ }, 200);+ return () => clearInterval(interval);+ }, []);++ return (+ <XDSChart+ data={[]}+ xKey="x"+ series={[streamGL('y', {handleRef, window: 60000, color: '#3b82f6'})]}+ grid={<XDSChartGrid horizontal />}+ axes={<><XDSChartAxis position="bottom" /><XDSChartAxis position="left" /></>}+ height={300}+ />+ );+ },+};++/** Mixed: bars with error bars, line, reference line, confidence band */+export const KitchenSink: StoryObj = {+ name: 'Kitchen Sink',+ render: () => {+ const data = salesData.map((d, i, arr) => ({+ ...d,+ runAvg: Math.round(arr.slice(0, i + 1).reduce((s, v) => s + v.sales, 0) / (i + 1) * 10) / 10,+ upper: Math.round((arr.slice(0, i + 1).reduce((s, v) => s + v.sales, 0) / (i + 1) + 8) * 10) / 10,+ lower: Math.round((arr.slice(0, i + 1).reduce((s, v) => s + v.sales, 0) / (i + 1) - 8) * 10) / 10,+ }));+ return (+ <XDSChart+ data={data}+ xKey="month"+ series={[+ referenceLine({y: 40, y2: 60, color: '#22c55e', opacity: 0.08}),+ referenceLine({y: 50, label: 'Target', color: '#ef4444'}),+ band({upper: 'upper', lower: 'lower', color: '#f59e0b', opacity: 0.15}),+ bar('sales', {color: '#3b82f6'}),+ errorBar({high: 'errorHigh', low: 'errorLow', color: '#1e3a5f'}),+ line('runAvg', {color: '#f59e0b', strokeWidth: 2}),+ ]}+ grid={<XDSChartGrid horizontal />}+ axes={<><XDSChartAxis position="bottom" /><XDSChartAxis position="left" /></>}+ height={400}+ />+ );+ },+};diff --git a/packages/lab/src/ChartV2/index.ts b/packages/lab/src/ChartV2/index.tsindex a30944f44a..c9db5e34fd 100644--- a/packages/lab/src/ChartV2/index.ts+++ b/packages/lab/src/ChartV2/index.ts@@ -1,5 +1,5 @@export {XDSChart, type XDSChartProps} from './XDSChart';-export {bar, line, dot, area, band, candlestick} from './marks';-export type {BarOptions, LineOptions, DotOptions, AreaOptions, BandOptions, CandlestickOptions} from './marks';+export {bar, line, dot, area, band, candlestick, errorBar, referenceLine, dotGL, dotGLInteractive, heatmapGL, streamGL} from './marks';+export type {BarOptions, LineOptions, DotOptions, AreaOptions, BandOptions, CandlestickOptions, ErrorBarOptions, ReferenceLineOptions, DotGLOptions, DotGLInteractiveOptions, HeatmapGLOptions, StreamGLOptions, StreamGLHandle} from './marks';export {useChartV2} from './ChartV2Context';export type {SeriesDef, ChartV2Context, ChartPointerEvent, ResolvedPoint, ResolvedPositions, SeriesContext} from './types';diff --git a/packages/lab/src/ChartV2/marks/dotGL.tsx b/packages/lab/src/ChartV2/marks/dotGL.tsxnew file mode 100644index 0000000000..0e0de43ffa--- /dev/null+++ b/packages/lab/src/ChartV2/marks/dotGL.tsx@@ -0,0 +1,183 @@+/**+ * @file marks/dotGL.tsx+ * @output WebGL scatter — canvas overlay, single draw call+ */++import {useRef, useEffect, useCallback} from 'react';+import type {SeriesDef, ResolvedPoint} from '../types';+import type {ScaleBand} from 'd3-scale';+import {useChartV2} from '../ChartV2Context';+import {+ hexToGL,+ getWebGLContext,+ setupGLState,+ sizeCanvas,+ mountCanvasOverSVG,+ createProgram,+ POINT_SIZE_COMPENSATION,+} from '../../Chart/webgl';++export interface DotGLOptions {+ color: string;+ size?: number;+ opacity?: number;+}++const VERT = `+ 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 * ${POINT_SIZE_COMPENSATION.toFixed(6)};+ }+`;++const FRAG = `+ precision mediump float;+ uniform vec3 u_color;+ uniform float u_opacity;+ void main() {+ vec2 coord = gl_PointCoord - vec2(0.5);+ float dist = length(coord);+ if (dist > 0.5) discard;+ float edge = 1.0 - smoothstep(0.48, 0.5, dist);+ float a = u_opacity * edge;+ gl_FragColor = vec4(u_color * a, a);+ }+`;++/**+ * Inline component returned by render() — manages the WebGL canvas lifecycle.+ * Needs access to svgRef from ChartV2Context to mount the canvas outside SVG.+ */+function DotGLCanvas({+ resolved,+ color,+ size,+ opacity,+ width,+ height,+}: {+ resolved: ResolvedPoint[];+ color: string;+ size: number;+ opacity: number;+ width: number;+ height: number;+}) {+ const {svgRef} = useChartV2();+ const canvasRef = useRef<HTMLCanvasElement | null>(null);+ const glRef = useRef<WebGLRenderingContext | null>(null);+ const programRef = useRef<WebGLProgram | null>(null);+ const markerRef = useRef<SVGGElement>(null);++ const getPositions = useCallback((): Float32Array => {+ const positions: number[] = [];+ for (const p of resolved) {+ positions.push(p.px, p.py);+ }+ return new Float32Array(positions);+ }, [resolved]);++ // Mount canvas outside SVG+ useEffect(() => {+ const marker = markerRef.current;+ if (!marker) return;+ if (!canvasRef.current)+ canvasRef.current = document.createElement('canvas');+ return mountCanvasOverSVG(marker, canvasRef.current, width, height);+ }, [width, height]);++ // Draw+ useEffect(() => {+ const canvas = canvasRef.current;+ if (!canvas || width <= 0 || height <= 0) return;++ const dpr = sizeCanvas(canvas, width, height);++ if (!glRef.current) glRef.current = getWebGLContext(canvas);+ const gl = glRef.current;+ if (!gl) return;++ if (!programRef.current) programRef.current = createProgram(gl, VERT, FRAG);+ const program = programRef.current;+ if (!program) return;++ gl.viewport(0, 0, canvas.width, canvas.height);+ setupGLState(gl);+ gl.useProgram(program);++ 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);++ 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);++ gl.drawArrays(gl.POINTS, 0, positions.length / 2);+ gl.deleteBuffer(posBuffer);+ }, [width, height, color, size, opacity, getPositions]);++ if (width <= 0 || height <= 0) return null;+ return <g ref={markerRef} />;+}++/**+ * WebGL scatter plot. Canvas mounted outside SVG for sharp Retina rendering.+ *+ * @example+ * ```+ * series={[dotGL('value', {color: '#4f46e5'})]}+ * ```+ */+export function dotGL(dataKey: string, options: DotGLOptions): SeriesDef {+ const {color} = options;+ const size = options.size ?? 6;+ const opacity = options.opacity ?? 0.8;++ return {+ type: 'dotGL',+ key: dataKey,+ dataKeys: [dataKey],+ layout: {},++ resolve(ctx) {+ const {data, xKey, xScale, yScale} = ctx;+ const points: ResolvedPoint[] = [];+ for (let i = 0; i < data.length; i++) {+ const d = data[i];+ let px: number;+ if ('bandwidth' in xScale) {+ px = ((xScale as ScaleBand<string>)(String(d[xKey])) ?? 0) + (xScale as ScaleBand<string>).bandwidth() / 2;+ } else {+ px = xScale(d[xKey] as number);+ }+ const v = typeof d[dataKey] === 'number' ? (d[dataKey] as number) : 0;+ points.push({px, py: yScale(v), py0: yScale(0), dataIndex: i});+ }+ return points;+ },++ render(resolved, ctx) {+ return (+ <DotGLCanvas+ resolved={resolved}+ color={color}+ size={size}+ opacity={opacity}+ width={ctx.width}+ height={ctx.height}+ />+ );+ },+ };+}diff --git a/packages/lab/src/ChartV2/marks/dotGLInteractive.tsx b/packages/lab/src/ChartV2/marks/dotGLInteractive.tsxnew file mode 100644index 0000000000..7b5fac4415--- /dev/null+++ b/packages/lab/src/ChartV2/marks/dotGLInteractive.tsx@@ -0,0 +1,452 @@+/**+ * @file marks/dotGLInteractive.tsx+ * @output WebGL scatter with GPU color-picking for O(1) nearest-point hover+ *+ * Each point gets a unique color encoding its index. On hover, readPixels+ * from an offscreen framebuffer decodes the hovered index — no JS iteration.+ */++import {+ useRef,+ useEffect,+ useCallback,+ useState,+ useMemo,+ type ReactNode,+} from 'react';+import type {SeriesDef, ResolvedPoint} from '../types';+import type {ScaleBand} from 'd3-scale';+import {hexToGL} from '../../Chart/webgl';++export interface DotGLInteractiveOptions {+ color: string;+ size?: number;+ opacity?: number;+ /** Custom tooltip renderer. Receives datum and index. */+ renderTooltip?: (datum: Record<string, unknown>, index: number) => ReactNode;+}++/** Encode a point index as an RGB color (supports up to 16.7M points) */+function indexToColor(i: number): [number, number, number] {+ 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;+}++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;+}++// Visible pass+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;+ 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);+ }+`;++/**+ * Inline component — manages visible + pick canvases and hover state.+ */+function DotGLInteractiveCanvas({+ resolved,+ color,+ size,+ opacity,+ width,+ height,+ data,+ renderTooltip,+}: {+ resolved: ResolvedPoint[];+ color: string;+ size: number;+ opacity: number;+ width: number;+ height: number;+ data: Record<string, unknown>[];+ renderTooltip?: (datum: Record<string, unknown>, index: number) => ReactNode;+}) {+ 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);++ const visGLRef = useRef<{gl: WebGLRenderingContext; prog: WebGLProgram} | null>(null);+ const pickGLRef = useRef<{+ gl: WebGLRenderingContext; prog: WebGLProgram;+ fb: WebGLFramebuffer; tex: WebGLTexture;+ } | null>(null);++ const positions = useMemo(() => {+ const pos: number[] = [];+ for (const p of resolved) {+ pos.push(p.px, p.py);+ }+ return new Float32Array(pos);+ }, [resolved]);++ const pickColors = useMemo(() => {+ const colors: number[] = [];+ for (let i = 0; i < resolved.length; i++) {+ const [r, g, b] = indexToColor(i);+ colors.push(r, g, b);+ }+ return new Float32Array(colors);+ }, [resolved.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,+ preserveDrawingBuffer: true,+ });+ if (gl) {+ const prog = linkProgram(gl, VERT_PICK, FRAG_PICK);+ const fb = gl.createFramebuffer();+ const tex = gl.createTexture();+ if (prog && fb && tex) {+ 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;++ 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);+ gl.useProgram(prog);++ 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);++ 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]);++ 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>+ );++ return (+ <g>+ <foreignObject x={0} y={0} width={width} height={height} style={{overflow: 'hidden'}}>+ <canvas ref={visCanvasRef} style={{width, height, pointerEvents: 'none'}} />+ </foreignObject>++ <foreignObject x={0} y={0} width={0} height={0} style={{overflow: 'hidden'}}>+ <canvas ref={pickCanvasRef} style={{display: 'none'}} />+ </foreignObject>++ <rect+ x={0} y={0} width={width} height={height}+ fill="transparent"+ onMouseMove={handleMouseMove}+ onMouseLeave={handleMouseLeave}+ />++ {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"+ />+ )}++ {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>+ );+}++/**+ * WebGL scatter with GPU color-picking hover. O(1) hit detection via offscreen+ * framebuffer — no JS iteration regardless of point count.+ *+ * @example+ * ```+ * series={[dotGLInteractive('value', {+ * color: '#4f46e5',+ * renderTooltip: (d, i) => <span>{d.name}: {d.value}</span>,+ * })]}+ * ```+ */+export function dotGLInteractive(dataKey: string, options: DotGLInteractiveOptions): SeriesDef {+ const {color} = options;+ const size = options.size ?? 6;+ const opacity = options.opacity ?? 0.8;+ const renderTooltip = options.renderTooltip;++ return {+ type: 'dotGLInteractive',+ key: dataKey,+ dataKeys: [dataKey],+ layout: {},++ resolve(ctx) {+ const {data, xKey, xScale, yScale} = ctx;+ const points: ResolvedPoint[] = [];+ for (let i = 0; i < data.length; i++) {+ const d = data[i];+ let px: number;+ if ('bandwidth' in xScale) {+ px = ((xScale as ScaleBand<string>)(String(d[xKey])) ?? 0) + (xScale as ScaleBand<string>).bandwidth() / 2;+ } else {+ px = xScale(d[xKey] as number);+ }+ const v = typeof d[dataKey] === 'number' ? (d[dataKey] as number) : 0;+ points.push({px, py: yScale(v), py0: yScale(0), dataIndex: i});+ }+ return points;+ },++ render(resolved, ctx) {+ return (+ <DotGLInteractiveCanvas+ resolved={resolved}+ color={color}+ size={size}+ opacity={opacity}+ width={ctx.width}+ height={ctx.height}+ data={ctx.data}+ renderTooltip={renderTooltip}+ />+ );+ },+ };+}diff --git a/packages/lab/src/ChartV2/marks/errorBar.tsx b/packages/lab/src/ChartV2/marks/errorBar.tsxnew file mode 100644index 0000000000..140da976e8--- /dev/null+++ b/packages/lab/src/ChartV2/marks/errorBar.tsx@@ -0,0 +1,87 @@+/**+ * @file marks/errorBar.tsx+ * @output Error bar (whisker) series — vertical high/low bounds+ */++import type {SeriesDef, ResolvedPoint} from '../types';+import type {ScaleBand} from 'd3-scale';++export interface ErrorBarOptions {+ /** Data key for the upper bound */+ high: string;+ /** Data key for the lower bound */+ low: string;+ /** Stroke color */+ color?: string;+ /** Stroke width */+ strokeWidth?: number;+ /** Width of the whisker caps in pixels */+ capWidth?: number;+}++/**+ * Error bars with whisker caps. Pair with bar() or dot().+ *+ * @example+ * ```+ * series={[bar('mean'), errorBar({high: 'upper95', low: 'lower95'})]}+ * ```+ */+export function errorBar(options: ErrorBarOptions): SeriesDef {+ const {high, low} = options;+ const color = options.color ?? 'var(--color-text-primary)';+ const strokeWidth = options.strokeWidth ?? 1.5;+ const capWidth = options.capWidth ?? 8;++ return {+ type: 'errorBar',+ key: `errorBar-${high}-${low}`,+ dataKeys: [high, low],+ layout: {},++ resolve(ctx) {+ const {data, xKey, xScale, yScale} = ctx;+ const points: ResolvedPoint[] = [];+ for (let i = 0; i < data.length; i++) {+ const d = data[i];+ let px: number;+ if ('bandwidth' in xScale) {+ px = ((xScale as ScaleBand<string>)(String(d[xKey])) ?? 0) + (xScale as ScaleBand<string>).bandwidth() / 2;+ } else {+ px = xScale(d[xKey] as number);+ }+ const upper = typeof d[high] === 'number' ? (d[high] as number) : 0;+ const lower = typeof d[low] === 'number' ? (d[low] as number) : 0;+ points.push({px, py: yScale(upper), py0: yScale(lower), dataIndex: i});+ }+ return points;+ },++ render(resolved) {+ const half = capWidth / 2;+ return (+ <g>+ {resolved.map((p, i) => (+ <g key={i}>+ {/* Vertical stem */}+ <line+ x1={p.px} x2={p.px} y1={p.py} y2={p.py0}+ stroke={color} strokeWidth={strokeWidth}+ />+ {/* Upper cap */}+ <line+ x1={p.px - half} x2={p.px + half} y1={p.py} y2={p.py}+ stroke={color} strokeWidth={strokeWidth}+ />+ {/* Lower cap */}+ <line+ x1={p.px - half} x2={p.px + half} y1={p.py0} y2={p.py0}+ stroke={color} strokeWidth={strokeWidth}+ />+ </g>+ ))}+ </g>+ );+ },+ };+}diff --git a/packages/lab/src/ChartV2/marks/heatmapGL.tsx b/packages/lab/src/ChartV2/marks/heatmapGL.tsxnew file mode 100644index 0000000000..8096a464f7--- /dev/null+++ b/packages/lab/src/ChartV2/marks/heatmapGL.tsx@@ -0,0 +1,253 @@+/**+ * @file marks/heatmapGL.tsx+ * @output WebGL heatmap — 2D grid of colored cells on canvas+ */++import {useRef, useEffect, useMemo} from 'react';+import {scaleBand} from 'd3-scale';+import type {SeriesDef, ResolvedPoint} from '../types';+import type {ScaleBand} from 'd3-scale';+import {useChartV2} from '../ChartV2Context';+import {+ hexToGL,+ getWebGLContext,+ setupGLState,+ sizeCanvas,+ mountCanvasOverSVG,+ createProgram,+} from '../../Chart/webgl';++export interface HeatmapGLOptions {+ xKey: string;+ yKey: string;+ valueKey: string;+ colorRange: string[];+ domain?: [number, number];+ cellGap?: number;+}++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 sampleRamp(+ ramp: [number, number, number][],+ t: number,+): [number, number, number] {+ const c = Math.max(0, Math.min(1, t));+ if (ramp.length === 1) return ramp[0];+ const s = c * (ramp.length - 1);+ const lo = Math.floor(s);+ const hi = Math.min(lo + 1, ramp.length - 1);+ const f = s - lo;+ return [+ ramp[lo][0] + f * (ramp[hi][0] - ramp[lo][0]),+ ramp[lo][1] + f * (ramp[hi][1] - ramp[lo][1]),+ ramp[lo][2] + f * (ramp[hi][2] - ramp[lo][2]),+ ];+}++/**+ * Inline component — manages the heatmap WebGL canvas and its own y band scale.+ */+function HeatmapGLCanvas({+ data,+ xKey,+ yKey,+ valueKey,+ xScale,+ colorRange,+ domain: domainProp,+ cellGap,+ width,+ height,+}: {+ data: Record<string, unknown>[];+ xKey: string;+ yKey: string;+ valueKey: string;+ xScale: ScaleBand<string>;+ colorRange: string[];+ domain?: [number, number];+ cellGap: number;+ width: number;+ height: number;+}) {+ const canvasRef = useRef<HTMLCanvasElement | null>(null);+ const glRef = useRef<WebGLRenderingContext | null>(null);+ const programRef = useRef<WebGLProgram | null>(null);+ const markerRef = useRef<SVGGElement>(null);++ const ramp = useMemo(() => colorRange.map(hexToGL), [colorRange]);++ const yBandScale = useMemo(() => {+ const cats = [...new Set(data.map(d => String(d[yKey])))];+ return scaleBand<string>().domain(cats).range([0, height]).padding(0.05);+ }, [data, yKey, height]);++ const domain = useMemo((): [number, number] => {+ if (domainProp) return domainProp;+ let min = Infinity, 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]);++ // Mount canvas outside SVG+ useEffect(() => {+ const marker = markerRef.current;+ if (!marker) return;+ if (!canvasRef.current)+ canvasRef.current = document.createElement('canvas');+ return mountCanvasOverSVG(marker, canvasRef.current, width, height);+ }, [width, height]);++ // Draw+ useEffect(() => {+ const canvas = canvasRef.current;+ if (!canvas || width <= 0 || height <= 0) return;++ sizeCanvas(canvas, width, height);++ if (!glRef.current) glRef.current = getWebGLContext(canvas);+ const gl = glRef.current;+ if (!gl) return;++ if (!programRef.current) programRef.current = createProgram(gl, VERT, FRAG);+ const program = programRef.current;+ if (!program) return;++ gl.viewport(0, 0, canvas.width, canvas.height);+ setupGLState(gl);+ 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, 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 <g ref={markerRef} />;+}++/**+ * WebGL heatmap. Renders a 2D grid of colored cells using triangles.+ * Manages its own y band scale for rows; uses the chart's x band scale for columns.+ *+ * @example+ * ```+ * series={[heatmapGL({+ * xKey: 'hour', yKey: 'day', valueKey: 'count',+ * colorRange: ['#f0f9ff', '#1e40af'],+ * })]}+ * ```+ */+export function heatmapGL(options: HeatmapGLOptions): SeriesDef {+ const {xKey, yKey, valueKey, colorRange} = options;+ const cellGap = options.cellGap ?? 1;++ return {+ type: 'heatmapGL',+ key: `heatmap-${valueKey}`,+ dataKeys: [valueKey],+ layout: {},++ resolve(ctx) {+ // Heatmap doesn't resolve per-point positions the standard way —+ // the canvas component handles its own cell layout.+ const {data, xScale, yScale} = ctx;+ const points: ResolvedPoint[] = [];+ if (!('bandwidth' in xScale)) return points;+ for (let i = 0; i < data.length; i++) {+ const d = data[i];+ const px = ((xScale as ScaleBand<string>)(String(d[xKey])) ?? 0) ++ (xScale as ScaleBand<string>).bandwidth() / 2;+ const v = typeof d[valueKey] === 'number' ? (d[valueKey] as number) : 0;+ points.push({px, py: yScale(v), py0: yScale(0), dataIndex: i});+ }+ return points;+ },++ render(_resolved, ctx) {+ if (!('bandwidth' in ctx.xScale)) return null;+ return (+ <HeatmapGLCanvas+ data={ctx.data}+ xKey={xKey}+ yKey={yKey}+ valueKey={valueKey}+ xScale={ctx.xScale as ScaleBand<string>}+ colorRange={colorRange}+ domain={options.domain}+ cellGap={cellGap}+ width={ctx.width}+ height={ctx.height}+ />+ );+ },+ };+}diff --git a/packages/lab/src/ChartV2/marks/index.ts b/packages/lab/src/ChartV2/marks/index.tsindex 252f47bfd3..ec226c8bc5 100644--- a/packages/lab/src/ChartV2/marks/index.ts+++ b/packages/lab/src/ChartV2/marks/index.ts@@ -4,3 +4,9 @@ export {dot, type DotOptions} from './dot';export {area, type AreaOptions} from './area';export {band, type BandOptions} from './band';export {candlestick, type CandlestickOptions} from './candlestick';+export {errorBar, type ErrorBarOptions} from './errorBar';+export {referenceLine, type ReferenceLineOptions} from './referenceLine';+export {dotGL, type DotGLOptions} from './dotGL';+export {dotGLInteractive, type DotGLInteractiveOptions} from './dotGLInteractive';+export {heatmapGL, type HeatmapGLOptions} from './heatmapGL';+export {streamGL, type StreamGLOptions, type StreamGLHandle} from './streamGL';diff --git a/packages/lab/src/ChartV2/marks/referenceLine.tsx b/packages/lab/src/ChartV2/marks/referenceLine.tsxnew file mode 100644index 0000000000..f5e14e1a4d--- /dev/null+++ b/packages/lab/src/ChartV2/marks/referenceLine.tsx@@ -0,0 +1,140 @@+/**+ * @file marks/referenceLine.tsx+ * @output Horizontal or vertical reference line/band annotation+ */++import type {SeriesDef, ResolvedPoint} from '../types';+import type {ScaleLinear} from 'd3-scale';++export interface ReferenceLineOptions {+ /** Horizontal reference at this y value */+ y?: number;+ /** Second y value — draws a shaded band between y and y2 */+ y2?: number;+ /** Vertical reference at this x value */+ x?: number;+ /** Line/band color */+ color?: string;+ /** Stroke width (for lines) */+ strokeWidth?: number;+ /** Dash pattern */+ strokeDasharray?: string;+ /** Text label */+ label?: string;+ /** Label position */+ labelPosition?: 'start' | 'end';+ /** Band fill opacity (when y2 is set) */+ bandOpacity?: number;+}++/**+ * Reference line or band annotation. Not a data series — renders at fixed values.+ *+ * @example+ * ```+ * series={[line('revenue'), referenceLine({y: 100, label: 'Target'})]}+ * ```+ */+export function referenceLine(options: ReferenceLineOptions): SeriesDef {+ const color = options.color ?? 'var(--color-border-emphasized)';+ const strokeWidth = options.strokeWidth ?? 1;+ const strokeDasharray = options.strokeDasharray ?? '6 3';+ const label = options.label;+ const labelPosition = options.labelPosition ?? 'end';+ const bandOpacity = options.bandOpacity ?? 0.1;++ // Badge dimensions — matches crosshair label style+ const badgeH = 14;+ const badgeRx = 3;+ const fontSize = 10;++ return {+ type: 'referenceLine',+ key: `ref-${options.y ?? options.x ?? 'none'}`,+ dataKeys: [],+ layout: {},++ // No data points to resolve — this is a fixed annotation+ resolve() {+ return [];+ },++ render(_resolved, ctx) {+ const {width, height, xScale, yScale} = ctx;++ // Horizontal reference line or band+ if (options.y != null) {+ const py = yScale(options.y);+ const textW = label ? label.length * 5.5 + 8 : 0;+ const bx = labelPosition === 'end' ? width - textW - 2 : 2;++ // Band mode: shaded region between y and y2+ if (options.y2 != null) {+ const py2 = yScale(options.y2);+ const top = Math.min(py, py2);+ const bandHeight = Math.abs(py2 - py);+ return (+ <g>+ <rect x={0} y={top} width={width} height={bandHeight}+ fill={color} opacity={bandOpacity} />+ <line x1={0} x2={width} y1={py} y2={py}+ stroke={color} strokeWidth={strokeWidth} strokeDasharray={strokeDasharray} />+ <line x1={0} x2={width} y1={py2} y2={py2}+ stroke={color} strokeWidth={strokeWidth} strokeDasharray={strokeDasharray} />+ {label && (+ <g transform={`translate(${bx},${py})`} pointerEvents="none">+ <rect x={0} y={-badgeH / 2} width={textW} height={badgeH} rx={badgeRx}+ fill="var(--color-background-popover)" fillOpacity={0.85}+ stroke={color} strokeWidth={0.5} />+ <text x={textW / 2} dy="0.35em" textAnchor="middle"+ fontSize={fontSize} fontWeight={500} fill={color}>{label}</text>+ </g>+ )}+ </g>+ );+ }++ // Single horizontal line+ return (+ <g>+ <line x1={0} x2={width} y1={py} y2={py}+ stroke={color} strokeWidth={strokeWidth} strokeDasharray={strokeDasharray} />+ {label && (+ <g transform={`translate(${bx},${py})`} pointerEvents="none">+ <rect x={0} y={-badgeH / 2} width={textW} height={badgeH} rx={badgeRx}+ fill="var(--color-background-popover)" fillOpacity={0.85}+ stroke={color} strokeWidth={0.5} />+ <text x={textW / 2} dy="0.35em" textAnchor="middle"+ fontSize={fontSize} fontWeight={500} fill={color}>{label}</text>+ </g>+ )}+ </g>+ );+ }++ // Vertical reference line+ if (options.x != null && !('bandwidth' in xScale)) {+ const px = (xScale as ScaleLinear<number, number>)(options.x);+ const textW = label ? label.length * 5.5 + 8 : 0;+ const by = labelPosition === 'end' ? 4 : height - badgeH - 4;+ return (+ <g>+ <line x1={px} x2={px} y1={0} y2={height}+ stroke={color} strokeWidth={strokeWidth} strokeDasharray={strokeDasharray} />+ {label && (+ <g transform={`translate(${px - textW / 2},${by})`} pointerEvents="none">+ <rect x={0} y={0} width={textW} height={badgeH} rx={badgeRx}+ fill="var(--color-background-popover)" fillOpacity={0.85}+ stroke={color} strokeWidth={0.5} />+ <text x={textW / 2} y={badgeH / 2} dy="0.35em" textAnchor="middle"+ fontSize={fontSize} fontWeight={500} fill={color}>{label}</text>+ </g>+ )}+ </g>+ );+ }++ return null;+ },+ };+}diff --git a/packages/lab/src/ChartV2/marks/streamGL.tsx b/packages/lab/src/ChartV2/marks/streamGL.tsxnew file mode 100644index 0000000000..0e7118e69f--- /dev/null+++ b/packages/lab/src/ChartV2/marks/streamGL.tsx@@ -0,0 +1,228 @@+/**+ * @file marks/streamGL.tsx+ * @output WebGL streaming time-series line — ring buffer, canvas outside SVG+ *+ * Data is pushed imperatively via the returned handle, not from the static dataset.+ * The chart's xScale/yScale map pushed values to pixel coordinates.+ */++import {+ useRef,+ useEffect,+ useImperativeHandle,+ useCallback,+ type MutableRefObject,+} from 'react';+import type {SeriesDef, ResolvedPoint} from '../types';+import {useChartV2} from '../ChartV2Context';+import {+ hexToGL,+ getWebGLContext,+ setupGLState,+ sizeCanvas,+ mountCanvasOverSVG,+ createProgram,+} from '../../Chart/webgl';++export interface StreamGLHandle {+ push(x: number, y: number): void;+ clear(): void;+}++export interface StreamGLOptions {+ color: string;+ bufferSize?: number;+ lineWidth?: number;+ opacity?: number;+ /** Ref to receive the push/clear handle */+ handleRef?: MutableRefObject<StreamGLHandle | null>;+}++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() {+ float a = u_opacity;+ gl_FragColor = vec4(u_color * a, a);+ }+`;++/**+ * Inline component — manages the ring buffer, canvas, and rAF draw loop.+ */+function StreamGLCanvas({+ color,+ bufferSize,+ lineWidth,+ opacity,+ width,+ height,+ handleRef,+}: {+ color: string;+ bufferSize: number;+ lineWidth: number;+ opacity: number;+ width: number;+ height: number;+ handleRef?: MutableRefObject<StreamGLHandle | null>;+}) {+ const {xScale, yScale} = useChartV2();+ const canvasRef = useRef<HTMLCanvasElement | null>(null);+ const glRef = useRef<WebGLRenderingContext | null>(null);+ const programRef = useRef<WebGLProgram | null>(null);+ const bufRef = useRef<WebGLBuffer | null>(null);+ const markerRef = useRef<SVGGElement>(null);++ const ring = useRef({+ data: new Float32Array(bufferSize * 2),+ head: 0,+ count: 0,+ });++ // Mount canvas outside SVG+ useEffect(() => {+ const marker = markerRef.current;+ if (!marker) return;+ if (!canvasRef.current)+ canvasRef.current = document.createElement('canvas');+ return mountCanvasOverSVG(marker, canvasRef.current, width, height);+ }, [width, height]);++ // Size canvas+ useEffect(() => {+ const canvas = canvasRef.current;+ if (!canvas || width <= 0 || height <= 0) return;+ sizeCanvas(canvas, width, height);+ }, [width, height]);++ const draw = useCallback(() => {+ const canvas = canvasRef.current;+ if (!canvas) return;+ if (!glRef.current) glRef.current = getWebGLContext(canvas);+ const gl = glRef.current;+ if (!gl) return;++ if (!programRef.current) programRef.current = createProgram(gl, VERT, FRAG);+ const program = programRef.current;+ if (!program) return;++ if (!bufRef.current) bufRef.current = gl.createBuffer();++ const {data: ringData, head, count} = ring.current;+ if (count < 2) return;++ const linearX = xScale as (v: number) => number;+ const drawBuf = new Float32Array(count * 2);+ for (let i = 0; i < count; i++) {+ const idx = ((head - count + i + bufferSize) % bufferSize) * 2;+ drawBuf[i * 2] = linearX(ringData[idx]);+ drawBuf[i * 2 + 1] = yScale(ringData[idx + 1]);+ }++ gl.viewport(0, 0, canvas.width, canvas.height);+ setupGLState(gl);+ gl.useProgram(program);++ gl.bindBuffer(gl.ARRAY_BUFFER, bufRef.current);+ 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, xScale, yScale]);++ // Expose push/clear handle via ref+ useImperativeHandle(+ handleRef as MutableRefObject<StreamGLHandle | null>,+ () => ({+ 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],+ );++ if (width <= 0 || height <= 0) return null;+ return <g ref={markerRef} />;+}++/**+ * WebGL streaming line. Data is pushed imperatively via handleRef,+ * not from the chart's static dataset. Internally uses a ring buffer.+ *+ * @example+ * ```+ * const streamRef = useRef<StreamGLHandle>(null);+ * // Push data points in a rAF loop or event handler:+ * streamRef.current?.push(Date.now(), value);+ *+ * <XDSChart series={[streamGL({color: '#10b981', handleRef: streamRef})]} />+ * ```+ */+export function streamGL(options: StreamGLOptions): SeriesDef {+ const {color} = options;+ const bufferSize = options.bufferSize ?? 500;+ const lineWidth = options.lineWidth ?? 2;+ const opacity = options.opacity ?? 1;+ const handleRef = options.handleRef;++ return {+ type: 'streamGL',+ key: 'stream',+ dataKeys: [],+ layout: {},++ // Streaming data is pushed, not in the static dataset+ resolve() {+ return [];+ },++ render(_resolved, ctx) {+ return (+ <StreamGLCanvas+ color={color}+ bufferSize={bufferSize}+ lineWidth={lineWidth}+ opacity={opacity}+ width={ctx.width}+ height={ctx.height}+ handleRef={handleRef}+ />+ );+ },+ };+}diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.tsindex 7664bb3a47..bd7b43d4e5 100644--- a/packages/lab/src/index.ts+++ b/packages/lab/src/index.ts@@ -198,6 +198,12 @@ export {area,band,candlestick,+ errorBar,+ referenceLine,+ dotGL,+ dotGLInteractive,+ heatmapGL,+ streamGL,useChartV2,type SeriesDef,type ChartV2Context,@@ -205,4 +211,11 @@ export {type ResolvedPoint,type ResolvedPositions,type SeriesContext,+ type ErrorBarOptions,+ type ReferenceLineOptions,+ type DotGLOptions,+ type DotGLInteractiveOptions,+ type HeatmapGLOptions,+ type StreamGLOptions,+ type StreamGLHandle,} from './ChartV2';