From bf0bcfbbd9d1b853e7b324d0cdb61b347e4a28b0 Mon Sep 17 00:00:00 2001 From: YektaY Date: Wed, 11 Nov 2026 19:04:10 -0800 Subject: [PATCH] Declare dimensions on typed-array line series Line and extension series carry their points as a flat Float64Array (25fb6c9). ECharts' development build asserts that typed-array data declares its dimensions ("dimensions must be given if data is TypedArray."), so in `pnpm dev` adding a trace crashed the plot. The production build strips the assert, which is why only dev broke. Both series now declare dimensions ['x', 'y']. They map to the axes in order, time then value, so no encode is needed, and [t, v] pairs read the same way: the main line keeps them when it switches to point data at an INVALID sample. PlotArea.option.test.tsx loads the option SinglePlot builds into a real server-side ECharts instance and reads the values back out of its store: an empty just-added trace, a line with its frozen (2048-anchor) and following (2-point) extension, a line switching between typed and point data on one chart, an INVALID-broken step line with its band, and LTTB sampling of a dense line keeping a one-sample spike. --- src/components/PlotArea.option.test.tsx | 323 ++++++++++++++++++++++++ src/components/PlotArea.tsx | 13 +- 2 files changed, 335 insertions(+), 1 deletion(-) create mode 100644 src/components/PlotArea.option.test.tsx diff --git a/src/components/PlotArea.option.test.tsx b/src/components/PlotArea.option.test.tsx new file mode 100644 index 0000000..ca5a083 --- /dev/null +++ b/src/components/PlotArea.option.test.tsx @@ -0,0 +1,323 @@ +// @vitest-environment jsdom +// +// The option SinglePlot builds must load in real ECharts. Line and extension +// series carry flat [t0, v0, t1, v1, ...] Float64Array data, and ECharts' +// development build asserts that typed-array data declares its `dimensions` +// ("dimensions must be given if data is TypedArray."). Production builds strip +// the assert, so only `pnpm dev` crashed, as soon as Add Trace made a series. +// Mounts SinglePlot with a mocked echarts-for-react, then hands the captured +// option to a server-side ECharts instance (NODE_ENV is "test", so the +// development asserts are live) and reads the values back out of its store. +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { render } from '@testing-library/react'; +import * as echarts from 'echarts'; +import { SinglePlot } from './PlotArea'; +import type { Plot, PVTrace } from '../types'; +import type { AlarmSeverity } from '../api/types'; +import type { ArchiveSeriesResult } from '../hooks/useArchiveSeries'; + +type Series = Record & { id: string; type: string; data: unknown }; +interface Option { + series: Series[]; +} + +const { lastOption } = vi.hoisted(() => ({ lastOption: { current: null as unknown } })); + +vi.mock('echarts-for-react', async () => { + const React = await import('react'); + class MockECharts extends React.Component<{ option: unknown }> { + getEchartsInstance() { + return undefined; + } + render() { + lastOption.current = this.props.option; + return React.createElement('div'); + } + } + return { default: MockECharts }; +}); + +const FROM_MS = Date.UTC(2026, 9, 1, 12, 0, 0); +const TO_MS = FROM_MS + 60_000; +const at = (s: number) => FROM_MS + s * 1000; + +function makeTrace(over: Partial = {}): PVTrace { + return { + id: 't1', + pvName: 'SIM:SINE', + displayName: 'SIM:SINE', + color: '#ff00aa', + visible: true, + axisId: 'ax1', + useLive: false, + updateRate: '1s', + useArchive: true, + lineWidth: 2, + lineType: 'direct', + lineStyle: 'solid', + showSymbol: false, + symbolShape: 'circle', + symbolSize: 4, + data: [], + ...over, + }; +} + +function makePlot(traces: PVTrace[], xAxis: Plot['xAxis']): Plot { + return { + id: 'p1', + title: 'Plot 1', + traces, + axes: [ + { + id: 'ax1', + name: 'Y', + orientation: 'left', + autoScale: true, + logScale: false, + visible: true, + }, + ], + backgroundColor: 'default', + showLegend: false, + showXGridlines: false, + showYGridlines: false, + showCrosshair: true, + gridStyle: 'solid', + gridOpacity: 1, + tickFontSize: 11, + xAxis, + }; +} + +const CUSTOM_WINDOW: Plot['xAxis'] = { + timeRange: 'custom', + timeFrom: new Date(FROM_MS).toISOString(), + timeTo: new Date(TO_MS).toISOString(), +}; + +type Pt = [seconds: number, value: number, severity?: AlarmSeverity]; +const samples = (pts: Pt[]) => + pts.map(([s, value, severity = 'NO_ALARM']) => ({ time: at(s), value, severity })); + +const raw = (pts: Pt[]): ArchiveSeriesResult => ({ + status: 'ready', + mode: 'raw', + mean: samples(pts), + band: [], +}); + +function mount( + traces: PVTrace[], + archive: Map, + { following = false, xAxis = CUSTOM_WINDOW }: { following?: boolean; xAxis?: Plot['xAxis'] } = {} +): Option { + const { unmount } = render( + + ); + unmount(); + return lastOption.current as Option; +} + +// ECharts measures label text on a canvas, which jsdom doesn't have. A rough +// width is enough to lay out the axes. +echarts.setPlatformAPI({ measureText: (text = '') => ({ width: text.length * 6 }) }); + +let chart: echarts.ECharts | null = null; +afterEach(() => { + chart?.dispose(); + chart = null; +}); + +// Hands the option to the chart the way echarts-for-react does. +function update(c: echarts.ECharts, option: Option) { + c.setOption(option as unknown as echarts.EChartsOption, { replaceMerge: ['series', 'yAxis'] }); + c.renderToSVGString(); +} + +// Loads the option into a new server-side chart. +function load(option: Option): echarts.ECharts { + chart = echarts.init(null, null, { renderer: 'svg', ssr: true, width: 600, height: 400 }); + update(chart, option); + return chart; +} + +// A series' values as ECharts stores them, read through its x and y mapping. +function stored(c: echarts.ECharts, id: string): [number, number][] { + const model = ( + c as unknown as { + getModel(): { + getSeries(): { + id: string; + getData(): { + count(): number; + mapDimension(coordDim: string): string; + get(dim: string, idx: number): number; + }; + }[]; + }; + } + ).getModel(); + const series = model.getSeries().find((s) => s.id === id); + if (!series) throw new Error(`no series ${id}`); + const data = series.getData(); + const x = data.mapDimension('x'); + const y = data.mapDimension('y'); + return Array.from({ length: data.count() }, (_, i) => [data.get(x, i), data.get(y, i)]); +} + +const typedSeries = (opt: Option) => + opt.series.filter((s) => ArrayBuffer.isView(s.data) && !(s.data instanceof DataView)); + +function expectTypedSeriesDeclareDimensions(opt: Option) { + for (const s of typedSeries(opt)) { + expect(s.dimensions, `series ${s.id}`).toEqual(['x', 'y']); + } +} + +describe('PlotArea: option loads in ECharts with typed-array series data', () => { + it('loads a just-added trace with no samples yet (the Add Trace crash)', () => { + const opt = mount([makeTrace()], new Map([['t1', raw([])]])); + const line = opt.series.find((s) => s.id === 't1')!; + expect(line.data).toBeInstanceOf(Float64Array); + expectTypedSeriesDeclareDimensions(opt); + expect(stored(load(opt), 't1')).toEqual([]); + }); + + it('stores time in x and value in y for the line and its frozen extension', () => { + const opt = mount( + [makeTrace()], + new Map([ + [ + 't1', + raw([ + [10, 1], + [20, 2], + [30, 3], + ]), + ], + ]) + ); + expect(typedSeries(opt).map((s) => s.id)).toEqual(['t1', 't1-extension']); + expectTypedSeriesDeclareDimensions(opt); + + const c = load(opt); + expect(stored(c, 't1')).toEqual([ + [at(10), 1], + [at(20), 2], + [at(30), 3], + ]); + // A frozen plot's extension: dense anchors from the last sample to the edge. + const ext = stored(c, 't1-extension'); + expect(ext).toHaveLength(2048); + expect(ext[0]).toEqual([at(30), 3]); + expect(ext.at(-1)).toEqual([TO_MS, 3]); + expect(ext.every(([, v]) => v === 3)).toBe(true); + }); + + it("loads a following plot's two-point extension", () => { + const opt = mount([makeTrace()], new Map([['t1', raw([[50, 7]])]]), { + following: true, + xAxis: { timeRange: '-1m' }, + }); + expectTypedSeriesDeclareDimensions(opt); + expect(stored(load(opt), 't1-extension')).toEqual([ + [at(50), 7], + [TO_MS, 7], + ]); + }); + + it('keeps reading a line that switches between typed and point data on one chart', () => { + const typedAgain: Pt[] = [ + [10, 1], + [20, 2], + [40, 4], + [50, 5], + ]; + const withInvalid: Pt[] = [ + [10, 1], + [20, 2], + [30, 99, 'INVALID'], + [40, 4], + ]; + const c = load(mount([makeTrace()], new Map([['t1', raw(typedAgain.slice(0, 2))]]))); + + // An INVALID sample arrives: the same series id now gets [t, v] pairs. + const broken = mount([makeTrace()], new Map([['t1', raw(withInvalid)]])); + expect(Array.isArray(broken.series.find((s) => s.id === 't1')!.data)).toBe(true); + update(c, broken); + expect(stored(c, 't1')).toEqual([ + [at(10), 1], + [at(20), 2], + [at(30), NaN], + [at(40), 4], + ]); + + // And back to typed once it's gone. + update(c, mount([makeTrace()], new Map([['t1', raw(typedAgain)]]))); + expect(stored(c, 't1')).toEqual(typedAgain.map(([s, v]) => [at(s), v])); + }); + + it('still loads point data for a line broken by an INVALID sample, with its band', () => { + const pts: Pt[] = [ + [10, 1], + [20, 99, 'INVALID'], + [30, 3], + ]; + const binned: ArchiveSeriesResult = { + status: 'ready', + mode: 'binned', + mean: samples(pts), + band: samples(pts).map((p) => ({ ...p, min: p.value - 1, max: p.value + 1 })), + }; + const opt = mount([makeTrace({ lineType: 'step' })], new Map([['t1', binned]])); + expect(Array.isArray(opt.series.find((s) => s.id === 't1')!.data)).toBe(true); + expectTypedSeriesDeclareDimensions(opt); + + const c = load(opt); + // The step line holds the last good value up to the INVALID sample, then breaks. + expect(stored(c, 't1')).toEqual([ + [at(10), 1], + [at(20), 1], + [at(20), NaN], + [at(30), 3], + ]); + // The band breaks and holds with it. + expect(stored(c, 't1-band-min')).toEqual([ + [at(10), 0], + [at(20), 0], + [at(20), NaN], + [at(30), 2], + ]); + }); + + it('LTTB-samples a dense typed line on its values, keeping a one-sample spike', () => { + // 6000 samples over the minute, far more than the ~500 px plot is wide, all + // zero but one. Sampling on the wrong dimension would drop the spike. + const n = 6000; + const spikeAt = 4321; + const dense: ArchiveSeriesResult = { + status: 'ready', + mode: 'raw', + mean: Array.from({ length: n }, (_, i) => ({ + time: FROM_MS + (i * 60_000) / n, + value: i === spikeAt ? 100 : 0, + severity: 'NO_ALARM' as const, + })), + band: [], + }; + const opt = mount([makeTrace()], new Map([['t1', dense]])); + expectTypedSeriesDeclareDimensions(opt); + + const line = stored(load(opt), 't1'); + expect(line.length).toBeLessThan(n / 2); + expect(line).toContainEqual([FROM_MS + (spikeAt * 60_000) / n, 100]); + }); +}); diff --git a/src/components/PlotArea.tsx b/src/components/PlotArea.tsx index 5833492..628ff71 100644 --- a/src/components/PlotArea.tsx +++ b/src/components/PlotArea.tsx @@ -198,6 +198,14 @@ const EXTENSION_ANCHORS = 2048; // each point through its option preprocessors. With plain [t, v] pairs that was // most of the cost of an update, and a following plot updates on every scroll // step as well as on every live batch. +// +// Typed data is flat, so it can't say how many values make a point: every +// series given xyData (or other flat data) must declare XY_DIMENSIONS. Without +// it ECharts' development build asserts ("dimensions must be given if data is +// TypedArray."), which the production build strips. The x and y dimensions map +// to the axes in order, time then value; [t, v] pairs read the same way. +const XY_DIMENSIONS = ['x', 'y']; + function xyData(points: readonly PlotSample[]): Float64Array { const out = new Float64Array(points.length * 2); for (let i = 0; i < points.length; i++) { @@ -395,10 +403,12 @@ export function SinglePlot({ type: 'line', yAxisIndex, // Typed unless it has to break at an INVALID sample: the nulls and - // step-line hold points need plain point data. + // step-line hold points need plain point data. Dimensions either way, + // since the series merges by id when it switches between the two. data: tracesWithInvalid.has(trace.id) ? gappedLineData(points, (p) => p.value, step) : xyData(points), + dimensions: XY_DIMENSIONS, step: step ? 'end' : false, lineStyle: { color: trace.color, @@ -858,6 +868,7 @@ export function SinglePlot({ type: 'line', yAxisIndex, data, + dimensions: XY_DIMENSIONS, lineStyle: { color: trace.color, width: trace.lineWidth,