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
+1469
-2147
No files matched your search
+2
-1
@@ -835,7 +835,8 @@ async function getTrendDisplayOptions(user) {
|
||||
}
|
||||
|
||||
async function fetchDisplayTrend(points, range, { maxSeries, defaultPresetDays }) {
|
||||
const trend = await fetchTrendSeries(pool, redis, points.slice(0, maxSeries), normalizeRange(range, defaultPresetDays));
|
||||
const displayedPoints = points.slice(0, maxSeries);
|
||||
const trend = await fetchTrendSeries(pool, redis, displayedPoints, normalizeRange(range, defaultPresetDays, displayedPoints.length));
|
||||
return { ...trend, requestedSeriesCount: points.length, maxSeries };
|
||||
}
|
||||
|
||||
|
||||
+27
-10
@@ -1,5 +1,6 @@
|
||||
import { AUTO_UNIT, DEFAULT_ANALOG_UNIT, resolveEngineeringUnit } from "../../../shared/engineering-units.mjs";
|
||||
import { LEGACY_DATUM_UTC, LEGACY_TREND_TIME_ZONE } from "../../../shared/trend-time.mjs";
|
||||
import { DEFAULT_TREND_ROWS, MIN_TREND_ROWS, maxTrendRowsForSeries } from "../../../shared/trend-preferences.mjs";
|
||||
|
||||
const META_PREFIX = "meta:isp:";
|
||||
export const LEGACY_POINT_LIMIT = 200;
|
||||
@@ -554,6 +555,7 @@ export async function fetchTrendSeries(pool, redis, points, range) {
|
||||
}, new Map());
|
||||
|
||||
const mergedRows = new Map();
|
||||
let rowLimitReached = false;
|
||||
|
||||
for (const [isp, pointDescriptors] of grouped.entries()) {
|
||||
const tableInfo = await describeTrendTable(pool, null, isp);
|
||||
@@ -562,8 +564,9 @@ export async function fetchTrendSeries(pool, redis, points, range) {
|
||||
}
|
||||
|
||||
if (tableInfo.storage === "narrow") {
|
||||
const placeholders = pointDescriptors.map(() => "?").join(", ");
|
||||
const limit = Math.max(pointDescriptors.length, (range.maxRows || 4000) * Math.max(1, pointDescriptors.length));
|
||||
const byIndex = new Map(pointDescriptors.map((point) => [point.pointIndex, point]));
|
||||
const placeholders = Array.from(byIndex, () => "?").join(", ");
|
||||
const limit = range.maxRows * byIndex.size;
|
||||
const [rows] = await pool.query(
|
||||
`
|
||||
SELECT datum, point_index, value
|
||||
@@ -573,16 +576,20 @@ export async function fetchTrendSeries(pool, redis, points, range) {
|
||||
ORDER BY datum DESC, id DESC
|
||||
LIMIT ?
|
||||
`,
|
||||
[...pointDescriptors.map((descriptor) => descriptor.pointIndex), range.from, range.to, limit]
|
||||
[...byIndex.keys(), range.from, range.to, limit + 1]
|
||||
);
|
||||
|
||||
if (rows.length > limit) {
|
||||
rows.pop();
|
||||
rowLimitReached = true;
|
||||
}
|
||||
rows.reverse().forEach((row) => {
|
||||
const timestamp = new Date(row.datum).toISOString();
|
||||
if (!mergedRows.has(timestamp)) {
|
||||
mergedRows.set(timestamp, { timestamp });
|
||||
}
|
||||
const target = mergedRows.get(timestamp);
|
||||
const descriptor = pointDescriptors.find((item) => item.pointIndex === Number(row.point_index));
|
||||
const descriptor = byIndex.get(Number(row.point_index));
|
||||
if (!descriptor) {
|
||||
return;
|
||||
}
|
||||
@@ -596,16 +603,20 @@ export async function fetchTrendSeries(pool, redis, points, range) {
|
||||
const columns = pointDescriptors
|
||||
.map((descriptor) => `\`Wert${descriptor.pointIndex}\``)
|
||||
.join(", ");
|
||||
const limit = range.maxRows || 4000;
|
||||
const limit = range.maxRows;
|
||||
|
||||
const [rows] = await pool.query(
|
||||
`SELECT ${LEGACY_DATUM_UTC} AS datum, ${columns} FROM \`${isp}\`
|
||||
WHERE datum BETWEEN DATE_SUB(?, INTERVAL 1 DAY) AND DATE_ADD(?, INTERVAL 1 DAY)
|
||||
AND ${LEGACY_DATUM_UTC} BETWEEN ? AND ?
|
||||
ORDER BY \`${isp}\`.datum DESC LIMIT ?`,
|
||||
[LEGACY_TREND_TIME_ZONE, range.from, range.to, LEGACY_TREND_TIME_ZONE, range.from, range.to, limit]
|
||||
[LEGACY_TREND_TIME_ZONE, range.from, range.to, LEGACY_TREND_TIME_ZONE, range.from, range.to, limit + 1]
|
||||
);
|
||||
|
||||
if (rows.length > limit) {
|
||||
rows.pop();
|
||||
rowLimitReached = true;
|
||||
}
|
||||
rows.reverse().forEach((row) => {
|
||||
const timestamp = new Date(row.datum).toISOString();
|
||||
|
||||
@@ -624,9 +635,13 @@ export async function fetchTrendSeries(pool, redis, points, range) {
|
||||
});
|
||||
}
|
||||
|
||||
const sortedRows = [...mergedRows.values()].sort((left, right) => left.timestamp.localeCompare(right.timestamp));
|
||||
return {
|
||||
series: descriptors,
|
||||
rows: [...mergedRows.values()].sort((left, right) => left.timestamp.localeCompare(right.timestamp)),
|
||||
rows: sortedRows.slice(-range.maxRows),
|
||||
effectiveMaxRows: range.maxRows,
|
||||
requestedMaxRows: range.requestedMaxRows,
|
||||
rowLimitReached: rowLimitReached || sortedRows.length > range.maxRows,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -714,9 +729,10 @@ export async function fetchLatestValues(pool, redis, points) {
|
||||
return values;
|
||||
}
|
||||
|
||||
export function normalizeRange(input = {}, defaultPresetDays = 1) {
|
||||
export function normalizeRange(input = {}, defaultPresetDays = 1, seriesCount = 1) {
|
||||
const presetDays = Number(input.presetDays || defaultPresetDays);
|
||||
const maxRows = Number(input.maxRows || 4000);
|
||||
const maxRows = Number(input.maxRows || DEFAULT_TREND_ROWS);
|
||||
const requestedMaxRows = Number.isFinite(maxRows) ? Math.trunc(maxRows) : DEFAULT_TREND_ROWS;
|
||||
const now = new Date();
|
||||
const to = input.to ? new Date(input.to) : now;
|
||||
const from = input.from ? new Date(input.from) : new Date(now.getTime() - presetDays * 24 * 60 * 60 * 1000);
|
||||
@@ -724,7 +740,8 @@ export function normalizeRange(input = {}, defaultPresetDays = 1) {
|
||||
return {
|
||||
from,
|
||||
to,
|
||||
maxRows: Number.isFinite(maxRows) ? Math.max(100, Math.min(maxRows, 10000)) : 4000,
|
||||
requestedMaxRows,
|
||||
maxRows: Math.max(MIN_TREND_ROWS, Math.min(requestedMaxRows, maxTrendRowsForSeries(seriesCount))),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -472,7 +472,7 @@ async function scanObjects(client, device, portNumber) {
|
||||
});
|
||||
}
|
||||
|
||||
return points;
|
||||
return { points, pointLimitReached: values.length > pointLimit };
|
||||
}
|
||||
|
||||
function encodeBacnetContextUnsigned(tagNumber, value) {
|
||||
@@ -764,7 +764,9 @@ async function scanNetwork(body) {
|
||||
if (resolvedName) {
|
||||
device.name = resolvedName;
|
||||
}
|
||||
device.points = await scanObjects(client, device, routing.port);
|
||||
const scan = await scanObjects(client, device, routing.port);
|
||||
device.points = scan.points;
|
||||
device.pointLimitReached = scan.pointLimitReached;
|
||||
device.pointCount = device.points.length;
|
||||
}
|
||||
}
|
||||
@@ -778,6 +780,7 @@ async function scanNetwork(body) {
|
||||
rawTrace: body.debug === true ? rawTrace : undefined,
|
||||
rawDebug: body.debug === true ? rawDebug : undefined,
|
||||
points: visibleDevices.flatMap((device) => device.points || []),
|
||||
pointLimitReached: visibleDevices.some((device) => device.pointLimitReached),
|
||||
scannedAt: new Date().toISOString(),
|
||||
};
|
||||
} finally {
|
||||
@@ -831,6 +834,7 @@ async function readCurrentValue(source, datapoint) {
|
||||
});
|
||||
});
|
||||
const raw = extractValue(propertyValue);
|
||||
if (raw == null || (typeof raw === "string" && !raw.trim())) return null;
|
||||
if (typeof raw === "boolean") {
|
||||
return raw ? 1 : 0;
|
||||
}
|
||||
|
||||
+16
-2
@@ -776,6 +776,8 @@ async function scanOpcuaEndpoint(body) {
|
||||
endpoints: [{ url: endpointUrl, securityMode: "auto", securityPolicy: "auto" }],
|
||||
tree,
|
||||
nodes: state.nodes,
|
||||
maxNodes: state.maxNodes,
|
||||
nodeLimitReached: state.nodes.length >= state.maxNodes,
|
||||
sampleNodes: state.nodes,
|
||||
scannedAt: new Date().toISOString(),
|
||||
};
|
||||
@@ -804,6 +806,7 @@ async function readOpcuaValue(source, datapoint) {
|
||||
const dataValue = await session.readVariableValue(nodeId);
|
||||
await session.close();
|
||||
const value = dataValue?.value?.value;
|
||||
if (value == null || (typeof value === "string" && !value.trim())) return null;
|
||||
if (typeof value === "boolean") {
|
||||
return value ? 1 : 0;
|
||||
}
|
||||
@@ -994,6 +997,7 @@ async function readIpsymconValue(source, datapoint) {
|
||||
}
|
||||
const response = await requestIpsymconApi(source, { function: "getvalue", id: variableId });
|
||||
const raw = response.value ?? response.variable?.value;
|
||||
if (raw == null || (typeof raw === "string" && !raw.trim())) return null;
|
||||
if (typeof raw === "boolean") {
|
||||
return raw ? 1 : 0;
|
||||
}
|
||||
@@ -1339,7 +1343,7 @@ async function scanBacnetObjects(client, device, portNumber) {
|
||||
hasValue: raw !== null,
|
||||
});
|
||||
}
|
||||
return points;
|
||||
return { points, pointLimitReached: values.length > LOCAL_POINT_LIMIT };
|
||||
}
|
||||
|
||||
async function requestExternalBacnetScan(body) {
|
||||
@@ -1368,6 +1372,7 @@ async function scanBacnetNetwork(body) {
|
||||
const bacnet = await loadOptionalPackage("node-bacnet");
|
||||
const portNumber = Number(body.port || 47808);
|
||||
const timeout = Number(body.timeout || 6000);
|
||||
const includeObjects = body.includeObjects === true || String(body.includeObjects).toLowerCase() === "true";
|
||||
const { client, routing } = createBacnetClientInstance(bacnet, body, timeout);
|
||||
const devices = [];
|
||||
|
||||
@@ -1381,13 +1386,18 @@ async function scanBacnetNetwork(body) {
|
||||
if (resolvedName) {
|
||||
device.name = resolvedName;
|
||||
}
|
||||
device.points = await scanBacnetObjects(client, device, portNumber);
|
||||
if (includeObjects) {
|
||||
const scan = await scanBacnetObjects(client, device, portNumber);
|
||||
device.points = scan.points;
|
||||
device.pointLimitReached = scan.pointLimitReached;
|
||||
}
|
||||
}
|
||||
try { client.close(); } catch {}
|
||||
resolve({
|
||||
routing,
|
||||
devices,
|
||||
points: devices.flatMap((device) => device.points || []),
|
||||
pointLimitReached: devices.some((device) => device.pointLimitReached),
|
||||
scannedAt: new Date().toISOString(),
|
||||
});
|
||||
} catch (error) {
|
||||
@@ -1475,6 +1485,10 @@ async function readBacnetValue(source, datapoint) {
|
||||
return;
|
||||
}
|
||||
const raw = value?.values?.[0]?.value;
|
||||
if (raw == null || (typeof raw === "string" && !raw.trim())) {
|
||||
resolve(null);
|
||||
return;
|
||||
}
|
||||
if (typeof raw === "boolean") {
|
||||
resolve(raw ? 1 : 0);
|
||||
return;
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
4. Die Fragen zur Konfiguration beantworten. Bei Passwörtern kannst du den sicher erzeugten Vorschlag übernehmen. Für vorhandene Controller aktiviert „Bestandsanlage“ den bisherigen Datenbankzugang `wago` mit Passwort `3112` und gibt den MariaDB-Port im Netzwerk frei.
|
||||
5. Docker Desktop bei Bedarf fertig einrichten. Der Assistent baut und startet die Dienste und prüft Web, API und Collector. Danach kannst du SE-LTD über den Link im Assistenten auf Port 81 öffnen.
|
||||
|
||||
Die Fortschrittsanzeige nennt den aktuellen Schritt und die bisherige Laufzeit. Mit „Nach Schritt anhalten“ stoppt der Assistent vor dem nächsten Schritt. Ein gerade laufender Build darf fertig werden; bereits gestartete Dienste und gespeicherte Daten werden nicht entfernt.
|
||||
|
||||
Die Option „Nur dieser Rechner“ beschränkt Web, API, Collector und Hilfsoberflächen auf die lokale IPv4-Adresse. „Zugriff aus dem Netzwerk“ öffnet Web, API und Collector und setzt `CORS_ORIGIN=*`. Der Assistent ändert keine Windows-Firewallregeln. Verwende den Netzzugriff nur im vertrauenswürdigen Netz.
|
||||
|
||||
Eine bestehende `.env` bleibt unverändert. „Bestandsanlage“ bezieht sich auf den Controller-Zugang für eine neu aufgesetzte Datenbank. Vorhandene Datenbank-Volumes ändern ihr Passwort nicht durch eine neue `.env`. Es wird kein Backup oder Datenimport durchgeführt und es werden keine bestehenden Docker-Volumes gelöscht.
|
||||
|
||||
@@ -109,31 +109,42 @@ namespace SeLtd.Setup
|
||||
return true;
|
||||
}
|
||||
|
||||
internal void Prepare(string folder, Action<string> progress)
|
||||
internal void Prepare(string folder, Action<string> progress, CancellationToken cancellation = default(CancellationToken))
|
||||
{
|
||||
Folder = Path.GetFullPath(folder);
|
||||
Legacy = Remote = false;
|
||||
foreach (var step in Config.prepare)
|
||||
for (int index = 0; index < Config.prepare.Length; index++)
|
||||
{
|
||||
progress(step.label);
|
||||
cancellation.ThrowIfCancellationRequested();
|
||||
var step = Config.prepare[index];
|
||||
progress(StepLabel(step, index, Config.prepare.Length));
|
||||
if (step.action == "checkout") Checkout();
|
||||
else if (step.action == "template") LoadTemplate();
|
||||
else if (step.action == "command") RunStep(step);
|
||||
else throw new InvalidDataException("Unbekannter Vorbereitungsschritt: " + step.action);
|
||||
}
|
||||
cancellation.ThrowIfCancellationRequested();
|
||||
}
|
||||
|
||||
internal void Install(Action<string> progress)
|
||||
internal void Install(Action<string> progress, CancellationToken cancellation = default(CancellationToken))
|
||||
{
|
||||
foreach (var step in Config.install)
|
||||
for (int index = 0; index < Config.install.Length; index++)
|
||||
{
|
||||
progress(step.label);
|
||||
cancellation.ThrowIfCancellationRequested();
|
||||
var step = Config.install[index];
|
||||
progress(StepLabel(step, index, Config.install.Length));
|
||||
if (step.action == "dockerReady") WaitForDocker(TimeoutFor(step, 180), progress);
|
||||
else if (step.action == "writeSetup") WriteSetup();
|
||||
else if (step.action == "command") RunStep(step);
|
||||
else if (step.action == "http") CheckHttp(Expand(step.url), TimeoutFor(step, 45));
|
||||
else throw new InvalidDataException("Unbekannter Installationsschritt: " + step.action);
|
||||
}
|
||||
cancellation.ThrowIfCancellationRequested();
|
||||
}
|
||||
|
||||
private static string StepLabel(Step step, int index, int count)
|
||||
{
|
||||
return string.Format("Schritt {0} von {1}: {2}", index + 1, count, step.label);
|
||||
}
|
||||
|
||||
internal string LocalOrigin
|
||||
|
||||
@@ -40,6 +40,25 @@ namespace SeLtd.Setup
|
||||
Application.SetCompatibleTextRenderingDefault(false);
|
||||
using (var wizard = new SetupWizard(setup)) Assert(wizard.Text == "SE-LTD Setup", "wizard initialization");
|
||||
|
||||
using (var pause = new CancellationTokenSource())
|
||||
{
|
||||
int announced = 0;
|
||||
bool paused = false;
|
||||
try
|
||||
{
|
||||
setup.Prepare(Path.Combine(root, "paused install"), phase =>
|
||||
{
|
||||
Assert(phase.StartsWith("Schritt 1 von 2:"), "visible progress position");
|
||||
announced++;
|
||||
pause.Cancel();
|
||||
}, pause.Token);
|
||||
}
|
||||
catch (OperationCanceledException) { paused = true; }
|
||||
Assert(paused && announced == 1, "pause between safe setup steps");
|
||||
Assert(Directory.Exists(Path.Combine(root, "paused install", ".git")), "active checkout completed before pausing");
|
||||
Assert(!File.Exists(Path.Combine(root, "paused install", ".env")), "pause does not write settings");
|
||||
}
|
||||
|
||||
foreach (bool legacy in new[] { false, true })
|
||||
{
|
||||
string target = Path.Combine(root, legacy ? "legacy install" : "new install");
|
||||
|
||||
@@ -2,6 +2,7 @@ using System;
|
||||
using System.Diagnostics;
|
||||
using System.Drawing;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
|
||||
@@ -15,6 +16,13 @@ namespace SeLtd.Setup
|
||||
private readonly FlowLayoutPanel body = new FlowLayoutPanel();
|
||||
private readonly Button back = new Button { Text = "Zurück", AutoSize = true };
|
||||
private readonly Button next = new Button { Text = "Weiter", AutoSize = true };
|
||||
private readonly Button pause = new Button { Text = "Nach Schritt anhalten", AutoSize = true, Visible = false };
|
||||
private readonly System.Windows.Forms.Timer progressTimer = new System.Windows.Forms.Timer { Interval = 1000 };
|
||||
private readonly Stopwatch elapsed = new Stopwatch();
|
||||
private CancellationTokenSource cancellation;
|
||||
private Label activeStep;
|
||||
private Label elapsedLabel;
|
||||
private ProgressBar progressBar;
|
||||
private TextBox input;
|
||||
private TextBox log;
|
||||
private CheckBox choice;
|
||||
@@ -66,7 +74,7 @@ namespace SeLtd.Setup
|
||||
body.Margin = new Padding(0);
|
||||
body.ClientSizeChanged += delegate { FitBody(); };
|
||||
var buttons = new FlowLayoutPanel { Dock = DockStyle.Fill, AutoSize = true, FlowDirection = FlowDirection.RightToLeft };
|
||||
buttons.Controls.AddRange(new Control[] { next, back });
|
||||
buttons.Controls.AddRange(new Control[] { next, back, pause });
|
||||
layout.Controls.Add(section, 0, 0);
|
||||
layout.Controls.Add(headline, 0, 1);
|
||||
layout.Controls.Add(body, 0, 2);
|
||||
@@ -75,7 +83,15 @@ namespace SeLtd.Setup
|
||||
AcceptButton = next;
|
||||
back.Click += OnBack;
|
||||
next.Click += OnNext;
|
||||
FormClosing += delegate(object sender, FormClosingEventArgs e) { if (busy) e.Cancel = true; };
|
||||
pause.Click += delegate { RequestPause(); };
|
||||
progressTimer.Tick += delegate { UpdateElapsed(); };
|
||||
Disposed += delegate { progressTimer.Dispose(); };
|
||||
FormClosing += delegate(object sender, FormClosingEventArgs e)
|
||||
{
|
||||
if (!busy) return;
|
||||
e.Cancel = true;
|
||||
RequestPause();
|
||||
};
|
||||
ShowChecks();
|
||||
}
|
||||
|
||||
@@ -88,6 +104,7 @@ namespace SeLtd.Setup
|
||||
next.Text = nextText;
|
||||
back.Visible = canGoBack;
|
||||
next.Enabled = true;
|
||||
pause.Visible = false;
|
||||
validation = null;
|
||||
input = null;
|
||||
choice = null;
|
||||
@@ -239,22 +256,72 @@ namespace SeLtd.Setup
|
||||
{
|
||||
page = 4;
|
||||
Screen("SE-LTD SETUP / LÄUFT", title, "Erneut versuchen", false);
|
||||
cancellation = new CancellationTokenSource();
|
||||
activeStep = Note("Wird vorbereitet …");
|
||||
elapsedLabel = Note("");
|
||||
progressBar = new ProgressBar { Style = ProgressBarStyle.Marquee, Height = 12, Width = 320, AccessibleName = "Arbeitsschritt läuft" };
|
||||
Add(progressBar);
|
||||
log = new TextBox { ReadOnly = true, Multiline = true, ScrollBars = ScrollBars.Vertical, Height = 200, AccessibleName = "Installationsfortschritt" };
|
||||
Add(log);
|
||||
elapsed.Restart();
|
||||
UpdateElapsed();
|
||||
progressTimer.Start();
|
||||
pause.Enabled = true;
|
||||
pause.Visible = true;
|
||||
SetBusy(true);
|
||||
}
|
||||
|
||||
private void UpdateElapsed()
|
||||
{
|
||||
if (elapsedLabel == null || elapsedLabel.IsDisposed) return;
|
||||
var state = cancellation != null && cancellation.IsCancellationRequested
|
||||
? "Aktueller Schritt wird abgeschlossen. Danach hält das Setup an."
|
||||
: "Setup läuft.";
|
||||
elapsedLabel.Text = state + " Laufzeit " + elapsed.Elapsed.ToString(@"hh\:mm\:ss");
|
||||
}
|
||||
|
||||
private void RequestPause()
|
||||
{
|
||||
if (!busy || cancellation == null || cancellation.IsCancellationRequested) return;
|
||||
cancellation.Cancel();
|
||||
pause.Enabled = false;
|
||||
UpdateElapsed();
|
||||
}
|
||||
|
||||
private void SetBusy(bool value)
|
||||
{
|
||||
busy = value;
|
||||
back.Enabled = !value;
|
||||
next.Enabled = !value;
|
||||
UseWaitCursor = value;
|
||||
if (!value)
|
||||
{
|
||||
progressTimer.Stop();
|
||||
elapsed.Stop();
|
||||
if (progressBar != null && !progressBar.IsDisposed)
|
||||
{
|
||||
progressBar.Style = ProgressBarStyle.Blocks;
|
||||
progressBar.Visible = false;
|
||||
}
|
||||
pause.Visible = false;
|
||||
if (cancellation != null)
|
||||
{
|
||||
cancellation.Dispose();
|
||||
cancellation = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void Progress(string line)
|
||||
{
|
||||
BeginInvoke(new Action(() => log.AppendText(line + Environment.NewLine)));
|
||||
var output = log;
|
||||
var label = activeStep;
|
||||
BeginInvoke(new Action(() =>
|
||||
{
|
||||
if (output.IsDisposed) return;
|
||||
label.Text = line;
|
||||
output.AppendText(line + Environment.NewLine);
|
||||
}));
|
||||
}
|
||||
|
||||
private void ShowSuccess()
|
||||
@@ -304,10 +371,12 @@ namespace SeLtd.Setup
|
||||
ShowProgress("Projekt wird vorbereitet");
|
||||
try
|
||||
{
|
||||
await Task.Run(() => setup.Prepare(folder, Progress));
|
||||
var stop = cancellation.Token;
|
||||
await Task.Run(() => setup.Prepare(folder, Progress, stop));
|
||||
if (setup.ExistingEnvironment) ShowExisting();
|
||||
else { variableIndex = 0; ShowVariable(); }
|
||||
}
|
||||
catch (OperationCanceledException) { ShowFolder(); }
|
||||
catch (Exception error) { ShowError(error); ShowFolder(); }
|
||||
finally { SetBusy(false); }
|
||||
}
|
||||
@@ -332,12 +401,19 @@ namespace SeLtd.Setup
|
||||
ShowProgress("SE-LTD wird installiert");
|
||||
try
|
||||
{
|
||||
await Task.Run(() => setup.Install(Progress));
|
||||
var stop = cancellation.Token;
|
||||
await Task.Run(() => setup.Install(Progress, stop));
|
||||
ShowSuccess();
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
headline.Text = "Setup angehalten";
|
||||
elapsedLabel.Text = "Bereits gestartete Dienste bleiben unverändert. Du kannst das Setup erneut starten.";
|
||||
}
|
||||
catch (Exception error)
|
||||
{
|
||||
log.AppendText(Environment.NewLine + error.Message);
|
||||
elapsedLabel.Text = "Setup fehlgeschlagen. Details stehen im Fortschrittsprotokoll.";
|
||||
ShowError(error);
|
||||
}
|
||||
finally { SetBusy(false); }
|
||||
|
||||
@@ -33,7 +33,8 @@
|
||||
{ "action": "dockerReady", "label": "Docker Desktop starten und Verbindung prüfen", "timeout": 180 },
|
||||
{ "action": "writeSetup", "label": "Lokale Installationseinstellungen schreiben" },
|
||||
{ "action": "command", "label": "Docker-Konfiguration prüfen", "tool": "docker", "arguments": ["compose", "--env-file", ".env", "config", "--quiet"], "timeout": 60 },
|
||||
{ "action": "command", "label": "Alle SE-LTD-Dienste bauen und starten", "tool": "docker", "arguments": ["compose", "--env-file", ".env", "up", "-d", "--build", "--wait", "--wait-timeout", "240"], "timeout": 2400 },
|
||||
{ "action": "command", "label": "Docker-Images für SE-LTD bauen", "tool": "docker", "arguments": ["compose", "--env-file", ".env", "build"], "timeout": 2400 },
|
||||
{ "action": "command", "label": "Dienste starten und auf Bereitschaft warten", "tool": "docker", "arguments": ["compose", "--env-file", ".env", "up", "-d", "--no-build", "--wait", "--wait-timeout", "240"], "timeout": 900 },
|
||||
{ "action": "http", "label": "Weboberfläche prüfen", "url": "http://127.0.0.1:{{WEB_PORT}}/", "timeout": 45 },
|
||||
{ "action": "http", "label": "API prüfen", "url": "http://127.0.0.1:{{API_PORT}}/api/health", "timeout": 45 },
|
||||
{ "action": "http", "label": "Collector prüfen", "url": "http://127.0.0.1:18110/health", "timeout": 45 }
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
export const DEFAULT_TREND_PRESET = "1";
|
||||
export const DEFAULT_MAX_TREND_SERIES = 10;
|
||||
export const MAX_TREND_SERIES = 100;
|
||||
export const DEFAULT_TREND_ROWS = 20_000;
|
||||
export const MIN_TREND_ROWS = 100;
|
||||
export const MAX_TREND_ROWS = 50_000;
|
||||
const MAX_TREND_SAMPLES = 250_000;
|
||||
|
||||
export function maxTrendRowsForSeries(seriesCount) {
|
||||
return Math.min(MAX_TREND_ROWS, Math.floor(MAX_TREND_SAMPLES / Math.max(1, seriesCount || 1)));
|
||||
}
|
||||
|
||||
export const TREND_PRESETS = [
|
||||
{ value: "0.0034722222", label: "5 min" },
|
||||
|
||||
@@ -146,6 +146,7 @@ async function readValue(source, datapoint) {
|
||||
}
|
||||
const response = await requestApi(source, { function: "getvalue", id: variableId });
|
||||
const raw = response.value ?? response.variable?.value;
|
||||
if (raw == null || (typeof raw === "string" && !raw.trim())) return null;
|
||||
if (typeof raw === "boolean") return raw ? 1 : 0;
|
||||
const numeric = Number(raw);
|
||||
return Number.isFinite(numeric) ? numeric * (Number(datapoint.scale || 1) || 1) : raw === null || raw === undefined ? null : String(raw);
|
||||
|
||||
+333
-287
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