Fix: Preserve chart state during zoom, pan, and date changes

- Added React.useMemo to memoize chartData and chartOptions to prevent unnecessary re-renders.
- Ensured chart zoom and pan states are maintained during interactions.
- Improved performance and user experience by avoiding chart
This commit is contained in:
ISA
2025-07-22 10:19:14 +02:00
parent 03ee4fb08e
commit 773e2c12b8
7 changed files with 357 additions and 274 deletions

View File

@@ -6,6 +6,6 @@ NEXT_PUBLIC_USE_MOCK_BACKEND_LOOP_START=false
NEXT_PUBLIC_EXPORT_STATIC=false
NEXT_PUBLIC_USE_CGI=false
# App-Versionsnummer
NEXT_PUBLIC_APP_VERSION=1.6.618
NEXT_PUBLIC_APP_VERSION=1.6.623
NEXT_PUBLIC_CPL_MODE=json # json (Entwicklungsumgebung) oder jsSimulatedProd (CPL ->CGI-Interface-Simulator) oder production (CPL-> CGI-Interface Platzhalter)

View File

@@ -5,5 +5,5 @@ NEXT_PUBLIC_CPL_API_PATH=/CPL
NEXT_PUBLIC_EXPORT_STATIC=true
NEXT_PUBLIC_USE_CGI=true
# App-Versionsnummer
NEXT_PUBLIC_APP_VERSION=1.6.618
NEXT_PUBLIC_APP_VERSION=1.6.623
NEXT_PUBLIC_CPL_MODE=production

View File

@@ -1,3 +1,53 @@
## [1.6.623] 2025-07-22
- feat(AnalogInputsChart): Zeitraum im DatePicker und Redux initialisieren und synchronisieren
- Initialwert für Zeitraum (letzte 30 Tage) im Redux-Store gesetzt
- DatePicker-Änderungen werden im Redux gespeichert
- Fetch-Button verwendet Zeitraum aus Redux und loggt die Fetch-URL
- Chart zeigt Daten entsprechend ausgewähltem Zeitraum
---
## [1.6.622] 2025-07-22
- feat(AnalogInputsChart): Zeitraum im DatePicker und Redux initialisieren und synchronisieren
- Initialwert für Zeitraum (letzte 30 Tage) im Redux-Store gesetzt
- DatePicker-Änderungen werden im Redux gespeichert
- Fetch-Button verwendet Zeitraum aus Redux und loggt die Fetch-URL
- Chart zeigt Daten entsprechend ausgewähltem Zeitraum
---
## [1.6.621] 2025-07-22
- feat(AnalogInputsChart): Zeitraum im DatePicker und Redux initialisieren und synchronisieren
- Initialwert für Zeitraum (letzte 30 Tage) im Redux-Store gesetzt
- DatePicker-Änderungen werden im Redux gespeichert
- Fetch-Button verwendet Zeitraum aus Redux und loggt die Fetch-URL
- Chart zeigt Daten entsprechend ausgewähltem Zeitraum
---
## [1.6.620] 2025-07-22
- feat(AnalogInputsChart): Zeitraum im DatePicker und Redux initialisieren und synchronisieren
- Initialwert für Zeitraum (letzte 30 Tage) im Redux-Store gesetzt
- DatePicker-Änderungen werden im Redux gespeichert
- Fetch-Button verwendet Zeitraum aus Redux und loggt die Fetch-URL
- Chart zeigt Daten entsprechend ausgewähltem Zeitraum
---
## [1.6.619] 2025-07-22
- feat(AnalogInputsChart): Zeitraum im DatePicker und Redux initialisieren und synchronisieren
- Initialwert für Zeitraum (letzte 30 Tage) im Redux-Store gesetzt
- DatePicker-Änderungen werden im Redux gespeichert
- Fetch-Button verwendet Zeitraum aus Redux und loggt die Fetch-URL
- Chart zeigt Daten entsprechend ausgewähltem Zeitraum
---
## [1.6.618] 2025-07-21
- feat(mock): Script fetchAnalogInputsData auf ES-Module (.mjs) umgestellt, Datum automatisch gesetzt

