OpenDataVisualizer/client/src/components/StationPanel.tsx
Claudio Schaad 7b65926aa2 Add Thurgau traffic visualizer and start page (#1)
- Thurgau hourly traffic counts (data.tg.ch) refreshed every 6 h into a per-day JSON cache
- Road geometry per station direction from swisstopo swissTLM3D; roundabout arms run outward from the roundabout centre
- Leaflet map with animated vehicles by class, time controls and base map switcher (grey, colour, aerial)
- Station panel with per-class counts and Chart.js charts
- Start page with map tiles; traffic map at /verkehr/thurgau
- Dockerfile and docker-compose, xUnit tests

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Claudio Schaad <c.schaad@pog.ch>
Co-committed-by: Claudio Schaad <c.schaad@pog.ch>
2026-11-06 20:17:26 +00:00

290 lines
9.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useQuery } from '@tanstack/react-query';
import {
BarElement,
CategoryScale,
Chart as ChartJS,
Filler,
Legend,
LinearScale,
LogarithmicScale,
LineElement,
PointElement,
Tooltip,
type ChartOptions,
} from 'chart.js';
import { Bar, Line } from 'react-chartjs-2';
import { fetchStationSummary, type DayView, type Station } from '../api/traffic';
import { formatDate, formatNumber } from '../traffic/format';
import {
DIRECTION_COLORS,
VEHICLE_CLASSES,
VEHICLE_GROUPS,
sumCounts,
} from '../traffic/vehicleClasses';
ChartJS.register(
CategoryScale,
LinearScale,
LogarithmicScale,
PointElement,
LineElement,
BarElement,
Filler,
Tooltip,
Legend,
);
ChartJS.defaults.font.family = 'system-ui, -apple-system, "Segoe UI", sans-serif';
ChartJS.defaults.font.size = 11;
ChartJS.defaults.color = '#475569';
interface StationPanelProps {
station: Station;
day: DayView | null;
hour: number;
onClose: () => void;
}
const HOUR_LABELS = Array.from({ length: 24 }, (_, h) => String(h).padStart(2, '0'));
const baseLineOptions: ChartOptions<'line'> = {
responsive: true,
maintainAspectRatio: false,
animation: false,
interaction: { mode: 'index', intersect: false },
plugins: { legend: { position: 'bottom', labels: { boxWidth: 12, boxHeight: 2 } } },
elements: { point: { radius: 0, hoverRadius: 3 }, line: { borderWidth: 1.75, tension: 0.25 } },
scales: {
x: { grid: { display: false }, ticks: { maxRotation: 0, autoSkipPadding: 16 } },
y: { beginAtZero: true, grid: { color: '#e2e8f0' }, title: { display: true, text: 'Fz/h' } },
},
};
export function StationPanel({ station, day, hour, onClose }: StationPanelProps) {
const summaryQuery = useQuery({
queryKey: ['station-summary', station.code],
queryFn: () => fetchStationSummary(station.code),
});
const summary = summaryQuery.data;
const stationDay = day?.stations.find((s) => s.code === station.code);
const hourIndex = Math.min(23, Math.max(0, hour));
const hourlyLabels = summary?.directions[0]?.hourly.map((h) => formatHourLabel(h.time)) ?? [];
const dailyLabels =
summary?.directions[0]?.daily.map((d) => formatDate(d.date, { year: undefined })) ?? [];
return (
<aside className="station-panel">
<header className="station-panel-header">
<div>
<h2>{station.name}</h2>
<p>
{station.road} · {station.address}, {station.municipality} · Zählstelle {station.code}
{!station.followsRoad && ' · Strassenverlauf geschätzt'}
</p>
</div>
<button type="button" className="close-button" onClick={onClose} aria-label="Schliessen">
×
</button>
</header>
<section>
<h3>
{day ? formatDate(day.date) : ''}, {HOUR_LABELS[hourIndex]}:00–
{HOUR_LABELS[(hourIndex + 1) % 24]}:00
</h3>
<table className="class-table">
<thead>
<tr>
<th>Fahrzeugklasse</th>
{station.directions.map((direction, i) => (
<th
key={direction.name}
style={{ color: DIRECTION_COLORS[i % DIRECTION_COLORS.length] }}
>
{direction.name}
</th>
))}
</tr>
</thead>
<tbody>
{VEHICLE_CLASSES.map((vehicleClass, classIndex) => (
<tr key={vehicleClass.label}>
<td>
<span
className="legend-dot small"
style={{ background: VEHICLE_GROUPS[vehicleClass.group].color }}
/>
{vehicleClass.label}
</td>
{station.directions.map((direction) => (
<td key={direction.name}>
{stationDay?.directions.find((d) => d.direction === direction.name)?.hours[
hourIndex
]?.[classIndex] ?? '–'}
</td>
))}
</tr>
))}
<tr className="total-row">
<td>Total</td>
{station.directions.map((direction) => (
<td key={direction.name}>
{formatNumber(
sumCounts(
stationDay?.directions.find((d) => d.direction === direction.name)?.hours[
hourIndex
],
),
)}
</td>
))}
</tr>
</tbody>
</table>
</section>
{summaryQuery.isLoading && <p className="muted">Lade Auswertung…</p>}
{summaryQuery.isError && <p className="error">Auswertung konnte nicht geladen werden.</p>}
{summary && (
<>
<section>
<h3>
Stundenwerte {formatDate(summary.from, { weekday: undefined })} –{' '}
{formatDate(summary.to, { weekday: undefined })}
</h3>
<div className="chart chart-tall">
<Line
options={baseLineOptions}
data={{
labels: hourlyLabels,
datasets: summary.directions.map((direction, i) => ({
label: direction.direction,
data: direction.hourly.map((h) => h.total),
borderColor: DIRECTION_COLORS[i % DIRECTION_COLORS.length],
backgroundColor: DIRECTION_COLORS[i % DIRECTION_COLORS.length],
})),
}}
/>
</div>
</section>
<section>
<h3>Durchschnittlicher Tagesverlauf</h3>
<div className="chart">
<Line
options={{
...baseLineOptions,
elements: {
...baseLineOptions.elements,
line: { borderWidth: 2, tension: 0.35 },
},
}}
data={{
labels: HOUR_LABELS,
datasets: summary.directions.flatMap((direction, i) => [
{
label: `${direction.direction} (Mo–Fr)`,
data: direction.weekdayProfile,
borderColor: DIRECTION_COLORS[i % DIRECTION_COLORS.length],
backgroundColor: DIRECTION_COLORS[i % DIRECTION_COLORS.length],
},
{
label: `${direction.direction} (Sa–So)`,
data: direction.weekendProfile,
borderColor: DIRECTION_COLORS[i % DIRECTION_COLORS.length],
backgroundColor: DIRECTION_COLORS[i % DIRECTION_COLORS.length],
borderDash: [5, 4],
},
]),
}}
/>
</div>
</section>
<section>
<h3>Tagesverkehr</h3>
<div className="chart">
<Bar
options={{
responsive: true,
maintainAspectRatio: false,
animation: false,
plugins: { legend: { position: 'bottom', labels: { boxWidth: 12 } } },
scales: {
x: { stacked: true, grid: { display: false } },
y: {
stacked: true,
beginAtZero: true,
grid: { color: '#e2e8f0' },
title: { display: true, text: 'Fz/Tag' },
},
},
}}
data={{
labels: dailyLabels,
datasets: summary.directions.map((direction, i) => ({
label: direction.direction,
data: direction.daily.map((d) => d.total),
backgroundColor: DIRECTION_COLORS[i % DIRECTION_COLORS.length],
borderRadius: 2,
})),
}}
/>
</div>
</section>
<section>
<h3>Fahrzeugklassen (Zeitraum gesamt)</h3>
<div className="chart">
<Bar
options={{
indexAxis: 'y',
responsive: true,
maintainAspectRatio: false,
animation: false,
plugins: {
legend: { display: false },
tooltip: {
callbacks: {
label: (context) => {
const total = sumCounts(summary.classTotals);
const value = Number(context.raw);
return `${formatNumber(value)} (${((value / Math.max(1, total)) * 100).toFixed(1)} %)`;
},
},
},
},
scales: {
x: {
type: 'logarithmic',
grid: { color: '#e2e8f0' },
title: { display: true, text: 'Fahrzeuge (log)' },
},
y: { grid: { display: false } },
},
}}
data={{
labels: VEHICLE_CLASSES.map((c) => c.label),
datasets: [
{
data: summary.classTotals,
backgroundColor: VEHICLE_CLASSES.map((c) => VEHICLE_GROUPS[c.group].color),
borderRadius: 2,
},
],
}}
/>
</div>
</section>
</>
)}
</aside>
);
}
function formatHourLabel(time: string): string {
const date = new Date(time);
return `${date.toLocaleDateString('de-CH', { weekday: 'short', day: '2-digit', month: '2-digit' })} ${String(date.getHours()).padStart(2, '0')}:00`;
}