From 57bd01d04eebdde78326020b473d585bae155efe Mon Sep 17 00:00:00 2001 From: Paul Golmann Date: Mon, 16 Nov 2026 23:08:24 +0100 Subject: [PATCH 1/3] Improve station comparison charts --- .changeset/compact-station-comparison.md | 7 + packages/count-aggregator-ui/README.md | 35 +++++ .../charts/time-series-chart.test.tsx | 145 +++++++++++++++++- .../components/charts/time-series-chart.tsx | 56 ++++--- .../src/components/ui/chart.test.tsx | 85 ++++++++++ .../src/components/ui/chart.tsx | 60 ++++++-- .../src/components/wizard/result-step.tsx | 9 +- .../src/components/wizard/station-label.tsx | 8 +- .../components/wizard/station-select.test.tsx | 69 +++++++++ .../src/components/wizard/station-select.tsx | 32 ++-- packages/count-aggregator-ui/src/index.ts | 2 +- .../src/lib/chart-data.test.ts | 137 +++++++++++++++++ .../count-aggregator-ui/src/lib/chart-data.ts | 90 +++++++++++ .../count-aggregator-ui/src/lib/dates.test.ts | 73 ++++++++- packages/count-aggregator-ui/src/lib/dates.ts | 16 ++ .../src/lib/stations.test.ts | 53 ++++++- .../count-aggregator-ui/src/lib/stations.ts | 33 ++++ .../count-aggregator-ui/src/types/index.ts | 2 + 18 files changed, 859 insertions(+), 53 deletions(-) create mode 100644 .changeset/compact-station-comparison.md create mode 100644 packages/count-aggregator-ui/src/components/ui/chart.test.tsx create mode 100644 packages/count-aggregator-ui/src/components/wizard/station-select.test.tsx create mode 100644 packages/count-aggregator-ui/src/lib/chart-data.test.ts create mode 100644 packages/count-aggregator-ui/src/lib/chart-data.ts diff --git a/.changeset/compact-station-comparison.md b/.changeset/compact-station-comparison.md new file mode 100644 index 00000000..38ed85c7 --- /dev/null +++ b/.changeset/compact-station-comparison.md @@ -0,0 +1,7 @@ +--- +"@mapsight/count-aggregator-ui": minor +--- + +Add an opt-in `comparisonTooltip: "compact"` app setting with short station identifiers, metric labels and colour swatches. Full labels remain the default, and single-series tooltips retain their existing labels. + +Fix intraday axis ticks for multi-day ranges, break line and area charts at missing resolution buckets without treating gaps as measurements, and disambiguate duplicate station names using existing station metadata. Export `buildStationLabels` for custom station selectors. diff --git a/packages/count-aggregator-ui/README.md b/packages/count-aggregator-ui/README.md index 437f3ccd..6bb2487f 100644 --- a/packages/count-aggregator-ui/README.md +++ b/packages/count-aggregator-ui/README.md @@ -143,6 +143,41 @@ The `/headless` entry also exports `CountAggregatorProvider`, `createStationType [`/count-aggregator/headless`](https://github.com/open-mapsight/mapsight/blob/main/apps/demos/src/count-aggregator/count-aggregator-headless-page.tsx) (mock API via `pnpm --filter @mapsight/demos dev`). +## Comparison charts + +Full station labels remain the tooltip default. A host application can opt into a compact tooltip +for charts with more than one series by setting `comparisonTooltip` on its app config: + +```ts +config.apps.bicycleSensorTotal = { + ...config.apps.bicycleSensorTotal, + comparisonTooltip: "compact", // default: "full" +}; +``` + +Compact tooltips show a colour swatch, a short station identifier, the metric (such as minimum, +maximum or average), and the bucket value. They use the station's existing `originId` when it is +unique within the comparison and at most 20 characters; otherwise they use `#` plus the numeric +station ID. Identifiers beginning with `#` also use the numeric fallback to avoid collisions. +The full series label remains available as a title. Width and height are bounded on small screens; +long comparisons scroll within the tooltip. Single-series charts keep full labels in either mode. +This setting applies to the wizard, overview charts and direct `TimeSeriesChart` use. + +Intraday axis ticks include dates when the selected range crosses a calendar-day boundary, and the +year when it crosses a year boundary. Single-day charts retain time-only ticks. + +Line and area charts break at missing resolution buckets. Missing stations or metrics remain null, +are omitted from tooltips, and never become zero measurements or contribute to bucket statistics. +Gap rows exist only in the merged chart data; source measurements and exports remain unchanged. +Daily, weekly, monthly and yearly steps use local calendar dates, matching API datetime parsing. +Gap expansion is limited to 5,000 rows plus one break marker for each remaining gap, so long outages +stay bounded while lines still break. + +Station selections, result labels and full chart tooltips disambiguate duplicate display names +using an existing section description, type name, origin ID, or numeric ID, in that order. Unique +names keep their existing formatting. Custom selectors can use the exported `buildStationLabels` +helper with the complete station collection to get the same labels. + ## CMS app-shell embed For host CMS pages that paste HTML rather than bundle your app, use the public Vite plugins: diff --git a/packages/count-aggregator-ui/src/components/charts/time-series-chart.test.tsx b/packages/count-aggregator-ui/src/components/charts/time-series-chart.test.tsx index 5fec45e5..081852bc 100644 --- a/packages/count-aggregator-ui/src/components/charts/time-series-chart.test.tsx +++ b/packages/count-aggregator-ui/src/components/charts/time-series-chart.test.tsx @@ -1,7 +1,8 @@ -import {createElement} from "react"; +import {type ReactElement, cloneElement, createElement} from "react"; -import {render, screen} from "@testing-library/react"; -import {describe, expect, it} from "vitest"; +import {cleanup, fireEvent, render, screen} from "@testing-library/react"; +import type * as Recharts from "recharts"; +import {afterEach, describe, expect, it, vi} from "vitest"; import {CountAggregatorProvider} from "../../context/count-aggregator-provider.js"; import type { @@ -151,3 +152,141 @@ describe("TimeSeriesChart", () => { expect(screen.getByText(/keine messwerte verfügbar/i)).toBeTruthy(); }); }); + +// Give Recharts dimensions in jsdom; keep its chart, axes and tooltip rendering real. +vi.mock("recharts", async (importOriginal) => { + const recharts = await importOriginal(); + return { + ...recharts, + ResponsiveContainer: ({ + children, + }: { + children: ReactElement<{width: number; height: number}>; + }) => cloneElement(children, {width: 640, height: 320}), + }; +}); + +afterEach(cleanup); + +function renderComparison( + options: { + compact?: boolean; + single?: boolean; + originIds?: string[]; + type?: "line" | "area" | "column"; + } = {}, +) { + const dates = [0, 1, 4, 5].map((hour) => new Date(2026, 0, 1, hour)); + const ids = options.single ? [1] : [1, 2]; + const stationMap = new Map( + ids.map((id) => [ + id, + { + id, + label: `Station ${id} with a long label`, + originId: options.originIds?.[id - 1] ?? `sensor-${id}`, + typeName: "Level", + status: null, + }, + ]), + ); + const comparisonConfig: CountAggregatorConfig = { + ...config, + locale: "en", + apps: { + ...config.apps, + waterLevelSurface: { + ...config.apps.waterLevelSurface!, + ...(options.compact + ? {comparisonTooltip: "compact" as const} + : {}), + }, + }, + }; + return render( + + ({ + key: `station_${id}_mean`, + stationId: id, + metric: "mean", + values: dates.map((date, i) => ({date, value: i})), + }))} + resolution="hourly" + startDate={dates[0]!} + endDate={new Date(2026, 0, 8)} + stationsById={stationMap} + /> + , + ); +} + +describe("comparison chart rendering", () => { + it.each([false, true])( + "uses the configured tooltip labels (compact: %s)", + async (compact) => { + renderComparison({compact}); + fireEvent.keyDown(screen.getByRole("application"), { + key: "ArrowRight", + }); + expect( + await screen.findByText( + compact + ? "sensor-1 · Average" + : "Station 1 with a long label", + ), + ).toBeTruthy(); + expect( + screen.getByText( + compact + ? "sensor-2 · Average" + : "Station 2 with a long label", + ), + ).toBeTruthy(); + }, + ); + + it("keeps full labels for a single series even when compact mode is configured", async () => { + renderComparison({compact: true, single: true}); + fireEvent.keyDown(screen.getByRole("application"), {key: "ArrowRight"}); + expect( + await screen.findByText("Station 1 with a long label"), + ).toBeTruthy(); + }); + + it.each([ + ["shared", "shared"], + ["#2", "#1"], + ["a".repeat(30), "b".repeat(30)], + ])( + "falls back to station ids when origin ids are ambiguous or long", + async (...originIds) => { + renderComparison({compact: true, originIds}); + fireEvent.keyDown(screen.getByRole("application"), { + key: "ArrowRight", + }); + expect(await screen.findByText("#1 · Average")).toBeTruthy(); + expect(screen.getByText("#2 · Average")).toBeTruthy(); + }, + ); + + it.each(["line", "area"] as const)( + "breaks %s paths at gaps and includes dates on hourly ticks", + (type) => { + const {container} = renderComparison({type}); + const paths = container.querySelectorAll(`.recharts-${type}-curve`); + expect(paths).toHaveLength(2); + for (const path of paths) + expect(path.getAttribute("d")?.match(/M/g)).toHaveLength(2); + const ticks = container.querySelectorAll( + ".recharts-xAxis-tick-labels .recharts-text", + ); + expect(ticks.length).toBeGreaterThan(0); + expect(ticks[0]?.textContent).toMatch(/Jan|01/); + }, + ); +}); diff --git a/packages/count-aggregator-ui/src/components/charts/time-series-chart.tsx b/packages/count-aggregator-ui/src/components/charts/time-series-chart.tsx index 194c92c2..48a4d8a8 100644 --- a/packages/count-aggregator-ui/src/components/charts/time-series-chart.tsx +++ b/packages/count-aggregator-ui/src/components/charts/time-series-chart.tsx @@ -27,6 +27,7 @@ import { Y_AXIS_UNIT_LABEL_TOP_MARGIN, createYAxisUnitLabel, } from "../../lib/chart-axis-label.js"; +import {type ChartDataRow, mergeSeriesData} from "../../lib/chart-data.js"; import {getColorForStationIndex} from "../../lib/colors.js"; import {formatChartAxisDate, getTooltipDateFormat} from "../../lib/dates.js"; import { @@ -35,7 +36,7 @@ import { metricValueFormatFromAppConfig, } from "../../lib/format-metric-value.js"; import {getMetricLabels} from "../../lib/i18n.js"; -import {formatStationLabel} from "../../lib/stations.js"; +import {buildStationLabels} from "../../lib/stations.js"; import {cn, getDocumentLocale, isDefined} from "../../lib/utils.js"; import type { AggregatedValuesData, @@ -72,7 +73,7 @@ function getFallbackResolutionMs(resolution: string): number { } function getColumnDomainPadding( - chartData: Array>, + chartData: ChartDataRow[], resolution: string, ): number { const timestamps = chartData @@ -93,25 +94,6 @@ function getColumnDomainPadding( return bucketMs / 2; } -function mergeSeriesData( - series: readonly ChartSeries[], -): Array> { - const byTimestamp = new Map>(); - - for (const entry of series) { - for (const {date, value} of entry.values) { - const ts = date.getTime(); - const row = byTimestamp.get(ts) ?? {date: ts}; - row[entry.key] = value; - byTimestamp.set(ts, row); - } - } - - return Array.from(byTimestamp.values()).sort( - (a, b) => (a.date ?? 0) - (b.date ?? 0), - ); -} - function limitChartSeries(series: readonly ChartSeries[]): { tooMuchData: boolean; limitedSeries: ChartSeries[]; @@ -187,20 +169,40 @@ export function TimeSeriesChart({ [locale, valueFormat], ); + const compactTooltip = + appConfig.comparisonTooltip === "compact" && + (chartSeries?.length ?? 0) > 1; const {chartConfig, chartData} = useMemo(() => { if (chartSeries === undefined) { return {chartConfig: {}, chartData: []}; } const config: ChartConfig = {}; + const stationLabels = buildStationLabels(stationsById?.values() ?? []); + const comparedIds = new Set( + chartSeries.map(({stationId}) => stationId), + ); + const shortLabels = [...comparedIds].map((id) => + stationsById?.get(id)?.originId.trim(), + ); + for (const entry of chartSeries) { const station = stationsById?.get(entry.stationId); const stationLabel = station === undefined ? entry.stationId.toString() - : formatStationLabel(station); - + : stationLabels.get(station.id)!; + + const originId = station?.originId.trim(); + const shortLabel = + originId && + originId.length <= 20 && + !originId.startsWith("#") && + shortLabels.filter((label) => label === originId).length === 1 + ? originId + : `#${entry.stationId}`; config[entry.key] = { + tooltipLabel: `${shortLabel} · ${metricLabels[entry.metric]}`, label: buildSeriesLabel( stationLabel, entry.metric, @@ -215,11 +217,12 @@ export function TimeSeriesChart({ return { chartConfig: config, - chartData: mergeSeriesData(chartSeries), + chartData: mergeSeriesData(chartSeries, resolution), }; }, [ chartSeries, metricLabels, + resolution, selectedStationIds, showMetricInLabel, stationsById, @@ -239,7 +242,7 @@ export function TimeSeriesChart({ const commonAxisProps = { domain: xDomain, tickFormatter: (value: number) => - formatChartAxisDate(value, resolution), + formatChartAxisDate(value, resolution, {startDate, endDate}), type: "number" as const, scale: "time" as const, dataKey: "date", @@ -273,6 +276,7 @@ export function TimeSeriesChart({ fillOpacity={0.2} strokeWidth={2} isAnimationActive={false} + connectNulls={false} dot={false} /> ); @@ -286,6 +290,7 @@ export function TimeSeriesChart({ stroke={color} strokeWidth={2} isAnimationActive={false} + connectNulls={false} dot={false} /> ); @@ -351,6 +356,7 @@ export function TimeSeriesChart({ tooltipFormatter.format(new Date(label)) } diff --git a/packages/count-aggregator-ui/src/components/ui/chart.test.tsx b/packages/count-aggregator-ui/src/components/ui/chart.test.tsx new file mode 100644 index 00000000..985cd656 --- /dev/null +++ b/packages/count-aggregator-ui/src/components/ui/chart.test.tsx @@ -0,0 +1,85 @@ +import {cleanup, render, screen} from "@testing-library/react"; +import {afterEach, describe, expect, it, vi} from "vitest"; + +import {ChartContainer, ChartTooltipContent} from "./chart.js"; + +afterEach(cleanup); + +const config = { + level: { + label: "Long station label (Average)", + tooltipLabel: "sensor-1 · Average", + color: "red", + }, +}; +const payload = [ + {dataKey: "level", color: "red", value: 0, payload: {date: 123}}, +]; + +describe("ChartTooltipContent", () => { + it.each([undefined, false, true])( + "keeps full labels unless compact is true (%s)", + (compact) => { + const {container} = render( + + `Date ${date}`} + valueFormatter={(value) => `${value} m`} + /> + , + ); + expect( + screen.getByText( + compact + ? "sensor-1 · Average" + : "Long station label (Average)", + ), + ).toBeTruthy(); + expect( + screen.getByTitle("Long station label (Average)"), + ).toBeTruthy(); + expect(screen.getByText("0 m")).toBeTruthy(); + expect(screen.getByText("Date 123")).toBeTruthy(); + expect( + container.querySelector('[style="background-color: red;"]'), + ).toBeTruthy(); + }, + ); + + it("omits gaps and non-finite values without formatting them", () => { + const formatter = vi.fn((value: number) => `${value} m`); + render( + + ({ + dataKey: `gap-${i}`, + name: `Missing ${i}`, + value, + })), + ]} + valueFormatter={formatter} + /> + , + ); + expect(formatter).toHaveBeenCalledExactlyOnceWith(0); + expect(screen.queryByText(/Missing/)).toBeNull(); + }); + + it("renders no tooltip for a bucket containing only gaps", () => { + const {container} = render( + + + , + ); + expect(container.textContent).toBe(""); + }); +}); diff --git a/packages/count-aggregator-ui/src/components/ui/chart.tsx b/packages/count-aggregator-ui/src/components/ui/chart.tsx index 2fa10409..40a5f054 100644 --- a/packages/count-aggregator-ui/src/components/ui/chart.tsx +++ b/packages/count-aggregator-ui/src/components/ui/chart.tsx @@ -14,6 +14,7 @@ export type ChartConfig = Record< string, { label?: ReactNode; + tooltipLabel?: ReactNode; color?: string; } >; @@ -85,7 +86,7 @@ export function ChartContainer({ interface TooltipPayloadItem { name?: string; - value?: number; + value?: number | null; color?: string; dataKey?: string | number; payload?: { @@ -95,11 +96,13 @@ interface TooltipPayloadItem { export function ChartTooltipContent({ active, + compact = false, payload, labelFormatter, valueFormatter, }: { active?: boolean; + compact?: boolean; payload?: TooltipPayloadItem[]; labelFormatter?: (label: number) => ReactNode; valueFormatter?: (value: number) => ReactNode; @@ -110,17 +113,27 @@ export function ChartTooltipContent({ return null; } - const label = payload[0]?.payload?.date; + const items = payload.filter( + (item) => typeof item.value === "number" && Number.isFinite(item.value), + ); + if (items.length === 0) return null; + const label = items[0]?.payload?.date; return ( -
+
{label !== undefined && labelFormatter !== undefined ? (
{labelFormatter(label)}
) : null}
- {payload.map((item) => { + {items.map((item) => { const key = String(item.dataKey ?? ""); const itemConfig = config[key]; @@ -129,17 +142,44 @@ export function ChartTooltipContent({ key={key} className="msca:flex msca:items-center msca:justify-between msca:gap-4" > -
+
- - {itemConfig?.label ?? item.name} + + {(compact + ? itemConfig?.tooltipLabel + : itemConfig?.label) ?? item.name}
- - {item.value === undefined + + {item.value == null ? undefined : (valueFormatter?.(item.value) ?? item.value.toLocaleString())} diff --git a/packages/count-aggregator-ui/src/components/wizard/result-step.tsx b/packages/count-aggregator-ui/src/components/wizard/result-step.tsx index 6a7610c0..af613421 100644 --- a/packages/count-aggregator-ui/src/components/wizard/result-step.tsx +++ b/packages/count-aggregator-ui/src/components/wizard/result-step.tsx @@ -15,6 +15,7 @@ import {getColorForStationIndex} from "../../lib/colors.js"; import {dateToYmd} from "../../lib/dates.js"; import {getValuesModeLabels} from "../../lib/i18n.js"; import {RAW_VALUES_RANGE_QUERY} from "../../lib/raw-values.js"; +import {buildStationLabels} from "../../lib/stations.js"; import {isDefined} from "../../lib/utils.js"; import { type AggregatedValuesData, @@ -87,6 +88,8 @@ export function ResultStep({ return []; } + const labels = buildStationLabels(stationsById.values()); + return selectedStationIds .map((stationId, index) => { const station = stationsById.get(stationId); @@ -95,7 +98,11 @@ export function ResultStep({ return (
  • - +
  • ); diff --git a/packages/count-aggregator-ui/src/components/wizard/station-label.tsx b/packages/count-aggregator-ui/src/components/wizard/station-label.tsx index a6a9fddc..e4c3b428 100644 --- a/packages/count-aggregator-ui/src/components/wizard/station-label.tsx +++ b/packages/count-aggregator-ui/src/components/wizard/station-label.tsx @@ -7,10 +7,12 @@ import {ColorDot} from "./color-dot.js"; export const StationLabel = memo(function StationLabel({ station, + label, color, isEnabled = true, }: { station?: Station; + label?: string; color: string; isEnabled?: boolean; }): ReactElement { @@ -25,8 +27,10 @@ export const StationLabel = memo(function StationLabel({ > {station ? ( <> - {formatStationLabel(station)} - {station.sectionDescription ? ( + {label ?? formatStationLabel(station)} + {station.sectionDescription && + label !== + `${formatStationLabel(station)} — ${station.sectionDescription.trim()}` ? ( {station.sectionDescription} diff --git a/packages/count-aggregator-ui/src/components/wizard/station-select.test.tsx b/packages/count-aggregator-ui/src/components/wizard/station-select.test.tsx new file mode 100644 index 00000000..140e3f90 --- /dev/null +++ b/packages/count-aggregator-ui/src/components/wizard/station-select.test.tsx @@ -0,0 +1,69 @@ +import {cleanup, fireEvent, render, screen} from "@testing-library/react"; +import {afterEach, describe, expect, it} from "vitest"; + +import {CountAggregatorProvider} from "../../context/count-aggregator-provider.js"; +import type {Station} from "../../types"; +import {StationSelect} from "./station-select.js"; + +const stations = new Map( + [1, 2, 3].map((id) => [ + id, + { + id, + originId: `sensor-${id}`, + label: "Shared path", + typeName: "Counter", + status: null, + sectionDescription: + id === 3 + ? "Upper section" + : id === 1 + ? "Upper section" + : "Lower section", + }, + ]), +); +afterEach(cleanup); + +const config = { + apps: {}, + links: {calendarUrl: () => "", eventUrl: () => ""}, + locale: "en" as const, +}; + +describe("StationSelect", () => { + it("disambiguates selected chips even when descriptions are hidden", () => { + render( + + {}} + isMulti + showDescriptionInSelection={false} + /> + , + ); + expect(screen.getByText("Shared path — sensor-1")).toBeTruthy(); + expect(screen.getByText("Shared path — sensor-2")).toBeTruthy(); + }); + + it("uses the same labels in the menu and permits searching by the disambiguator", () => { + render( + + {}} + /> + , + ); + fireEvent.change(screen.getByRole("combobox"), { + target: {value: "sensor-2"}, + }); + expect(screen.getByRole("option").textContent).toContain( + "Shared path — sensor-2", + ); + expect(screen.queryByText("Shared path — sensor-1")).toBeNull(); + }); +}); diff --git a/packages/count-aggregator-ui/src/components/wizard/station-select.tsx b/packages/count-aggregator-ui/src/components/wizard/station-select.tsx index cd3f34f5..76709f84 100644 --- a/packages/count-aggregator-ui/src/components/wizard/station-select.tsx +++ b/packages/count-aggregator-ui/src/components/wizard/station-select.tsx @@ -9,7 +9,7 @@ import Select, { import {useCountAggregatorI18n} from "../../context/count-aggregator-provider.js"; import {useCountAggregatorPortal} from "../../context/count-aggregator-root.js"; -import {formatStationLabel} from "../../lib/stations.js"; +import {buildStationLabels, formatStationLabel} from "../../lib/stations.js"; import {isDefined} from "../../lib/utils.js"; import type {Station} from "../../types"; @@ -49,12 +49,19 @@ export function getSelectStyles( }; } -function createFormatOptionLabel(showDescriptionInSelection: boolean) { +function createFormatOptionLabel( + showDescriptionInSelection: boolean, + labels: ReadonlyMap, +) { return function formatOptionLabel( station: Station, {context}: {context: "menu" | "value"}, ): ReactElement { - const showDesc = showDescriptionInSelection || context === "menu"; + const label = labels.get(station.id) ?? formatStationLabel(station); + const showDesc = + (showDescriptionInSelection || context === "menu") && + label !== + `${formatStationLabel(station)} — ${station.sectionDescription?.trim()}`; return ( @@ -62,7 +69,7 @@ function createFormatOptionLabel(showDescriptionInSelection: boolean) { className="msca:font-bold" title={`${station.label ?? ""} ${station.sectionDescription ?? ""} (${station.originId})`} > - {formatStationLabel(station)} + {label} {showDesc && station.sectionDescription ? ( <> @@ -77,10 +84,6 @@ function createFormatOptionLabel(showDescriptionInSelection: boolean) { }; } -function getOptionLabel(station: Station): string { - return `${formatStationLabel(station)} ${station.typeName} ${station.sectionDescription ?? ""}`; -} - export const StationSelect = memo(function StationSelect({ stationsById, stationIds, @@ -105,6 +108,16 @@ export const StationSelect = memo(function StationSelect({ const portalTarget = useCountAggregatorPortal(); const {t} = useCountAggregatorI18n(); + const labels = useMemo( + () => buildStationLabels(stationsById?.values() ?? []), + [stationsById], + ); + const getOptionLabel = useCallback( + (station: Station): string => + `${labels.get(station.id)} ${station.typeName} ${station.sectionDescription ?? ""}`, + [labels], + ); + const options = useMemo( () => stationsById === undefined @@ -112,7 +125,7 @@ export const StationSelect = memo(function StationSelect({ : Array.from(stationsById.values()).sort((a, b) => getOptionLabel(a).localeCompare(getOptionLabel(b)), ), - [stationsById], + [getOptionLabel, stationsById], ); const value = useMemo(() => { @@ -156,6 +169,7 @@ export const StationSelect = memo(function StationSelect({ getOptionValue={(station) => station.id.toString(10)} formatOptionLabel={createFormatOptionLabel( showDescriptionInSelection, + labels, )} styles={getSelectStyles(styleOverrides)} menuPortalTarget={portalTarget} diff --git a/packages/count-aggregator-ui/src/index.ts b/packages/count-aggregator-ui/src/index.ts index b954de27..3b8dd31e 100644 --- a/packages/count-aggregator-ui/src/index.ts +++ b/packages/count-aggregator-ui/src/index.ts @@ -69,7 +69,7 @@ export { } from "./lib/format-metric-value.js"; export {getColorForStationIndex, STATION_COLORS} from "./lib/colors.js"; export {dateToYmd, ymdToDate} from "./lib/dates.js"; -export {formatStationLabel} from "./lib/stations.js"; +export {buildStationLabels, formatStationLabel} from "./lib/stations.js"; export { groupStationTypesByCategory, type StationTypeCategoryGroup, diff --git a/packages/count-aggregator-ui/src/lib/chart-data.test.ts b/packages/count-aggregator-ui/src/lib/chart-data.test.ts new file mode 100644 index 00000000..0da39644 --- /dev/null +++ b/packages/count-aggregator-ui/src/lib/chart-data.test.ts @@ -0,0 +1,137 @@ +import {describe, expect, it} from "vitest"; + +import type {BucketMetric, ChartSeries, DataResolution} from "../types"; +import {mergeSeriesData} from "./chart-data.js"; + +function series( + key: string, + dates: Date[], + metric: BucketMetric = "mean", +): ChartSeries { + return { + key, + stationId: 1, + metric, + values: dates.map((date, i) => ({date, value: i * 10})), + }; +} + +describe("mergeSeriesData", () => { + it.each<[DataResolution, number]>([ + ["5min", 5], + ["15min", 15], + ["hourly", 60], + ])( + "inserts missing %s buckets when all stations have a gap", + (resolution, minutes) => { + const start = new Date(2026, 0, 1).getTime(); + const dates = [0, 3].map( + (i) => new Date(start + i * minutes * 60_000), + ); + const rows = mergeSeriesData( + [series("a", dates), series("b", dates)], + resolution, + ); + expect(rows).toEqual([ + {date: start, a: 0, b: 0}, + {date: start + minutes * 60_000, a: null, b: null}, + {date: start + 2 * minutes * 60_000, a: null, b: null}, + {date: dates[1]!.getTime(), a: 10, b: 10}, + ]); + }, + ); + + it("keeps missing stations and metrics null while retaining real zeros", () => { + const dates = [1, 2, 3].map((day) => new Date(2026, 0, day)); + const input = [ + series("min", [dates[0]!, dates[2]!], "min"), + series("max", dates, "max"), + ]; + const original = structuredClone(input); + const rows = mergeSeriesData(input, "daily"); + expect(rows[1]).toEqual({ + date: dates[1]!.getTime(), + min: null, + max: 10, + }); + expect(rows[0]?.min).toBe(0); + expect(input).toEqual(original); + expect( + rows.flatMap((row) => (row.min === null ? [] : [row.min])), + ).toEqual([0, 10]); + }); + + it.each<[DataResolution, Date[]]>([ + [ + "daily", + [ + new Date(2026, 2, 28), + new Date(2026, 2, 29), + new Date(2026, 2, 30), + ], + ], + [ + "weekly", + [ + new Date(2026, 9, 19), + new Date(2026, 9, 26), + new Date(2026, 10, 2), + ], + ], + [ + "monthly", + [ + new Date(2024, 0, 31), + new Date(2024, 1, 29), + new Date(2024, 2, 31), + ], + ], + [ + "yearly", + [ + new Date(2024, 1, 29), + new Date(2025, 1, 28), + new Date(2026, 1, 28), + ], + ], + ])("uses calendar steps for %s buckets", (resolution, dates) => { + const rows = mergeSeriesData( + [series("a", [dates[0]!, dates[2]!])], + resolution, + ); + expect(rows.map((row) => row.date)).toEqual( + dates.map((date) => date.getTime()), + ); + expect(rows[1]?.a).toBeNull(); + expect(mergeSeriesData([series("a", dates)], resolution)).toHaveLength( + 3, + ); + }); + + it("sorts unsorted input and does not synthesize values for empty series", () => { + const dates = [3, 1, 2].map((day) => new Date(2026, 0, day)); + const rows = mergeSeriesData( + [series("a", dates), series("b", [])], + "daily", + ); + expect(rows.map((row) => row.a)).toEqual([10, 20, 0]); + expect(rows.map((row) => row.b)).toEqual([null, null, null]); + expect(mergeSeriesData([], "daily")).toEqual([]); + }); + + it("bounds expansion for long outages and preserves subsequent break markers", () => { + const dates = [ + new Date(2000, 0, 1), + new Date(2020, 0, 1), + new Date(2026, 0, 1), + ]; + const rows = mergeSeriesData([series("a", dates)], "5min"); + expect(rows.length).toBeLessThanOrEqual(5004); + const second = rows.findIndex( + (row) => row.date === dates[1]!.getTime(), + ); + expect(rows[second - 1]?.a).toBeNull(); + expect(rows[second + 1]?.a).toBeNull(); + expect(rows.at(-1)?.a).toBe(20); + }); +}); diff --git a/packages/count-aggregator-ui/src/lib/chart-data.ts b/packages/count-aggregator-ui/src/lib/chart-data.ts new file mode 100644 index 00000000..a152208a --- /dev/null +++ b/packages/count-aggregator-ui/src/lib/chart-data.ts @@ -0,0 +1,90 @@ +import type {ChartSeries, DataResolution} from "../types"; + +export type ChartDataRow = {date: number} & Record; + +const MAX_GAP_ROWS = 5_000; + +/** Calendar buckets follow local dates, like the API's local datetimes. */ +function stepTimestamp( + timestamp: number, + resolution: DataResolution, + steps = 1, +): number { + const date = new Date(timestamp); + switch (resolution) { + case "5min": + return timestamp + steps * 5 * 60_000; + case "15min": + return timestamp + steps * 15 * 60_000; + case "hourly": + return timestamp + steps * 60 * 60_000; + case "daily": + return date.setDate(date.getDate() + steps); + case "weekly": + return date.setDate(date.getDate() + steps * 7); + case "monthly": + case "yearly": { + const day = date.getDate(); + const isMonthEnd = + day === + new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate(); + date.setDate(1); + date.setMonth( + date.getMonth() + steps * (resolution === "monthly" ? 1 : 12), + ); + const lastDay = new Date( + date.getFullYear(), + date.getMonth() + 1, + 0, + ).getDate(); + return date.setDate( + resolution === "monthly" && isMonthEnd + ? lastDay + : Math.min(day, lastDay), + ); + } + } +} + +export function mergeSeriesData( + series: readonly ChartSeries[], + resolution: DataResolution, +): ChartDataRow[] { + const byTimestamp = new Map(); + const emptyValues = Object.fromEntries(series.map(({key}) => [key, null])); + const createRow = (date: number): ChartDataRow => ({...emptyValues, date}); + + for (const entry of series) { + for (const {date, value} of entry.values) { + const ts = date.getTime(); + if (!Number.isFinite(ts)) continue; + const row = byTimestamp.get(ts) ?? createRow(ts); + row[entry.key] = Number.isFinite(value) ? value : null; + byTimestamp.set(ts, row); + } + } + + const rows = [...byTimestamp.values()].sort((a, b) => a.date - b.date); + const result: ChartDataRow[] = []; + let gapRows = 0; + for (const [index, row] of rows.entries()) { + const previous = rows[index - 1]; + if (previous !== undefined) { + let steps = 1; + let next = stepTimestamp(previous.date, resolution, steps); + // Always retain a break marker, even after the expansion budget is used. + if (next < row.date) { + result.push(createRow(next)); + gapRows += 1; + next = stepTimestamp(previous.date, resolution, ++steps); + while (next < row.date && gapRows < MAX_GAP_ROWS) { + result.push(createRow(next)); + gapRows += 1; + next = stepTimestamp(previous.date, resolution, ++steps); + } + } + } + result.push(row); + } + return result; +} diff --git a/packages/count-aggregator-ui/src/lib/dates.test.ts b/packages/count-aggregator-ui/src/lib/dates.test.ts index c839b712..dde62d96 100644 --- a/packages/count-aggregator-ui/src/lib/dates.test.ts +++ b/packages/count-aggregator-ui/src/lib/dates.test.ts @@ -1,7 +1,7 @@ import {describe, expect, it} from "vitest"; import {applyPresetDateRanges} from "../config/platform.js"; -import {dateToYmd, ymdToDate} from "./dates.js"; +import {dateToYmd, formatChartAxisDate, ymdToDate} from "./dates.js"; describe("dates", () => { it("round-trips ymd dates", () => { @@ -25,3 +25,74 @@ describe("applyPresetDateRanges", () => { expect(result.endDate).toEqual(end); }); }); + +describe("formatChartAxisDate", () => { + const tick = new Date(2026, 9, 2, 8, 30); + it.each(["5min", "15min", "hourly"] as const)( + "includes date and time for a multi-day %s range", + (resolution) => { + expect( + formatChartAxisDate(tick.getTime(), resolution, { + startDate: new Date(2026, 9, 1), + endDate: new Date(2026, 9, 8), + }), + ).toBe( + tick.toLocaleString(undefined, { + day: "numeric", + month: "short", + hour: "2-digit", + minute: "2-digit", + }), + ); + }, + ); + it("uses dates even for a short range crossing midnight", () => { + const label = formatChartAxisDate(tick.getTime(), "hourly", { + startDate: new Date(2026, 9, 1, 23), + endDate: tick, + }); + expect(label).toContain( + tick.toLocaleDateString(undefined, {month: "short"}), + ); + }); + it("preserves time-only labels for a single day and callers without a range", () => { + const expected = tick.toLocaleTimeString(undefined, { + hour: "2-digit", + minute: "2-digit", + }); + expect( + formatChartAxisDate(tick.getTime(), "hourly", { + startDate: new Date(2026, 9, 2), + endDate: tick, + }), + ).toBe(expected); + expect(formatChartAxisDate(tick.getTime(), "hourly")).toBe(expected); + }); + it("includes the year when the range crosses a year boundary", () => { + expect( + formatChartAxisDate(tick.getTime(), "hourly", { + startDate: new Date(2025, 11, 31), + endDate: tick, + }), + ).toBe( + tick.toLocaleString(undefined, { + day: "numeric", + month: "short", + year: "2-digit", + hour: "2-digit", + minute: "2-digit", + }), + ); + }); + it.each(["daily", "weekly", "monthly", "yearly"] as const)( + "preserves existing %s labels", + (resolution) => { + expect( + formatChartAxisDate(tick.getTime(), resolution, { + startDate: new Date(2026, 9, 1), + endDate: tick, + }), + ).toBe(formatChartAxisDate(tick.getTime(), resolution)); + }, + ); +}); diff --git a/packages/count-aggregator-ui/src/lib/dates.ts b/packages/count-aggregator-ui/src/lib/dates.ts index 2ee2b1af..a4e44dc3 100644 --- a/packages/count-aggregator-ui/src/lib/dates.ts +++ b/packages/count-aggregator-ui/src/lib/dates.ts @@ -107,6 +107,7 @@ export function getTooltipDateFormat( export function formatChartAxisDate( timestamp: number, resolution: DataResolution, + range?: {startDate: Date; endDate: Date}, ): string { const date = new Date(timestamp); @@ -121,6 +122,21 @@ export function formatChartAxisDate( case "5min": case "15min": case "hourly": + if ( + range !== undefined && + dateToYmd(range.startDate) !== dateToYmd(range.endDate) + ) { + return date.toLocaleString(undefined, { + day: "numeric", + month: "short", + hour: "2-digit", + minute: "2-digit", + ...(range.startDate.getFullYear() !== + range.endDate.getFullYear() + ? {year: "2-digit" as const} + : {}), + }); + } return date.toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit", diff --git a/packages/count-aggregator-ui/src/lib/stations.test.ts b/packages/count-aggregator-ui/src/lib/stations.test.ts index d4a6dfaa..b9728d1f 100644 --- a/packages/count-aggregator-ui/src/lib/stations.test.ts +++ b/packages/count-aggregator-ui/src/lib/stations.test.ts @@ -1,7 +1,7 @@ import {describe, expect, it} from "vitest"; import type {Station} from "../types"; -import {formatStationLabel} from "./stations.js"; +import {buildStationLabels, formatStationLabel} from "./stations.js"; function createStation(overrides: Partial): Station { return { @@ -44,3 +44,54 @@ describe("formatStationLabel", () => { ); }); }); + +describe("buildStationLabels", () => { + it("leaves unique names unchanged and disambiguates names after suffix removal", () => { + const stations = [ + createStation({ + id: 1, + label: "Shared path (min)", + sectionDescription: "Upper section", + }), + createStation({ + id: 2, + label: "Shared path (max)", + sectionDescription: "Lower section", + }), + createStation({id: 3, label: "Other path"}), + ]; + expect([...buildStationLabels(stations).values()]).toEqual([ + "Shared path — Upper section", + "Shared path — Lower section", + "Other path", + ]); + expect(buildStationLabels(stations.toReversed())).toEqual( + buildStationLabels(stations), + ); + }); + + it("uses type, origin id, then numeric id when descriptions are absent or identical", () => { + const stations = [ + createStation({id: 1, typeName: "Counter", originId: "sensor-a"}), + createStation({id: 2, typeName: "Level", originId: "sensor-b"}), + ]; + expect([...buildStationLabels(stations).values()]).toEqual([ + "Station — Counter", + "Station — Level", + ]); + const sameType = stations.map((station) => ({ + ...station, + typeName: "Counter", + sectionDescription: "Same section", + })); + expect([...buildStationLabels(sameType).values()]).toEqual([ + "Station — sensor-a", + "Station — sensor-b", + ]); + expect([ + ...buildStationLabels( + sameType.map((station) => ({...station, originId: "shared"})), + ).values(), + ]).toEqual(["Station — 1", "Station — 2"]); + }); +}); diff --git a/packages/count-aggregator-ui/src/lib/stations.ts b/packages/count-aggregator-ui/src/lib/stations.ts index 4f09d9b8..06eb6c9d 100644 --- a/packages/count-aggregator-ui/src/lib/stations.ts +++ b/packages/count-aggregator-ui/src/lib/stations.ts @@ -40,3 +40,36 @@ export function formatStationLabel(station: Station | undefined): string { : trimTrailingMetricSuffix(station.label)) || station.originId ); } + +/** Resolve duplicate display names using only metadata present on the stations. */ +export function buildStationLabels( + stations: Iterable, +): Map { + const groups = new Map(); + for (const station of stations) { + const label = formatStationLabel(station); + const group = groups.get(label) ?? []; + group.push(station); + groups.set(label, group); + } + + const labels = new Map(); + for (const [label, group] of groups) { + const fields = ["sectionDescription", "typeName", "originId"] as const; + const field = fields.find((key) => { + const values = group.map((station) => station[key]?.trim()); + return ( + values.every(Boolean) && new Set(values).size === group.length + ); + }); + for (const station of group) { + const suffix = + field === undefined ? station.id : station[field]?.trim(); + labels.set( + station.id, + group.length === 1 ? label : `${label} — ${suffix}`, + ); + } + } + return labels; +} diff --git a/packages/count-aggregator-ui/src/types/index.ts b/packages/count-aggregator-ui/src/types/index.ts index 423afcb6..42cc66ad 100644 --- a/packages/count-aggregator-ui/src/types/index.ts +++ b/packages/count-aggregator-ui/src/types/index.ts @@ -133,6 +133,8 @@ export interface CountAggregatorAppConfig { displayPrecision?: number; defaultResolution?: Resolution; defaultChartType?: ChartType; + /** Compact comparison labels; full station labels remain the default. */ + comparisonTooltip?: "full" | "compact"; resolutions?: readonly Resolution[]; resolutionLabels?: Partial>; features?: CountAggregatorFeatures; From 4dba0d8acd14471a7ebc2109cb82fe28d785e7c9 Mon Sep 17 00:00:00 2001 From: Paul Golmann Date: Fri, 20 Nov 2026 13:23:46 +0100 Subject: [PATCH 2/3] Keep raw value charts connected Raw values use a 5-minute chart resolution for formatting but have no fixed step, so gap filling would isolate every point. Add a breakAtGaps prop to TimeSeriesChart (default true) and disable it for raw values in the wizard. --- .changeset/compact-station-comparison.md | 2 +- packages/count-aggregator-ui/README.md | 3 ++- .../charts/time-series-chart.test.tsx | 10 ++++++++ .../components/charts/time-series-chart.tsx | 7 +++++- .../components/wizard/result-step.test.tsx | 25 +++++++++++++++++-- .../src/components/wizard/result-step.tsx | 1 + .../src/lib/chart-data.test.ts | 13 ++++++++++ .../count-aggregator-ui/src/lib/chart-data.ts | 7 +++++- .../count-aggregator-ui/src/types/index.ts | 5 ++++ 9 files changed, 67 insertions(+), 6 deletions(-) diff --git a/.changeset/compact-station-comparison.md b/.changeset/compact-station-comparison.md index 38ed85c7..e27ed8d1 100644 --- a/.changeset/compact-station-comparison.md +++ b/.changeset/compact-station-comparison.md @@ -4,4 +4,4 @@ Add an opt-in `comparisonTooltip: "compact"` app setting with short station identifiers, metric labels and colour swatches. Full labels remain the default, and single-series tooltips retain their existing labels. -Fix intraday axis ticks for multi-day ranges, break line and area charts at missing resolution buckets without treating gaps as measurements, and disambiguate duplicate station names using existing station metadata. Export `buildStationLabels` for custom station selectors. +Fix intraday axis ticks for multi-day ranges, break line and area charts at missing resolution buckets without treating gaps as measurements, and disambiguate duplicate station names using existing station metadata. Raw values stay connected; `TimeSeriesChart` accepts `breakAtGaps={false}` for other irregular series. Export `buildStationLabels` for custom station selectors. diff --git a/packages/count-aggregator-ui/README.md b/packages/count-aggregator-ui/README.md index 6bb2487f..e9983d05 100644 --- a/packages/count-aggregator-ui/README.md +++ b/packages/count-aggregator-ui/README.md @@ -171,7 +171,8 @@ are omitted from tooltips, and never become zero measurements or contribute to b Gap rows exist only in the merged chart data; source measurements and exports remain unchanged. Daily, weekly, monthly and yearly steps use local calendar dates, matching API datetime parsing. Gap expansion is limited to 5,000 rows plus one break marker for each remaining gap, so long outages -stay bounded while lines still break. +stay bounded while lines still break. Raw values have no fixed step, so the wizard keeps connecting +them; pass `breakAtGaps={false}` to `TimeSeriesChart` for other irregular series. Station selections, result labels and full chart tooltips disambiguate duplicate display names using an existing section description, type name, origin ID, or numeric ID, in that order. Unique diff --git a/packages/count-aggregator-ui/src/components/charts/time-series-chart.test.tsx b/packages/count-aggregator-ui/src/components/charts/time-series-chart.test.tsx index 081852bc..b0f9a812 100644 --- a/packages/count-aggregator-ui/src/components/charts/time-series-chart.test.tsx +++ b/packages/count-aggregator-ui/src/components/charts/time-series-chart.test.tsx @@ -174,6 +174,7 @@ function renderComparison( single?: boolean; originIds?: string[]; type?: "line" | "area" | "column"; + breakAtGaps?: boolean; } = {}, ) { const dates = [0, 1, 4, 5].map((hour) => new Date(2026, 0, 1, hour)); @@ -220,6 +221,7 @@ function renderComparison( startDate={dates[0]!} endDate={new Date(2026, 0, 8)} stationsById={stationMap} + breakAtGaps={options.breakAtGaps} /> , ); @@ -289,4 +291,12 @@ describe("comparison chart rendering", () => { expect(ticks[0]?.textContent).toMatch(/Jan|01/); }, ); + + it("connects irregular measurements when gap breaks are disabled", () => { + const {container} = renderComparison({breakAtGaps: false}); + const paths = container.querySelectorAll(".recharts-line-curve"); + expect(paths).toHaveLength(2); + for (const path of paths) + expect(path.getAttribute("d")?.match(/M/g)).toHaveLength(1); + }); }); diff --git a/packages/count-aggregator-ui/src/components/charts/time-series-chart.tsx b/packages/count-aggregator-ui/src/components/charts/time-series-chart.tsx index 48a4d8a8..c803762b 100644 --- a/packages/count-aggregator-ui/src/components/charts/time-series-chart.tsx +++ b/packages/count-aggregator-ui/src/components/charts/time-series-chart.tsx @@ -142,6 +142,7 @@ export function TimeSeriesChart({ startDate, endDate, stationsById, + breakAtGaps = true, className = "msca:h-[calc(100vh-400px)] msca:min-h-[300px] msca:max-h-[700px]", emptyMessage = "No measurements are available for the current selection.", }: TimeSeriesChartProps): ReactElement { @@ -217,9 +218,13 @@ export function TimeSeriesChart({ return { chartConfig: config, - chartData: mergeSeriesData(chartSeries, resolution), + chartData: mergeSeriesData( + chartSeries, + breakAtGaps ? resolution : undefined, + ), }; }, [ + breakAtGaps, chartSeries, metricLabels, resolution, diff --git a/packages/count-aggregator-ui/src/components/wizard/result-step.test.tsx b/packages/count-aggregator-ui/src/components/wizard/result-step.test.tsx index 4f8bb70d..e382d9b9 100644 --- a/packages/count-aggregator-ui/src/components/wizard/result-step.test.tsx +++ b/packages/count-aggregator-ui/src/components/wizard/result-step.test.tsx @@ -16,8 +16,13 @@ vi.mock("../charts/time-series-chart.js", async (importActual) => { return { ...actual, - TimeSeriesChart() { - return
    ; + TimeSeriesChart({breakAtGaps}: {breakAtGaps?: boolean}) { + return ( +
    + ); }, }; }); @@ -117,6 +122,22 @@ describe("ResultStep", () => { expect(screen.queryByRole("link", {name: /csv/i})).toBeNull(); }); + it.each([ + ["raw", "false"], + ["daily", "true"], + ] as const)( + "sets gap breaks for %s values to %s", + (valuesMode, expected) => { + renderResultStep({valuesMode}); + + expect( + screen + .getByTestId("time-series-chart") + .getAttribute("data-break-at-gaps"), + ).toBe(expected); + }, + ); + it("builds a raw-values CSV href in Rohwerte mode", () => { renderResultStep({ valuesMode: "raw", diff --git a/packages/count-aggregator-ui/src/components/wizard/result-step.tsx b/packages/count-aggregator-ui/src/components/wizard/result-step.tsx index af613421..53c7abfa 100644 --- a/packages/count-aggregator-ui/src/components/wizard/result-step.tsx +++ b/packages/count-aggregator-ui/src/components/wizard/result-step.tsx @@ -204,6 +204,7 @@ export function ResultStep({ startDate={startDate} endDate={endDate} stationsById={stationsById} + breakAtGaps={!isRaw} emptyMessage={t("chart.empty")} /> diff --git a/packages/count-aggregator-ui/src/lib/chart-data.test.ts b/packages/count-aggregator-ui/src/lib/chart-data.test.ts index 0da39644..16202db5 100644 --- a/packages/count-aggregator-ui/src/lib/chart-data.test.ts +++ b/packages/count-aggregator-ui/src/lib/chart-data.test.ts @@ -41,6 +41,19 @@ describe("mergeSeriesData", () => { }, ); + it("only merges existing timestamps without a resolution", () => { + const start = new Date(2026, 0, 1).getTime(); + const dates = [0, 15, 45].map( + (minutes) => new Date(start + minutes * 60_000), + ); + const rows = mergeSeriesData([series("a", dates)], undefined); + expect(rows).toEqual([ + {date: dates[0]!.getTime(), a: 0}, + {date: dates[1]!.getTime(), a: 10}, + {date: dates[2]!.getTime(), a: 20}, + ]); + }); + it("keeps missing stations and metrics null while retaining real zeros", () => { const dates = [1, 2, 3].map((day) => new Date(2026, 0, day)); const input = [ diff --git a/packages/count-aggregator-ui/src/lib/chart-data.ts b/packages/count-aggregator-ui/src/lib/chart-data.ts index a152208a..23cf44ec 100644 --- a/packages/count-aggregator-ui/src/lib/chart-data.ts +++ b/packages/count-aggregator-ui/src/lib/chart-data.ts @@ -46,9 +46,13 @@ function stepTimestamp( } } +/** + * Merge series into chart rows. With a `resolution`, missing buckets become null rows so lines + * break at gaps; without one, rows are only created for existing timestamps. + */ export function mergeSeriesData( series: readonly ChartSeries[], - resolution: DataResolution, + resolution: DataResolution | undefined, ): ChartDataRow[] { const byTimestamp = new Map(); const emptyValues = Object.fromEntries(series.map(({key}) => [key, null])); @@ -65,6 +69,7 @@ export function mergeSeriesData( } const rows = [...byTimestamp.values()].sort((a, b) => a.date - b.date); + if (resolution === undefined) return rows; const result: ChartDataRow[] = []; let gapRows = 0; for (const [index, row] of rows.entries()) { diff --git a/packages/count-aggregator-ui/src/types/index.ts b/packages/count-aggregator-ui/src/types/index.ts index 42cc66ad..f95daebd 100644 --- a/packages/count-aggregator-ui/src/types/index.ts +++ b/packages/count-aggregator-ui/src/types/index.ts @@ -160,6 +160,11 @@ export interface TimeSeriesChartProps { startDate: Date; endDate: Date; stationsById: Map | undefined; + /** + * Insert empty buckets at the `resolution` step so line and area charts break at missing data. + * Disable for irregular measurements such as raw values. Defaults to `true`. + */ + breakAtGaps?: boolean; className?: string; emptyMessage?: string; } From 47d8e850369c2fc1f8294c7ea661aebda01d63b4 Mon Sep 17 00:00:00 2001 From: Paul Golmann Date: Fri, 20 Nov 2026 13:43:15 +0100 Subject: [PATCH 3/3] Resolve station label disambiguators as structured parts Station select and result labels decided whether to hide the section description by rebuilding the formatted label string. Resolve labels into a name plus the disambiguating field instead, and format the string in one place. When the section description disambiguates, show it as the usual description text rather than appending it to the name. buildStationLabels keeps its signature. --- packages/count-aggregator-ui/README.md | 4 +- .../src/components/wizard/result-step.tsx | 4 +- .../components/wizard/station-label.test.tsx | 62 ++++++++++++++++ .../src/components/wizard/station-label.tsx | 19 +++-- .../components/wizard/station-select.test.tsx | 20 +++++ .../src/components/wizard/station-select.tsx | 35 ++++++--- .../src/lib/stations.test.ts | 41 ++++++++++- .../count-aggregator-ui/src/lib/stations.ts | 73 +++++++++++++++---- 8 files changed, 223 insertions(+), 35 deletions(-) create mode 100644 packages/count-aggregator-ui/src/components/wizard/station-label.test.tsx diff --git a/packages/count-aggregator-ui/README.md b/packages/count-aggregator-ui/README.md index e9983d05..8bcdf9d1 100644 --- a/packages/count-aggregator-ui/README.md +++ b/packages/count-aggregator-ui/README.md @@ -176,7 +176,9 @@ them; pass `breakAtGaps={false}` to `TimeSeriesChart` for other irregular series Station selections, result labels and full chart tooltips disambiguate duplicate display names using an existing section description, type name, origin ID, or numeric ID, in that order. Unique -names keep their existing formatting. Custom selectors can use the exported `buildStationLabels` +names keep their existing formatting. When the section description disambiguates, selections and +result labels show it as their usual description text, including selected values that otherwise +hide descriptions. Custom selectors can use the exported `buildStationLabels` helper with the complete station collection to get the same labels. ## CMS app-shell embed diff --git a/packages/count-aggregator-ui/src/components/wizard/result-step.tsx b/packages/count-aggregator-ui/src/components/wizard/result-step.tsx index 53c7abfa..1a58644d 100644 --- a/packages/count-aggregator-ui/src/components/wizard/result-step.tsx +++ b/packages/count-aggregator-ui/src/components/wizard/result-step.tsx @@ -15,7 +15,7 @@ import {getColorForStationIndex} from "../../lib/colors.js"; import {dateToYmd} from "../../lib/dates.js"; import {getValuesModeLabels} from "../../lib/i18n.js"; import {RAW_VALUES_RANGE_QUERY} from "../../lib/raw-values.js"; -import {buildStationLabels} from "../../lib/stations.js"; +import {resolveStationLabelParts} from "../../lib/stations.js"; import {isDefined} from "../../lib/utils.js"; import { type AggregatedValuesData, @@ -88,7 +88,7 @@ export function ResultStep({ return []; } - const labels = buildStationLabels(stationsById.values()); + const labels = resolveStationLabelParts(stationsById.values()); return selectedStationIds .map((stationId, index) => { diff --git a/packages/count-aggregator-ui/src/components/wizard/station-label.test.tsx b/packages/count-aggregator-ui/src/components/wizard/station-label.test.tsx new file mode 100644 index 00000000..600f2587 --- /dev/null +++ b/packages/count-aggregator-ui/src/components/wizard/station-label.test.tsx @@ -0,0 +1,62 @@ +import {cleanup, render} from "@testing-library/react"; +import {afterEach, describe, expect, it} from "vitest"; + +import {resolveStationLabelParts} from "../../lib/stations.js"; +import type {Station} from "../../types"; +import {StationLabel} from "./station-label.js"; + +afterEach(cleanup); + +function station(id: number, overrides: Partial = {}): Station { + return { + id, + originId: `sensor-${id}`, + label: "Shared path", + typeName: "Counter", + status: null, + ...overrides, + }; +} + +function renderLabel(stations: Station[], id: number) { + const labels = resolveStationLabelParts(stations); + return render( + entry.id === id)} + label={labels.get(id)} + color="#000" + />, + ).container.textContent; +} + +describe("StationLabel", () => { + it("shows a disambiguating section description once, as description text", () => { + const stations = [ + station(1, {sectionDescription: "Upper section"}), + station(2, {sectionDescription: "Lower section"}), + ]; + expect(renderLabel(stations, 1)).toBe("Shared pathUpper section"); + }); + + it("appends other disambiguators and keeps the description", () => { + const stations = [ + station(1, {sectionDescription: "Same section"}), + station(2, {sectionDescription: "Same section"}), + ]; + expect(renderLabel(stations, 2)).toBe( + "Shared path — sensor-2Same section", + ); + }); + + it("keeps the description when a unique name already ends with it", () => { + const stations = [ + station(1, { + label: "Path — Upper section", + sectionDescription: "Upper section", + }), + ]; + expect(renderLabel(stations, 1)).toBe( + "Path — Upper sectionUpper section", + ); + }); +}); diff --git a/packages/count-aggregator-ui/src/components/wizard/station-label.tsx b/packages/count-aggregator-ui/src/components/wizard/station-label.tsx index e4c3b428..e726a486 100644 --- a/packages/count-aggregator-ui/src/components/wizard/station-label.tsx +++ b/packages/count-aggregator-ui/src/components/wizard/station-label.tsx @@ -1,6 +1,10 @@ import {type ReactElement, memo} from "react"; -import {formatStationLabel} from "../../lib/stations.js"; +import { + type StationLabelParts, + formatStationLabel, + formatStationLabelParts, +} from "../../lib/stations.js"; import {cn} from "../../lib/utils.js"; import type {Station} from "../../types"; import {ColorDot} from "./color-dot.js"; @@ -12,7 +16,7 @@ export const StationLabel = memo(function StationLabel({ isEnabled = true, }: { station?: Station; - label?: string; + label?: StationLabelParts; color: string; isEnabled?: boolean; }): ReactElement { @@ -27,10 +31,13 @@ export const StationLabel = memo(function StationLabel({ > {station ? ( <> - {label ?? formatStationLabel(station)} - {station.sectionDescription && - label !== - `${formatStationLabel(station)} — ${station.sectionDescription.trim()}` ? ( + {label === undefined + ? formatStationLabel(station) + : label.disambiguator?.field === + "sectionDescription" + ? label.name + : formatStationLabelParts(label)} + {station.sectionDescription ? ( {station.sectionDescription} diff --git a/packages/count-aggregator-ui/src/components/wizard/station-select.test.tsx b/packages/count-aggregator-ui/src/components/wizard/station-select.test.tsx index 140e3f90..849d7dff 100644 --- a/packages/count-aggregator-ui/src/components/wizard/station-select.test.tsx +++ b/packages/count-aggregator-ui/src/components/wizard/station-select.test.tsx @@ -48,6 +48,26 @@ describe("StationSelect", () => { expect(screen.getByText("Shared path — sensor-2")).toBeTruthy(); }); + it("shows the section description for description-disambiguated chips", () => { + render( + + [id, stations.get(id)!])) + } + stationIds={[1, 2]} + onChange={() => {}} + isMulti + showDescriptionInSelection={false} + /> + , + ); + expect(screen.getAllByText("Shared path")).toHaveLength(2); + expect(screen.getByText("Upper section")).toBeTruthy(); + expect(screen.getByText("Lower section")).toBeTruthy(); + expect(screen.queryByText(/Shared path —/)).toBeNull(); + }); + it("uses the same labels in the menu and permits searching by the disambiguator", () => { render( diff --git a/packages/count-aggregator-ui/src/components/wizard/station-select.tsx b/packages/count-aggregator-ui/src/components/wizard/station-select.tsx index 76709f84..0de81e04 100644 --- a/packages/count-aggregator-ui/src/components/wizard/station-select.tsx +++ b/packages/count-aggregator-ui/src/components/wizard/station-select.tsx @@ -9,7 +9,12 @@ import Select, { import {useCountAggregatorI18n} from "../../context/count-aggregator-provider.js"; import {useCountAggregatorPortal} from "../../context/count-aggregator-root.js"; -import {buildStationLabels, formatStationLabel} from "../../lib/stations.js"; +import { + type StationLabelParts, + formatStationLabel, + formatStationLabelParts, + resolveStationLabelParts, +} from "../../lib/stations.js"; import {isDefined} from "../../lib/utils.js"; import type {Station} from "../../types"; @@ -51,17 +56,23 @@ export function getSelectStyles( function createFormatOptionLabel( showDescriptionInSelection: boolean, - labels: ReadonlyMap, + labels: ReadonlyMap, ) { return function formatOptionLabel( station: Station, {context}: {context: "menu" | "value"}, ): ReactElement { - const label = labels.get(station.id) ?? formatStationLabel(station); + const parts = labels.get(station.id) ?? { + name: formatStationLabel(station), + }; + // The description already disambiguates; show it instead of appending it to the name. + const byDescription = + parts.disambiguator?.field === "sectionDescription"; + const label = byDescription + ? parts.name + : formatStationLabelParts(parts); const showDesc = - (showDescriptionInSelection || context === "menu") && - label !== - `${formatStationLabel(station)} — ${station.sectionDescription?.trim()}`; + showDescriptionInSelection || context === "menu" || byDescription; return ( @@ -109,12 +120,18 @@ export const StationSelect = memo(function StationSelect({ const {t} = useCountAggregatorI18n(); const labels = useMemo( - () => buildStationLabels(stationsById?.values() ?? []), + () => resolveStationLabelParts(stationsById?.values() ?? []), [stationsById], ); const getOptionLabel = useCallback( - (station: Station): string => - `${labels.get(station.id)} ${station.typeName} ${station.sectionDescription ?? ""}`, + (station: Station): string => { + const parts = labels.get(station.id); + const label = + parts === undefined + ? formatStationLabel(station) + : formatStationLabelParts(parts); + return `${label} ${station.typeName} ${station.sectionDescription ?? ""}`; + }, [labels], ); diff --git a/packages/count-aggregator-ui/src/lib/stations.test.ts b/packages/count-aggregator-ui/src/lib/stations.test.ts index b9728d1f..f3e95765 100644 --- a/packages/count-aggregator-ui/src/lib/stations.test.ts +++ b/packages/count-aggregator-ui/src/lib/stations.test.ts @@ -1,7 +1,11 @@ import {describe, expect, it} from "vitest"; import type {Station} from "../types"; -import {buildStationLabels, formatStationLabel} from "./stations.js"; +import { + buildStationLabels, + formatStationLabel, + resolveStationLabelParts, +} from "./stations.js"; function createStation(overrides: Partial): Station { return { @@ -95,3 +99,38 @@ describe("buildStationLabels", () => { ]).toEqual(["Station — 1", "Station — 2"]); }); }); + +describe("resolveStationLabelParts", () => { + it("reports which field disambiguates a duplicate name", () => { + const stations = [ + createStation({id: 1, sectionDescription: " Upper section "}), + createStation({id: 2, sectionDescription: "Lower section"}), + createStation({id: 3, label: "Other — Upper section"}), + ]; + expect(resolveStationLabelParts(stations)).toEqual( + new Map([ + [ + 1, + { + name: "Station", + disambiguator: { + field: "sectionDescription", + value: "Upper section", + }, + }, + ], + [ + 2, + { + name: "Station", + disambiguator: { + field: "sectionDescription", + value: "Lower section", + }, + }, + ], + [3, {name: "Other — Upper section"}], + ]), + ); + }); +}); diff --git a/packages/count-aggregator-ui/src/lib/stations.ts b/packages/count-aggregator-ui/src/lib/stations.ts index 06eb6c9d..0b775546 100644 --- a/packages/count-aggregator-ui/src/lib/stations.ts +++ b/packages/count-aggregator-ui/src/lib/stations.ts @@ -41,35 +41,76 @@ export function formatStationLabel(station: Station | undefined): string { ); } +export interface StationLabelParts { + /** Display name from `formatStationLabel`. */ + name: string; + /** Set only when another station shares `name`. */ + disambiguator?: { + field: "sectionDescription" | "typeName" | "originId" | "id"; + value: string; + }; +} + +const DISAMBIGUATOR_FIELDS = [ + "sectionDescription", + "typeName", + "originId", +] as const; + /** Resolve duplicate display names using only metadata present on the stations. */ -export function buildStationLabels( +export function resolveStationLabelParts( stations: Iterable, -): Map { +): Map { const groups = new Map(); for (const station of stations) { - const label = formatStationLabel(station); - const group = groups.get(label) ?? []; + const name = formatStationLabel(station); + const group = groups.get(name) ?? []; group.push(station); - groups.set(label, group); + groups.set(name, group); } - const labels = new Map(); - for (const [label, group] of groups) { - const fields = ["sectionDescription", "typeName", "originId"] as const; - const field = fields.find((key) => { + const parts = new Map(); + for (const [name, group] of groups) { + if (group.length === 1) { + parts.set(group[0]!.id, {name}); + continue; + } + const field = DISAMBIGUATOR_FIELDS.find((key) => { const values = group.map((station) => station[key]?.trim()); return ( values.every(Boolean) && new Set(values).size === group.length ); }); for (const station of group) { - const suffix = - field === undefined ? station.id : station[field]?.trim(); - labels.set( - station.id, - group.length === 1 ? label : `${label} — ${suffix}`, - ); + parts.set(station.id, { + name, + disambiguator: + field === undefined + ? {field: "id", value: String(station.id)} + : {field, value: station[field]!.trim()}, + }); } } - return labels; + return parts; +} + +export function formatStationLabelParts({ + name, + disambiguator, +}: StationLabelParts): string { + return disambiguator === undefined + ? name + : `${name} — ${disambiguator.value}`; +} + +/** Display labels for all stations; duplicate names get a ` — ` disambiguator. */ +export function buildStationLabels( + stations: Iterable, +): Map { + return new Map( + Array.from(resolveStationLabelParts(stations), ([id, parts]) => [ + id, + formatStationLabelParts(parts), + ]), + ); }