View File

@@ -18,6 +18,7 @@ import {
} from "chart.js";
import "chartjs-adapter-date-fns";
import { de } from "date-fns/locale";
import { Listbox } from "@headlessui/react";
import { getAnalogInputsHistoryThunk } from "@/redux/thunks/getAnalogInputsHistoryThunk";
import {
setVonDatum,
@@ -25,10 +26,10 @@ import {
setZeitraum,
setAutoLoad,
} from "@/redux/slices/analogInputs/analogInputsHistorySlice";
import DateRangePicker from "@/components/common/DateRangePicker";
import { Listbox } from "@headlessui/react";
import { getColor } from "@/utils/colors";
import AnalogInputsDatePicker from "./AnalogInputsDatePicker";
// ✅ Nur die Basis-ChartJS-Module registrieren
ChartJS.register(
LineElement,
PointElement,
@@ -40,47 +41,38 @@ ChartJS.register(
TimeScale
);
type AnalogInputHistoryPoint = {
t: string;
m?: number;
i?: number;
a?: number;
g?: number;
};
export default function AnalogInputsChart() {
useEffect(() => {
const loadZoomPlugin = async () => {
const zoomPlugin = (await import("chartjs-plugin-zoom")).default;
if (!ChartJS.registry.plugins.get("zoom")) {
ChartJS.register(zoomPlugin);
}
};
loadZoomPlugin();
}, []);
const dispatch = useDispatch<AppDispatch>();
const chartRef = useRef<any>(null);
const chartRef = useRef<Line | null>(null);
// Redux Werte für Chart-Daten
const { zeitraum, vonDatum, bisDatum, data, autoLoad, selectedId } =
useSelector((state: RootState) => state.analogInputsHistory);
const selectedAnalogInput = useSelector(
(state: RootState) => state.selectedAnalogInput
);
const [localZeitraum, setLocalZeitraum] = React.useState(zeitraum);
// Synchronisiere lokalen State, wenn Redux-Value sich ändert (z.B. nach Reset)
React.useEffect(() => {
setLocalZeitraum(zeitraum);
}, [zeitraum]);
// Initialisiere Zeitraum im Redux-Store, falls leer
// Redux initiale Datum-Werte
const vonDatumRedux = useSelector(
(state: RootState) => state.dateRangePicker.vonDatum
);
const bisDatumRedux = useSelector(
(state: RootState) => state.dateRangePicker.bisDatum
);
// ✅ Lokale States für Picker + Zeitraum
const [localVonDatum, setLocalVonDatum] = React.useState(vonDatumRedux || "");
const [localBisDatum, setLocalBisDatum] = React.useState(bisDatumRedux || "");
const [localZeitraum, setLocalZeitraum] = React.useState(zeitraum);
// Synchronisiere lokale Werte mit Redux (z.B. nach AutoLoad Reset)
useEffect(() => {
setLocalVonDatum(vonDatumRedux || "");
setLocalBisDatum(bisDatumRedux || "");
setLocalZeitraum(zeitraum);
}, [vonDatumRedux, bisDatumRedux, zeitraum]);
// Initiale Default-Werte: 30 Tage zurück
useEffect(() => {
if (!vonDatumRedux || !bisDatumRedux) {
const today = new Date();
@@ -88,125 +80,60 @@ export default function AnalogInputsChart() {
const fromDateObj = new Date(today);
fromDateObj.setDate(today.getDate() - 30);
const fromDate = fromDateObj.toISOString().slice(0, 10);
dispatch(setVonDatum(fromDate));
dispatch(setBisDatum(toDate));
setLocalVonDatum(fromDate);
setLocalBisDatum(toDate);
}
}, [vonDatumRedux, bisDatumRedux, dispatch]);
}, []);
// ✅ Button-Klick → Fetch auslösen
// ✅ Nur lokale Änderung beim Picker
const handleDateChange = (from: string, to: string) => {
setLocalVonDatum(from);
setLocalBisDatum(to);
};
// ✅ Button → Redux + Fetch triggern
const handleFetchData = () => {
if (!selectedAnalogInput?.id) return;
// Zeitraum aus Redux holen
const latestVonDatum =
vonDatumRedux || new Date().toISOString().slice(0, 10);
const latestBisDatum =
bisDatumRedux || new Date().toISOString().slice(0, 10);
// Redux aktualisieren
dispatch(setVonDatum(localVonDatum));
dispatch(setBisDatum(localBisDatum));
dispatch(setZeitraum(localZeitraum));
// Debug: Fetch-URL loggen
const debugUrl = `/api/cpl/getAnalogInputsHistory?eingang=${selectedAnalogInput.id}&zeitraum=${localZeitraum}&von=${latestVonDatum}&bis=${latestBisDatum}`;
console.log("Fetch-URL:", debugUrl);
// Debug anzeigen
console.log(
"Fetch-URL:",
`/api/cpl/getAnalogInputsHistory?eingang=${selectedAnalogInput.id}&zeitraum=${localZeitraum}&von=${localVonDatum}&bis=${localBisDatum}`
);
// Thunk-Fetch mit neuen Werten
dispatch(
getAnalogInputsHistoryThunk({
eingang: selectedAnalogInput.id,
zeitraum: localZeitraum,
vonDatum: latestVonDatum,
bisDatum: latestBisDatum,
vonDatum: localVonDatum,
bisDatum: localBisDatum,
})
);
if (
chartRef.current &&
chartRef.current.options &&
chartRef.current.options.scales &&
chartRef.current.options.scales.x
) {
const chart = chartRef.current;
chart.options.scales.x.min = new Date(latestVonDatum).getTime();
chart.options.scales.x.max = new Date(latestBisDatum).getTime();
// Aktualisiere die Daten des Diagramms
const chartKey = selectedAnalogInput?.id
? String(selectedAnalogInput.id + 99)
: null;
const inputData = chartKey ? data[chartKey] ?? [] : [];
const filteredData = inputData.filter((point) => {
const date = new Date(point.t);
const from = new Date(latestVonDatum);
const to = new Date(latestBisDatum);
return (!from || date >= from) && (!to || date <= to);
});
chart.data.datasets = [
{
label: selectedAnalogInput?.label
? `Messwerteingang ${selectedAnalogInput.label}`
: "Messwerte",
data: filteredData.map((point) => ({
x: new Date(point.t),
y: point.m,
})),
fill: false,
borderColor: getColor("littwin-blue"),
backgroundColor: "rgba(59,130,246,0.3)",
borderWidth: 2,
pointRadius: 0,
tension: 0.1,
},
];
chart.update("none");
}
};
// ✅ Filtere Daten aus Redux
// ✅ Chart-Daten aus Redux filtern (Chart reagiert nur nach Button)
const chartKey = selectedAnalogInput?.id
? String(selectedAnalogInput.id + 99)
: null;
const inputData = chartKey ? data[chartKey] ?? [] : [];
// ✅ Zeitbereich anwenden (nur Anzeige gefiltert)
const filteredData = inputData.filter((point) => {
const date = new Date(point.t);
const from = vonDatumRedux ? new Date(vonDatumRedux) : null;
const to = bisDatumRedux ? new Date(bisDatumRedux) : null;
return (!from || date >= from) && (!to || date <= to);
});
useEffect(() => {
const today = new Date();
const vor30Tagen = new Date(today);
vor30Tagen.setDate(today.getDate() - 30);
if (!vonDatum) dispatch(setVonDatum(vor30Tagen.toISOString().slice(0, 10)));
if (!bisDatum) dispatch(setBisDatum(today.toISOString().slice(0, 10)));
}, [dispatch, vonDatum, bisDatum]);
const handleFetchChartData = () => {
if (!selectedId) return;
dispatch(
getAnalogInputsHistoryThunk({
eingang: selectedId,
zeitraum,
vonDatum,
bisDatum,
})
);
};
const dataKey = selectedId ? String(selectedId + 99) : null;
let filteredPoints: AnalogInputHistoryPoint[] = [];
if (dataKey && data[dataKey]) {
const fromDate = vonDatum ? new Date(vonDatum) : null;
const toDate = bisDatum ? new Date(bisDatum) : null;
filteredPoints = data[dataKey].filter((p: AnalogInputHistoryPoint) => {
const pointDate = new Date(p.t);
return (
(!fromDate || pointDate >= fromDate) && (!toDate || pointDate <= toDate)
);
});
}
const chartData = {
const memoizedChartData = React.useMemo(() => {
return {
datasets:
filteredPoints.length > 0
filteredData.length > 0
? zeitraum === "DIA0"
? [
{
@@ -214,9 +141,8 @@ export default function AnalogInputsChart() {
? `Messwert (m) ${selectedAnalogInput.label}`
: "Messwert (m)",
data: filteredData
.filter((point) => typeof point.m === "number")
.map((point) => ({ x: new Date(point.t), y: point.m })),
fill: false,
.filter((p) => typeof p.m === "number")
.map((p) => ({ x: new Date(p.t), y: p.m })),
borderColor: getColor("littwin-blue"),
backgroundColor: "rgba(59,130,246,0.3)",
borderWidth: 2,
@@ -226,25 +152,23 @@ export default function AnalogInputsChart() {
{
label: "Minimum (i)",
data: filteredData
.filter((point) => typeof point.i === "number")
.map((point) => ({ x: new Date(point.t), y: point.i })),
fill: false,
borderColor: "gray", // grau
.filter((p) => typeof p.i === "number")
.map((p) => ({ x: new Date(p.t), y: p.i })),
borderColor: "gray",
borderDash: [4, 2],
borderWidth: 1,
pointRadius: 0,
borderDash: [4, 2],
tension: 0.1,
},
{
label: "Maximum (a)",
data: filteredData
.filter((point) => typeof point.a === "number")
.map((point) => ({ x: new Date(point.t), y: point.a })),
fill: false,
borderColor: "gray", // rot
.filter((p) => typeof p.a === "number")
.map((p) => ({ x: new Date(p.t), y: p.a })),
borderColor: "gray",
borderDash: [4, 2],
borderWidth: 1,
pointRadius: 0,
borderDash: [4, 2],
tension: 0.1,
},
]
@@ -252,33 +176,30 @@ export default function AnalogInputsChart() {
{
label: "Minimum (i)",
data: filteredData
.filter((point) => typeof point.i === "number")
.map((point) => ({ x: new Date(point.t), y: point.i })),
fill: false,
borderColor: "gray", // grün
.filter((p) => typeof p.i === "number")
.map((p) => ({ x: new Date(p.t), y: p.i })),
borderColor: "gray",
borderDash: [4, 2],
borderWidth: 1,
pointRadius: 0,
borderDash: [4, 2],
tension: 0.1,
},
{
label: "Maximum (a)",
data: filteredData
.filter((point) => typeof point.a === "number")
.map((point) => ({ x: new Date(point.t), y: point.a })),
fill: false,
borderColor: "gray", // rot
.filter((p) => typeof p.a === "number")
.map((p) => ({ x: new Date(p.t), y: p.a })),
borderColor: "gray",
borderDash: [4, 2],
borderWidth: 1,
pointRadius: 0,
borderDash: [4, 2],
tension: 0.1,
},
{
label: "Durchschnitt (g)",
data: filteredData
.filter((point) => typeof point.g === "number")
.map((point) => ({ x: new Date(point.t), y: point.g })),
fill: false,
.filter((p) => typeof p.g === "number")
.map((p) => ({ x: new Date(p.t), y: p.g })),
borderColor: getColor("littwin-blue"),
backgroundColor: "rgba(59,130,246,0.3)",
borderWidth: 2,
@@ -288,8 +209,10 @@ export default function AnalogInputsChart() {
]
: [],
};
}, [filteredData, zeitraum, selectedAnalogInput]);
const chartOptions = {
const memoizedChartOptions = React.useMemo(() => {
return {
responsive: true,
plugins: {
legend: { position: "top" as const },
@@ -297,12 +220,12 @@ export default function AnalogInputsChart() {
mode: "index" as const,
intersect: false,
callbacks: {
label: function (context: TooltipItem<"line">) {
label: (context: TooltipItem<"line">) => {
const label = context.dataset.label || "";
return `${label}: ${context.parsed.y}`;
},
title: function (tooltipItems: TooltipItem<"line">[]) {
const date = tooltipItems[0].parsed.x;
title: (items: TooltipItem<"line">[]) => {
const date = items[0].parsed.x;
return `Zeitpunkt: ${new Date(date).toLocaleString("de-DE")}`;
},
},
@@ -314,11 +237,14 @@ export default function AnalogInputsChart() {
: "Messwert-Verlauf",
},
zoom: {
pan: { enabled: true, mode: "x" as const },
pan: {
enabled: true,
mode: "x",
},
zoom: {
wheel: { enabled: true },
pinch: { enabled: true },
mode: "x" as const,
mode: "x",
},
},
},
@@ -334,7 +260,6 @@ export default function AnalogInputsChart() {
},
adapters: { date: { locale: de } },
title: { display: true, text: "Zeit" },
// ✅ Hier definieren wir den sichtbaren Bereich dynamisch
min: vonDatum ? new Date(vonDatum).getTime() : undefined,
max: bisDatum ? new Date(bisDatum).getTime() : undefined,
},
@@ -346,11 +271,9 @@ export default function AnalogInputsChart() {
},
},
};
// DateRangePicker Event → Redux-Datum setzen (aber KEIN Fetch!)
const handleDateChange = (from: string, to: string) => {
dispatch(setVonDatum(from));
dispatch(setBisDatum(to));
};
}, [vonDatum, bisDatum, selectedAnalogInput]);
// ✅ AutoLoad nur beim ersten Laden
useEffect(() => {
if (autoLoad && selectedId) {
dispatch(
@@ -361,15 +284,30 @@ export default function AnalogInputsChart() {
bisDatum,
})
);
dispatch(setAutoLoad(false)); // ✅ zurücksetzen, sonst endlose Schleife
dispatch(setAutoLoad(false));
}
}, [autoLoad, selectedId, dispatch, zeitraum, vonDatum, bisDatum]);
// Dynamisches Importieren von chartjs-plugin-zoom nur im Browser
useEffect(() => {
if (typeof window !== "undefined") {
import("chartjs-plugin-zoom").then((module) => {
ChartJS.register(module.default);
});
}
}, []);
return (
<div className="flex flex-col gap-3">
<div className="flex flex-wrap items-center gap-4 mb-2">
<DateRangePicker />
{/* ✅ Neuer DatePicker mit schönem Styling (lokal, ohne Redux) */}
<AnalogInputsDatePicker
from={localVonDatum}
to={localBisDatum}
onChange={handleDateChange}
/>
{/* ✅ Zeitraum-Auswahl (Listbox nur lokal) */}
<Listbox value={localZeitraum} onChange={setLocalZeitraum}>
<div className="relative w-48">
<Listbox.Button className="w-full border px-3 py-1 rounded bg-white flex justify-between items-center text-sm">
@@ -400,6 +338,7 @@ export default function AnalogInputsChart() {
</div>
</Listbox>
{/* ✅ Button: lädt die Daten & aktualisiert Redux */}
<button
onClick={handleFetchData}
className="px-4 py-1 bg-littwin-blue text-white rounded text-sm"
@@ -408,20 +347,21 @@ export default function AnalogInputsChart() {
</button>
</div>
{/* Chart-Anzeige */}
<div className="h-[50vh] w-full">
{!selectedAnalogInput?.id ? (
<div className="flex items-center justify-center h-full text-gray-500 text-lg gap-2">
<i
className="bi bi-info-circle text-2xl mr-2"
aria-hidden="true"
></i>
<i className="bi bi-info-circle text-2xl mr-2" />
<span>
Bitte wählen Sie einen Eingang aus von der Tabelle, um die
Messkurve anzuzeigen
Bitte wählen Sie einen Eingang aus, um die Messkurve anzuzeigen
</span>
</div>
) : (
<Line ref={chartRef} data={chartData} options={chartOptions} />
<Line
ref={chartRef}
data={memoizedChartData}
options={memoizedChartOptions}
/>
)}
</div>
</div>

View File

@@ -0,0 +1,93 @@
"use client";
// components/main/analogInputs/AnalogInputsDatePicker.tsx
import React, { useEffect, useState } from "react";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
type Props = {
from: string;
to: string;
onChange: (from: string, to: string) => void;
};
export default function AnalogInputsDatePicker({ from, to, onChange }: Props) {
const today = new Date();
const thirtyDaysAgo = new Date();
thirtyDaysAgo.setDate(today.getDate() - 30);
const sixMonthsAgo = new Date();
sixMonthsAgo.setMonth(today.getMonth() - 6);
// interne Date-Objekte für react-datepicker
const parseISO = (dateStr: string) => {
if (!dateStr) return null;
const [year, month, day] = dateStr.split("-").map(Number);
return new Date(year, month - 1, day);
};
const formatISO = (date: Date) => date.toLocaleDateString("sv-SE"); // yyyy-MM-dd
const [localFromDate, setLocalFromDate] = useState<Date | null>(
from ? parseISO(from) : thirtyDaysAgo
);
const [localToDate, setLocalToDate] = useState<Date | null>(
to ? parseISO(to) : today
);
// Wenn Props von außen kommen (z.B. Reset), synchronisieren
useEffect(() => {
if (from) setLocalFromDate(parseISO(from));
if (to) setLocalToDate(parseISO(to));
}, [from, to]);
const handleFromChange = (date: Date | null) => {
setLocalFromDate(date);
if (date && localToDate) {
onChange(formatISO(date), formatISO(localToDate));
}
};
const handleToChange = (date: Date | null) => {
setLocalToDate(date);
if (localFromDate && date) {
onChange(formatISO(localFromDate), formatISO(date));
}
};
return (
<div className="flex space-x-4 items-center">
{/* Von */}
<div className="flex items-center space-x-2">
<label className="block text-sm font-semibold">Von</label>
<DatePicker
selected={localFromDate}
onChange={handleFromChange}
selectsStart
startDate={localFromDate}
endDate={localToDate}
minDate={sixMonthsAgo}
maxDate={today}
dateFormat="dd.MM.yyyy"
className="border px-2 py-1 rounded"
/>
</div>
{/* Bis */}
<div className="flex items-center space-x-2">
<label className="block text-sm font-semibold">Bis</label>
<DatePicker
selected={localToDate}
onChange={handleToChange}
selectsEnd
startDate={localFromDate}
endDate={localToDate}
minDate={sixMonthsAgo}
maxDate={today}
dateFormat="dd.MM.yyyy"
className="border px-2 py-1 rounded"
/>
</div>
</div>
);
}

4
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "cpl-v4",
"version": "1.6.618",
"version": "1.6.623",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "cpl-v4",
"version": "1.6.618",
"version": "1.6.623",
"dependencies": {
"@fontsource/roboto": "^5.1.0",
"@headlessui/react": "^2.2.4",

View File

@@ -1,6 +1,6 @@
{
"name": "cpl-v4",
"version": "1.6.618",
"version": "1.6.623",
"private": true,
"scripts": {
"dev": "next dev",