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] } }, 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..e0bfeb2 100644 --- a/modules/PowerShellUniversal.Component.ECharts/CHANGELOG.md +++ b/modules/PowerShellUniversal.Component.ECharts/CHANGELOG.md @@ -23,6 +23,15 @@ 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. 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 d475a45..0df86da 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,34 @@ 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; +} + +// 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. @@ -78,8 +107,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); @@ -91,6 +120,8 @@ export default function EChart(props) { const customTheme = useMemo(() => (customKey ? JSON.parse(customKey) : undefined), [customKey]); // the latest props for event handlers registered once const latest = useLatest(props); + // 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 +163,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 @@ -153,11 +174,16 @@ 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. 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(() => { 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); // 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 +203,15 @@ export default function EChart(props) { return () => { cancelAnimationFrame(frame); resize.disconnect(); + // 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; }; // 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 +219,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 +237,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..a70934a 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 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); + 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()].filter((g) => g.length > 1)) { + 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..825519a --- /dev/null +++ b/modules/PowerShellUniversal.Component.ECharts/Components/viewState.js @@ -0,0 +1,73 @@ +/* + * 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 (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. + */ + +// 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) { + 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 = 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; +} + +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 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, chart) { + const view = readView(chart); + if (id === undefined || id === null || !view) { + return; + } + const entry = { view }; + handedOver.set(id, entry); + setTimeout(() => { + if (handedOver.get(id) === entry) { + handedOver.delete(id); + } + }, 0); +} + +export function takeHandedOverView(id) { + const entry = handedOver.get(id); + handedOver.delete(id); + return entry ? 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..a9d9b67 --- /dev/null +++ b/tests/js/echarts-view.test.js @@ -0,0 +1,114 @@ +// 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); + // 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", () => { + 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 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", zoomed()); + assert.deepEqual(takeHandedOverView("chart1"), { zoom: [{ dataZoomIndex: 0, start: 40, end: 60 }], legend: {}, brush: [] }); + // taken once + assert.equal(takeHandedOverView("chart1"), null); + // an id nobody mounts at once (the page was left) is forgotten + handOverView("chart2", zoomed()); + await new Promise((resolve) => setTimeout(resolve, 5)); + assert.equal(takeHandedOverView("chart2"), null); + // no id: nothing to match + handOverView(undefined, zoomed()); + assert.equal(takeHandedOverView(undefined), 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) }] + }; + // 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); + 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", chart); + chart.dispose(); + const again = make(); + applyView(again, takeHandedOverView("t")); + assert.deepEqual(state(again), expected); + again.dispose(); +}); diff --git a/tests/js/echarts.test.js b/tests/js/echarts.test.js index 6a9868d..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,6 +57,72 @@ 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 (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 }]; + // 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, 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"]]); +}); + +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: 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"]]); + // 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"]]); +}); + +// 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] });