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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/compact-station-comparison.md
Original file line number Diff line number Diff line change
@@ -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.
38 changes: 38 additions & 0 deletions packages/count-aggregator-ui/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -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<typeof Recharts>();
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(
<CountAggregatorProvider config={comparisonConfig}>
<TimeSeriesChart
appId="waterLevelSurface"
type={options.type ?? "line"}
selectedStationIds={ids}
selectedMetrics={["mean"]}
chartSeries={ids.map((id) => ({
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}
/>
</CountAggregatorProvider>,
);
}

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);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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,
Expand Down Expand Up @@ -72,7 +73,7 @@ function getFallbackResolutionMs(resolution: string): number {
}

function getColumnDomainPadding(
chartData: Array<Record<string, number>>,
chartData: ChartDataRow[],
resolution: string,
): number {
const timestamps = chartData
Expand All @@ -93,25 +94,6 @@ function getColumnDomainPadding(
return bucketMs / 2;
}

function mergeSeriesData(
series: readonly ChartSeries[],
): Array<Record<string, number>> {
const byTimestamp = new Map<number, Record<string, number>>();

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[];
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand All @@ -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",
Expand Down Expand Up @@ -273,6 +281,7 @@ export function TimeSeriesChart({
fillOpacity={0.2}
strokeWidth={2}
isAnimationActive={false}
connectNulls={false}
dot={false}
/>
);
Expand All @@ -286,6 +295,7 @@ export function TimeSeriesChart({
stroke={color}
strokeWidth={2}
isAnimationActive={false}
connectNulls={false}
dot={false}
/>
);
Expand Down Expand Up @@ -351,6 +361,7 @@ export function TimeSeriesChart({
<Tooltip
content={
<ChartTooltipContent
compact={compactTooltip}
labelFormatter={(label) =>
tooltipFormatter.format(new Date(label))
}
Expand Down
Loading
Loading