Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions build/growth-baseline.json
Original file line number Diff line number Diff line change
Expand Up @@ -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]
}
},
Expand Down
3 changes: 2 additions & 1 deletion docs/echarts/lines-and-time.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
1 change: 1 addition & 0 deletions docs/echarts/themes.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
9 changes: 9 additions & 0 deletions modules/PowerShellUniversal.Component.ECharts/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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.
Expand All @@ -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);
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -177,19 +203,23 @@ 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]);

// theme follows PSU's light/dark switch
useEffect(() => {
const chart = chartRef.current;
if (chart) {
chart.setTheme(ensureTheme(echarts, mode, psuTheme, customTheme));
setThemeKeepingView(chart, ensureTheme(echarts, mode, psuTheme, customTheme));
}
}, [mode, psuTheme, customTheme]);

Expand All @@ -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]);
Expand Down
Original file line number Diff line number Diff line change
@@ -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";

Expand Down Expand Up @@ -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",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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 -----------------------------------------------------------------------------------

/*
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
}
Loading
Loading