diff --git a/.changeset/compact-station-comparison.md b/.changeset/compact-station-comparison.md new file mode 100644 index 00000000..e27ed8d1 --- /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. 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 437f3ccd..8bcdf9d1 100644 --- a/packages/count-aggregator-ui/README.md +++ b/packages/count-aggregator-ui/README.md @@ -143,6 +143,44 @@ 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. 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 +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 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..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 @@ -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,151 @@ 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"; + breakAtGaps?: boolean; + } = {}, +) { + 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} + breakAtGaps={options.breakAtGaps} + /> + , + ); +} + +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/); + }, + ); + + 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 194c92c2..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 @@ -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[]; @@ -160,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 { @@ -187,20 +170,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 +218,16 @@ export function TimeSeriesChart({ return { chartConfig: config, - chartData: mergeSeriesData(chartSeries), + chartData: mergeSeriesData( + chartSeries, + breakAtGaps ? resolution : undefined, + ), }; }, [ + breakAtGaps, chartSeries, metricLabels, + resolution, selectedStationIds, showMetricInLabel, stationsById, @@ -239,7 +247,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 +281,7 @@ export function TimeSeriesChart({ fillOpacity={0.2} strokeWidth={2} isAnimationActive={false} + connectNulls={false} dot={false} /> ); @@ -286,6 +295,7 @@ export function TimeSeriesChart({ stroke={color} strokeWidth={2} isAnimationActive={false} + connectNulls={false} dot={false} /> ); @@ -351,6 +361,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.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 6a7610c0..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,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 {resolveStationLabelParts} from "../../lib/stations.js"; import {isDefined} from "../../lib/utils.js"; import { type AggregatedValuesData, @@ -87,6 +88,8 @@ export function ResultStep({ return []; } + const labels = resolveStationLabelParts(stationsById.values()); + return selectedStationIds .map((stationId, index) => { const station = stationsById.get(stationId); @@ -95,7 +98,11 @@ export function ResultStep({ return (
  • - +
  • ); @@ -197,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/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 a6a9fddc..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,16 +1,22 @@ 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"; export const StationLabel = memo(function StationLabel({ station, + label, color, isEnabled = true, }: { station?: Station; + label?: StationLabelParts; color: string; isEnabled?: boolean; }): ReactElement { @@ -25,7 +31,12 @@ export const StationLabel = memo(function StationLabel({ > {station ? ( <> - {formatStationLabel(station)} + {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 new file mode 100644 index 00000000..849d7dff --- /dev/null +++ b/packages/count-aggregator-ui/src/components/wizard/station-select.test.tsx @@ -0,0 +1,89 @@ +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("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( + + {}} + /> + , + ); + 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..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 {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"; @@ -49,12 +54,25 @@ 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 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" || byDescription; return ( @@ -62,7 +80,7 @@ function createFormatOptionLabel(showDescriptionInSelection: boolean) { className="msca:font-bold" title={`${station.label ?? ""} ${station.sectionDescription ?? ""} (${station.originId})`} > - {formatStationLabel(station)} + {label} {showDesc && station.sectionDescription ? ( <> @@ -77,10 +95,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 +119,22 @@ export const StationSelect = memo(function StationSelect({ const portalTarget = useCountAggregatorPortal(); const {t} = useCountAggregatorI18n(); + const labels = useMemo( + () => resolveStationLabelParts(stationsById?.values() ?? []), + [stationsById], + ); + const getOptionLabel = useCallback( + (station: Station): string => { + const parts = labels.get(station.id); + const label = + parts === undefined + ? formatStationLabel(station) + : formatStationLabelParts(parts); + return `${label} ${station.typeName} ${station.sectionDescription ?? ""}`; + }, + [labels], + ); + const options = useMemo( () => stationsById === undefined @@ -112,7 +142,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 +186,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..16202db5 --- /dev/null +++ b/packages/count-aggregator-ui/src/lib/chart-data.test.ts @@ -0,0 +1,150 @@ +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("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 = [ + 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..23cf44ec --- /dev/null +++ b/packages/count-aggregator-ui/src/lib/chart-data.ts @@ -0,0 +1,95 @@ +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), + ); + } + } +} + +/** + * 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 | undefined, +): 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); + if (resolution === undefined) return rows; + 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..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 {formatStationLabel} from "./stations.js"; +import { + buildStationLabels, + formatStationLabel, + resolveStationLabelParts, +} from "./stations.js"; function createStation(overrides: Partial): Station { return { @@ -44,3 +48,89 @@ 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"]); + }); +}); + +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 4f09d9b8..0b775546 100644 --- a/packages/count-aggregator-ui/src/lib/stations.ts +++ b/packages/count-aggregator-ui/src/lib/stations.ts @@ -40,3 +40,77 @@ export function formatStationLabel(station: Station | undefined): string { : trimTrailingMetricSuffix(station.label)) || station.originId ); } + +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 resolveStationLabelParts( + stations: Iterable, +): Map { + const groups = new Map(); + for (const station of stations) { + const name = formatStationLabel(station); + const group = groups.get(name) ?? []; + group.push(station); + groups.set(name, group); + } + + 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) { + parts.set(station.id, { + name, + disambiguator: + field === undefined + ? {field: "id", value: String(station.id)} + : {field, value: station[field]!.trim()}, + }); + } + } + 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), + ]), + ); +} diff --git a/packages/count-aggregator-ui/src/types/index.ts b/packages/count-aggregator-ui/src/types/index.ts index 423afcb6..f95daebd 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; @@ -158,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; }