From 1eb0849264fc5f723997e9e3dfd362e99bd19228 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Eizedev?= <6794362+eizedev@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:52:55 +0100 Subject: [PATCH 1/5] fix(echarts): keep zoom, legend and brush over a theme switch; place statistic labels by height ECharts' setTheme builds the chart from its option again and drops the zoom, the legend selection and the brush; PSU also mounts the component again on the first light/dark switch after a page loads. viewState.js reads the view before and sets it again with silent actions, around setTheme and across that remount (same id, other mode, same task). markLine statistic labels were placed above or below by series index, so close lines overlapped when the second was higher. They now follow the drawn values: the highest line's label above, the lowest's below, one in between away from its nearer neighbour, per statistic and value axis, stacked series by their stacked values. Co-Authored-By: Claude Opus 5.5 --- docs/echarts/lines-and-time.md | 3 +- docs/echarts/themes.md | 1 + .../CHANGELOG.md | 8 ++ .../Components/EChart.jsx | 43 ++++--- .../Components/cartesian.js | 9 +- .../Components/optionParts.js | 94 ++++++++++++++- .../Components/viewState.js | 70 +++++++++++ tests/js/echarts-view.test.js | 110 ++++++++++++++++++ tests/js/echarts.test.js | 41 +++++++ 9 files changed, 354 insertions(+), 25 deletions(-) create mode 100644 modules/PowerShellUniversal.Component.ECharts/Components/viewState.js create mode 100644 tests/js/echarts-view.test.js diff --git a/docs/echarts/lines-and-time.md b/docs/echarts/lines-and-time.md index cd70837..4529c7c 100644 --- a/docs/echarts/lines-and-time.md +++ b/docs/echarts/lines-and-time.md @@ -19,7 +19,8 @@ lines, `-SecondaryY` puts named series on a second axis, `-LogScale` makes the v ## Reference lines and pins `-MarkLine 'median', 'average'` per series, or fixed lines: `@{ value = 48; name = 'SLA'; color = '#e53935' }` -(`axis = 'x'` for a vertical line). +(`axis = 'x'` for a vertical line). With several series, the label of the higher line of a statistic +sits above it and the lower one's below, so the labels of close lines do not overlap. `-MarkPoint 'max', 'min'` pins those values on every series; `@{ x = 'Thu'; y = 306; label = 'Outage' }` pins one point (add `series = 'Mail'` for another series than the first). diff --git a/docs/echarts/themes.md b/docs/echarts/themes.md index 3c9991f..edc7576 100644 --- a/docs/echarts/themes.md +++ b/docs/echarts/themes.md @@ -5,6 +5,7 @@ description: "Themes of New-UDEChart: light and dark with the app, an ECharts th # Themes and corporate design Light and dark follow the app's theme switch (`-Theme Auto`); `-Theme Light` or `Dark` pins one. +The zoom, the series hidden in the legend and a brushed range stay when the theme switches. `-Palette` sets the series colours, `-Decal` adds patterns for colour-blind readers and print (off by default). The default palette is not checked for contrast. The charts on this site follow its light/dark switch the same way. diff --git a/modules/PowerShellUniversal.Component.ECharts/CHANGELOG.md b/modules/PowerShellUniversal.Component.ECharts/CHANGELOG.md index e7af870..6080ec9 100644 --- a/modules/PowerShellUniversal.Component.ECharts/CHANGELOG.md +++ b/modules/PowerShellUniversal.Component.ECharts/CHANGELOG.md @@ -23,6 +23,14 @@ All notable changes to PowerShellUniversal.Component.ECharts. Format: holds entries that are no objects, such as `$null`. Before, the row came from the wrong place in the data. `New-UDEChart` and `Set-UDEChartData` never send such entries. This affects only an app that sets the data another way, such as `Set-UDElement -Properties @{ data = ... }`. +- The zoom, the series hidden in the legend and a brushed range stay when PSU's light/dark switch + changes the theme. Before, the chart started over at full range with every series shown. No + `-OnZoom`, `-OnSelect` or `-OnLegendChange` runs for the switch. +- `-MarkLine 'average'` (and `median`, `min`, `max`) with several series: the label of the higher line + sits above it and the lower one's below. Before, the side came from the series' order, so the labels + of close lines overlapped when the second line was higher. A label position for a series' whole + `markLine` in `-Options` no longer moves these labels; set it per line instead: + `markLine = @{ data = @(@{ label = @{ position = 'insideStartBottom' } }) }`. ### Changed diff --git a/modules/PowerShellUniversal.Component.ECharts/Components/EChart.jsx b/modules/PowerShellUniversal.Component.ECharts/Components/EChart.jsx index d475a45..9bc0a06 100644 --- a/modules/PowerShellUniversal.Component.ECharts/Components/EChart.jsx +++ b/modules/PowerShellUniversal.Component.ECharts/Components/EChart.jsx @@ -4,6 +4,7 @@ import { buildOption, dataRows, rowOf, responsive, optionForWidth, tooltipTracks import { tooltipState } from "./tooltipMode"; import { ensureTheme, themeObject, pageFontSize } from "./themes"; import { scaleFonts } from "./fonts"; +import { applyView, handOverView, setThemeKeepingView, takeHandedOverView } from "./viewState"; import { fitPlot, insideLabelColors, legendRows, needsFit } from "./layout"; import { registerLocales, echartsLocale } from "./locales"; import { usePsuTheme, effectiveMode } from "../../../shared/js/psuTheme"; @@ -57,6 +58,21 @@ function toggleFullscreen(el) { } } +// whether the element is on the whole screen now (the button, Esc or the browser's own way out) +function useFullscreen(ref) { + const [full, setFull] = useState(false); + useEffect(() => { + const onChange = () => setFull(fullscreenElement() === ref.current); + document.addEventListener("fullscreenchange", onChange); + document.addEventListener("webkitfullscreenchange", onChange); + return () => { + document.removeEventListener("fullscreenchange", onChange); + document.removeEventListener("webkitfullscreenchange", onChange); + }; + }, [ref]); + return full; +} + /* * Values from ECharts events turned into something PowerShell can use: time axis values (epoch ms) * become ISO strings, category indices become the category names. @@ -78,8 +94,8 @@ function axisValue(chart, axisIndex, value) { export default function EChart(props) { const outer = useRef(null); const container = useRef(null); - const [full, setFull] = useState(false); const chartRef = useRef(null); + const full = useFullscreen(outer); const psuTheme = usePsuTheme(); const mode = effectiveMode(props.theme, psuTheme); const locale = defaultLocale(props.locale); @@ -89,8 +105,11 @@ export default function EChart(props) { // one object per content: PSU sends the theme anew with every update of the props, which must // not set the theme again const customTheme = useMemo(() => (customKey ? JSON.parse(customKey) : undefined), [customKey]); - // the latest props for event handlers registered once + // the latest props for event handlers registered once, the latest mode for the chart's disposal const latest = useLatest(props); + const latestMode = useLatest(mode); + // zoom, legend and brush of the chart this one replaces after PSU's light/dark switch (viewState.js) + const handedView = useRef(null); // Get-UDElement: the last click, range and zoom, kept here because PSU asks for them synchronously // (shared/js/elementState.js). The component's state holds them too; the wrapper's late POST sends // that copy, which PSU ignores @@ -132,16 +151,6 @@ export default function EChart(props) { } }, [props, locale, mode, latest]); - useEffect(() => { - const onChange = () => setFull(fullscreenElement() === outer.current); - document.addEventListener("fullscreenchange", onChange); - document.addEventListener("webkitfullscreenchange", onChange); - return () => { - document.removeEventListener("fullscreenchange", onChange); - document.removeEventListener("webkitfullscreenchange", onChange); - }; - }, []); - // layout key of the container: the option is applied again only when the width crosses a rule's // limit, or - for charts without a grid, whose plot is placed by size (fitPlot) - when the size or // the number of legend lines changes noticeably @@ -158,6 +167,7 @@ export default function EChart(props) { registerLocales(echarts); const chart = echarts.init(container.current, ensureTheme(echarts, mode, psuTheme, customTheme), { renderer: props.renderer === "svg" ? "svg" : "canvas", locale: echartsLocale(locale) }); chartRef.current = chart; + handedView.current = takeHandedOverView(props.id, mode); // the ECharts instance on its element, for page scripts and tests: element.echarts.getOption() container.current.echarts = chart; // resize in the next frame: resizing inside the observer's callback changes the layout it is @@ -177,11 +187,14 @@ export default function EChart(props) { return () => { cancelAnimationFrame(frame); resize.disconnect(); + // the mode at disposal, not at creation: a value, not a node, so the rule's case does not apply + // eslint-disable-next-line react-hooks/exhaustive-deps + handOverView(props.id, latestMode.current, chart); chart.dispose(); chartRef.current = null; }; // made again only for another renderer or locale: the theme is the starting one, a new theme - // goes to the living chart (next effect), so zoom, legend and brush stay + // goes to the living chart (next effect); zoom, legend and brush stay over both (viewState.js) // eslint-disable-next-line react-hooks/exhaustive-deps }, [props.renderer, locale]); @@ -189,7 +202,7 @@ export default function EChart(props) { useEffect(() => { const chart = chartRef.current; if (chart) { - chart.setTheme(ensureTheme(echarts, mode, psuTheme, customTheme)); + setThemeKeepingView(chart, ensureTheme(echarts, mode, psuTheme, customTheme)); } }, [mode, psuTheme, customTheme]); @@ -207,6 +220,8 @@ export default function EChart(props) { const placed = fitPlot(sized, { width, height: chart.getHeight() }, props.options); const theme = themeObject(mode, psuTheme, customTheme); chart.setOption(insideLabelColors(placed, theme.color, theme.textStyle && theme.textStyle.color), { replaceMerge: REPLACED }); + applyView(chart, handedView.current); + handedView.current = null; // the series are as built again (a toolbox switch to line, bar or stack is gone) tipState.current.live = null; }, [option, layoutKey, mode, psuTheme, customTheme, props.options]); diff --git a/modules/PowerShellUniversal.Component.ECharts/Components/cartesian.js b/modules/PowerShellUniversal.Component.ECharts/Components/cartesian.js index c1f56c1..97ebb3d 100644 --- a/modules/PowerShellUniversal.Component.ECharts/Components/cartesian.js +++ b/modules/PowerShellUniversal.Component.ECharts/Components/cartesian.js @@ -1,7 +1,7 @@ import { resolveColumn, resolveColumns } from "../../../shared/js/columns.js"; import { formatter } from "./formatters.js"; import { html } from "./html.js"; -import { LARGE, CARTESIAN, SHADE, list, num, axisTypeFor, unique, displayName, isPlainObject, valueFormatter, labelFormatter, titleOf, legendOf, gridOf, dataZoomOf, toolboxOf, markAreaOf, markLineOf, markPointOf, axisBreaks, maxOf, minOf, aggregate, groupRows, toTime, linearFit, medianStep } from "./optionParts.js"; +import { LARGE, CARTESIAN, SHADE, list, num, axisTypeFor, unique, displayName, isPlainObject, valueFormatter, labelFormatter, titleOf, legendOf, gridOf, dataZoomOf, toolboxOf, markAreaOf, markLineOf, addStatisticLines, markPointOf, axisBreaks, maxOf, minOf, aggregate, groupRows, toTime, linearFit, medianStep } from "./optionParts.js"; import { timeAxisLabel } from "./timeaxis.js"; import { cartesianTooltipFormatter, resolveTooltipMode } from "./tooltipMode.js"; @@ -279,12 +279,7 @@ export function cartesian(props_, rows, keys, ctx) { }); } - // markLine statistics belong to every series, fixed lines once - if (list(props.markLine).some((m) => typeof m === "string")) { - series.slice(1).forEach((s, i) => { - s.markLine = markLineOf({ markLine: list(props.markLine).filter((m) => typeof m === "string") }, horizontal, fmt, i + 1); - }); - } + addStatisticLines(series, props, horizontal, fmt); const valueAxis = (index) => ({ type: props.logScale ? "log" : "value", diff --git a/modules/PowerShellUniversal.Component.ECharts/Components/optionParts.js b/modules/PowerShellUniversal.Component.ECharts/Components/optionParts.js index d352c7d..a06b9f2 100644 --- a/modules/PowerShellUniversal.Component.ECharts/Components/optionParts.js +++ b/modules/PowerShellUniversal.Component.ECharts/Components/optionParts.js @@ -291,9 +291,10 @@ export function markAreaOf(props, xType, horizontal) { /* * markLine entries from PowerShell: "median", "average", "min", "max" (of each series) or - * @{ value = 48; name = 'SLA'; axis = 'y' } for a fixed line. + * @{ value = 48; name = 'SLA'; axis = 'y' } for a fixed line. Labels sit above the line's end; + * placeStatisticLabels moves those of statistic lines that lie below another series' line. */ -export function markLineOf(props, horizontal, fmt, seriesIndex = 0) { +export function markLineOf(props, horizontal, fmt) { const items = list(props.markLine); if (items.length === 0) { return undefined; @@ -316,12 +317,99 @@ export function markLineOf(props, horizontal, fmt, seriesIndex = 0) { } return { symbol: ["none", "none"], - label: { formatter: (p) => `${p.name ? p.name + ": " : ""}${fmt ? fmt(p.value) : p.value}`, position: seriesIndex % 2 === 0 ? "insideEndTop" : "insideEndBottom" }, + label: { formatter: (p) => `${p.name ? p.name + ": " : ""}${fmt ? fmt(p.value) : p.value}`, position: "insideEndTop" }, lineStyle: { type: "dashed" }, data }; } +// -MarkLine statistics belong to every series of a cartesian chart; fixed lines only to the first, +// which has them from markLineOf already +export function addStatisticLines(series, props, horizontal, fmt) { + const statistics = list(props.markLine).filter((m) => typeof m === "string"); + if (statistics.length === 0) { + return; + } + series.slice(1).forEach((s) => { + s.markLine = markLineOf({ markLine: statistics }, horizontal, fmt); + }); + placeStatisticLabels(series, horizontal); +} + +// the value a statistic line is drawn at, as ECharts computes it (marker/markerHelper.js numCalculate) +const STATISTICS = { + average: (v) => AGGREGATES.avg(v), + median: (v) => quantile([...v].sort((a, b) => a - b), 0.5), + min: (v) => AGGREGATES.min(v), + max: (v) => AGGREGATES.max(v) +}; + +// a data item as built: a number, { value }, [x, y] or { value: [x, y] } ([y, x] for horizontal bars) +function pointOf(item, index, horizontal) { + const point = item && typeof item === "object" && !Array.isArray(item) ? item.value : item; + return Array.isArray(point) ? { x: point[horizontal ? 1 : 0], value: num(point[horizontal ? 0 : 1]) } : { x: index, value: num(point) }; +} + +// each series' values as drawn: a stacked series on top of the earlier ones of its stack with the same +// sign (ECharts' default stackStrategy), matched by x on a time or value axis, by position otherwise +function drawnValues(series, horizontal) { + const stacks = new Map(); + return series.map((s) => { + const sums = s.stack ? stacks.get(s.stack) ?? new Map() : null; + if (sums) { + stacks.set(s.stack, sums); + } + return (s.data || []).map((item, i) => { + const { x, value } = pointOf(item, i, horizontal); + if (!sums || value === null) { + return value; + } + const key = `${x}|${value < 0 ? "-" : "+"}`; + sums.set(key, (sums.get(key) ?? 0) + value); + return sums.get(key); + }); + }); +} + +// highest line: label above; lowest: below; one in between: away from its nearer neighbour +function labelSide(lines, rank) { + if (rank === 0) { + return "insideEndTop"; + } + if (rank === lines.length - 1) { + return "insideEndBottom"; + } + const gapAbove = lines[rank - 1].value - lines[rank].value; + const gapBelow = lines[rank].value - lines[rank + 1].value; + return gapBelow <= gapAbove ? "insideEndTop" : "insideEndBottom"; +} + +/* + * The labels of statistic lines of several series, by where the lines lie, so the labels of close + * lines face away from each other. Each statistic is ordered on its own, among the series on the same + * value axis; equal values keep the series order. A label set on a line item wins over one set for + * the series' markLine (-Options). + */ +export function placeStatisticLabels(series, horizontal) { + const drawn = drawnValues(series, horizontal); + const groups = new Map(); + series.forEach((s, i) => { + const values = drawn[i].filter((v) => v !== null); + for (const item of (s.markLine && s.markLine.data) || []) { + if (STATISTICS[item.type] && values.length) { + const key = `${item.type}|${s.yAxisIndex ?? 0}`; + groups.set(key, [...(groups.get(key) ?? []), { item, value: STATISTICS[item.type](values) }]); + } + } + }); + for (const lines of groups.values()) { + lines.sort((a, b) => b.value - a.value); + lines.forEach((line, rank) => { + line.item.label = { position: labelSide(lines, rank) }; + }); + } +} + // ---- axis breaks ----------------------------------------------------------------------------------- /* diff --git a/modules/PowerShellUniversal.Component.ECharts/Components/viewState.js b/modules/PowerShellUniversal.Component.ECharts/Components/viewState.js new file mode 100644 index 0000000..765bd4a --- /dev/null +++ b/modules/PowerShellUniversal.Component.ECharts/Components/viewState.js @@ -0,0 +1,70 @@ +/* + * What the reader did to a chart and a theme change must not undo: the zoom, the series hidden in the + * legend and the brushed range. ECharts' setTheme builds the chart from its option again and drops + * them, and PSU mounts the component again on the first light/dark switch after a page loads. Both + * read the view before and set it again afterwards, with silent actions, so no -OnZoom, -OnSelect or + * -OnLegendChange fires. A toolbox switch to line, bar or stack is not kept: the option is set anew. + */ + +// the view of a living chart, or null when there is nothing to keep +export function readView(chart) { + if (!chart || chart.isDisposed()) { + return null; + } + const option = chart.getOption() || {}; + const zoom = (option.dataZoom || []).map((z, dataZoomIndex) => ({ dataZoomIndex, start: z.start, end: z.end })); + const legend = Object.assign({}, ...(option.legend || []).map((l) => l.selected || {})); + const brushModel = chart.getModel().getComponent("brush"); + // the range in data values and the grid it is drawn in; ECharts computes the pixels again + const brush = ((brushModel && brushModel.areas) || []).map((a) => ({ brushType: a.brushType, coordRange: a.coordRange, panelId: a.panelId })); + return zoom.length || Object.keys(legend).length || brush.length ? { zoom, legend, brush } : null; +} + +export function applyView(chart, view) { + if (!chart || !view) { + return; + } + const silent = { silent: true }; + if (view.zoom.length) { + chart.dispatchAction({ type: "dataZoom", batch: view.zoom }, silent); + } + for (const [name, shown] of Object.entries(view.legend)) { + chart.dispatchAction({ type: shown ? "legendSelect" : "legendUnSelect", name }, silent); + } + if (view.brush.length) { + chart.dispatchAction({ type: "brush", areas: view.brush }, silent); + } +} + +export function setThemeKeepingView(chart, theme) { + const view = readView(chart); + chart.setTheme(theme); + applyView(chart, view); +} + +/* + * PSU's remount: the old chart hands its view over when it is disposed, the new one of the same id + * takes it in the same task. Only in the other mode, so a chart drawn again for other reasons (a + * New-UDDynamic that refreshes) starts as built, as before; an id nobody takes is forgotten. + */ +const handedOver = new Map(); + +export function handOverView(id, mode, chart) { + const view = readView(chart); + if (id === undefined || id === null || !view) { + return; + } + const entry = { mode, view }; + handedOver.set(id, entry); + setTimeout(() => { + if (handedOver.get(id) === entry) { + handedOver.delete(id); + } + }, 0); +} + +export function takeHandedOverView(id, mode) { + const entry = handedOver.get(id); + handedOver.delete(id); + return entry && entry.mode !== mode ? entry.view : null; +} diff --git a/tests/js/echarts-view.test.js b/tests/js/echarts-view.test.js new file mode 100644 index 0000000..4b41911 --- /dev/null +++ b/tests/js/echarts-view.test.js @@ -0,0 +1,110 @@ +// Tests for what a chart keeps over PSU's light/dark switch: zoom, legend selection and brush +// (modules/PowerShellUniversal.Component.ECharts/Components/viewState.js). Run: node --test tests/js/ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync } from "node:fs"; +import { readView, applyView, setThemeKeepingView, handOverView, takeHandedOverView } from "../../modules/PowerShellUniversal.Component.ECharts/Components/viewState.js"; + +// a chart that answers getOption and the brush model and records the actions it is sent +function fakeChart(option, brushAreas) { + const actions = []; + return { + actions, + isDisposed: () => false, + getOption: () => option, + getModel: () => ({ getComponent: (type) => (type === "brush" && brushAreas ? { areas: brushAreas } : undefined) }), + dispatchAction: (payload, opt) => actions.push({ payload, opt }) + }; +} + +test("readView: the zoom of each dataZoom, the legend selection of all legends and the brush areas", () => { + const chart = fakeChart( + { dataZoom: [{ start: 40, end: 60 }, { start: 40, end: 60 }], legend: [{ selected: { a: true, b: false } }, { selected: { c: false } }] }, + [{ brushType: "lineX", coordRange: [5, 8], panelId: "grid--0", range: [100, 200], brushStyle: {} }] + ); + assert.deepEqual(readView(chart), { + zoom: [{ dataZoomIndex: 0, start: 40, end: 60 }, { dataZoomIndex: 1, start: 40, end: 60 }], + legend: { a: true, b: false, c: false }, + brush: [{ brushType: "lineX", coordRange: [5, 8], panelId: "grid--0" }] + }); + // a chart without zoom, legend and brush has nothing to keep; nor has one not drawn yet + assert.equal(readView(fakeChart({})), null); + assert.equal(readView(fakeChart({ legend: [{ selected: {} }] })), null); + assert.equal(readView(null), null); +}); + +test("applyView: the kept state as silent actions, so no -OnZoom, -OnSelect or -OnLegendChange fires", () => { + const chart = fakeChart({}); + applyView(chart, { zoom: [{ dataZoomIndex: 0, start: 40, end: 60 }], legend: { a: true, b: false }, brush: [{ brushType: "lineX", coordRange: [5, 8], panelId: "grid--0" }] }); + assert.deepEqual(chart.actions, [ + { payload: { type: "dataZoom", batch: [{ dataZoomIndex: 0, start: 40, end: 60 }] }, opt: { silent: true } }, + { payload: { type: "legendSelect", name: "a" }, opt: { silent: true } }, + { payload: { type: "legendUnSelect", name: "b" }, opt: { silent: true } }, + { payload: { type: "brush", areas: [{ brushType: "lineX", coordRange: [5, 8], panelId: "grid--0" }] }, opt: { silent: true } } + ]); + const empty = fakeChart({}); + applyView(empty, null); + applyView(empty, { zoom: [], legend: {}, brush: [] }); + assert.deepEqual(empty.actions, []); +}); + +test("handOverView: a chart mounted again at once with the same id in the other mode gets the view; the same mode or later gets nothing", async () => { + const zoomed = () => fakeChart({ dataZoom: [{ start: 40, end: 60 }] }); + handOverView("chart1", "light", zoomed()); + assert.deepEqual(takeHandedOverView("chart1", "dark"), { zoom: [{ dataZoomIndex: 0, start: 40, end: 60 }], legend: {}, brush: [] }); + // taken once + assert.equal(takeHandedOverView("chart1", "dark"), null); + // drawn again in the same mode (a New-UDDynamic that refreshes): starts as built, as before + handOverView("chart1", "light", zoomed()); + assert.equal(takeHandedOverView("chart1", "light"), null); + // an id nobody mounts at once (the page was left) is forgotten + handOverView("chart2", "light", zoomed()); + await new Promise((resolve) => setTimeout(resolve, 5)); + assert.equal(takeHandedOverView("chart2", "dark"), null); + // no id: nothing to match + handOverView(undefined, "light", zoomed()); + assert.equal(takeHandedOverView(undefined, "dark"), null); +}); + +// the same against the real ECharts of the module (server-side rendering, no DOM) +const echartsUrl = new URL("../../modules/PowerShellUniversal.Component.ECharts/node_modules/echarts/index.js", import.meta.url); +test("ECharts: zoom, legend selection and brush survive setTheme and a new instance", { skip: existsSync(echartsUrl) ? false : "the ECharts module's packages are not installed" }, async () => { + const echarts = await import(echartsUrl); + const option = { + animation: false, + legend: {}, + brush: { xAxisIndex: 0 }, + xAxis: { type: "category", data: Array.from({ length: 20 }, (_, i) => String(i)) }, + yAxis: { type: "value" }, + dataZoom: [{ type: "inside", xAxisIndex: [0], filterMode: "none" }, { type: "slider", xAxisIndex: [0] }], + series: [{ name: "a", type: "line", data: Array.from({ length: 20 }, (_, i) => i) }, { name: "b", type: "line", data: Array.from({ length: 20 }, (_, i) => 20 - i) }] + }; + const make = () => { + const chart = echarts.init(null, null, { renderer: "svg", ssr: true, width: 600, height: 400 }); + chart.setOption(option); + return chart; + }; + const state = (chart) => { + const o = chart.getOption(); + return { zoom: o.dataZoom.map((d) => [d.start, d.end]), selected: o.legend[0].selected, brush: chart.getModel().getComponent("brush").areas.map((a) => a.coordRange) }; + }; + const chart = make(); + chart.dispatchAction({ type: "dataZoom", start: 40, end: 60 }); + chart.dispatchAction({ type: "legendUnSelect", name: "b" }); + chart.dispatchAction({ type: "brush", areas: [{ brushType: "lineX", xAxisIndex: 0, coordRange: [5, 8] }] }); + const expected = { zoom: [[40, 60], [40, 60]], selected: { a: true, b: false }, brush: [[5, 8]] }; + assert.deepEqual(state(chart), expected); + const events = []; + ["datazoom", "legendselectchanged"].forEach((name) => chart.on(name, () => events.push(name))); + // setTheme alone builds the chart from its option again: zoom, legend and brush are gone + setThemeKeepingView(chart, { color: ["#ff0000", "#00ff00"] }); + assert.deepEqual(state(chart), expected); + assert.deepEqual(events, []); + // PSU mounts the chart again on its first theme switch: a new instance of the same id + handOverView("t", "light", chart); + chart.dispose(); + const again = make(); + applyView(again, takeHandedOverView("t", "dark")); + assert.deepEqual(state(again), expected); + again.dispose(); +}); diff --git a/tests/js/echarts.test.js b/tests/js/echarts.test.js index 6a9868d..51db1f2 100644 --- a/tests/js/echarts.test.js +++ b/tests/js/echarts.test.js @@ -57,6 +57,47 @@ test("markLine: statistics per series, fixed line once", () => { assert.equal(o.series[0].markLine.data[1].yAxis, 48); }); +// the label side of each statistic line: [series][line] -> position +const statLabels = (o) => o.series.map((s) => (s.markLine ? s.markLine.data.filter((d) => d.type).map((d) => d.label.position) : [])); + +test("markLine: the higher statistic line is labelled above, the lower one below, whichever series it is", () => { + const rows = [{ d: "1", a: 2, b: 5 }, { d: "2", a: 4, b: 7 }]; + // second series higher: before, its label faced the first one's and both overlapped + assert.deepEqual(statLabels(buildOption({ chartType: "line", data: rows, x: "d", y: ["a", "b"], markLine: ["average"] }, {})), [["insideEndBottom"], ["insideEndTop"]]); + // first series higher: as before + assert.deepEqual(statLabels(buildOption({ chartType: "line", data: rows, x: "d", y: ["b", "a"], markLine: ["average"] }, {})), [["insideEndTop"], ["insideEndBottom"]]); + // one series: above its line, as before + assert.deepEqual(statLabels(buildOption({ chartType: "line", data: rows, x: "d", y: ["a"], markLine: ["average"] }, {})), [["insideEndTop"]]); +}); + +test("markLine: each statistic is ordered on its own, a middle line's label faces away from its nearer neighbour", () => { + // averages a 3, b 6, c 10: b is nearer to a, so its label goes above; maxima a 4, b 7, c 12 alike + const rows = [{ d: "1", a: 2, b: 5, c: 8 }, { d: "2", a: 4, b: 7, c: 12 }]; + assert.deepEqual(statLabels(buildOption({ chartType: "line", data: rows, x: "d", y: ["c", "a", "b"], markLine: ["average", "max"] }, {})), [ + ["insideEndTop", "insideEndTop"], + ["insideEndBottom", "insideEndBottom"], + ["insideEndTop", "insideEndTop"] + ]); + // min of a is higher than b's, its average lower: each line by its own value + const crossing = [{ d: "1", a: 5, b: 1 }, { d: "2", a: 5, b: 20 }]; + assert.deepEqual(statLabels(buildOption({ chartType: "line", data: crossing, x: "d", y: ["a", "b"], markLine: ["average", "min"] }, {})), [ + ["insideEndBottom", "insideEndTop"], + ["insideEndTop", "insideEndBottom"] + ]); +}); + +test("markLine: lines are compared on their own value axis, stacked series by their stacked values, median as ECharts computes it", () => { + const rows = [{ d: "1", a: 2, b: 50 }, { d: "2", a: 4, b: 70 }]; + // b on the secondary axis: alone there, so both labels above their lines + assert.deepEqual(statLabels(buildOption({ chartType: "line", data: rows, x: "d", y: ["b", "a"], secondaryY: ["b"], markLine: ["average"] }, {})), [["insideEndTop"], ["insideEndTop"]]); + // stacked: ECharts draws b's line at a + b, above a, although b alone is smaller here + const stacked = [{ d: "1", a: 10, b: 1 }, { d: "2", a: 12, b: 1 }]; + assert.deepEqual(statLabels(buildOption({ chartType: "area", data: stacked, x: "d", y: ["a", "b"], stacked: true, markLine: ["average"] }, {})), [["insideEndBottom"], ["insideEndTop"]]); + // median of an even count is the mean of the two middle values: a 5.5 against b 5 + const median = [{ d: "1", a: 1, b: 5 }, { d: "2", a: 10, b: 5 }, { d: "3", a: 1, b: 5 }, { d: "4", a: 10, b: 5 }]; + assert.deepEqual(statLabels(buildOption({ chartType: "bar", data: median, x: "d", y: ["b", "a"], markLine: ["median"] }, {})), [["insideEndBottom"], ["insideEndTop"]]); +}); + test("every formatter returns a string", () => { const o = buildOption({ chartType: "line", data: days, x: "day", y: ["opened"], dataLabels: true }, {}); const label = o.series[0].label.formatter({ value: ["x", 5] }); From 7eea5e98b81003ea015f552297ac54b214aeb353 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Eizedev?= <6794362+eizedev@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:55:31 +0100 Subject: [PATCH 2/5] fix(echarts): read no view from a chart before its first option The theme effect runs before the option effect on mount; ECharts has no model then, and readView threw, so the chart did not render on PSU. Co-Authored-By: Claude Opus 5.5 --- .../Components/viewState.js | 8 +++++--- tests/js/echarts-view.test.js | 7 +++++++ 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/modules/PowerShellUniversal.Component.ECharts/Components/viewState.js b/modules/PowerShellUniversal.Component.ECharts/Components/viewState.js index 765bd4a..7db26d2 100644 --- a/modules/PowerShellUniversal.Component.ECharts/Components/viewState.js +++ b/modules/PowerShellUniversal.Component.ECharts/Components/viewState.js @@ -6,15 +6,17 @@ * -OnLegendChange fires. A toolbox switch to line, bar or stack is not kept: the option is set anew. */ -// the view of a living chart, or null when there is nothing to keep +// the view of a living chart, or null when there is nothing to keep (also before its first option, +// when ECharts has no model yet) export function readView(chart) { - if (!chart || chart.isDisposed()) { + const model = chart && !chart.isDisposed() ? chart.getModel() : undefined; + if (!model) { return null; } const option = chart.getOption() || {}; const zoom = (option.dataZoom || []).map((z, dataZoomIndex) => ({ dataZoomIndex, start: z.start, end: z.end })); const legend = Object.assign({}, ...(option.legend || []).map((l) => l.selected || {})); - const brushModel = chart.getModel().getComponent("brush"); + const brushModel = model.getComponent("brush"); // the range in data values and the grid it is drawn in; ECharts computes the pixels again const brush = ((brushModel && brushModel.areas) || []).map((a) => ({ brushType: a.brushType, coordRange: a.coordRange, panelId: a.panelId })); return zoom.length || Object.keys(legend).length || brush.length ? { zoom, legend, brush } : null; diff --git a/tests/js/echarts-view.test.js b/tests/js/echarts-view.test.js index 4b41911..154e923 100644 --- a/tests/js/echarts-view.test.js +++ b/tests/js/echarts-view.test.js @@ -31,6 +31,8 @@ test("readView: the zoom of each dataZoom, the legend selection of all legends a assert.equal(readView(fakeChart({})), null); assert.equal(readView(fakeChart({ legend: [{ selected: {} }] })), null); assert.equal(readView(null), null); + // before its first setOption a chart has no model (the theme effect runs before the option effect) + assert.equal(readView({ isDisposed: () => false, getModel: () => undefined, getOption: () => undefined }), null); }); test("applyView: the kept state as silent actions, so no -OnZoom, -OnSelect or -OnLegendChange fires", () => { @@ -79,6 +81,11 @@ test("ECharts: zoom, legend selection and brush survive setTheme and a new insta dataZoom: [{ type: "inside", xAxisIndex: [0], filterMode: "none" }, { type: "slider", xAxisIndex: [0] }], series: [{ name: "a", type: "line", data: Array.from({ length: 20 }, (_, i) => i) }, { name: "b", type: "line", data: Array.from({ length: 20 }, (_, i) => 20 - i) }] }; + // nothing to keep before the first option + const blank = echarts.init(null, null, { renderer: "svg", ssr: true, width: 600, height: 400 }); + setThemeKeepingView(blank, { color: ["#ff0000"] }); + assert.equal(readView(blank), null); + blank.dispose(); const make = () => { const chart = echarts.init(null, null, { renderer: "svg", ssr: true, width: 600, height: 400 }); chart.setOption(option); From a38a3c026990929a7bb39dcf328e10dceacb5441 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Eizedev?= <6794362+eizedev@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:59:31 +0100 Subject: [PATCH 3/5] fix(echarts): hand the view over when the component unmounts, whatever the mode On PSU the remount comes before data-theme changes, so the new chart started in the old mode and the mode check dropped the view. The view is now handed over only when the component unmounts (an effect declared before the chart's sets the flag), not when the chart is made again for another renderer or locale. Co-Authored-By: Claude Opus 5.5 --- .../Components/EChart.jsx | 17 +++++++++----- .../Components/viewState.js | 14 +++++------ tests/js/echarts-view.test.js | 23 ++++++++----------- 3 files changed, 28 insertions(+), 26 deletions(-) diff --git a/modules/PowerShellUniversal.Component.ECharts/Components/EChart.jsx b/modules/PowerShellUniversal.Component.ECharts/Components/EChart.jsx index 9bc0a06..2dc4bcd 100644 --- a/modules/PowerShellUniversal.Component.ECharts/Components/EChart.jsx +++ b/modules/PowerShellUniversal.Component.ECharts/Components/EChart.jsx @@ -105,9 +105,8 @@ export default function EChart(props) { // one object per content: PSU sends the theme anew with every update of the props, which must // not set the theme again const customTheme = useMemo(() => (customKey ? JSON.parse(customKey) : undefined), [customKey]); - // the latest props for event handlers registered once, the latest mode for the chart's disposal + // the latest props for event handlers registered once const latest = useLatest(props); - const latestMode = useLatest(mode); // zoom, legend and brush of the chart this one replaces after PSU's light/dark switch (viewState.js) const handedView = useRef(null); // Get-UDElement: the last click, range and zoom, kept here because PSU asks for them synchronously @@ -162,12 +161,19 @@ export default function EChart(props) { return o && needsFit(o) ? `${base}|${Math.round(w / 32)}|${Math.round(h / 16)}|${legendRows(o, w)}` : base; }; + // the component goes (not only the chart, made again for another renderer or locale): its chart + // hands its view over. Declared before the chart's effect, so React runs this cleanup first + const unmounting = useRef(false); + useEffect(() => () => { + unmounting.current = true; + }, []); + // create once, dispose on unmount; follow the container's size useEffect(() => { registerLocales(echarts); const chart = echarts.init(container.current, ensureTheme(echarts, mode, psuTheme, customTheme), { renderer: props.renderer === "svg" ? "svg" : "canvas", locale: echartsLocale(locale) }); chartRef.current = chart; - handedView.current = takeHandedOverView(props.id, mode); + handedView.current = takeHandedOverView(props.id); // the ECharts instance on its element, for page scripts and tests: element.echarts.getOption() container.current.echarts = chart; // resize in the next frame: resizing inside the observer's callback changes the layout it is @@ -187,9 +193,8 @@ export default function EChart(props) { return () => { cancelAnimationFrame(frame); resize.disconnect(); - // the mode at disposal, not at creation: a value, not a node, so the rule's case does not apply - // eslint-disable-next-line react-hooks/exhaustive-deps - handOverView(props.id, latestMode.current, chart); + // set by the unmount effect above when the component goes, not for another renderer or locale + if (unmounting.current) handOverView(props.id, chart); chart.dispose(); chartRef.current = null; }; diff --git a/modules/PowerShellUniversal.Component.ECharts/Components/viewState.js b/modules/PowerShellUniversal.Component.ECharts/Components/viewState.js index 7db26d2..a57684b 100644 --- a/modules/PowerShellUniversal.Component.ECharts/Components/viewState.js +++ b/modules/PowerShellUniversal.Component.ECharts/Components/viewState.js @@ -45,18 +45,18 @@ export function setThemeKeepingView(chart, theme) { } /* - * PSU's remount: the old chart hands its view over when it is disposed, the new one of the same id - * takes it in the same task. Only in the other mode, so a chart drawn again for other reasons (a - * New-UDDynamic that refreshes) starts as built, as before; an id nobody takes is forgotten. + * PSU's remount: the unmounted chart hands its view over, and the one mounted with the same id in the + * same task takes it. PSU mounts it before it sets the new data-theme, so both charts start in the old + * mode; the theme follows through setThemeKeepingView. An id nobody takes is forgotten. */ const handedOver = new Map(); -export function handOverView(id, mode, chart) { +export function handOverView(id, chart) { const view = readView(chart); if (id === undefined || id === null || !view) { return; } - const entry = { mode, view }; + const entry = { view }; handedOver.set(id, entry); setTimeout(() => { if (handedOver.get(id) === entry) { @@ -65,8 +65,8 @@ export function handOverView(id, mode, chart) { }, 0); } -export function takeHandedOverView(id, mode) { +export function takeHandedOverView(id) { const entry = handedOver.get(id); handedOver.delete(id); - return entry && entry.mode !== mode ? entry.view : null; + return entry ? entry.view : null; } diff --git a/tests/js/echarts-view.test.js b/tests/js/echarts-view.test.js index 154e923..a9d9b67 100644 --- a/tests/js/echarts-view.test.js +++ b/tests/js/echarts-view.test.js @@ -50,22 +50,19 @@ test("applyView: the kept state as silent actions, so no -OnZoom, -OnSelect or - assert.deepEqual(empty.actions, []); }); -test("handOverView: a chart mounted again at once with the same id in the other mode gets the view; the same mode or later gets nothing", async () => { +test("handOverView: a chart mounted with the same id in the same task gets the view; later gets nothing", async () => { const zoomed = () => fakeChart({ dataZoom: [{ start: 40, end: 60 }] }); - handOverView("chart1", "light", zoomed()); - assert.deepEqual(takeHandedOverView("chart1", "dark"), { zoom: [{ dataZoomIndex: 0, start: 40, end: 60 }], legend: {}, brush: [] }); + handOverView("chart1", zoomed()); + assert.deepEqual(takeHandedOverView("chart1"), { zoom: [{ dataZoomIndex: 0, start: 40, end: 60 }], legend: {}, brush: [] }); // taken once - assert.equal(takeHandedOverView("chart1", "dark"), null); - // drawn again in the same mode (a New-UDDynamic that refreshes): starts as built, as before - handOverView("chart1", "light", zoomed()); - assert.equal(takeHandedOverView("chart1", "light"), null); + assert.equal(takeHandedOverView("chart1"), null); // an id nobody mounts at once (the page was left) is forgotten - handOverView("chart2", "light", zoomed()); + handOverView("chart2", zoomed()); await new Promise((resolve) => setTimeout(resolve, 5)); - assert.equal(takeHandedOverView("chart2", "dark"), null); + assert.equal(takeHandedOverView("chart2"), null); // no id: nothing to match - handOverView(undefined, "light", zoomed()); - assert.equal(takeHandedOverView(undefined, "dark"), null); + handOverView(undefined, zoomed()); + assert.equal(takeHandedOverView(undefined), null); }); // the same against the real ECharts of the module (server-side rendering, no DOM) @@ -108,10 +105,10 @@ test("ECharts: zoom, legend selection and brush survive setTheme and a new insta assert.deepEqual(state(chart), expected); assert.deepEqual(events, []); // PSU mounts the chart again on its first theme switch: a new instance of the same id - handOverView("t", "light", chart); + handOverView("t", chart); chart.dispose(); const again = make(); - applyView(again, takeHandedOverView("t", "dark")); + applyView(again, takeHandedOverView("t")); assert.deepEqual(state(again), expected); again.dispose(); }); From 524015faee717e642f18a4d28d050c196989c7ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Eizedev?= <6794362+eizedev@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:05:01 +0100 Subject: [PATCH 4/5] fix(echarts): review findings - lone statistic lines keep their position, unmount flag, real render test - A statistic line without another series' line of the same statistic on its axis gets no label of its own, so a position from -Options for the series' markLine applies as before. - The unmount flag lives in useUnmounting and is false again after React's trial unmount in StrictMode. - A test draws two close averages with the module's ECharts and checks that the labels do not overlap (fails on main). Co-Authored-By: Claude Opus 5.5 --- .../CHANGELOG.md | 5 ++- .../Components/EChart.jsx | 24 +++++++++--- .../Components/optionParts.js | 6 +-- .../Components/viewState.js | 5 ++- tests/js/echarts.test.js | 37 ++++++++++++++++--- 5 files changed, 58 insertions(+), 19 deletions(-) diff --git a/modules/PowerShellUniversal.Component.ECharts/CHANGELOG.md b/modules/PowerShellUniversal.Component.ECharts/CHANGELOG.md index 6080ec9..e0bfeb2 100644 --- a/modules/PowerShellUniversal.Component.ECharts/CHANGELOG.md +++ b/modules/PowerShellUniversal.Component.ECharts/CHANGELOG.md @@ -28,8 +28,9 @@ All notable changes to PowerShellUniversal.Component.ECharts. Format: `-OnZoom`, `-OnSelect` or `-OnLegendChange` runs for the switch. - `-MarkLine 'average'` (and `median`, `min`, `max`) with several series: the label of the higher line sits above it and the lower one's below. Before, the side came from the series' order, so the labels - of close lines overlapped when the second line was higher. A label position for a series' whole - `markLine` in `-Options` no longer moves these labels; set it per line instead: + of close lines overlapped when the second line was higher. Where another series has the same + statistic on the same axis, a label position for a series' whole `markLine` in `-Options` no + longer moves these labels; set it per line instead: `markLine = @{ data = @(@{ label = @{ position = 'insideStartBottom' } }) }`. ### Changed diff --git a/modules/PowerShellUniversal.Component.ECharts/Components/EChart.jsx b/modules/PowerShellUniversal.Component.ECharts/Components/EChart.jsx index 2dc4bcd..0df86da 100644 --- a/modules/PowerShellUniversal.Component.ECharts/Components/EChart.jsx +++ b/modules/PowerShellUniversal.Component.ECharts/Components/EChart.jsx @@ -73,6 +73,19 @@ function useFullscreen(ref) { return full; } +// true from the moment the component unmounts, read by the cleanups of effects declared after it +function useUnmounting() { + const ref = useRef(false); + useEffect(() => { + // false again after React's trial unmount and mount in StrictMode + ref.current = false; + return () => { + ref.current = true; + }; + }, []); + return ref; +} + /* * Values from ECharts events turned into something PowerShell can use: time axis values (epoch ms) * become ISO strings, category indices become the category names. @@ -162,11 +175,8 @@ export default function EChart(props) { }; // the component goes (not only the chart, made again for another renderer or locale): its chart - // hands its view over. Declared before the chart's effect, so React runs this cleanup first - const unmounting = useRef(false); - useEffect(() => () => { - unmounting.current = true; - }, []); + // hands its view over. Called before the chart's effect, so React runs this cleanup first + const unmounting = useUnmounting(); // create once, dispose on unmount; follow the container's size useEffect(() => { @@ -193,7 +203,9 @@ export default function EChart(props) { return () => { cancelAnimationFrame(frame); resize.disconnect(); - // set by the unmount effect above when the component goes, not for another renderer or locale + // set by useUnmounting when the component goes, not for another renderer or locale: read at + // cleanup on purpose, and a flag, not a node + // eslint-disable-next-line react-hooks/exhaustive-deps if (unmounting.current) handOverView(props.id, chart); chart.dispose(); chartRef.current = null; diff --git a/modules/PowerShellUniversal.Component.ECharts/Components/optionParts.js b/modules/PowerShellUniversal.Component.ECharts/Components/optionParts.js index a06b9f2..a70934a 100644 --- a/modules/PowerShellUniversal.Component.ECharts/Components/optionParts.js +++ b/modules/PowerShellUniversal.Component.ECharts/Components/optionParts.js @@ -387,8 +387,8 @@ function labelSide(lines, rank) { /* * The labels of statistic lines of several series, by where the lines lie, so the labels of close * lines face away from each other. Each statistic is ordered on its own, among the series on the same - * value axis; equal values keep the series order. A label set on a line item wins over one set for - * the series' markLine (-Options). + * value axis; equal values keep the series order. A line alone there keeps the series' position (from + * markLineOf or -Options); a position set here on a line item wins over the series' one. */ export function placeStatisticLabels(series, horizontal) { const drawn = drawnValues(series, horizontal); @@ -402,7 +402,7 @@ export function placeStatisticLabels(series, horizontal) { } } }); - for (const lines of groups.values()) { + for (const lines of [...groups.values()].filter((g) => g.length > 1)) { lines.sort((a, b) => b.value - a.value); lines.forEach((line, rank) => { line.item.label = { position: labelSide(lines, rank) }; diff --git a/modules/PowerShellUniversal.Component.ECharts/Components/viewState.js b/modules/PowerShellUniversal.Component.ECharts/Components/viewState.js index a57684b..825519a 100644 --- a/modules/PowerShellUniversal.Component.ECharts/Components/viewState.js +++ b/modules/PowerShellUniversal.Component.ECharts/Components/viewState.js @@ -1,8 +1,9 @@ /* * What the reader did to a chart and a theme change must not undo: the zoom, the series hidden in the * legend and the brushed range. ECharts' setTheme builds the chart from its option again and drops - * them, and PSU mounts the component again on the first light/dark switch after a page loads. Both - * read the view before and set it again afterwards, with silent actions, so no -OnZoom, -OnSelect or + * them, and PSU mounts the component again on the first light/dark switch after a page loads (the + * hand-over below covers every remount of a chart with the same id in the same task). Both read the + * view before and set it again afterwards, with silent actions, so no -OnZoom, -OnSelect or * -OnLegendChange fires. A toolbox switch to line, bar or stack is not kept: the option is set anew. */ diff --git a/tests/js/echarts.test.js b/tests/js/echarts.test.js index 51db1f2..db2fd80 100644 --- a/tests/js/echarts.test.js +++ b/tests/js/echarts.test.js @@ -1,7 +1,7 @@ // Tests for the ECharts option builder. Run: node --test tests/js/ import { test } from "node:test"; import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; +import { existsSync, readFileSync } from "node:fs"; import { buildOption, dataRows, rowOf, mergeOptions, boxStats, quantile, displayName, linearFit, tooltipTracksHover, CHART_TYPES, LARGE } from "../../modules/PowerShellUniversal.Component.ECharts/Components/buildOption.js"; import { echartsLocale, LANGUAGES } from "../../modules/PowerShellUniversal.Component.ECharts/Components/language.js"; import { textsFor, TEXT_LANGUAGES } from "../../modules/PowerShellUniversal.Component.ECharts/Components/texts.js"; @@ -57,8 +57,8 @@ test("markLine: statistics per series, fixed line once", () => { assert.equal(o.series[0].markLine.data[1].yAxis, 48); }); -// the label side of each statistic line: [series][line] -> position -const statLabels = (o) => o.series.map((s) => (s.markLine ? s.markLine.data.filter((d) => d.type).map((d) => d.label.position) : [])); +// the label side of each statistic line: [series][line] -> position (its own, else the series' markLine's) +const statLabels = (o) => o.series.map((s) => (s.markLine ? s.markLine.data.filter((d) => d.type).map((d) => (d.label || s.markLine.label).position) : [])); test("markLine: the higher statistic line is labelled above, the lower one below, whichever series it is", () => { const rows = [{ d: "1", a: 2, b: 5 }, { d: "2", a: 4, b: 7 }]; @@ -66,7 +66,10 @@ test("markLine: the higher statistic line is labelled above, the lower one below assert.deepEqual(statLabels(buildOption({ chartType: "line", data: rows, x: "d", y: ["a", "b"], markLine: ["average"] }, {})), [["insideEndBottom"], ["insideEndTop"]]); // first series higher: as before assert.deepEqual(statLabels(buildOption({ chartType: "line", data: rows, x: "d", y: ["b", "a"], markLine: ["average"] }, {})), [["insideEndTop"], ["insideEndBottom"]]); - // one series: above its line, as before + // one series: above its line, as before, and a position from -Options for its markLine still applies + const one = buildOption({ chartType: "line", data: rows, x: "d", y: ["a"], markLine: ["average"], options: { series: [{ markLine: { label: { position: "end" } } }] } }, {}); + assert.equal(one.series[0].markLine.data[0].label, undefined); + assert.equal(one.series[0].markLine.label.position, "end"); assert.deepEqual(statLabels(buildOption({ chartType: "line", data: rows, x: "d", y: ["a"], markLine: ["average"] }, {})), [["insideEndTop"]]); }); @@ -88,8 +91,10 @@ test("markLine: each statistic is ordered on its own, a middle line's label face test("markLine: lines are compared on their own value axis, stacked series by their stacked values, median as ECharts computes it", () => { const rows = [{ d: "1", a: 2, b: 50 }, { d: "2", a: 4, b: 70 }]; - // b on the secondary axis: alone there, so both labels above their lines - assert.deepEqual(statLabels(buildOption({ chartType: "line", data: rows, x: "d", y: ["b", "a"], secondaryY: ["b"], markLine: ["average"] }, {})), [["insideEndTop"], ["insideEndTop"]]); + // b on the secondary axis: each line alone on its axis keeps the series' label above it + const apart = buildOption({ chartType: "line", data: rows, x: "d", y: ["b", "a"], secondaryY: ["b"], markLine: ["average"] }, {}); + assert.deepEqual(statLabels(apart), [["insideEndTop"], ["insideEndTop"]]); + assert.deepEqual(apart.series.map((s) => s.markLine.data[0].label), [undefined, undefined]); // stacked: ECharts draws b's line at a + b, above a, although b alone is smaller here const stacked = [{ d: "1", a: 10, b: 1 }, { d: "2", a: 12, b: 1 }]; assert.deepEqual(statLabels(buildOption({ chartType: "area", data: stacked, x: "d", y: ["a", "b"], stacked: true, markLine: ["average"] }, {})), [["insideEndBottom"], ["insideEndTop"]]); @@ -98,6 +103,26 @@ test("markLine: lines are compared on their own value axis, stacked series by th assert.deepEqual(statLabels(buildOption({ chartType: "bar", data: median, x: "d", y: ["b", "a"], markLine: ["median"] }, {})), [["insideEndBottom"], ["insideEndTop"]]); }); +// the same drawn by the module's ECharts (server-side rendering): the two "Average" labels do not overlap +const echartsUrl = new URL("../../modules/PowerShellUniversal.Component.ECharts/node_modules/echarts/index.js", import.meta.url); +test("markLine: ECharts draws the labels of close averages apart, also on horizontal bars", { skip: existsSync(echartsUrl) ? false : "the ECharts module's packages are not installed" }, async () => { + const echarts = await import(echartsUrl); + // averages 10.9 and 11.5: the second series is higher + const rows = Array.from({ length: 10 }, (_, i) => ({ d: String(i), a: 10 + (i % 3), b: 11 + (i % 2) })); + for (const extra of [{ chartType: "line" }, { chartType: "bar", horizontal: true }]) { + const chart = echarts.init(null, null, { renderer: "svg", ssr: true, width: 700, height: 400 }); + chart.setOption({ ...buildOption({ ...extra, data: rows, x: "d", y: ["a", "b"], markLine: ["average"] }, { locale: "en-US" }), animation: false }); + const boxes = chart.getZr().storage.getDisplayList(true).filter((el) => el.style && /^Average/.test(el.style.text || "")).map((el) => { + const r = el.getBoundingRect().clone(); + r.applyTransform(el.getComputedTransform()); + return r; + }); + chart.dispose(); + assert.equal(boxes.length, 2, extra.chartType); + assert.equal(boxes[0].intersect(boxes[1]), false, `${extra.chartType}${extra.horizontal ? " horizontal" : ""}: labels overlap`); + } +}); + test("every formatter returns a string", () => { const o = buildOption({ chartType: "line", data: days, x: "day", y: ["opened"], dataLabels: true }, {}); const label = o.series[0].label.formatter({ value: ["x", 5] }); From db5d6eb58259a181e5ae8f37b2ff97b3576892aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Eizedev?= <6794362+eizedev@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:14:15 +0100 Subject: [PATCH 5/5] build(growth): lower the baseline for EChart and cartesian, which this change made smaller Co-Authored-By: Claude Opus 5.5 --- build/growth-baseline.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/build/growth-baseline.json b/build/growth-baseline.json index 9358242..51f67d3 100644 --- a/build/growth-baseline.json +++ b/build/growth-baseline.json @@ -7,16 +7,16 @@ }, "javascript": { "complexity": { - "Function 'cartesian'": [46], + "Function 'cartesian'": [45], "Function 'formatter'": [26], "Function 'histogram'": [27], "Function 'responsive'": [38], "modules/PowerShellUniversal.Component.ECharts/Components/cartesian.js Arrow function": [35] }, "lines": { - "Function 'EChart'": [254], + "Function 'EChart'": [251], "Function 'Perspective'": [135], - "Function 'cartesian'": [337], + "Function 'cartesian'": [333], "modules/PowerShellUniversal.Component.ECharts/Components/EChart.jsx Arrow function": [127] } },