feat: add modal dialog, paged results, scan status, and trend value table components
- Introduced ModalDialog component for displaying modal dialogs with accessibility features. - Added PagedResults component to handle pagination of items with customizable rendering. - Created ScanStatus component to display the status of a scan with elapsed time. - Implemented TrendValueTable component for displaying trend data in a paginated table format. - Added measurement utility functions for formatting and validating measurement values. - Included tests for measurement functions and trend series fetching logic to ensure correctness.
This commit is contained in:
1 parent
c19c77334f
commit
a8b6cd4061
23 files changed
+1479
-2157
No files matched your search
+343
-297
File diff suppressed because it is too large.
Load diff
@@ -1,8 +1,10 @@
|
||||
export default function Gauge({ value, min = 0, max = 100, label, unit, timestamp }) {
|
||||
import { formatMeasurement, measurementNumber } from "./measurement.mjs";
|
||||
|
||||
export default function Gauge({ value, min = 0, max = 100, label, unit, timestamp }) {
|
||||
const safeMin = Number.isFinite(Number(min)) ? Number(min) : 0;
|
||||
const safeMax = Number.isFinite(Number(max)) ? Number(max) : 100;
|
||||
const safeValue = Number.isFinite(Number(value)) ? Number(value) : safeMin;
|
||||
const ratio = Math.max(0, Math.min(1, (safeValue - safeMin) / (safeMax - safeMin || 1)));
|
||||
const numeric = measurementNumber(value);
|
||||
const ratio = numeric === null ? 0 : Math.max(0, Math.min(1, (numeric - safeMin) / (safeMax - safeMin || 1)));
|
||||
const angle = -110 + ratio * 220;
|
||||
const radians = (angle * Math.PI) / 180;
|
||||
const cx = 110;
|
||||
@@ -13,25 +15,25 @@
|
||||
|
||||
return (
|
||||
<div className="gauge-card">
|
||||
<svg viewBox="0 0 220 150" className="gauge-svg">
|
||||
<svg viewBox="0 0 220 150" className="gauge-svg" aria-hidden="true">
|
||||
<path d="M25 110 A85 85 0 0 1 195 110" className="gauge-track" />
|
||||
<path
|
||||
{numeric !== null ? <path
|
||||
d={`M110 110 L${x.toFixed(1)} ${y.toFixed(1)}`}
|
||||
className="gauge-needle"
|
||||
/>
|
||||
/> : null}
|
||||
<circle cx="110" cy="110" r="7" className="gauge-center" />
|
||||
</svg>
|
||||
<div className="gauge-current">Aktuell</div>
|
||||
<div className="gauge-value">
|
||||
<span>{Number.isFinite(safeValue) ? safeValue.toFixed(2) : "--"}</span>
|
||||
<small>{unit}</small>
|
||||
<span>{formatMeasurement(numeric)}</span>
|
||||
{numeric !== null ? <small>{unit}</small> : null}
|
||||
</div>
|
||||
<div className="gauge-label">{label}</div>
|
||||
<div className="gauge-range">
|
||||
<span>{safeMin}</span>
|
||||
<span>{safeMax}</span>
|
||||
</div>
|
||||
<div className="gauge-stamp">{timestampLabel}</div>
|
||||
{numeric !== null || timestamp ? <div className="gauge-stamp">{timestampLabel}</div> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { useLayoutEffect, useRef } from "react";
|
||||
|
||||
export default function ModalDialog({ titleId, trigger, onDismiss, children }) {
|
||||
const ref = useRef(null);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const dialog = ref.current;
|
||||
const opener = trigger || document.activeElement;
|
||||
dialog.showModal();
|
||||
return () => {
|
||||
if (dialog.open) dialog.close();
|
||||
if (opener?.isConnected) opener.focus();
|
||||
else document.querySelector("main h1")?.focus();
|
||||
};
|
||||
}, [trigger]);
|
||||
|
||||
return (
|
||||
<dialog ref={ref} className="modal-card source-modal" aria-labelledby={titleId}
|
||||
onCancel={(event) => { event.preventDefault(); onDismiss(); }}>
|
||||
{children}
|
||||
</dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { useState } from "react";
|
||||
|
||||
export default function PagedResults({ items, render, listClassName, empty, pageSize = 48 }) {
|
||||
const [page, setPage] = useState(0);
|
||||
const count = Math.ceil(items.length / pageSize);
|
||||
const current = Math.min(page, Math.max(0, count - 1));
|
||||
const start = current * pageSize;
|
||||
const end = Math.min(start + pageSize, items.length);
|
||||
if (!items.length) return empty ?? null;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="button-row table-pagination">
|
||||
{count > 1 ? <button type="button" className="ghost-button compact-button" disabled={current === 0} onClick={() => setPage(current - 1)}>Zurück</button> : null}
|
||||
<small role="status">{start + 1}–{end} von {items.length.toLocaleString("de-DE")}</small>
|
||||
{count > 1 ? <button type="button" className="ghost-button compact-button" disabled={current + 1 >= count} onClick={() => setPage(current + 1)}>Weiter</button> : null}
|
||||
</div>
|
||||
<div className={listClassName} key={current}>{items.slice(start, end).map(render)}</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
export default function ScanStatus({ status }) {
|
||||
const [now, setNow] = useState(Date.now);
|
||||
const startedAt = status?.phase === "running" ? status.startedAt : null;
|
||||
useEffect(() => {
|
||||
if (startedAt === null) return;
|
||||
const timer = window.setInterval(() => setNow(Date.now()), 1000);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [startedAt]);
|
||||
if (!status) return null;
|
||||
|
||||
const elapsed = Math.floor(Math.max(0, now - status.startedAt) / 1000);
|
||||
return (
|
||||
<div className="scan-status">
|
||||
<small role={status.phase === "error" ? "alert" : "status"}>{status.message}</small>
|
||||
{startedAt !== null ? <small aria-hidden="true">{elapsed} s</small> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -19,7 +19,7 @@ function linkMonogram(label) {
|
||||
|
||||
function SidebarIcon({ name }) {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
|
||||
<path d={icons[name]} />
|
||||
</svg>
|
||||
);
|
||||
@@ -38,12 +38,9 @@ export default function Sidebar({ collapsed, onToggle, views, activeView, onNavi
|
||||
<div className="sidebar-top">
|
||||
<div className="sidebar-brand-row">
|
||||
<div className="logo-lockup">
|
||||
<img src="/logo.png" alt="SE Logo" />
|
||||
<img src="/logo.png" alt={collapsed ? "SE" : ""} />
|
||||
{collapsed ? null : (
|
||||
<div>
|
||||
<div className="eyebrow">SE</div>
|
||||
<div className="logo-title">SE Local Trenddata.</div>
|
||||
</div>
|
||||
<div className="logo-title">SE Local Trenddata</div>
|
||||
)}
|
||||
</div>
|
||||
<button type="button" className="icon-button sidebar-toggle" title={toggleLabel} aria-label={toggleLabel} aria-expanded={!collapsed} onClick={onToggle}>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useMemo, useRef, useState } from "react";
|
||||
import { useId, useMemo, useRef, useState } from "react";
|
||||
import { jsPDF } from "jspdf";
|
||||
import * as XLSX from "xlsx";
|
||||
import {
|
||||
@@ -6,15 +6,18 @@ import {
|
||||
Customized,
|
||||
Line,
|
||||
LineChart,
|
||||
ReferenceLine,
|
||||
ResponsiveContainer,
|
||||
Tooltip,
|
||||
XAxis,
|
||||
YAxis,
|
||||
} from "recharts";
|
||||
import TrendChartSettings from "./TrendChartSettings.jsx";
|
||||
import TrendValueTable from "./TrendValueTable.jsx";
|
||||
import { formatMeasurement } from "./measurement.mjs";
|
||||
import { getTimeZoom, getTrendAxes, getTrendAxisScale, seriesAxisId } from "./trend-scales.mjs";
|
||||
import { DEFAULT_CHART_SETTINGS } from "../../../shared/trend-chart-settings.mjs";
|
||||
import { assignTrendColors } from "./trend-colors.mjs";
|
||||
import { assignTrendColors, trendDashPattern } from "./trend-colors.mjs";
|
||||
|
||||
function downloadBlob(filename, blob) {
|
||||
const url = URL.createObjectURL(blob);
|
||||
@@ -30,8 +33,7 @@ function quoteCell(value) {
|
||||
}
|
||||
|
||||
function formatTrendNumber(value) {
|
||||
const numeric = Number(value);
|
||||
return Number.isFinite(numeric) ? numeric.toFixed(2) : "--";
|
||||
return formatMeasurement(value);
|
||||
}
|
||||
|
||||
function TimeZoomOverlay({ offset, onZoom, touchMode }) {
|
||||
@@ -109,14 +111,17 @@ export default function TrendChart({
|
||||
savingSettings,
|
||||
}) {
|
||||
const chartHostRef = useRef(null);
|
||||
const hintId = useId();
|
||||
const [cursor, setCursor] = useState(null);
|
||||
const [selectedKeys, setSelectedKeys] = useState([]);
|
||||
const [zoomDomain, setZoomDomain] = useState(null);
|
||||
const [exportFormat, setExportFormat] = useState("csv");
|
||||
const [transparentBackground, setTransparentBackground] = useState(false);
|
||||
|
||||
const series = useMemo(() => assignTrendColors(result?.series || [])
|
||||
.map((item) => ({
|
||||
.map((item, index) => ({
|
||||
...item,
|
||||
dash: trendDashPattern(index),
|
||||
name: `${item.displayName} · ${item.alias}${item.unit ? ` (${item.unit})` : ""}`,
|
||||
})), [result]);
|
||||
|
||||
@@ -130,6 +135,11 @@ export default function TrendChart({
|
||||
: [(rows[0]?.timestampMs ?? 0) - 1000, (rows[0]?.timestampMs ?? 0) + 1000];
|
||||
const activeZoom = zoomDomain && zoomDomain.result === result ? zoomDomain.domain : null;
|
||||
const xDomain = activeZoom || baseXDomain;
|
||||
const visibleRows = useMemo(() => activeZoom
|
||||
? rows.filter((row) => row.timestampMs >= activeZoom[0] && row.timestampMs <= activeZoom[1])
|
||||
: rows, [activeZoom, rows]);
|
||||
const cursorIndex = cursor?.rows === visibleRows ? cursor.index : -1;
|
||||
const cursorRow = visibleRows[cursorIndex];
|
||||
const axes = useMemo(() => getTrendAxes(series, settings.assignments).map((axis) => ({
|
||||
...axis,
|
||||
scale: getTrendAxisScale(axis, settings.axes[axis.id], rows, activeZoom, settings.divisions),
|
||||
@@ -138,8 +148,23 @@ export default function TrendChart({
|
||||
const activeKeys = new Set(series.filter((entry) => selectedKeys.includes(entry.key)).map((entry) => entry.key));
|
||||
const hasFocusSelection = activeKeys.size > 0 && activeKeys.size < series.length;
|
||||
const seriesLimited = result?.requestedSeriesCount > result?.maxSeries;
|
||||
const rowLimitAdjusted = result?.effectiveMaxRows != null && result.effectiveMaxRows !== result.requestedMaxRows;
|
||||
const normalizedLineWidth = Number.isFinite(Number(lineWidth)) ? Number(lineWidth) : 1.8;
|
||||
|
||||
function moveCursor(event) {
|
||||
if (event.target !== event.currentTarget || visibleRows.length === 0) return;
|
||||
const last = visibleRows.length - 1;
|
||||
const next = {
|
||||
ArrowLeft: cursorIndex < 0 ? last : Math.max(0, cursorIndex - 1),
|
||||
ArrowRight: Math.min(last, cursorIndex + 1),
|
||||
Home: 0,
|
||||
End: last,
|
||||
}[event.key];
|
||||
if (next === undefined) return;
|
||||
event.preventDefault();
|
||||
setCursor({ rows: visibleRows, index: next });
|
||||
}
|
||||
|
||||
function zoomTime(start, end) {
|
||||
const domain = getTimeZoom(xDomain, start, end);
|
||||
if (domain) setZoomDomain({ result, domain });
|
||||
@@ -296,8 +321,8 @@ export default function TrendChart({
|
||||
if (!rows.length) {
|
||||
return (
|
||||
<div className={compact ? "panel chart-panel compact-chart empty-state" : "panel chart-panel empty-state"}>
|
||||
<h3>{title}</h3>
|
||||
<p>Keine Daten im gewählten Zeitraum.</p>
|
||||
{!compact ? <h3>{title}</h3> : null}
|
||||
<p>Keine Daten im gewählten Zeitraum</p>
|
||||
{seriesLimited ? <small>Diagrammlimit: {result.maxSeries} von {result.requestedSeriesCount} Datenpunkten.</small> : null}
|
||||
</div>
|
||||
);
|
||||
@@ -305,16 +330,16 @@ export default function TrendChart({
|
||||
|
||||
return (
|
||||
<div className={expanded ? "panel chart-panel focus-mode" : compact ? "panel chart-panel compact-chart" : "panel chart-panel"}>
|
||||
<div className="panel-header compact-header chart-toolbar">
|
||||
{!compact || allowExports || onSettingsChange || allowFocusMode || activeZoom || touchMode ? <div className="panel-header compact-header chart-toolbar">
|
||||
<div>
|
||||
<h3>{title}</h3>
|
||||
{rows.length > 1 && !compact ? <p>{touchMode ? "Zeitzoom mit + und − einstellen." : "Zum Zeitzoom einen Bereich im Diagramm aufziehen."}</p> : null}
|
||||
{!compact ? <h3>{title}</h3> : null}
|
||||
{rows.length > 1 && !compact ? <p>{touchMode ? "Zeitzoom mit + und − einstellen" : "Zum Zoomen einen Zeitbereich im Diagramm markieren"}</p> : null}
|
||||
{seriesLimited ? <p>Diagrammlimit: {result.maxSeries} von {result.requestedSeriesCount} Datenpunkten.</p> : null}
|
||||
</div>
|
||||
<div className="chart-actions">
|
||||
{allowExports ? (
|
||||
<>
|
||||
<select value={exportFormat} onChange={(event) => setExportFormat(event.target.value)}>
|
||||
<select aria-label="Exportformat" value={exportFormat} onChange={(event) => setExportFormat(event.target.value)}>
|
||||
<option value="csv">CSV</option>
|
||||
<option value="xlsx">XLSX</option>
|
||||
<option value="png">PNG</option>
|
||||
@@ -323,7 +348,7 @@ export default function TrendChart({
|
||||
<option value="pdf">PDF</option>
|
||||
</select>
|
||||
{exportFormat === "csv" ? (
|
||||
<select value={csvDelimiter} onChange={(event) => onCsvDelimiterChange?.(event.target.value)}>
|
||||
<select aria-label="CSV-Trennzeichen" value={csvDelimiter} onChange={(event) => onCsvDelimiterChange?.(event.target.value)}>
|
||||
<option value=";">; Trennzeichen</option>
|
||||
<option value=",">, Trennzeichen</option>
|
||||
<option value="\t">Tab Trennzeichen</option>
|
||||
@@ -353,12 +378,21 @@ export default function TrendChart({
|
||||
{activeZoom ? <button className="ghost-button" type="button" onClick={() => setZoomDomain(null)}>Zoom zurück</button> : null}
|
||||
{allowFocusMode ? <button className="ghost-button" type="button" onClick={onToggleExpanded}>{expanded ? "Normalansicht" : "Vollbild"}</button> : null}
|
||||
</div>
|
||||
</div>
|
||||
</div> : seriesLimited ? <small>Diagrammlimit: {result.maxSeries} von {result.requestedSeriesCount} Datenpunkten</small> : null}
|
||||
|
||||
<div className={settings.highContrast ? "chart-wrapper high-contrast" : "chart-wrapper"}>
|
||||
<div ref={chartHostRef} className="chart-host" style={{ minWidth: 220 + axes.length * 64 }}>
|
||||
<ResponsiveContainer width="100%" height={expanded ? 680 : compact ? 280 : 360}>
|
||||
<LineChart data={rows} margin={{ top: 8, right: 18, left: 0, bottom: 8 }}>
|
||||
{rowLimitAdjusted || result?.rowLimitReached ? (
|
||||
<p className="warning-note">
|
||||
{rows.length.toLocaleString("de-DE")} Zeitpunkte geladen (Limit: {result.effectiveMaxRows.toLocaleString("de-DE")}).
|
||||
{result.rowLimitReached ? " Ältere Messwerte im gewählten Zeitraum wurden nicht geladen." : ""}
|
||||
</p>
|
||||
) : null}
|
||||
<small id={hintId}>Messwerte mit Pfeiltasten erkunden, mit Pos1 oder Ende zum Rand springen</small>
|
||||
<div className={settings.highContrast ? "chart-wrapper high-contrast" : "chart-wrapper"}
|
||||
role="group" aria-label={`Diagramm: ${title}`} aria-describedby={hintId} tabIndex={0} onKeyDown={moveCursor}
|
||||
aria-keyshortcuts="ArrowLeft ArrowRight Home End">
|
||||
<div ref={chartHostRef} className="chart-host chart-plot" style={{ minWidth: 220 + axes.length * 64 }} aria-hidden="true">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<LineChart data={rows} margin={{ top: 8, right: 16, left: 12, bottom: 8 }}>
|
||||
<CartesianGrid
|
||||
horizontal={settings.grid === "both" || settings.grid === "horizontal"}
|
||||
vertical={settings.grid === "both" || settings.grid === "vertical"}
|
||||
@@ -375,7 +409,8 @@ export default function TrendChart({
|
||||
allowDataOverflow
|
||||
tickCount={settings.divisions + 1}
|
||||
tickFormatter={(value) => new Date(value).toLocaleString("de-DE", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" })}
|
||||
minTickGap={28}
|
||||
minTickGap={32}
|
||||
tick={{ fontSize: 11, fill: "var(--trend-axis)" }}
|
||||
stroke="var(--trend-axis)"
|
||||
/>
|
||||
{axes.map((axis, index) => (
|
||||
@@ -389,7 +424,7 @@ export default function TrendChart({
|
||||
stroke="var(--trend-axis)"
|
||||
allowDataOverflow
|
||||
interval={0}
|
||||
tick={{ fontSize: 10 }}
|
||||
tick={{ fontSize: 11, fill: "var(--trend-axis)" }}
|
||||
tickFormatter={axis.digital ? String : formatTrendNumber}
|
||||
label={axis.unit ? {
|
||||
value: axis.unit,
|
||||
@@ -411,6 +446,9 @@ export default function TrendChart({
|
||||
fontSize: 12,
|
||||
}}
|
||||
/>
|
||||
{cursorRow && axes.length ? (
|
||||
<ReferenceLine x={cursorRow.timestampMs} yAxisId={0} stroke="var(--trend-axis)" strokeDasharray="4 3" />
|
||||
) : null}
|
||||
{series.map((entry) => {
|
||||
const isolated = hasFocusSelection && !activeKeys.has(entry.key);
|
||||
return (
|
||||
@@ -423,6 +461,7 @@ export default function TrendChart({
|
||||
connectNulls
|
||||
strokeWidth={normalizedLineWidth + (settings.highContrast ? 0.6 : 0) + (activeKeys.has(entry.key) ? 0.55 : 0)}
|
||||
stroke={entry.color}
|
||||
strokeDasharray={entry.dash}
|
||||
strokeOpacity={(isolated ? 0.1 : 1) * settings.opacity / 100}
|
||||
isAnimationActive={false}
|
||||
name={entry.name}
|
||||
@@ -434,6 +473,18 @@ export default function TrendChart({
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
</div>
|
||||
<div className="trend-cursor" role="status" aria-atomic="true">
|
||||
{cursorRow ? (
|
||||
<>
|
||||
<strong>{new Date(cursorRow.timestampMs).toLocaleString("de-DE")}</strong>
|
||||
<ul>{series.map((entry) => (
|
||||
<li key={entry.key}>
|
||||
{entry.name}: {formatMeasurement(cursorRow[entry.key])}
|
||||
</li>
|
||||
))}</ul>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="legend-row">
|
||||
<div className="legend-grid">
|
||||
@@ -445,9 +496,12 @@ export default function TrendChart({
|
||||
key={entry.key}
|
||||
type="button"
|
||||
className={active ? "legend-item active" : dimmed ? "legend-item dimmed" : "legend-item"}
|
||||
aria-pressed={active}
|
||||
onClick={(event) => handleLegendClick(event, entry.key)}
|
||||
>
|
||||
<span className="legend-swatch" style={{ background: entry.color }} />
|
||||
<svg className="legend-swatch" viewBox="0 0 32 6" aria-hidden="true">
|
||||
<line x1="0" x2="32" y1="3" y2="3" stroke={entry.color} strokeWidth="2" strokeDasharray={entry.dash} />
|
||||
</svg>
|
||||
<span>{entry.name}</span>
|
||||
</button>
|
||||
);
|
||||
@@ -459,6 +513,7 @@ export default function TrendChart({
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
<TrendValueTable rows={visibleRows} series={series} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { useState } from "react";
|
||||
import { formatMeasurement } from "./measurement.mjs";
|
||||
|
||||
const PAGE_SIZE = 20;
|
||||
|
||||
export default function TrendValueTable({ rows, series }) {
|
||||
const [page, setPage] = useState(0);
|
||||
const pageCount = Math.max(1, Math.ceil(rows.length / PAGE_SIZE));
|
||||
const current = Math.min(page, pageCount - 1);
|
||||
const start = current * PAGE_SIZE;
|
||||
const end = Math.min(start + PAGE_SIZE, rows.length);
|
||||
|
||||
return (
|
||||
<details className="trend-value-table">
|
||||
<summary>Messwerte als Tabelle ({rows.length.toLocaleString("de-DE")})</summary>
|
||||
{rows.length === 0 ? <p>Keine Messwerte im sichtbaren Zeitbereich</p> : (
|
||||
<>
|
||||
<div className="button-row table-pagination" aria-label="Tabellenseiten">
|
||||
<button type="button" className="ghost-button compact-button" disabled={current === 0} onClick={() => setPage(current - 1)}>Vorherige Seite</button>
|
||||
<span role="status">Zeilen {start + 1}–{end} von {rows.length.toLocaleString("de-DE")}</span>
|
||||
<button type="button" className="ghost-button compact-button" disabled={current + 1 === pageCount} onClick={() => setPage(current + 1)}>Nächste Seite</button>
|
||||
</div>
|
||||
<div className="trend-table-scroll" role="region" aria-label="Messwerte im sichtbaren Zeitbereich" tabIndex={0}>
|
||||
<table className="trend-table" aria-label="Messwerte und Zeitstempel">
|
||||
<thead><tr><th scope="col">Zeitstempel</th>{series.map((entry) => <th key={entry.key} scope="col">{entry.name}</th>)}</tr></thead>
|
||||
<tbody>
|
||||
{rows.slice(start, end).map((row, index) => (
|
||||
<tr key={start + index}>
|
||||
<th scope="row"><time dateTime={new Date(row.timestampMs).toISOString()}>{new Date(row.timestampMs).toLocaleString("de-DE")}</time></th>
|
||||
{series.map((entry) => <td key={entry.key}>{formatMeasurement(row[entry.key])}</td>)}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</details>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
export function measurementNumber(value) {
|
||||
if (typeof value === "string" && !value.trim()) return null;
|
||||
if (!["number", "boolean", "string"].includes(typeof value)) return null;
|
||||
const numeric = Number(value);
|
||||
return Number.isFinite(numeric) ? numeric : null;
|
||||
}
|
||||
|
||||
export function formatMeasurement(value) {
|
||||
return measurementNumber(value)?.toFixed(2) ?? "Kein Messwert";
|
||||
}
|
||||
@@ -3,6 +3,11 @@ const PALETTE = [
|
||||
"#e03b53", "#167b93", "#3e7b0d", "#87543f", "#d14caa", "#4d6090",
|
||||
];
|
||||
|
||||
const DASH_PATTERNS = [undefined, "8 3", "2 3", "8 3 2 3", "4 4", "12 3", "2 2 2 5", "7 2 3 2", "3 5", "12 3 2 3"];
|
||||
export function trendDashPattern(index) {
|
||||
return index < DASH_PATTERNS.length ? DASH_PATTERNS[index] : `${14 + Math.floor(index / 5)} 3 ${2 + index % 5} 3`;
|
||||
}
|
||||
|
||||
function hexRgb(color) {
|
||||
const short = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec(color);
|
||||
const hex = short ? short.slice(1).map((digit) => digit.repeat(2)).join("") : color.slice(1);
|
||||
@@ -12,6 +17,28 @@ function hexRgb(color) {
|
||||
return null;
|
||||
}
|
||||
|
||||
function luminance(rgb) {
|
||||
return rgb.reduce((sum, value, index) => {
|
||||
const channel = value / 255;
|
||||
const linear = channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4;
|
||||
return sum + linear * [0.2126, 0.7152, 0.0722][index];
|
||||
}, 0);
|
||||
}
|
||||
|
||||
function accessibleAutomaticColor(color) {
|
||||
const rgb = hexRgb(color);
|
||||
const [dark, light] = ["#292e2c", "#f5f6f5"].map((background) => luminance(hexRgb(background)));
|
||||
const min = 3.2 * (dark + 0.05) - 0.05;
|
||||
const max = (light + 0.05) / 3.2 - 0.05;
|
||||
const target = luminance(rgb) < min ? 255 : 0;
|
||||
for (let percent = 0; percent < 100; percent += 1) {
|
||||
const candidate = rgb.map((channel) => Math.round(channel + (target - channel) * percent / 100));
|
||||
const value = luminance(candidate);
|
||||
if (value >= min && value <= max) return "#" + candidate.map((channel) => channel.toString(16).padStart(2, "0")).join("");
|
||||
}
|
||||
return "#797979";
|
||||
}
|
||||
|
||||
function distance(left, right) {
|
||||
const [red, green, blue] = left.map((channel, index) => channel - right[index]);
|
||||
const redMean = (left[0] + right[0]) / 512;
|
||||
@@ -49,7 +76,7 @@ export function assignTrendColors(series) {
|
||||
|
||||
const manual = series.filter((entry) => !isAutomaticColor(entry.color?.trim()));
|
||||
const used = manual.map((entry) => hexRgb(entry.color.trim())).filter(Boolean);
|
||||
const candidates = [...new Set(palette)].map((color) => ({
|
||||
const candidates = [...new Set(palette.map(accessibleAutomaticColor))].map((color) => ({
|
||||
color,
|
||||
rgb: hexRgb(color),
|
||||
contrast: Infinity,
|
||||
@@ -60,6 +87,7 @@ export function assignTrendColors(series) {
|
||||
used.forEach(compareTo);
|
||||
const colors = new Map();
|
||||
for (const entry of automatic) {
|
||||
if (candidates.length === 0) break;
|
||||
const best = candidates.reduce((index, candidate, current) => candidate.contrast > candidates[index].contrast ? current : index, 0);
|
||||
const [chosen] = candidates.splice(best, 1);
|
||||
colors.set(entry.key, chosen.color);
|
||||
|
||||
+649
-1797
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,74 @@
|
||||
import { strict as assert } from "node:assert";
|
||||
import { test } from "node:test";
|
||||
import { fetchTrendSeries, normalizeRange } from "../../api/src/lib/isp.js";
|
||||
import { maxTrendRowsForSeries } from "../../shared/trend-preferences.mjs";
|
||||
import { formatMeasurement, measurementNumber } from "../src/components/measurement.mjs";
|
||||
import { assignTrendColors, trendDashPattern } from "../src/components/trend-colors.mjs";
|
||||
|
||||
test("missing measurements do not become zero", () => {
|
||||
for (const value of [null, undefined, "", " ", NaN, Infinity, {}, []]) {
|
||||
assert.equal(measurementNumber(value), null);
|
||||
assert.equal(formatMeasurement(value), "Kein Messwert");
|
||||
}
|
||||
for (const value of [0, "0", false]) assert.equal(formatMeasurement(value), "0.00");
|
||||
assert.equal(formatMeasurement(17.25), "17.25");
|
||||
});
|
||||
|
||||
test("trend range preserves 20,000 by default and exposes the effective query cap", () => {
|
||||
assert.equal(normalizeRange({}, 1, 10).maxRows, 20_000);
|
||||
assert.equal(normalizeRange({ maxRows: 40_000 }, 1, 2).maxRows, 40_000);
|
||||
const capped = normalizeRange({ maxRows: 40_000 }, 1, 10);
|
||||
assert.equal(capped.requestedMaxRows, 40_000);
|
||||
assert.equal(capped.maxRows, maxTrendRowsForSeries(10));
|
||||
assert.equal(capped.maxRows, 25_000);
|
||||
assert.equal(normalizeRange({ maxRows: -1 }).maxRows, 100);
|
||||
assert.equal(normalizeRange({ maxRows: 100_000 }).maxRows, 50_000);
|
||||
});
|
||||
|
||||
test("trend samples are capped after merging sources and keep null distinct from zero", async () => {
|
||||
const points = [
|
||||
{ isp: "isp_a", pointIndex: 1 },
|
||||
{ isp: "isp_b", pointIndex: 1 },
|
||||
];
|
||||
const queriedLimits = [];
|
||||
const pool = {
|
||||
async query(sql, args) {
|
||||
if (sql.includes("information_schema.COLUMNS")) return [[{ columnName: "Wert1" }]];
|
||||
if (sql.includes("COUNT(*)")) return [[{ rowCount: 60 }]];
|
||||
if (sql.includes("source_datapoint_registry")) return [[]];
|
||||
if (sql.includes("Wert1")) {
|
||||
queriedLimits.push(args.at(-1));
|
||||
const offset = sql.includes("isp_a") ? 0 : 1;
|
||||
return [Array.from({ length: 60 }, (_, i) => ({
|
||||
datum: new Date(1_700_000_000_000 + (59 - i) * 2000 + offset * 1000),
|
||||
Wert1: i % 2 ? null : 0,
|
||||
}))];
|
||||
}
|
||||
throw new Error("Unexpected query in fixture: " + sql);
|
||||
},
|
||||
};
|
||||
const result = await fetchTrendSeries(pool, { get: async () => null, set: async () => {} }, points,
|
||||
normalizeRange({ maxRows: 100 }, 1, points.length));
|
||||
assert.deepEqual(queriedLimits, [101, 101]);
|
||||
assert.equal(result.rows.length, 100);
|
||||
assert.equal(result.effectiveMaxRows, 100);
|
||||
assert.equal(result.rowLimitReached, true);
|
||||
assert.equal(result.rows.at(-1)["isp_b:1"], 0);
|
||||
assert.equal(result.rows.at(-3)["isp_b:1"], null);
|
||||
});
|
||||
|
||||
test("automatic series have contrast in both themes and manual color is preserved", () => {
|
||||
const luminance = (hex) => hex.slice(1).match(/.{2}/g).map((value) => parseInt(value, 16) / 255)
|
||||
.map((channel) => channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4)
|
||||
.reduce((sum, value, idx) => sum + value * [0.2126, 0.7152, 0.0722][idx], 0);
|
||||
const series = assignTrendColors(Array.from({ length: 100 }, (_, index) =>
|
||||
({ key: String(index), color: index ? "#000000" : "#232323" })));
|
||||
assert.equal(series[0].color, "#232323");
|
||||
for (const { color } of series.slice(1)) {
|
||||
for (const theme of ["#292e2c", "#f5f6f5"]) {
|
||||
const [min, max] = [luminance(color), luminance(theme)].sort((a, b) => a - b);
|
||||
assert.ok((max + 0.05) / (min + 0.05) >= 3.2, color + " on " + theme);
|
||||
}
|
||||
}
|
||||
assert.equal(new Set(series.map((_, index) => trendDashPattern(index))).size, series.length);
|
||||
});
|
||||
Reference in new issue
Block a user