From 1c13e02ecee9de3e2f2f8300df9e9df687567191 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 22:37:44 +0100 Subject: [PATCH 1/2] fix: react-hooks lint findings as errors, ticket report periods in the ECharts showcase - shared/js/useLatest.js: the latest props for handlers registered once, written in an insertion effect instead of during render (React 18 has no useEffectEvent) - EChart, Perspective, PivotReport and the pivot hooks: refs no longer written during render, effect dependencies complete; the chart-creating effect keeps its two dependencies on purpose (disabled with the reason) - useTemplateEndpoints: new server templates reset the local ones during render, not in an effect - usePsuTheme keeps its object when the colours did not change - eslint.config.js: recommended-latest rules on, exhaustive-deps an error - ECharts showcase: the period chart ends on the newest ticket's day, the averages are labelled at opposite ends, the per-day chart no longer parses dates in the server's culture Refs #217 Co-Authored-By: Claude Opus 5.5 --- build/growth-baseline.json | 6 +- eslint.config.js | 13 +-- .../Apps/Showcase.ps1 | 12 +-- .../CHANGELOG.md | 10 +++ .../CHANGELOG.md | 4 + .../Components/EChart.jsx | 89 ++++++++++--------- .../CHANGELOG.md | 7 ++ .../Components/Perspective.jsx | 16 ++-- .../CHANGELOG.md | 8 ++ .../Components/PivotReport.jsx | 9 +- .../Components/useLoadedFile.js | 20 ++--- .../Components/useStoredView.js | 11 +-- .../Components/useTemplateEndpoints.js | 21 +++-- shared/js/psuTheme.js | 7 +- shared/js/useLatest.js | 16 ++++ tests/powershell/ECharts.Tests.ps1 | 37 ++++++++ 16 files changed, 192 insertions(+), 94 deletions(-) create mode 100644 shared/js/useLatest.js diff --git a/build/growth-baseline.json b/build/growth-baseline.json index 46468a3..07e40c2 100644 --- a/build/growth-baseline.json +++ b/build/growth-baseline.json @@ -3,7 +3,7 @@ "pages": { "README.md": [108] }, - "totalLines": 5182 + "totalLines": 5194 }, "javascript": { "complexity": { @@ -14,8 +14,8 @@ "modules/PowerShellUniversal.Component.ECharts/Components/cartesian.js Arrow function": [35] }, "lines": { - "Function 'EChart'": [276], - "Function 'Perspective'": [138], + "Function 'EChart'": [254], + "Function 'Perspective'": [135], "Function 'cartesian'": [337], "modules/PowerShellUniversal.Component.ECharts/Components/EChart.jsx Arrow function": [127] } diff --git a/eslint.config.js b/eslint.config.js index 68cc91e..988765c 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -1,5 +1,5 @@ // `npm run lint`: ESLint's recommended rules, which find real errors (undefined names, unreachable -// code, unused variables), and the rules of hooks for the React code. Formatting is left to +// code, unused variables), and the React hooks rules for the React code. Formatting is left to // .editorconfig. Function length and complexity are no rules here: they are a ratchet in // build/growth.js (`npm run growth`), because today's long functions would fail a rule. Both read the // same code the same way (build/javascript-sources.js). @@ -42,12 +42,13 @@ export default [ languageOptions: { globals: { ...globals.browser, UniversalDashboard: "readonly", require: "readonly", __PIVOT_IMPORT_WORKER__: "readonly" } }, }, { - // a broken rule of hooks fails. A missing effect dependency only warns: the components keep - // the latest props in a ref for event handlers registered once, which this rule cannot see. - // The React Compiler rules of the plugin's recommended set stay off: they flag that same - // ref pattern, and the modules are not built with the React Compiler + // the plugin's recommended rules for React 18 code, with a missing effect dependency as an + // error too: the rules of hooks and the React Compiler's checks (no ref read or written during + // render, no setState in an effect body). Props that handlers registered once need are kept in a + // ref written in an effect (shared/js/useLatest.js); a dependency left out on purpose is + // disabled on its line with the reason files: BROWSER, plugins: { "react-hooks": reactHooks }, - rules: { "react-hooks/rules-of-hooks": "error", "react-hooks/exhaustive-deps": "warn" }, + rules: { ...reactHooks.configs["recommended-latest"].rules, "react-hooks/exhaustive-deps": "error" }, }, ]; diff --git a/modules/PowerShellUniversal.Component.ECharts.Demo/Apps/Showcase.ps1 b/modules/PowerShellUniversal.Component.ECharts.Demo/Apps/Showcase.ps1 index ee2c7e4..b7d3552 100644 --- a/modules/PowerShellUniversal.Component.ECharts.Demo/Apps/Showcase.ps1 +++ b/modules/PowerShellUniversal.Component.ECharts.Demo/Apps/Showcase.ps1 @@ -190,10 +190,12 @@ New-UDApp -Title 'ECharts for PowerShell Universal' -Pages @( } New-UDGrid -Item -ExtraSmallSize 12 -MediumSize 8 -Content { New-UDCard -Title 'Opened per day: this period vs previous period' -Content { - # last 60 days against the 60 before, aligned by day number - $today = (Get-Date).Date + # the last 60 days of the data against the 60 before, aligned by day number. The period + # ends on the newest ticket's day, not today: the data ends yesterday and stays in + # $Cache: for days, so counting up to today would show days without data as zeros + $lastDay = ($tickets.Created | Measure-Object -Maximum).Maximum.Date $perDay = foreach ($offset in 0..59) { - $now = $today.AddDays(-59 + $offset) + $now = $lastDay.AddDays(-59 + $offset) $before = $now.AddDays(-60) [pscustomobject]@{ Day = 'Day {0}' -f ($offset + 1) @@ -202,7 +204,7 @@ New-UDApp -Title 'ECharts for PowerShell Universal' -Pages @( } } New-UDEChart -Data $perDay -Type line -X Day -Y Current, Previous -Smooth -Height 260px -MarkLine average ` - -Options @{ series = @(@{ name = 'This period' }, @{ name = 'Previous period'; lineStyle = @{ type = 'dashed' }; itemStyle = @{ opacity = 0.6 } }) } + -Options @{ series = @(@{ name = 'This period' }, @{ name = 'Previous period'; lineStyle = @{ type = 'dashed' }; itemStyle = @{ opacity = 0.6 }; markLine = @{ label = @{ position = 'insideStartBottom' } } }) } } } New-UDGrid -Item -ExtraSmallSize 12 -MediumSize 6 -Content { @@ -246,7 +248,7 @@ New-UDApp -Title 'ECharts for PowerShell Universal' -Pages @( New-UDGrid -Item -ExtraSmallSize 12 -Content { New-UDCard -Title 'Tickets per day: select a range (brush button) to filter the table' -Content { $daily = $tickets | Group-Object { $_.Created.Date } | ForEach-Object { - [pscustomobject]@{ Day = [datetime]$_.Name; Opened = $_.Count; P1 = @($_.Group | Where-Object Priority -EQ 'P1').Count } + [pscustomobject]@{ Day = $_.Group[0].Created.Date; Opened = $_.Count; P1 = @($_.Group | Where-Object Priority -EQ 'P1').Count } } | Sort-Object Day New-UDEChart -Data $daily -Type bar -X Day -Y Opened, P1 -SecondaryY P1 -SecondaryTitle 'P1' -Zoom Both -Brush -Height 320px ` -Options @{ series = @(@{}, @{ type = 'line'; smooth = $true }) } -OnSelect { diff --git a/modules/PowerShellUniversal.Component.ECharts.Demo/CHANGELOG.md b/modules/PowerShellUniversal.Component.ECharts.Demo/CHANGELOG.md index ef8a336..ecfdd38 100644 --- a/modules/PowerShellUniversal.Component.ECharts.Demo/CHANGELOG.md +++ b/modules/PowerShellUniversal.Component.ECharts.Demo/CHANGELOG.md @@ -17,6 +17,16 @@ All notable changes to PowerShellUniversal.Component.ECharts.Demo. Format: The diverging survey chart lost an `-Options` entry that changed nothing. - The help and README say that the generated data counts its dates from today. +### Fixed + +- Ticket report, "Opened per day: this period vs previous period": the period ends on the day of the + newest ticket. Before, it ended today, and the generated tickets end yesterday and stay cached for + days, so the last days of "This period" dropped to 0. +- The same chart labels the previous period's average at the start of its line. The two "Average" + labels overlapped at the right edge when the averages were close. +- The "Tickets per day" chart of the Ticket report no longer fails on a server whose culture writes + dates other than en-US does, such as de-DE. + ## [0.3.0] - 2026-11-09 ### Changed diff --git a/modules/PowerShellUniversal.Component.ECharts/CHANGELOG.md b/modules/PowerShellUniversal.Component.ECharts/CHANGELOG.md index dbcbc07..e7af870 100644 --- a/modules/PowerShellUniversal.Component.ECharts/CHANGELOG.md +++ b/modules/PowerShellUniversal.Component.ECharts/CHANGELOG.md @@ -40,6 +40,10 @@ All notable changes to PowerShellUniversal.Component.ECharts. Format: `New-UDEChart` runs its steps through helpers. Commands, parameters, help and output are unchanged ([#169](https://github.com/eizedev/powershell-universal-components/issues/169)). - The help of `-Value`, `-Path`, `-Source` and `-Target` names every chart type that reads them. +- The component passes the React hooks lint rules, which are now errors in CI: the latest props + for its event handlers are kept in a ref written in an effect, not during render + ([#217](https://github.com/eizedev/powershell-universal-components/issues/217)). Clicks, selections, zoom, the + export buttons and the theme switch work as before. ## [0.3.1] - 2026-11-22 diff --git a/modules/PowerShellUniversal.Component.ECharts/Components/EChart.jsx b/modules/PowerShellUniversal.Component.ECharts/Components/EChart.jsx index 01ee252..d475a45 100644 --- a/modules/PowerShellUniversal.Component.ECharts/Components/EChart.jsx +++ b/modules/PowerShellUniversal.Component.ECharts/Components/EChart.jsx @@ -1,4 +1,4 @@ -import React, { useEffect, useMemo, useRef, useState } from "react"; +import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"; import * as echarts from "echarts"; import { buildOption, dataRows, rowOf, responsive, optionForWidth, tooltipTracksHover, NARROW, TINY } from "./buildOption"; import { tooltipState } from "./tooltipMode"; @@ -11,6 +11,7 @@ import { defaultLocale } from "./formatters.js"; import { toCsv, toXlsxBytes, download, safeFileName } from "./exporter.js"; import { pickColumns } from "../../../shared/js/columns"; import { answerStateRequests } from "../../../shared/js/elementState"; +import { useLatest } from "../../../shared/js/useLatest"; // components replaced (not merged) on every update, so a live update that changes the shape of the // chart leaves no stale axes or coordinate systems behind; zoom and legend state are kept @@ -32,6 +33,30 @@ function fullscreenElement() { return document.fullscreenElement || document.webkitFullscreenElement || null; } +// CSV/Excel of the rows behind the chart (p: the chart's props), columns and types from -ExportColumns +function exportRows(kind, p) { + const name = safeFileName(p.exportFileName || p.title, "chart"); + const data = p.data || []; + if (kind === "csv") { + download(`${name}.csv`, toCsv(data, p.exportColumns, defaultLocale(p.locale)), "text/csv;charset=utf-8"); + } else { + download(`${name}.xlsx`, toXlsxBytes(data, p.exportColumns, p.title || "Data"), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); + } +} + +// the chart (its outer element) alone on the whole screen and back (Esc or the button); zoom, +// selection and the hidden series stay, because it is the same chart +function toggleFullscreen(el) { + if (!el) { + return; + } + if (fullscreenElement() === el) { + (document.exitFullscreen || document.webkitExitFullscreen).call(document); + } else { + (el.requestFullscreen || el.webkitRequestFullscreen).call(el); + } +} + /* * Values from ECharts events turned into something PowerShell can use: time axis values (epoch ms) * become ISO strings, category indices become the category names. @@ -59,19 +84,21 @@ export default function EChart(props) { const mode = effectiveMode(props.theme, psuTheme); const locale = defaultLocale(props.locale); // -LightTheme / -DarkTheme: the corporate ECharts theme for the current mode - const customTheme = mode === "dark" ? props.darkTheme : props.lightTheme; - const customKey = customTheme ? JSON.stringify(customTheme) : ""; + const customProp = mode === "dark" ? props.darkTheme : props.lightTheme; + const customKey = customProp ? JSON.stringify(customProp) : ""; + // 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 - const latest = useRef(props); - latest.current = props; + const latest = useLatest(props); // 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 const elementState = useRef({}); - const remember = (part) => { + const remember = useCallback((part) => { elementState.current = { ...elementState.current, ...part }; if (typeof latest.current.setState === "function") latest.current.setState(part); - }; + }, [latest]); useEffect(() => { const pubsub = typeof window !== "undefined" ? window.UniversalDashboard : undefined; elementState.current = {}; @@ -91,42 +118,20 @@ export default function EChart(props) { try { const exportIcons = { ...EXPORT_ICONS, - onCsv: props.export === false ? undefined : () => exportAs("csv"), - onXlsx: props.export === false ? undefined : () => exportAs("xlsx"), - onFullscreen: props.fullscreen === false || !canFullscreen() ? undefined : () => toggleFullscreen() + onCsv: props.export === false ? undefined : () => exportRows("csv", latest.current), + onXlsx: props.export === false ? undefined : () => exportRows("xlsx", latest.current), + onFullscreen: props.fullscreen === false || !canFullscreen() ? undefined : () => toggleFullscreen(outer.current) }; + // the option only keeps these: the buttons read the props and the element when clicked, the + // tooltip formatter reads its state on hover, never during render + // eslint-disable-next-line react-hooks/refs const base = buildOption(props, { locale, exportIcons, mode, tooltipState: tipState.current }); return { value: base, rules: responsive(base, props, { locale }) }; } catch (e) { return { error: e.message }; } - }, [props, locale, mode]); + }, [props, locale, mode, latest]); - // CSV/Excel of the rows behind the chart, columns and types from -ExportColumns - function exportAs(kind) { - const p = latest.current; - const name = safeFileName(p.exportFileName || p.title, "chart"); - const data = p.data || []; - if (kind === "csv") { - download(`${name}.csv`, toCsv(data, p.exportColumns, defaultLocale(p.locale)), "text/csv;charset=utf-8"); - } else { - download(`${name}.xlsx`, toXlsxBytes(data, p.exportColumns, p.title || "Data"), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); - } - } - - // the chart alone on the whole screen and back (Esc or the button); zoom, selection and the - // hidden series stay, because it is the same chart - function toggleFullscreen() { - const el = outer.current; - if (!el) { - return; - } - if (fullscreenElement() === el) { - (document.exitFullscreen || document.webkitExitFullscreen).call(document); - } else { - (el.requestFullscreen || el.webkitRequestFullscreen).call(el); - } - } useEffect(() => { const onChange = () => setFull(fullscreenElement() === outer.current); document.addEventListener("fullscreenchange", onChange); @@ -141,8 +146,7 @@ export default function EChart(props) { // 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 const [layoutKey, setLayoutKey] = useState("wide"); - const latestOption = useRef(null); - latestOption.current = option.value; + const latestOption = useLatest(option.value); const keyOf = (w, h) => { const base = w <= TINY ? "tiny" : w <= NARROW ? "narrow" : "wide"; const o = latestOption.current; @@ -176,6 +180,9 @@ export default function EChart(props) { 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 + // eslint-disable-next-line react-hooks/exhaustive-deps }, [props.renderer, locale]); // theme follows PSU's light/dark switch @@ -184,7 +191,7 @@ export default function EChart(props) { if (chart) { chart.setTheme(ensureTheme(echarts, mode, psuTheme, customTheme)); } - }, [mode, psuTheme.text, customKey]); + }, [mode, psuTheme, customTheme]); // option: series, axes and datasets are replaced, zoom and legend state survive data updates. // After the width rules and the text sizes: the plot of a chart without a grid placed clear of title, toolbox and @@ -202,7 +209,7 @@ export default function EChart(props) { chart.setOption(insideLabelColors(placed, theme.color, theme.textStyle && theme.textStyle.color), { replaceMerge: REPLACED }); // the series are as built again (a toolbox switch to line, bar or stack is gone) tipState.current.live = null; - }, [option, layoutKey, mode, psuTheme.text, customKey]); + }, [option, layoutKey, mode, psuTheme, customTheme, props.options]); // linked charts: same -Group share tooltip, zoom and legend; a removed group unlinks the chart useEffect(() => { @@ -358,7 +365,7 @@ export default function EChart(props) { chart.off("datazoom", onZoom); chart.off("legendselectchanged", onLegend); }; - }, [option]); + }, [option, latest, remember]); return ( // -ClassName and -Style as on PSU's own components; -Width wins over a width in -Style diff --git a/modules/PowerShellUniversal.Component.Perspective/CHANGELOG.md b/modules/PowerShellUniversal.Component.Perspective/CHANGELOG.md index 3dbfb2c..a88e4bf 100644 --- a/modules/PowerShellUniversal.Component.Perspective/CHANGELOG.md +++ b/modules/PowerShellUniversal.Component.Perspective/CHANGELOG.md @@ -23,9 +23,16 @@ All notable changes to PowerShellUniversal.Component.Perspective. Format: before, about 40 ms now, measured on a PSU test instance): no function call per cell, and large DataTables go through a small class compiled on first use (Add-Type, once per PSU process). The rows the component gets are the same as before. +- The component passes the React hooks lint rules, which are now errors in CI: the latest props + for its event handlers are kept in a ref written in an effect, not during render + ([#217](https://github.com/eizedev/powershell-universal-components/issues/217)). Clicks, the toolbar and the theme switch + work as before. ### Fixed +- New `columnNames` with the same rows (`Set-UDElement -Properties @{ columnNames = ... }`) reach the + viewer. Before, they waited for the next new data. + - In dark mode, the chart picker at the top of the editor no longer turns white under the mouse. - When new rows hold a value the table refuses, the viewer frees the half-built table in its worker. Before, its memory stayed until the reader closed the page. diff --git a/modules/PowerShellUniversal.Component.Perspective/Components/Perspective.jsx b/modules/PowerShellUniversal.Component.Perspective/Components/Perspective.jsx index 34f4b42..a5815d4 100644 --- a/modules/PowerShellUniversal.Component.Perspective/Components/Perspective.jsx +++ b/modules/PowerShellUniversal.Component.Perspective/Components/Perspective.jsx @@ -1,5 +1,6 @@ import React, { useEffect, useRef, useState } from "react"; import { usePsuTheme, effectiveMode } from "../../../shared/js/psuTheme"; +import { useLatest } from "../../../shared/js/useLatest"; import { THEMES, viewerConfig, prepareRows, toolbarLabels, switchTarget, isChartPlugin, TABLE_PLUGIN } from "./prepare"; /* @@ -90,12 +91,9 @@ export default function Perspective(props) { const psuTheme = usePsuTheme(); const mode = effectiveMode(props.theme, psuTheme); const prepared = React.useMemo(() => prepareRows(Array.isArray(props.data) ? props.data : [], props.columnNames), [props.data, props.columnNames]); - const keys = prepared.columns; - const latest = useRef(props); - latest.current = props; + const latest = useLatest(props); // the mode when a load finishes, not when it started: PSU's theme switch can come in between - const modeRef = useRef(mode); - modeRef.current = mode; + const modeRef = useLatest(mode); // toolbar: whether the configuration panel is open and which plugin the view shows, kept in step // with the viewer's own events (the reader can also change both in the panel) const [settingsOpen, setSettingsOpen] = useState(Boolean(props.settings)); @@ -104,7 +102,7 @@ export default function Perspective(props) { const labels = toolbarLabels(props.labels); const colors = TOOLBAR_COLORS[mode] || TOOLBAR_COLORS.light; - // table: created once, replaced in place when the data changes (the view keeps its layout) + // table: created once, replaced in place when the data or its column names change (the view keeps its layout) useEffect(() => { let cancelled = false; (async () => { @@ -135,7 +133,7 @@ export default function Perspective(props) { // first load, or other columns: the reader's layout may name columns that are // gone, so the view starts again from the parameters const problems = []; - await viewerRef.current.restore(viewerConfig(latest.current, keys, modeRef.current, prepared.schema, problems)); + await viewerRef.current.restore(viewerConfig(latest.current, prepared.columns, modeRef.current, prepared.schema, problems)); if (problems.length && !cancelled) setError(problems.join("; ")); } } finally { @@ -149,7 +147,7 @@ export default function Perspective(props) { return () => { cancelled = true; }; - }, [props.data]); + }, [prepared, latest, modeRef]); // theme follows PSU's light/dark switch without resetting what the user arranged useEffect(() => { @@ -213,7 +211,7 @@ export default function Perspective(props) { }; viewer.addEventListener("perspective-click", onClick); return () => viewer.removeEventListener("perspective-click", onClick); - }, []); + }, [latest]); // free the viewer and the table when the component leaves the page useEffect(() => () => { diff --git a/modules/PowerShellUniversal.Component.Pivot/CHANGELOG.md b/modules/PowerShellUniversal.Component.Pivot/CHANGELOG.md index 2585bf0..218b57d 100644 --- a/modules/PowerShellUniversal.Component.Pivot/CHANGELOG.md +++ b/modules/PowerShellUniversal.Component.Pivot/CHANGELOG.md @@ -5,6 +5,14 @@ All notable changes to PowerShellUniversal.Component.Pivot. Format: ## [Unreleased] +### Changed + +- The component passes the React hooks lint rules, which are now errors in CI: the latest props + for its event handlers are kept in a ref written in an effect, not during render + ([#217](https://github.com/eizedev/powershell-universal-components/issues/217)). The reader's view, a loaded file, + `-OnViewChange`, `-OnCellClick` and the templates work as before. New templates from the server + replace the ones saved in the browser in the same render, not in one after it. + ## [0.10.1] - 2026-11-25 ### Fixed diff --git a/modules/PowerShellUniversal.Component.Pivot/Components/PivotReport.jsx b/modules/PowerShellUniversal.Component.Pivot/Components/PivotReport.jsx index 46d7e63..5258b8e 100644 --- a/modules/PowerShellUniversal.Component.Pivot/Components/PivotReport.jsx +++ b/modules/PowerShellUniversal.Component.Pivot/Components/PivotReport.jsx @@ -1,4 +1,4 @@ -import React, { useMemo, useRef } from "react"; +import React, { useMemo } from "react"; import { PivotReport as Report } from "pivotkit-react"; // Excel workbooks for -AllowImport: a small descriptor; its reader is imported on the first workbook import xlsxReader from "pivotkit-xlsx"; @@ -6,6 +6,7 @@ import { bundleScriptOf, importWorkerOf, workerUrlOf } from "./importWorker"; import "pivotkit-react/styles.css"; import "./psu.css"; import { useNarrowWindow } from "./hooks"; +import { useLatest } from "../../../shared/js/useLatest"; import { useStoredView } from "./useStoredView"; import { useLoadedFile } from "./useLoadedFile"; import { useTemplateEndpoints } from "./useTemplateEndpoints"; @@ -50,8 +51,7 @@ export default function PsuPivotReport(props) { const rows = useMemo(() => (records ? records.table : restoreRows(props.data, props.columnNames)), [records, props.data, props.columnNames]); // a text that does not parse is the server's fault, never a partial report const problem = problemOf(props.problem) ?? (typeof props.records === "string" && !records ? problemOf({ kind: "serverError" }) : undefined); - const latest = useRef(props); - latest.current = props; + const latest = useLatest(props); const narrow = useNarrowWindow(); // the view, a file the reader loaded, the templates and the settings, in this order (hooks.js and use*.js) @@ -61,8 +61,7 @@ export default function PsuPivotReport(props) { const { fieldDefaults, chartOptions, tips, source, schemaUrl, exportData, labels } = useReportOptions(props); // ---- clicks ---------------------------------------------------------------------------------- - const viewRef = useRef(view); - viewRef.current = view; + const viewRef = useLatest(view); // the rows of a loaded file never go to the server: -OnCellClick runs on the app's data only const onCellClick = !fileShown && typeof props.onCellClick === "function" ? (cell) => { diff --git a/modules/PowerShellUniversal.Component.Pivot/Components/useLoadedFile.js b/modules/PowerShellUniversal.Component.Pivot/Components/useLoadedFile.js index 054d15a..b36bd83 100644 --- a/modules/PowerShellUniversal.Component.Pivot/Components/useLoadedFile.js +++ b/modules/PowerShellUniversal.Component.Pivot/Components/useLoadedFile.js @@ -4,9 +4,9 @@ import { dataLoadEvent, VIEW_EVENT_DELAY_MS } from "./prepare"; /* * -AllowImport and -OnViewChange: which data pivotkit shows (the app's or a file the reader loaded), * and the view changes of the app's data, passed on after the reader paused. - * latest: a ref to the current props; stored: what useStoredView returned. + * latestRef: a ref to the current props; stored: what useStoredView returned. */ -export function useLoadedFile(latest, stored) { +export function useLoadedFile(latestRef, stored) { const { setView, remember, fileRef, hostView, shownKey } = stored; // ---- a file the reader loaded (-AllowImport) --------------------------------------------------- // While a file's data is shown, its view, its cells and its saved views stay in the browser: the @@ -24,11 +24,11 @@ export function useLoadedFile(latest, stored) { const { next } = pending.current; clearTimeout(pending.current.timer); pending.current = null; - const handler = latest.current.onViewChange; + const handler = latestRef.current.onViewChange; if (typeof handler === "function") { handler({ view: next, json: JSON.stringify(next) }); } - }, []); + }, [latestRef]); useEffect(() => () => flush(), [flush]); // the view of the app's data leaves the component: remembered, in the state, to -OnViewChange @@ -37,13 +37,13 @@ export function useLoadedFile(latest, stored) { hostView.current = next; remember(next); // the component's state holds the view (withComponentFeatures passes it back as props.view) - if (typeof latest.current.setState === "function") latest.current.setState({ view: next }); - if (typeof latest.current.onViewChange === "function") { + if (typeof latestRef.current.setState === "function") latestRef.current.setState({ view: next }); + if (typeof latestRef.current.onViewChange === "function") { if (pending.current) clearTimeout(pending.current.timer); pending.current = { next, timer: setTimeout(flush, VIEW_EVENT_DELAY_MS) }; } }, - [flush, remember] + [flush, remember, hostView, latestRef] ); const onViewChange = useCallback( (next) => { @@ -58,7 +58,7 @@ export function useLoadedFile(latest, stored) { if (!fileRef.current && lastView.current === next) publish(next); }); }, - [publish] + [publish, fileRef, setView, shownKey] ); const onDataLoad = useCallback( (detail) => { @@ -84,7 +84,7 @@ export function useLoadedFile(latest, stored) { if (!fileRef.current && lastView.current === shown) publish(shown); }); } - const handler = latest.current.onDataLoad; + const handler = latestRef.current.onDataLoad; try { if (typeof handler === "function") handler(dataLoadEvent(detail)); } catch (error) { @@ -96,7 +96,7 @@ export function useLoadedFile(latest, stored) { // never false: the server is told, it cannot refuse a file (pivotkit does not wait for it) return undefined; }, - [flush, publish] + [flush, publish, fileRef, hostView, latestRef, setView, shownKey] ); return { fileShown, onViewChange, onDataLoad }; } diff --git a/modules/PowerShellUniversal.Component.Pivot/Components/useStoredView.js b/modules/PowerShellUniversal.Component.Pivot/Components/useStoredView.js index 523ae38..e4c8ab5 100644 --- a/modules/PowerShellUniversal.Component.Pivot/Components/useStoredView.js +++ b/modules/PowerShellUniversal.Component.Pivot/Components/useStoredView.js @@ -15,9 +15,10 @@ function sessionStorageOrNull() { /* * The report's view: the server's start view (-View), then the reader's. The reader's view of this tab * is kept in the address bar and in sessionStorage, restored on mount, and answers Get-UDElement. - * latest: a ref to the current props. Returns the view and what useLoadedFile needs of it. + * latestRef: a ref to the current props (named ...Ref in these hooks, so the React Compiler rules of the lint + * see a ref, not a value). Returns the view and what useLoadedFile needs of it. */ -export function useStoredView(props, latest) { +export function useStoredView(props, latestRef) { const serverViewKey = JSON.stringify(parseView(props.view) ?? null); // the reader's view of this tab survives PSU mounting the component anew (its light/dark switch) // and a reload: in the address bar (#pivot-=...) and in sessionStorage, the fallback for a @@ -28,7 +29,7 @@ export function useStoredView(props, latest) { const showInLink = useCallback((next) => { const s = store.current; // -NoAddressBar; and only on the page the report was mounted on (PSU's menu may have moved on) - if (latest.current.addressBar === false || !s.linkKey || typeof window === "undefined" || window.location.pathname !== s.path) return; + if (latestRef.current.addressBar === false || !s.linkKey || typeof window === "undefined" || window.location.pathname !== s.path) return; try { const hash = writeLinkView(window.location.hash, s.linkKey, next); if (hash === window.location.hash || (hash === "" && !window.location.hash)) return; @@ -37,7 +38,7 @@ export function useStoredView(props, latest) { } catch { // a browser that refuses (Safari limits replaceState calls): sessionStorage still has it } - }, []); + }, [latestRef]); const remember = useCallback((next) => { const s = store.current; if (!s.key) return; @@ -90,7 +91,7 @@ export function useStoredView(props, latest) { if (start.inStorage) showInLink(start.view); else remember(start.view); // the component's state holds the restored view too (withComponentFeatures passes it back as props.view) - if (typeof latest.current.setState === "function") latest.current.setState({ view: start.view }); + if (typeof latestRef.current.setState === "function") latestRef.current.setState({ view: start.view }); } // eslint-disable-next-line react-hooks/exhaustive-deps }, []); diff --git a/modules/PowerShellUniversal.Component.Pivot/Components/useTemplateEndpoints.js b/modules/PowerShellUniversal.Component.Pivot/Components/useTemplateEndpoints.js index 8a9f4f0..b2a7c5d 100644 --- a/modules/PowerShellUniversal.Component.Pivot/Components/useTemplateEndpoints.js +++ b/modules/PowerShellUniversal.Component.Pivot/Components/useTemplateEndpoints.js @@ -1,22 +1,25 @@ -import { useCallback, useEffect, useMemo, useState } from "react"; +import { useCallback, useMemo, useState } from "react"; import { callEndpoint, mergeTemplates, readTemplates, templateKey } from "./prepare"; /* * The Views menu's templates (-Templates and a template store) and the endpoints that save, delete and * publish them (-OnSaveTemplate, -OnDeleteTemplate, -OnPublishTemplate). - * latest: a ref to the current props; fileShown: whether a reader's file is shown. + * latestRef: a ref to the current props; fileShown: whether a reader's file is shown. */ -export function useTemplateEndpoints(props, latest, fileShown) { +export function useTemplateEndpoints(props, latestRef, fileShown) { // ---- templates ------------------------------------------------------------------------------- const templatesKey = JSON.stringify(props.templates ?? null); const serverTemplates = useMemo(() => readTemplates(JSON.parse(templatesKey)), [templatesKey]); const [saved, setSaved] = useState([]); const [deleted, setDeleted] = useState(() => new Set()); - useEffect(() => { - // new templates from the server include what was saved and leave out what was deleted + // new templates from the server include what was saved and leave out what was deleted: reset during + // the render that brings them (react.dev/learn/you-might-not-need-an-effect), not in an effect after it + const [keptFor, setKeptFor] = useState(templatesKey); + if (keptFor !== templatesKey) { + setKeptFor(templatesKey); setSaved([]); setDeleted(new Set()); - }, [templatesKey]); + } const templates = useMemo(() => mergeTemplates(serverTemplates, saved, deleted), [serverTemplates, saved, deleted]); // while a file is shown, "My views" are the browser's views of that file: the reader's own views of // the app's data on the server stay out (they cannot be saved over or deleted from here) @@ -37,21 +40,21 @@ export function useTemplateEndpoints(props, latest, fileShown) { const serverSaves = !fileShown; const onSaveTemplate = serverSaves && typeof props.onSaveTemplate === "function" ? async (name, current) => { - await callEndpoint(latest.current.onSaveTemplate, { name, view: current, json: JSON.stringify(current), scope: "user" }); + await callEndpoint(latestRef.current.onSaveTemplate, { name, view: current, json: JSON.stringify(current), scope: "user" }); keep({ name, view: current, scope: "user", deletable: true }); } : undefined; const onDeleteTemplate = serverSaves && typeof props.onDeleteTemplate === "function" ? async (name, how) => { const scope = how && how.scope === "shared" ? "shared" : "user"; - await callEndpoint(latest.current.onDeleteTemplate, { name, scope }); + await callEndpoint(latestRef.current.onDeleteTemplate, { name, scope }); setDeleted((set) => new Set(set).add(templateKey(scope, name))); } : undefined; // -AdminRole: the server sends canPublish only to readers with one of its roles, and checks again const onPublishTemplate = serverSaves && props.canPublish === true && typeof props.onPublishTemplate === "function" ? async (name, current) => { - await callEndpoint(latest.current.onPublishTemplate, { name, view: current, json: JSON.stringify(current), scope: "shared" }); + await callEndpoint(latestRef.current.onPublishTemplate, { name, view: current, json: JSON.stringify(current), scope: "shared" }); keep({ name, view: current, scope: "shared", deletable: true }); } : undefined; diff --git a/shared/js/psuTheme.js b/shared/js/psuTheme.js index 422b86f..99c2cef 100644 --- a/shared/js/psuTheme.js +++ b/shared/js/psuTheme.js @@ -35,7 +35,12 @@ export function readPsuTheme() { export function usePsuTheme() { const [theme, setTheme] = useState(readPsuTheme); useEffect(() => { - const observer = new MutationObserver(() => setTheme(readPsuTheme())); + // the same colours again (data-theme set to the value it has) keep the object: no new render, + // and effects that depend on the theme do not run again + const observer = new MutationObserver(() => { + const next = readPsuTheme(); + setTheme((previous) => (JSON.stringify(previous) === JSON.stringify(next) ? previous : next)); + }); observer.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] }); return () => observer.disconnect(); }, []); diff --git a/shared/js/useLatest.js b/shared/js/useLatest.js new file mode 100644 index 0000000..e08f706 --- /dev/null +++ b/shared/js/useLatest.js @@ -0,0 +1,16 @@ +import { useInsertionEffect, useRef } from "react"; + +/* + * A ref that holds the latest value, for event handlers and callbacks registered once (a chart's or a + * viewer's listeners, pivotkit's callbacks). React 18 has no useEffectEvent, and a ref must not be + * written during render (react.dev/reference/react/useRef). The insertion effect runs before every + * layout and passive effect of the commit, also the children's, so a callback a child fires from its + * own layout effect already reads the new value. + */ +export function useLatest(value) { + const ref = useRef(value); + useInsertionEffect(() => { + ref.current = value; + }); + return ref; +} diff --git a/tests/powershell/ECharts.Tests.ps1 b/tests/powershell/ECharts.Tests.ps1 index 9b7d156..6e751e5 100644 --- a/tests/powershell/ECharts.Tests.ps1 +++ b/tests/powershell/ECharts.Tests.ps1 @@ -206,6 +206,43 @@ Describe 'Demo module' { $readme | Should -Match '\]\(https://github\.com/[^)]+/blob/HEAD/modules/PowerShellUniversal\.Component\.ECharts\.Demo/Apps/Showcase\.ps1\)' Join-Path $built.FullName 'Apps' 'Showcase.ps1' | Should -Exist } + + Context 'Ticket report' { + BeforeAll { + # what PSU provides: $Cache; the layout commands draw their content, the others draw nothing. + # New-UDEChart is the real one + if (-not (Get-PSDrive -Name Cache -ErrorAction Ignore)) { New-PSDrive -Name Cache -PSProvider Variable -Root '' -Scope Global | Out-Null } + function global:New-UDApp { param($Title, $Pages) @{ Title = $Title; Pages = @($Pages) } } + function global:New-UDPage { param($Name, $Url, $Content) @{ Name = $Name; Url = $Url; Content = $Content } } + foreach ($name in 'New-UDGrid', 'New-UDCard', 'New-UDDynamic') { + Set-Item -Path "function:global:$name" -Value { param($Content) if ($Content) { & $Content } } + } + foreach ($name in 'New-UDTypography', 'New-UDButton', 'New-UDTable', 'Sync-UDElement', 'Show-UDToast') { + Set-Item -Path "function:global:$name" -Value { } + } + } + AfterAll { + foreach ($name in 'New-UDApp', 'New-UDPage', 'New-UDGrid', 'New-UDCard', 'New-UDDynamic', 'New-UDTypography', 'New-UDButton', 'New-UDTable', 'Sync-UDElement', 'Show-UDToast') { + Remove-Item -Path "function:$name" -ErrorAction Ignore + } + Remove-PSDrive -Name Cache -ErrorAction Ignore + } + + It 'compares the two periods on days with tickets, also when the cached tickets are days old, with the averages apart' { + # dot-sourced: the stub $Cache holds the app's variables in this scope, where the pages read them + $app = . (Join-Path $script:repo 'modules' 'PowerShellUniversal.Component.ECharts.Demo' 'Apps' 'Showcase.ps1') + # PSU keeps $Cache for days: the tickets were made two days ago + foreach ($ticket in $Cache:EChartsTickets) { $ticket.Created = $ticket.Created.AddDays(-2) } + $page = $app.Pages | Where-Object Name -EQ 'Ticket report' + $chart = & $page.Content | Where-Object { $_ -is [hashtable] -and $_.options -and $_.options.series -and $_.options.series[0].name -eq 'This period' } + $chart | Should -HaveCount 1 + $chart.data | Should -HaveCount 60 + # a day without data would be a zero: the generated data has tickets on every day + @($chart.data | Where-Object { $_.Current -eq 0 -or $_.Previous -eq 0 }) | Should -BeNullOrEmpty + # the first series' average is labelled at the end (the module's default), the second's at the start + $chart.options.series[1].markLine.label.position | Should -BeLike 'insideStart*' + } + } } Describe '-TooltipMode' { From a932f30ec5934d85315a728ad36a54bbb111afa0 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 22:43:30 +0100 Subject: [PATCH 2/2] fix: review findings: Perspective comment and CHANGELOG on new column names, useLatest in AGENTS.md Refs #217 Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 3 ++- .../PowerShellUniversal.Component.Perspective/CHANGELOG.md | 4 ++-- .../Components/Perspective.jsx | 3 ++- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 357a986..33ddbc0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -32,7 +32,8 @@ The modules form one product. Judge code, tests, docs and these rules as a whole A module without `package.json` is PowerShell only (the demo modules with their app in `Apps/`). A module's `Build.psd1` names files from elsewhere in the repository the build copies into it (the pivot demo carries the site's examples and data snapshots and the pivot showcase), so each is defined once. -- `shared/js/` - JavaScript used by several modules: the PSU theme bridge, column matching and the answer +- `shared/js/` - JavaScript used by several modules: the PSU theme bridge, the latest props for handlers + registered once (`useLatest.js`), column matching and the answer to `Get-UDElement` in `elementState.js`. Compiled into each module's bundle; never a runtime dependency between modules. Formats, the CSV/XLSX export and text contrast on fills serve only the ECharts module and live in its `Components/`. diff --git a/modules/PowerShellUniversal.Component.Perspective/CHANGELOG.md b/modules/PowerShellUniversal.Component.Perspective/CHANGELOG.md index a88e4bf..ec58da9 100644 --- a/modules/PowerShellUniversal.Component.Perspective/CHANGELOG.md +++ b/modules/PowerShellUniversal.Component.Perspective/CHANGELOG.md @@ -31,8 +31,8 @@ All notable changes to PowerShellUniversal.Component.Perspective. Format: ### Fixed - New `columnNames` with the same rows (`Set-UDElement -Properties @{ columnNames = ... }`) reach the - viewer. Before, they waited for the next new data. - + viewer. Before, they waited for the next new data. As with new columns in the data, the view then + starts again from the parameters. - In dark mode, the chart picker at the top of the editor no longer turns white under the mouse. - When new rows hold a value the table refuses, the viewer frees the half-built table in its worker. Before, its memory stayed until the reader closed the page. diff --git a/modules/PowerShellUniversal.Component.Perspective/Components/Perspective.jsx b/modules/PowerShellUniversal.Component.Perspective/Components/Perspective.jsx index a5815d4..57daec5 100644 --- a/modules/PowerShellUniversal.Component.Perspective/Components/Perspective.jsx +++ b/modules/PowerShellUniversal.Component.Perspective/Components/Perspective.jsx @@ -102,7 +102,8 @@ export default function Perspective(props) { const labels = toolbarLabels(props.labels); const colors = TOOLBAR_COLORS[mode] || TOOLBAR_COLORS.light; - // table: created once, replaced in place when the data or its column names change (the view keeps its layout) + // table: created once; new rows with the same columns and types replace its rows in place (the view + // keeps its layout), other columns or column names build a new table and the view starts again useEffect(() => { let cancelled = false; (async () => {