feat: enhance sidebar functionality and styling

- Updated sidebar component to support dynamic width based on collapsed state.
- Improved sidebar icon rendering and added user account management features.
- Introduced new trend chart settings component for better user interaction.
- Added utility functions for engineering units and trend chart settings.
- Implemented color assignment logic for trend series to enhance visual representation.
- Enhanced CSS styles for better responsiveness and usability across different screen sizes.
- Introduced new configuration for Vite server to allow shared directory access.
- Added .dockerignore file to optimize Docker build context.
This commit is contained in:
jhartworks committed 2026-11-19 13:51:04 +01:00
1 parent 2f5f86452f
commit 3203577a9d
28 files changed
+1470 -720

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
**
!api/
!api/package*.json
!api/src/
!api/src/**
!collector/
!collector/package*.json
!collector/src/
!collector/src/**
!runner/
!runner/package*.json
!runner/src/
!runner/src/**
!web/
!web/package*.json
!web/index.html
!web/vite.config.js
!web/public/
!web/public/**
!web/src/
!web/src/**
!shared/
!shared/*.mjs
**/node_modules
**/dist
**/.env
**/.env.*
**/.git
+2 -1
View File
@@ -9,5 +9,6 @@ MARIADB_ROOT_PASSWORD=SE3112
MARIADB_PASSWORD=3112 MARIADB_PASSWORD=3112
DB_PASSWORD_FALLBACK=root DB_PASSWORD_FALLBACK=root
REDIS_PASSWORD=replace-with-a-long-random-redis-password REDIS_PASSWORD=replace-with-a-long-random-redis-password
CORS_ORIGIN=http://localhost:5173 CORS_ORIGIN=http://localhost:81
LEGACY_TREND_TIME_ZONE=Europe/Berlin
VITE_API_PORT=18080 VITE_API_PORT=18080
-1
View File
@@ -4,5 +4,4 @@ dist
npm-debug.log* npm-debug.log*
.scratch/runtime .scratch/runtime
data/ data/
web/src
.env .env
+6 -26
View File
@@ -89,7 +89,7 @@ SeLTD/
```text ```text
Browser Browser
│ │
│ http://localhost:5173 │ http://localhost:81
▼ ▼
React/Vite Frontend (web) React/Vite Frontend (web)
│ │
@@ -115,7 +115,7 @@ Wichtig: Die API laeuft im Container intern auf Port `8080`, wird aber nach auss
| Service | Container | Interner Port | Host-Port | Zweck | | Service | Container | Interner Port | Host-Port | Zweck |
| --- | --- | ---: | ---: | --- | | --- | --- | ---: | ---: | --- |
| Web | `seltd-web` | 5173 | 5173 | React/Vite-Oberflaeche | | Web | `seltd-web` | 5173 | 81 | React/Vite-Oberflaeche |
| API | `seltd-api` | 8080 | 18080 | REST-API | | API | `seltd-api` | 8080 | 18080 | REST-API |
| Collector | `seltd-collector` | 18110 | 18110 | Quellen, Datenpunkte, Scans, Polling | | Collector | `seltd-collector` | 18110 | 18110 | Quellen, Datenpunkte, Scans, Polling |
| MariaDB | `seltd-mariadb` | 3306 | 3306 | Trend- und Benutzerdaten | | MariaDB | `seltd-mariadb` | 3306 | 3306 | Trend- und Benutzerdaten |
@@ -168,30 +168,9 @@ docker ps -a
### 3. Aufrufen ### 3. Aufrufen
Nun stehen dir mehrere Tools zur Verfügung: Nun stehen dir mehrere Tools zur Verfügung:
<<<<<<< HEAD | Frontend | `http://localhost:81` |
Frontend | `http://localhost:5173`
--> Das ist die normale Weboberfläche zum anschauen, editieren und anpassen von Trends. --> Das ist die normale Weboberfläche zum anschauen, editieren und anpassen von Trends.
API Healthcheck | `http://localhost:18080/api/health`
--> hier kannst du schauen ob die API läuft
Collector Healthcheck | `http://localhost:18110/health`
--> hier kannst du schauen ob der Collector läuft, was nur wichtig ist, wenn du Datenpunkte per OPC,KNX, Modbus oder Bacnet angebunden hast.
Dockhand | `http://localhost:3000`
--> Dockhand ist Container verwaltungstool, dass es dir ermöglicht, auch grafisch den Zustand deiner Container und deines Stacks zu sehen.
Der Vorteil hier, im Gegensatz zur normalen Docker Desktopoberfläche: Du kannst es auf jedem beliebigen anderen Rechner, der auf dein Netzwerk zugriff hat, öffnen.
cAdvisor | `http://localhost:9090`
--> Cadvisor stellt alle Containerdaten für Monitoring und Analyticprogramme bereit.
So kann bei einer größeren Anlage, das Dockersystem mitr Prometheus oder ähnlichem überwacht werden.
Cadvisor stellt di Daten per html bereit, kannst du dir gern anschauen, ist aber ziemlich unübersichtlich.
=======
| Frontend | `http://localhost:5173` |
--> Das ist die normale Weboberfläche zum anschauen, editieren und anpassen von Trends.
>>>>>>> c06fe1fd4df46b203002412d6d8d0362c979166c
| API Healthcheck | `http://localhost:18080/api/health` | | API Healthcheck | `http://localhost:18080/api/health` |
--> hier kannst du schauen ob die API läuft --> hier kannst du schauen ob die API läuft
@@ -230,6 +209,7 @@ Die wichtigsten Variablen liegen in `.env`.
| `MARIADB_ROOT_PASSWORD` | `SE3112` | MariaDB-Root-Passwort | | `MARIADB_ROOT_PASSWORD` | `SE3112` | MariaDB-Root-Passwort |
| `DB_PASSWORD_FALLBACK` | `root` | Fallback fuer alte Entwicklungsvolumes | | `DB_PASSWORD_FALLBACK` | `root` | Fallback fuer alte Entwicklungsvolumes |
| `CORS_ORIGIN` | `*` | Erlaubter Browser-Ursprung fuer API-Aufrufe | | `CORS_ORIGIN` | `*` | Erlaubter Browser-Ursprung fuer API-Aufrufe |
| `LEGACY_TREND_TIME_ZONE` | `Europe/Berlin` | Zeitzone der gespeicherten Controllerzeit in Bestandstabellen mit `Wert1` usw. Fuer bereits in UTC gespeicherte Bestandsdaten `+00:00` setzen. |
| `VITE_API_PORT` | `18080` | API-Port, den das Frontend im Browser nutzt | | `VITE_API_PORT` | `18080` | API-Port, den das Frontend im Browser nutzt |
| `POLL_TICK_MS` | `1000` | Collector-Tick fuer Polling-Pruefung | | `POLL_TICK_MS` | `1000` | Collector-Tick fuer Polling-Pruefung |
@@ -538,10 +518,10 @@ docker ps
curl http://localhost:18080/api/health curl http://localhost:18080/api/health
``` ```
Wenn Frontend lokal auf `localhost:5173` laeuft: Wenn das Frontend lokal auf `localhost:81` laeuft:
```env ```env
CORS_ORIGIN=* CORS_ORIGIN=http://localhost:81
``` ```
Danach API neu starten: Danach API neu starten:
+4 -3
View File
@@ -1,11 +1,12 @@
FROM node:22-alpine FROM node:22-alpine
WORKDIR /app WORKDIR /app/api
COPY package*.json ./ COPY api/package*.json ./
RUN npm ci RUN npm ci
COPY src ./src COPY api/src ./src
COPY shared /app/shared
EXPOSE 8080 EXPOSE 8080
+19 -4
View File
@@ -1,8 +1,9 @@
import mysql from "mysql2/promise"; import mysql from "mysql2/promise";
import { config } from "./config.js"; import { config } from "./config.js";
import { setUtcSession } from "../../shared/trend-time.mjs";
function createPool(password) { function createPool(password) {
return mysql.createPool({ const pool = mysql.createPool({
host: config.dbHost, host: config.dbHost,
port: config.dbPort, port: config.dbPort,
user: config.dbUser, user: config.dbUser,
@@ -13,7 +14,10 @@ function createPool(password) {
namedPlaceholders: true, namedPlaceholders: true,
multipleStatements: true, multipleStatements: true,
charset: "utf8mb4", charset: "utf8mb4",
timezone: "Z",
}); });
pool.on("connection", setUtcSession);
return pool;
} }
const candidatePasswords = [...new Set([config.dbPassword, config.dbPasswordFallback].filter(Boolean))]; const candidatePasswords = [...new Set([config.dbPassword, config.dbPasswordFallback].filter(Boolean))];
@@ -32,9 +36,19 @@ function delay(milliseconds) {
return new Promise((resolve) => setTimeout(resolve, milliseconds)); return new Promise((resolve) => setTimeout(resolve, milliseconds));
} }
async function queryWithCredentials(sql, values) { async function execute(pool, sql, values, isolated) {
if (!isolated) return pool.query(sql, values);
const connection = await pool.getConnection();
try { try {
return await activePool.query(sql, values); return await connection.query(sql);
} finally {
connection.destroy();
}
}
async function queryWithCredentials(sql, values, isolated) {
try {
return await execute(activePool, sql, values, isolated);
} catch (error) { } catch (error) {
if (!isAccessDenied(error) || candidatePasswords.length < 2) { if (!isAccessDenied(error) || candidatePasswords.length < 2) {
throw error; throw error;
@@ -44,7 +58,7 @@ async function queryWithCredentials(sql, values) {
if (password === activePassword) continue; if (password === activePassword) continue;
const fallbackPool = createPool(password); const fallbackPool = createPool(password);
try { try {
const result = await fallbackPool.query(sql, values); const result = await execute(fallbackPool, sql, values, isolated);
const previousPool = activePool; const previousPool = activePool;
activePool = fallbackPool; activePool = fallbackPool;
activePassword = password; activePassword = password;
@@ -75,3 +89,4 @@ async function query(sql, values) {
} }
export const pool = { query }; export const pool = { query };
export const importSql = (sql) => queryWithCredentials(sql, undefined, true);
+79 -23
View File
@@ -3,7 +3,10 @@ import cors from "cors";
import express from "express"; import express from "express";
import { authenticateToken, authenticateTokenOptional, createToken, requireRoles } from "./auth.js"; import { authenticateToken, authenticateTokenOptional, createToken, requireRoles } from "./auth.js";
import { config } from "./config.js"; import { config } from "./config.js";
import { pool } from "./db.js"; import { importSql, pool } from "./db.js";
import { AUTO_UNIT } from "../../shared/engineering-units.mjs";
import { normalizeTrendChartSettings } from "../../shared/trend-chart-settings.mjs";
import { DEFAULT_TREND_PRESET, TREND_PRESETS } from "../../shared/trend-preferences.mjs";
import { import {
createTrendTable, createTrendTable,
ensureIspMetadata, ensureIspMetadata,
@@ -11,12 +14,14 @@ import {
fetchLatestValues, fetchLatestValues,
fetchTrendSeries, fetchTrendSeries,
getAvailableIsps, getAvailableIsps,
migrateLegacyUserLevels,
normalizeEngineeringUnit, normalizeEngineeringUnit,
normalizeRange, normalizeRange,
resolveTrendTablePointCount, resolveTrendTablePointCount,
sanitizeIspName, sanitizeIspName,
sanitizePointIndex, sanitizePointIndex,
updateIspMetadata, updateIspMetadata,
verifyLegacyTrendTimeZone,
} from "./lib/isp.js"; } from "./lib/isp.js";
import { import {
deleteSelection, deleteSelection,
@@ -292,17 +297,19 @@ async function listRunnerQueue() {
} }
}); });
} }
async function resolveSelectionPoints(body, user) { async function resolveAccessibleSelection(selectionId, user) {
if (body.selectionId) { const selection = await getSelection(redis, selectionId);
const selection = await getSelection(redis, body.selectionId);
if (!canUseSelection(selection, user)) { if (!canUseSelection(selection, user)) {
throw new Error("Selection not found or not accessible."); throw new Error("Selection not found or not accessible.");
} }
return selection;
return assertPoints(selection.points || []);
} }
async function resolveSelectionPoints(body, user) {
if (body.selectionId) {
const selection = await resolveAccessibleSelection(body.selectionId, user);
return assertPoints(selection.points || []);
}
return assertPoints(body.points || []); return assertPoints(body.points || []);
} }
@@ -536,15 +543,21 @@ app.put(
points.forEach((point) => { points.forEach((point) => {
const pointIndex = sanitizePointIndex(point.pointIndex); const pointIndex = sanitizePointIndex(point.pointIndex);
const key = String(pointIndex); const key = String(pointIndex);
const existing = metadata.points[key] || {};
const alias = String(point.alias || "").trim() || existing.alias || `Wert${pointIndex}`;
const kind = point.kind === "digital" ? "digital" : "analog";
const unit = point.unit ?? existing.unit;
const unitAuto = unit === AUTO_UNIT || !unit || (point.unit == null && existing.unitAuto === true);
metadata.points[key] = { metadata.points[key] = {
...metadata.points[key], ...existing,
alias: String(point.alias || metadata.points[key].alias).trim() || metadata.points[key].alias, alias,
unit: normalizeEngineeringUnit(point.unit || metadata.points[key].unit), unit: normalizeEngineeringUnit(unitAuto ? AUTO_UNIT : unit, kind, alias),
factor: Number.isFinite(Number(point.factor)) ? Number(point.factor) : metadata.points[key].factor, unitAuto,
kind: point.kind === "digital" ? "digital" : "analog", factor: Number.isFinite(Number(point.factor)) ? Number(point.factor) : (existing.factor ?? 1),
min: Number.isFinite(Number(point.min)) ? Number(point.min) : metadata.points[key].min, kind,
max: Number.isFinite(Number(point.max)) ? Number(point.max) : metadata.points[key].max, min: Number.isFinite(Number(point.min)) ? Number(point.min) : (existing.min ?? 0),
color: typeof point.color === "string" ? point.color : metadata.points[key].color, max: Number.isFinite(Number(point.max)) ? Number(point.max) : (existing.max ?? 100),
color: typeof point.color === "string" ? point.color : existing.color,
}; };
}); });
} }
@@ -574,7 +587,7 @@ app.post("/api/units", authenticateToken, requirePermission("edit_aliases"), wra
})); }));
app.patch("/api/units/:symbol", authenticateToken, requirePermission("edit_aliases"), wrap(async (req, res) => { app.patch("/api/units/:symbol", authenticateToken, requirePermission("edit_aliases"), wrap(async (req, res) => {
const existingSymbol = decodeURIComponent(req.params.symbol || "").trim(); const existingSymbol = String(req.params.symbol || "").trim();
if (!existingSymbol) { if (!existingSymbol) {
return res.status(400).json({ error: "Einheit fehlt." }); return res.status(400).json({ error: "Einheit fehlt." });
} }
@@ -632,7 +645,8 @@ app.post(
throw new Error("SQL-Inhalt ist leer."); throw new Error("SQL-Inhalt ist leer.");
} }
await pool.query(sql); await importSql(sql);
await migrateLegacyUserLevels(pool);
const isps = await getAvailableIsps(pool, config.dbName); const isps = await getAvailableIsps(pool, config.dbName);
res.json({ ok: true, importedTables: isps.length, filename: req.body.filename || null }); res.json({ ok: true, importedTables: isps.length, filename: req.body.filename || null });
}) })
@@ -757,6 +771,7 @@ app.post("/api/selections", authenticateToken, requirePermission("view_trends"),
description: String(req.body.description || "").trim(), description: String(req.body.description || "").trim(),
shared: Boolean(req.body.shared), shared: Boolean(req.body.shared),
points, points,
chartSettings: normalizeTrendChartSettings(req.body.chartSettings, points),
}); });
res.status(201).json({ selection }); res.status(201).json({ selection });
@@ -779,9 +794,12 @@ app.put("/api/selections/:selectionId", authenticateToken, requirePermission("vi
{ {
...existing, ...existing,
name: String(req.body.name || existing.name).trim(), name: String(req.body.name || existing.name).trim(),
description: String(req.body.description || existing.description || "").trim(), description: String(req.body.description ?? existing.description ?? "").trim(),
shared: typeof req.body.shared === "boolean" ? req.body.shared : existing.shared, shared: typeof req.body.shared === "boolean" ? req.body.shared : existing.shared,
points, points,
chartSettings: normalizeTrendChartSettings(
req.body.chartSettings === undefined ? existing.chartSettings : req.body.chartSettings, points
),
}, },
existing.id existing.id
); );
@@ -804,9 +822,37 @@ app.delete("/api/selections/:selectionId", authenticateToken, requirePermission(
res.status(204).send(); res.status(204).send();
})); }));
async function getTrendDefaults() {
const stored = await redis.get("settings:trend:default-preset");
return { defaultPresetDays: TREND_PRESETS.some(({ value }) => value === stored) ? stored : DEFAULT_TREND_PRESET };
}
async function getTrendDisplayOptions(user) {
const [preferences, defaults] = await Promise.all([getPreferences(redis, user?.sub), getTrendDefaults()]);
return { ...defaults, maxSeries: preferences.maxTrendSeries };
}
async function fetchDisplayTrend(points, range, { maxSeries, defaultPresetDays }) {
const trend = await fetchTrendSeries(pool, redis, points.slice(0, maxSeries), normalizeRange(range, defaultPresetDays));
return { ...trend, requestedSeriesCount: points.length, maxSeries };
}
app.get("/api/settings/trend", wrap(async (_req, res) => {
res.json(await getTrendDefaults());
}));
app.put("/api/settings/trend", authenticateToken, requireRoles("admin"), wrap(async (req, res) => {
const defaultPresetDays = String(req.body?.defaultPresetDays ?? "");
if (!TREND_PRESETS.some(({ value }) => value === defaultPresetDays)) {
return res.status(400).json({ error: "Bitte einen gültigen Standardzeitraum auswählen." });
}
await redis.set("settings:trend:default-preset", defaultPresetDays);
res.json({ defaultPresetDays });
}));
app.post("/api/trends/query", authenticateTokenOptional, wrap(async (req, res) => { app.post("/api/trends/query", authenticateTokenOptional, wrap(async (req, res) => {
const points = await resolveSelectionPoints(req.body, resolveViewerUser(req)); const points = await resolveSelectionPoints(req.body, resolveViewerUser(req));
const trendData = await fetchTrendSeries(pool, redis, points, normalizeRange(req.body.range)); const trendData = await fetchDisplayTrend(points, req.body.range, await getTrendDisplayOptions(req.user));
res.json(trendData); res.json(trendData);
})); }));
@@ -830,13 +876,20 @@ app.post("/api/dashboard/data", authenticateTokenOptional, wrap(async (req, res)
const widgets = Array.isArray(req.body.widgets) ? req.body.widgets : []; const widgets = Array.isArray(req.body.widgets) ? req.body.widgets : [];
const results = []; const results = [];
const viewer = resolveViewerUser(req); const viewer = resolveViewerUser(req);
const trendOptions = widgets.some((widget) => widget.type === "chart") ? await getTrendDisplayOptions(req.user) : null;
for (const widget of widgets) { for (const widget of widgets) {
const points = widget.selectionId ? await resolveSelectionPoints({ selectionId: widget.selectionId }, viewer) : assertPoints(widget.points || []); const selection = widget.selectionId ? await resolveAccessibleSelection(widget.selectionId, viewer) : null;
const points = assertPoints(selection ? selection.points : (widget.points || []));
if (widget.type === "chart") { if (widget.type === "chart") {
const trendData = await fetchTrendSeries(pool, redis, points, normalizeRange(widget.range)); const trendData = await fetchDisplayTrend(points, widget.range, trendOptions);
results.push({ id: widget.id, type: widget.type, ...trendData }); results.push({
id: widget.id,
type: widget.type,
...trendData,
...(selection ? { chartSettings: normalizeTrendChartSettings(selection.chartSettings, points) } : {}),
});
} else { } else {
const values = await fetchLatestValues(pool, redis, points); const values = await fetchLatestValues(pool, redis, points);
results.push({ id: widget.id, type: widget.type, values }); results.push({ id: widget.id, type: widget.type, values });
@@ -870,7 +923,8 @@ app.put("/api/integrations", authenticateToken, requirePermission("manage_integr
})); }));
app.get("/api/runner/jobs", authenticateToken, requirePermission("manage_runner"), wrap(async (_req, res) => { app.get("/api/runner/jobs", authenticateToken, requirePermission("manage_runner"), wrap(async (_req, res) => {
res.json({ jobs: await listRunnerJobs(), queue: await listRunnerQueue() }); const [jobs, queue, integration] = await Promise.all([listRunnerJobs(), listRunnerQueue(), redis.get("integration:api")]);
res.json({ jobs, queue, mailConfigured: Boolean(JSON.parse(integration || "{}").mailApiKey) });
})); }));
app.post("/api/runner/jobs", authenticateToken, requirePermission("manage_runner"), wrap(async (req, res) => { app.post("/api/runner/jobs", authenticateToken, requirePermission("manage_runner"), wrap(async (req, res) => {
@@ -922,6 +976,8 @@ app.use((error, _req, res, _next) => {
await ensureUtf8Database(); await ensureUtf8Database();
await ensureUserSchema(); await ensureUserSchema();
await verifyLegacyTrendTimeZone(pool);
await migrateLegacyUserLevels(pool);
await ensureRolesSchema(); await ensureRolesSchema();
await ensureAdminUser(); await ensureAdminUser();
+68 -44
View File
@@ -1,4 +1,7 @@
const META_PREFIX = "meta:isp:"; 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";
const META_PREFIX = "meta:isp:";
export const LEGACY_POINT_LIMIT = 200; export const LEGACY_POINT_LIMIT = 200;
export const LOCAL_POINT_LIMIT = 2000; export const LOCAL_POINT_LIMIT = 2000;
@@ -106,40 +109,18 @@ function parseHslColor(value) {
}; };
} }
function createRandomPointColor(seed) { export const normalizeEngineeringUnit = resolveEngineeringUnit;
const hue = Math.round((seed * 47 + 17 + Math.random() * 28) % 360);
const saturation = 72 + (seed % 4) * 4;
const lightness = 45 + (seed % 3) * 4;
return hslToHex(hue, saturation, lightness);
}
export function normalizeEngineeringUnit(value, kind = "analog") {
const normalizedKind = kind === "digital" ? "digital" : "analog";
const raw = String(value ?? "").trim();
if (!raw) {
return normalizedKind === "digital" ? "bool" : "\u00B0C";
}
if (normalizedKind === "digital" && /^(?:bool|boolean)$/i.test(raw)) {
return "bool";
}
if (/^\?C$/i.test(raw) || /^\u00B0\s*C$/i.test(raw) || (/[^\x00-\x7F]/.test(raw) && /C/i.test(raw))) {
return normalizedKind === "digital" ? "bool" : "\u00B0C";
}
return raw;
}
function createDefaultPoint(index) { function createDefaultPoint(index) {
return { return {
alias: `Wert${index}`, alias: `Wert${index}`,
unit: "\u00B0C", unit: DEFAULT_ANALOG_UNIT,
unitAuto: true,
factor: 1, factor: 1,
kind: "analog", kind: "analog",
min: 0, min: 0,
max: 100, max: 100,
color: createRandomPointColor(index), color: "#000000",
}; };
} }
@@ -174,7 +155,7 @@ export async function createLegacyWideTrendTable(pool, tableName) {
CREATE TABLE IF NOT EXISTS \`${safeTable}\` ( CREATE TABLE IF NOT EXISTS \`${safeTable}\` (
\`id\` INT(11) NOT NULL AUTO_INCREMENT, \`id\` INT(11) NOT NULL AUTO_INCREMENT,
\`datum\` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, \`datum\` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
\`userlevel\` INT(1) NOT NULL, \`userlevel\` INT(1) NULL DEFAULT NULL,
${buildValueColumns()}, ${buildValueColumns()},
PRIMARY KEY (\`id\`) PRIMARY KEY (\`id\`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
@@ -205,6 +186,40 @@ export async function createTrendTable(pool, tableName) {
return safeTable; return safeTable;
} }
export async function migrateLegacyUserLevels(pool) {
const [columns] = await pool.query(`
SELECT c.TABLE_NAME AS tableName, c.COLUMN_TYPE AS columnType,
c.COLUMN_DEFAULT AS defaultValue, c.COLUMN_COMMENT AS comment
FROM information_schema.COLUMNS c
JOIN information_schema.TABLES t
ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME
WHERE c.TABLE_SCHEMA = DATABASE()
AND c.TABLE_NAME REGEXP '^(isp[a-z0-9_]*|trend_[a-z0-9_]+)$'
AND t.TABLE_TYPE = 'BASE TABLE'
AND c.COLUMN_NAME = 'userlevel' AND c.IS_NULLABLE = 'NO'
AND EXISTS (
SELECT 1 FROM information_schema.COLUMNS v
WHERE v.TABLE_SCHEMA = c.TABLE_SCHEMA AND v.TABLE_NAME = c.TABLE_NAME
AND v.COLUMN_NAME REGEXP '^Wert[0-9]+$'
)
`);
for (const { tableName, columnType, defaultValue, comment } of columns) {
const table = sanitizeIspName(tableName);
if (!/^(?:tinyint|smallint|mediumint|int|bigint)(?:\(\d+\))?(?: unsigned)?(?: zerofill)?$/i.test(columnType)) {
throw new Error(`Unexpected userlevel column type in ${table}.`);
}
const defaultSql = /^-?\d+$/.test(String(defaultValue)) ? String(defaultValue) : "NULL";
await pool.query(`ALTER TABLE \`${table}\` MODIFY COLUMN \`userlevel\` ${columnType} NULL DEFAULT ${defaultSql} COMMENT ?`, [comment]);
}
}
export async function verifyLegacyTrendTimeZone(pool) {
const [[row]] = await pool.query("SELECT CONVERT_TZ('2026-01-01 12:00:00', ?, '+00:00') AS converted", [LEGACY_TREND_TIME_ZONE]);
if (!row.converted) {
throw new Error(`MariaDB cannot resolve LEGACY_TREND_TIME_ZONE=${LEGACY_TREND_TIME_ZONE}. Check its time zone tables.`);
}
}
async function loadSourcePointSeeds(pool, tableName) { async function loadSourcePointSeeds(pool, tableName) {
const safeTable = sanitizeIspName(tableName); const safeTable = sanitizeIspName(tableName);
@@ -275,7 +290,10 @@ async function describeTrendTable(pool, dbName, tableName) {
const widePointCount = columnNames.filter((name) => /^Wert\d+$/i.test(name)).length; const widePointCount = columnNames.filter((name) => /^Wert\d+$/i.test(name)).length;
if (widePointCount > 0) { if (widePointCount > 0) {
const [rows] = await pool.query(`SELECT COUNT(*) AS rowCount, MAX(datum) AS latestTimestamp FROM \`${safeTable}\``); const [rows] = await pool.query(
`SELECT COUNT(*) AS rowCount, CONVERT_TZ(MAX(datum), ?, '+00:00') AS latestTimestamp FROM \`${safeTable}\``,
[LEGACY_TREND_TIME_ZONE]
);
return { return {
tableName: safeTable, tableName: safeTable,
storage: "wide", storage: "wide",
@@ -393,7 +411,8 @@ export async function ensureIspMetadata(pool, redis, isp, pointCount = LEGACY_PO
parsed.points[pointKey] = { parsed.points[pointKey] = {
...defaultPoint, ...defaultPoint,
alias: initialAlias, alias: initialAlias,
unit: normalizeEngineeringUnit(sourceSeed?.unit || defaultPoint.unit, sourceSeed?.kind || defaultPoint.kind), unit: normalizeEngineeringUnit(sourceSeed?.unit, sourceSeed?.kind || defaultPoint.kind, initialAlias),
unitAuto: !sourceSeed?.unit,
kind: sourceSeed?.kind || defaultPoint.kind, kind: sourceSeed?.kind || defaultPoint.kind,
}; };
changed = true; changed = true;
@@ -412,18 +431,16 @@ export async function ensureIspMetadata(pool, redis, isp, pointCount = LEGACY_PO
point.kind = sourceSeed.kind; point.kind = sourceSeed.kind;
changed = true; changed = true;
} }
const normalizedUnit = normalizeEngineeringUnit(point.unit, point.kind || sourceSeed?.kind || defaultPoint.kind); const kind = point.kind || sourceSeed?.kind || defaultPoint.kind;
const normalizedUnit = normalizeEngineeringUnit(
point.unitAuto === true ? AUTO_UNIT : (point.unit || sourceSeed?.unit),
kind,
point.alias
);
if (normalizedUnit !== point.unit) { if (normalizedUnit !== point.unit) {
point.unit = normalizedUnit; point.unit = normalizedUnit;
changed = true; changed = true;
} }
if ((!point.unit || point.unit === normalizeEngineeringUnit(defaultPoint.unit, defaultPoint.kind)) && sourceSeed?.unit) {
const seededUnit = normalizeEngineeringUnit(sourceSeed.unit, sourceSeed.kind || point.kind || defaultPoint.kind);
if (point.unit !== seededUnit) {
point.unit = seededUnit;
changed = true;
}
}
if (!point.kind) { if (!point.kind) {
point.kind = sourceSeed?.kind || defaultPoint.kind; point.kind = sourceSeed?.kind || defaultPoint.kind;
changed = true; changed = true;
@@ -468,7 +485,8 @@ export async function ensureIspMetadata(pool, redis, isp, pointCount = LEGACY_PO
metadata.points[pointKey] = { metadata.points[pointKey] = {
...metadata.points[pointKey], ...metadata.points[pointKey],
alias: sourceSeed.alias || sourceSeed.name || metadata.points[pointKey].alias, alias: sourceSeed.alias || sourceSeed.name || metadata.points[pointKey].alias,
unit: normalizeEngineeringUnit(sourceSeed.unit || metadata.points[pointKey].unit, sourceSeed.kind || metadata.points[pointKey].kind), unit: normalizeEngineeringUnit(sourceSeed.unit, sourceSeed.kind, sourceSeed.alias || sourceSeed.name),
unitAuto: !sourceSeed.unit,
kind: sourceSeed.kind || metadata.points[pointKey].kind, kind: sourceSeed.kind || metadata.points[pointKey].kind,
}; };
}); });
@@ -581,8 +599,11 @@ export async function fetchTrendSeries(pool, redis, points, range) {
const limit = range.maxRows || 4000; const limit = range.maxRows || 4000;
const [rows] = await pool.query( const [rows] = await pool.query(
`SELECT datum, ${columns} FROM \`${isp}\` WHERE datum BETWEEN ? AND ? ORDER BY datum DESC LIMIT ?`, `SELECT ${LEGACY_DATUM_UTC} AS datum, ${columns} FROM \`${isp}\`
[range.from, range.to, limit] 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]
); );
rows.reverse().forEach((row) => { rows.reverse().forEach((row) => {
@@ -673,7 +694,10 @@ export async function fetchLatestValues(pool, redis, points) {
.map((descriptor) => `\`Wert${descriptor.pointIndex}\``) .map((descriptor) => `\`Wert${descriptor.pointIndex}\``)
.join(", "); .join(", ");
const [rows] = await pool.query(`SELECT datum, ${columns} FROM \`${isp}\` ORDER BY datum DESC LIMIT 1`); const [rows] = await pool.query(
`SELECT ${LEGACY_DATUM_UTC} AS datum, ${columns} FROM \`${isp}\` ORDER BY \`${isp}\`.datum DESC LIMIT 1`,
[LEGACY_TREND_TIME_ZONE]
);
const row = rows[0]; const row = rows[0];
pointDescriptors.forEach((descriptor) => { pointDescriptors.forEach((descriptor) => {
@@ -690,8 +714,8 @@ export async function fetchLatestValues(pool, redis, points) {
return values; return values;
} }
export function normalizeRange(input = {}) { export function normalizeRange(input = {}, defaultPresetDays = 1) {
const presetDays = Number(input.presetDays || 1); const presetDays = Number(input.presetDays || defaultPresetDays);
const maxRows = Number(input.maxRows || 4000); const maxRows = Number(input.maxRows || 4000);
const now = new Date(); const now = new Date();
const to = input.to ? new Date(input.to) : now; const to = input.to ? new Date(input.to) : now;
+17 -28
View File
@@ -1,4 +1,7 @@
const SELECTION_SET_KEY = "selection:ids"; const SELECTION_SET_KEY = "selection:ids";
import { DEFAULT_UNITS as DEFAULT_UNIT_DEFINITIONS, normalizeUnitSymbol as canonicalUnitSymbol } from "../../../shared/engineering-units.mjs";
import { DEFAULT_MAX_TREND_SERIES, normalizeMaxTrendSeries } from "../../../shared/trend-preferences.mjs";
const SELECTION_SEQ_KEY = "selection:seq"; const SELECTION_SEQ_KEY = "selection:seq";
const ROLE_SET_KEY = "role:names"; const ROLE_SET_KEY = "role:names";
const UNIT_SET_KEY = "unit:symbols"; const UNIT_SET_KEY = "unit:symbols";
@@ -24,33 +27,12 @@ export const DEFAULT_ROLE_DEFINITIONS = [
}, },
]; ];
export const DEFAULT_UNIT_DEFINITIONS = [
{ symbol: "\u00B0C", label: "Grad Celsius", isSystem: true },
{ symbol: "%", label: "Prozent", isSystem: true },
{ symbol: "K", label: "Kelvin", isSystem: true },
{ symbol: "V", label: "Volt", isSystem: true },
{ symbol: "A", label: "Ampere", isSystem: true },
{ symbol: "Pa", label: "Pascal", isSystem: true },
{ symbol: "bool", label: "Digital / Bool", isSystem: true },
];
function safeParse(jsonValue) { function safeParse(jsonValue) {
return jsonValue ? JSON.parse(jsonValue) : null; return jsonValue ? JSON.parse(jsonValue) : null;
} }
function normalizeUnitSymbol(value, fallback = "") { function normalizeUnitSymbol(value, fallback = "") {
const raw = String(value ?? "").trim(); return canonicalUnitSymbol(value) || fallback;
const collapsed = raw.replace(/\s+/g, "");
if (!collapsed) {
return fallback;
}
if (/^\?C$/i.test(collapsed) || /^Â?\u00B0C$/i.test(collapsed)) {
return "\u00B0C";
}
return raw;
} }
function unitStorageKey(symbol) { function unitStorageKey(symbol) {
@@ -179,11 +161,14 @@ export async function listUnits(redis) {
const symbols = await redis.smembers(UNIT_SET_KEY); const symbols = await redis.smembers(UNIT_SET_KEY);
const items = await Promise.all(symbols.map((symbol) => redis.get(unitStorageKey(symbol)))); const items = await Promise.all(symbols.map((symbol) => redis.get(unitStorageKey(symbol))));
return items const units = new Map();
.map((item) => safeParse(item)) for (const item of items) {
.filter(Boolean) const record = safeParse(item);
.map((unit) => normalizeUnitRecord(unit)) if (!record) continue;
.sort((left, right) => left.symbol.localeCompare(right.symbol, "de-DE")); const unit = normalizeUnitRecord(record);
if (!units.has(unit.symbol) || record.symbol === unit.symbol) units.set(unit.symbol, unit);
}
return [...units.values()].sort((left, right) => left.symbol.localeCompare(right.symbol, "de-DE"));
} }
export async function saveUnit(redis, unit, previousSymbol = "") { export async function saveUnit(redis, unit, previousSymbol = "") {
@@ -264,11 +249,14 @@ export async function saveDashboard(redis, userId, dashboard) {
} }
export async function getPreferences(redis, userId) { export async function getPreferences(redis, userId) {
return safeParse(await redis.get(`preferences:${userId}`)) || { const stored = userId == null ? null : safeParse(await redis.get(`preferences:${userId}`));
return {
theme: "system", theme: "system",
csvDelimiter: ";", csvDelimiter: ";",
sidebarPinned: true, sidebarPinned: true,
trendLineWidth: 1.8, trendLineWidth: 1.8,
...stored,
maxTrendSeries: normalizeMaxTrendSeries(stored?.maxTrendSeries, DEFAULT_MAX_TREND_SERIES),
}; };
} }
@@ -281,6 +269,7 @@ export async function savePreferences(redis, userId, preferences) {
csvDelimiter: preferences.csvDelimiter || current.csvDelimiter || ";", csvDelimiter: preferences.csvDelimiter || current.csvDelimiter || ";",
sidebarPinned: typeof preferences.sidebarPinned === "boolean" ? preferences.sidebarPinned : current.sidebarPinned, sidebarPinned: typeof preferences.sidebarPinned === "boolean" ? preferences.sidebarPinned : current.sidebarPinned,
trendLineWidth: Number.isFinite(Number(preferences.trendLineWidth)) ? Number(preferences.trendLineWidth) : Number(current.trendLineWidth || 1.8), trendLineWidth: Number.isFinite(Number(preferences.trendLineWidth)) ? Number(preferences.trendLineWidth) : Number(current.trendLineWidth || 1.8),
maxTrendSeries: normalizeMaxTrendSeries(preferences.maxTrendSeries, current.maxTrendSeries),
updatedAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
}; };
await redis.set(`preferences:${userId}`, JSON.stringify(payload)); await redis.set(`preferences:${userId}`, JSON.stringify(payload));
+3 -2
View File
@@ -2,10 +2,11 @@ FROM node:22-alpine
WORKDIR /app WORKDIR /app
COPY package*.json ./ COPY collector/package*.json ./
RUN npm ci RUN npm ci
COPY src ./src COPY collector/src ./src
COPY shared /shared
RUN mkdir -p /app/data RUN mkdir -p /app/data
EXPOSE 18110 EXPOSE 18110
+11 -29
View File
@@ -5,6 +5,7 @@ import { fileURLToPath } from "node:url";
import { Buffer } from "node:buffer"; import { Buffer } from "node:buffer";
import net from "node:net"; import net from "node:net";
import mysql from "mysql2/promise"; import mysql from "mysql2/promise";
import { resolveEngineeringUnit } from "../../shared/engineering-units.mjs";
const __dirname = dirname(fileURLToPath(import.meta.url)); const __dirname = dirname(fileURLToPath(import.meta.url));
const dataDir = join(__dirname, "..", "data"); const dataDir = join(__dirname, "..", "data");
@@ -192,27 +193,8 @@ function normalizeText(value) {
return repairText(String(value === undefined || value === null ? "" : value).trim()); return repairText(String(value === undefined || value === null ? "" : value).trim());
} }
function normalizeUnit(value) { function normalizePointUnit(value, kind, name) {
const raw = normalizeText(value); return resolveEngineeringUnit(normalizeText(value), normalizePointKind(kind), name);
const collapsed = raw.replace(/\s+/g, "");
if (!collapsed) {
return "°C";
}
if (/^(?:\?C|\u00B0C)$/i.test(collapsed)) {
return "°C";
}
return raw;
}
function normalizePointUnit(value, kind = "analog") {
const normalizedKind = normalizePointKind(kind);
const raw = normalizeText(value);
if (!raw) {
return normalizedKind === "digital" ? "bool" : "°C";
}
return normalizeUnit(raw);
} }
function normalizePointIndex(value, fallback) { function normalizePointIndex(value, fallback) {
@@ -308,7 +290,7 @@ function parseModbusCsv(payload) {
pointIndex, pointIndex,
name: normalizeText(get("name", `Register ${index + 1}`)) || `Register ${index + 1}`, name: normalizeText(get("name", `Register ${index + 1}`)) || `Register ${index + 1}`,
alias: normalizeText(get("alias", get("name", `Register ${index + 1}`))) || normalizeText(get("name", `Register ${index + 1}`)) || `Register ${index + 1}`, alias: normalizeText(get("alias", get("name", `Register ${index + 1}`))) || normalizeText(get("name", `Register ${index + 1}`)) || `Register ${index + 1}`,
unit: normalizePointUnit(get("unit"), get("kind", get("type", "analog"))), unit: normalizePointUnit(get("unit"), get("kind", get("type", "analog")), get("alias", get("name"))),
dataType: get("datatype", "holding-register"), dataType: get("datatype", "holding-register"),
kind: normalizePointKind(get("kind", get("type", "analog"))), kind: normalizePointKind(get("kind", get("type", "analog"))),
enabled: payload.enabled === true, enabled: payload.enabled === true,
@@ -361,7 +343,7 @@ function parseKnxXml(payload) {
pointIndex: index + 1, pointIndex: index + 1,
name, name,
alias: name, alias: name,
unit: normalizePointUnit("", dpt.startsWith("1.") ? "digital" : "analog"), unit: normalizePointUnit("", dpt.startsWith("1.") ? "digital" : "analog", name),
dataType: dpt || "group-address", dataType: dpt || "group-address",
kind: dpt.startsWith("1.") ? "digital" : "analog", kind: dpt.startsWith("1.") ? "digital" : "analog",
enabled: payload.enabled === true, enabled: payload.enabled === true,
@@ -401,7 +383,7 @@ function createManualDatapoint(store, payload) {
pointIndex, pointIndex,
name, name,
alias, alias,
unit: normalizePointUnit(payload.unit, payload.kind), unit: normalizePointUnit(payload.unit, payload.kind, alias),
kind: normalizePointKind(payload.kind), kind: normalizePointKind(payload.kind),
enabled: payload.enabled !== false, enabled: payload.enabled !== false,
alarmEnabled: payload.alarmEnabled === true, alarmEnabled: payload.alarmEnabled === true,
@@ -438,7 +420,7 @@ function createScanDatapoint(source, payload, index) {
pointIndex, pointIndex,
name: normalizeText(payload.name || alias) || alias, name: normalizeText(payload.name || alias) || alias,
alias, alias,
unit: normalizePointUnit(payload.unit, payload.kind), unit: normalizePointUnit(payload.unit, payload.kind, alias),
kind: normalizePointKind(payload.kind), kind: normalizePointKind(payload.kind),
enabled: payload.enabled === true, enabled: payload.enabled === true,
alarmEnabled: payload.alarmEnabled === true, alarmEnabled: payload.alarmEnabled === true,
@@ -936,7 +918,7 @@ function mapIpsymconVariable(source, variable, categoryId, index) {
nodeId: String(variableId), nodeId: String(variableId),
dataType: variableType ? `ipsymcon-${variableType}` : "ipsymcon-variable", dataType: variableType ? `ipsymcon-${variableType}` : "ipsymcon-variable",
kind, kind,
unit: normalizePointUnit(variable?.unit, kind), unit: normalizePointUnit(variable?.unit, kind, name),
currentValue: variable?.value ?? null, currentValue: variable?.value ?? null,
quality: normalizeText(variable?.quality || "unknown"), quality: normalizeText(variable?.quality || "unknown"),
path: normalizeText(variable?.actual_path || ""), path: normalizeText(variable?.actual_path || ""),
@@ -1744,7 +1726,7 @@ async function ensureTrendTable(tableName) {
CREATE TABLE IF NOT EXISTS \`${table}\` ( CREATE TABLE IF NOT EXISTS \`${table}\` (
\`id\` INT(11) NOT NULL AUTO_INCREMENT, \`id\` INT(11) NOT NULL AUTO_INCREMENT,
\`datum\` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, \`datum\` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
\`userlevel\` INT(1) NOT NULL, \`userlevel\` INT(1) NULL DEFAULT NULL,
${buildValueColumns()}, ${buildValueColumns()},
PRIMARY KEY (\`id\`) PRIMARY KEY (\`id\`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
@@ -1898,7 +1880,7 @@ async function syncDatapointRegistryEntries(datapoints) {
normalizeText(datapoint.alias || datapoint.name || `Wert${datapoint.pointIndex}`), normalizeText(datapoint.alias || datapoint.name || `Wert${datapoint.pointIndex}`),
normalizeText(datapoint.name || datapoint.alias || `Wert${datapoint.pointIndex}`), normalizeText(datapoint.name || datapoint.alias || `Wert${datapoint.pointIndex}`),
String(datapoint.protocol || "unknown"), String(datapoint.protocol || "unknown"),
normalizeUnit(datapoint.unit || ""), normalizePointUnit(datapoint.unit, datapoint.kind, datapoint.alias || datapoint.name),
String(datapoint.kind || "analog"), String(datapoint.kind || "analog"),
datapoint.enabled === true ? 1 : 0, datapoint.enabled === true ? 1 : 0,
datapoint.alarmEnabled === true ? 1 : 0, datapoint.alarmEnabled === true ? 1 : 0,
@@ -2359,7 +2341,7 @@ const server = createServer(async (req, res) => {
address: typeof body.address === "string" ? normalizeText(body.address) : store.datapoints[index].address, address: typeof body.address === "string" ? normalizeText(body.address) : store.datapoints[index].address,
nodeId: typeof body.nodeId === "string" ? normalizeText(body.nodeId) : store.datapoints[index].nodeId, nodeId: typeof body.nodeId === "string" ? normalizeText(body.nodeId) : store.datapoints[index].nodeId,
dataType: typeof body.dataType === "string" && body.dataType.trim() ? normalizeText(body.dataType) : store.datapoints[index].dataType, dataType: typeof body.dataType === "string" && body.dataType.trim() ? normalizeText(body.dataType) : store.datapoints[index].dataType,
unit: body.unit ? normalizePointUnit(body.unit, body.kind || store.datapoints[index].kind) : store.datapoints[index].unit, unit: body.unit != null ? normalizePointUnit(body.unit, body.kind || store.datapoints[index].kind, body.alias || body.name || store.datapoints[index].alias) : store.datapoints[index].unit,
kind: body.kind ? normalizePointKind(body.kind) : store.datapoints[index].kind, kind: body.kind ? normalizePointKind(body.kind) : store.datapoints[index].kind,
scale: Number.isFinite(Number(body.scale)) ? Number(body.scale) : store.datapoints[index].scale, scale: Number.isFinite(Number(body.scale)) ? Number(body.scale) : store.datapoints[index].scale,
}; };
+11 -5
View File
@@ -38,7 +38,8 @@ services:
api: api:
build: build:
context: ./api context: .
dockerfile: api/Dockerfile
container_name: seltd-api container_name: seltd-api
restart: unless-stopped restart: unless-stopped
environment: environment:
@@ -49,6 +50,7 @@ services:
DB_USER: root DB_USER: root
DB_PASSWORD: ${MARIADB_ROOT_PASSWORD:-SE3112} DB_PASSWORD: ${MARIADB_ROOT_PASSWORD:-SE3112}
DB_PASSWORD_FALLBACK: ${DB_PASSWORD_FALLBACK:-root} DB_PASSWORD_FALLBACK: ${DB_PASSWORD_FALLBACK:-root}
LEGACY_TREND_TIME_ZONE: ${LEGACY_TREND_TIME_ZONE:-Europe/Berlin}
REDIS_URL: redis://:${REDIS_PASSWORD:?Set REDIS_PASSWORD in .env}@redis:6379/0 REDIS_URL: redis://:${REDIS_PASSWORD:?Set REDIS_PASSWORD in .env}@redis:6379/0
JWT_SECRET: ${JWT_SECRET:-change-me} JWT_SECRET: ${JWT_SECRET:-change-me}
ADMIN_USERNAME: ${ADMIN_USERNAME:-admin} ADMIN_USERNAME: ${ADMIN_USERNAME:-admin}
@@ -71,13 +73,14 @@ services:
web: web:
build: build:
context: ./web context: .
dockerfile: web/Dockerfile
container_name: seltd-web container_name: seltd-web
restart: unless-stopped restart: unless-stopped
environment: environment:
VITE_API_PORT: ${VITE_API_PORT:-18080} VITE_API_PORT: ${VITE_API_PORT:-18080}
ports: ports:
- "5173:5173" - "81:5173"
depends_on: depends_on:
api: api:
condition: service_healthy condition: service_healthy
@@ -89,7 +92,8 @@ services:
collector: collector:
build: build:
context: ./collector context: .
dockerfile: collector/Dockerfile
container_name: seltd-collector container_name: seltd-collector
restart: unless-stopped restart: unless-stopped
environment: environment:
@@ -160,7 +164,8 @@ services:
runner: runner:
build: build:
context: ./runner context: .
dockerfile: runner/Dockerfile
container_name: seltd-runner container_name: seltd-runner
restart: unless-stopped restart: unless-stopped
environment: environment:
@@ -173,6 +178,7 @@ services:
EXPORT_DIR: /exports EXPORT_DIR: /exports
RUNNER_TICK_MS: ${RUNNER_TICK_MS:-1000} RUNNER_TICK_MS: ${RUNNER_TICK_MS:-1000}
RUNNER_TIMEZONE: ${RUNNER_TIMEZONE:-Europe/Berlin} RUNNER_TIMEZONE: ${RUNNER_TIMEZONE:-Europe/Berlin}
LEGACY_TREND_TIME_ZONE: ${LEGACY_TREND_TIME_ZONE:-Europe/Berlin}
volumes: volumes:
- runner_exports:/exports - runner_exports:/exports
depends_on: depends_on:
+4 -3
View File
@@ -1,7 +1,8 @@
FROM node:22-alpine FROM node:22-alpine
WORKDIR /app WORKDIR /app/runner
COPY package*.json ./ COPY runner/package*.json ./
RUN npm install RUN npm install
COPY src ./src COPY runner/src ./src
COPY shared /app/shared
RUN mkdir -p /exports RUN mkdir -p /exports
CMD ["npm", "start"] CMD ["npm", "start"]
+9 -3
View File
@@ -5,6 +5,8 @@ import https from "node:https";
import path from "node:path"; import path from "node:path";
import Redis from "ioredis"; import Redis from "ioredis";
import mysql from "mysql2/promise"; import mysql from "mysql2/promise";
import { LEGACY_DATUM_UTC, LEGACY_TREND_TIME_ZONE, setUtcSession } from "../../shared/trend-time.mjs";
import { normalizeUnitSymbol } from "../../shared/engineering-units.mjs";
const redis = new Redis(process.env.REDIS_URL || "redis://redis:6379", { maxRetriesPerRequest: 2 }); const redis = new Redis(process.env.REDIS_URL || "redis://redis:6379", { maxRetriesPerRequest: 2 });
const db = mysql.createPool({ const db = mysql.createPool({
@@ -14,9 +16,11 @@ const db = mysql.createPool({
user: process.env.DB_USER || "root", user: process.env.DB_USER || "root",
password: process.env.DB_PASSWORD || "SE3112", password: process.env.DB_PASSWORD || "SE3112",
charset: "utf8mb4", charset: "utf8mb4",
timezone: "Z",
waitForConnections: true, waitForConnections: true,
connectionLimit: 3, connectionLimit: 3,
}); });
db.on("connection", setUtcSession);
const exportDir = process.env.EXPORT_DIR || "/exports"; const exportDir = process.env.EXPORT_DIR || "/exports";
const tickMs = Math.max(500, Number(process.env.RUNNER_TICK_MS || 1000)); const tickMs = Math.max(500, Number(process.env.RUNNER_TICK_MS || 1000));
const timeZone = process.env.RUNNER_TIMEZONE || "Europe/Berlin"; const timeZone = process.env.RUNNER_TIMEZONE || "Europe/Berlin";
@@ -87,7 +91,7 @@ async function getPointMeta(isp, pointIndex) {
const point = Array.isArray(points) const point = Array.isArray(points)
? points.find((item) => Number(item.pointIndex) === Number(pointIndex)) ? points.find((item) => Number(item.pointIndex) === Number(pointIndex))
: points[String(pointIndex)] || points[Number(pointIndex)]; : points[String(pointIndex)] || points[Number(pointIndex)];
return { alias: point?.alias || `Wert${pointIndex}`, unit: point?.unit || "" }; return { alias: point?.alias || `Wert${pointIndex}`, unit: normalizeUnitSymbol(point?.unit) };
} }
async function exportSelection(job, selection) { async function exportSelection(job, selection) {
@@ -113,8 +117,10 @@ async function exportSelection(job, selection) {
} else { } else {
const column = `Wert${pointIndex}`; const column = `Wert${pointIndex}`;
const [data] = await db.query( const [data] = await db.query(
`SELECT datum, \`${column}\` AS value FROM \`${table}\` WHERE datum >= ? ORDER BY datum ASC`, `SELECT ${LEGACY_DATUM_UTC} AS datum, \`${column}\` AS value FROM \`${table}\`
[since], WHERE datum >= DATE_SUB(?, INTERVAL 1 DAY) AND ${LEGACY_DATUM_UTC} >= ?
ORDER BY \`${table}\`.datum ASC`,
[LEGACY_TREND_TIME_ZONE, since, LEGACY_TREND_TIME_ZONE, since],
); );
for (const item of data) { for (const item of data) {
const value = formatExportValue(item.value); const value = formatExportValue(item.value);
+49
View File
@@ -0,0 +1,49 @@
export const AUTO_UNIT = "__auto__";
export const DEFAULT_ANALOG_UNIT = "\u00B0C";
export const DIGITAL_UNIT = "Digital";
export const DEFAULT_UNITS = [
[DEFAULT_ANALOG_UNIT, "Grad Celsius"],
["%", "Prozent"],
["K", "Kelvin"],
["V", "Volt"],
["A", "Ampere"],
["Pa", "Pascal"],
[DIGITAL_UNIT, "Digital"],
["ppm", "Parts per million"],
["%RH", "Relative Feuchte"],
["COV", "COV"],
["mBar", "Millibar"],
["Bar", "Bar"],
["kW", "Kilowatt"],
["kWh", "Kilowattstunden"],
["Liter", "Liter"],
["m\u00B3", "Kubikmeter"],
].map(([symbol, label]) => ({ symbol, label, isSystem: true }));
export function normalizeUnitSymbol(value) {
const symbol = String(value ?? "").trim();
if (/^(?:bool|boolean|digital)$/i.test(symbol)) return DIGITAL_UNIT;
if (/^(?:\?C|\u00C2*\u00B0\s*C)$/i.test(symbol)) return DEFAULT_ANALOG_UNIT;
if (/^%\s*rh$/i.test(symbol)) return "%RH";
if (/^m(?:\^?3|\u00B3)$/i.test(symbol)) return "m\u00B3";
return DEFAULT_UNITS.find((unit) => unit.symbol.toLowerCase() === symbol.toLowerCase())?.symbol ?? symbol;
}
export function detectEngineeringUnit(name, kind) {
if (kind === "digital") return DIGITAL_UNIT;
const label = String(name ?? "").toLowerCase();
if (/co[2\u2082]/.test(label)) return "ppm";
if (/feucht|humidity/.test(label)) return "%RH";
if (/energie|energy|kwh/.test(label)) return "kWh";
if (/leistung|power/.test(label)) return "kW";
if (/druck|pressure/.test(label)) return /m\s*bar|millibar/.test(label) ? "mBar" : "Pa";
if (/temp|f(?:\u00FC|ue)hler/.test(label)) return DEFAULT_ANALOG_UNIT;
return "";
}
export function resolveEngineeringUnit(value, kind, name) {
const unit = normalizeUnitSymbol(value);
if (unit && unit !== AUTO_UNIT) return unit;
return detectEngineeringUnit(name, kind) || DEFAULT_ANALOG_UNIT;
}
+51
View File
@@ -0,0 +1,51 @@
export const CHART_DIVISIONS = [3, 4, 6, 8, 10];
export const DEFAULT_CHART_SETTINGS = {
divisions: 6,
grid: "both",
gridStyle: "dashed",
shadedBands: false,
opacity: 100,
highContrast: false,
axes: {},
assignments: {},
};
function entries(value) {
return value && typeof value === "object" && !Array.isArray(value) ? Object.entries(value) : [];
}
function numericBound(value) {
if (typeof value === "number" && Number.isFinite(value)) return value;
if (typeof value === "string" && value.trim() && Number.isFinite(Number(value))) return Number(value);
return "";
}
export function normalizeTrendChartSettings(input, points) {
const settings = input || {};
const pointKeys = points && new Set(points.map((point) => `${point.isp}:${point.pointIndex}`));
const axes = Object.fromEntries(entries(settings.axes)
.filter(([id, axis]) => axis && typeof axis === "object" && (
(id.startsWith("unit:") && id.length <= 261)
|| (id.startsWith("point:") && (!pointKeys || pointKeys.has(id.slice(6))))
))
.map(([id, axis]) => [id, {
...(axis.side === "left" || axis.side === "right" ? { side: axis.side } : {}),
mode: axis.mode === "manual" ? "manual" : "auto",
min: numericBound(axis.min),
max: numericBound(axis.max),
}]));
const assignments = Object.fromEntries(entries(settings.assignments)
.filter(([key, value]) => value === "own" && (!pointKeys || pointKeys.has(key))));
return {
divisions: CHART_DIVISIONS.includes(settings.divisions) ? settings.divisions : DEFAULT_CHART_SETTINGS.divisions,
grid: ["both", "horizontal", "vertical", "none"].includes(settings.grid) ? settings.grid : DEFAULT_CHART_SETTINGS.grid,
gridStyle: settings.gridStyle === "solid" ? "solid" : DEFAULT_CHART_SETTINGS.gridStyle,
shadedBands: settings.shadedBands === true,
opacity: Number.isFinite(settings.opacity) ? Math.max(20, Math.min(100, settings.opacity)) : DEFAULT_CHART_SETTINGS.opacity,
highContrast: settings.highContrast === true,
axes,
assignments,
};
}
+24
View File
@@ -0,0 +1,24 @@
export const DEFAULT_TREND_PRESET = "1";
export const DEFAULT_MAX_TREND_SERIES = 10;
export const MAX_TREND_SERIES = 100;
export const TREND_PRESETS = [
{ value: "0.0034722222", label: "5 min" },
{ value: "0.0069444444", label: "10 min" },
{ value: "0.0208333333", label: "30 min" },
{ value: "0.0416666667", label: "1 h" },
{ value: "0.0833333333", label: "2 h" },
{ value: "0.25", label: "6 h" },
{ value: "0.5", label: "12 h" },
{ value: "1", label: "24 h" },
{ value: "2", label: "2 Tage" },
{ value: "3", label: "3 Tage" },
{ value: "7", label: "7 Tage" },
{ value: "14", label: "14 Tage" },
{ value: "30", label: "30 Tage" },
];
export function normalizeMaxTrendSeries(value, fallback = DEFAULT_MAX_TREND_SERIES) {
const count = Number(value);
return Number.isInteger(count) && count >= 1 && count <= MAX_TREND_SERIES ? count : fallback;
}
+6
View File
@@ -0,0 +1,6 @@
export const LEGACY_TREND_TIME_ZONE = process.env.LEGACY_TREND_TIME_ZONE || "Europe/Berlin";
export const LEGACY_DATUM_UTC = "CONVERT_TZ(datum, ?, '+00:00')";
export function setUtcSession(connection) {
connection.query("SET time_zone = '+00:00'");
}
+6 -3
View File
@@ -1,11 +1,14 @@
FROM node:22-alpine FROM node:22-alpine
WORKDIR /app WORKDIR /app/web
COPY package*.json ./ COPY web/package*.json ./
RUN npm ci RUN npm ci
COPY . . COPY web/index.html web/vite.config.js ./
COPY web/src ./src
COPY web/public ./public
COPY shared /app/shared
EXPOSE 5173 EXPOSE 5173
+323 -306
View File
File diff suppressed because it is too large. Load diff
+2
View File
@@ -80,6 +80,8 @@ export const api = {
loadDashboardData: (token, body) => apiRequest("/dashboard/data", { method: "POST", token, body }), loadDashboardData: (token, body) => apiRequest("/dashboard/data", { method: "POST", token, body }),
getPreferences: (token) => apiRequest("/preferences", { token }), getPreferences: (token) => apiRequest("/preferences", { token }),
savePreferences: (token, body) => apiRequest("/preferences", { method: "PUT", token, body }), savePreferences: (token, body) => apiRequest("/preferences", { method: "PUT", token, body }),
getTrendDefaults: () => apiRequest("/settings/trend"),
saveTrendDefaults: (token, body) => apiRequest("/settings/trend", { method: "PUT", token, body }),
getIntegrations: (token) => apiRequest("/integrations", { token }), getIntegrations: (token) => apiRequest("/integrations", { token }),
saveIntegrations: (token, body) => apiRequest("/integrations", { method: "PUT", token, body }), saveIntegrations: (token, body) => apiRequest("/integrations", { method: "PUT", token, body }),
getRunnerJobs: (token) => apiRequest("/runner/jobs", { token }), getRunnerJobs: (token) => apiRequest("/runner/jobs", { token }),
+83
View File
@@ -0,0 +1,83 @@
const icons = {
dashboard: "M3 3h7v7H3z M14 3h7v7h-7z M3 14h7v7H3z M14 14h7v7h-7z",
trends: "M3 4v16h18 M6 15l5-5 4 3 6-7",
admin: "M12 22s7-3 7-10V5l-7-3-7 3v7c0 7 7 10 7 10Z M9 12l2 2 4-4",
settings: "M4 6h6m4 0h6 M4 12h10m4 0h2 M4 18h2m4 0h10 M10 4v4m4 2v4m-8 2v4",
expand: "M3 5h18v14H3z M9 5v14 M13 9l3 3-3 3",
collapse: "M3 5h18v14H3z M9 5v14 M16 9l-3 3 3 3",
login: "M14 4h6v16h-6 M4 12h12 M12 8l4 4-4 4",
logout: "M10 4H4v16h6 M8 12h12 M16 8l4 4-4 4",
};
function SidebarIcon({ name }) {
return (
<svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
<path d={icons[name]} />
</svg>
);
}
export function SmallFootnote() {
return <div className="tiny-note">by J.H. | SE Inno GmbH</div>;
}
export default function Sidebar({ collapsed, onToggle, views, activeView, onNavigate, user, userLabel, onLogout }) {
const toggleLabel = collapsed ? "Seitenleiste ausklappen" : "Seitenleiste einklappen";
const accountLabel = user ? "Abmelden" : "Anmelden";
return (
<aside className={collapsed ? "sidebar collapsed" : "sidebar"}>
<div className="sidebar-top">
<div className="sidebar-brand-row">
<div className="logo-lockup">
<img src="/logo.png" alt="SE Logo" />
{collapsed ? null : (
<div>
<div className="eyebrow">SE</div>
<div className="logo-title">SE Local Trenddata.</div>
</div>
)}
</div>
<button type="button" className="icon-button sidebar-toggle" title={toggleLabel} aria-label={toggleLabel} aria-expanded={!collapsed} onClick={onToggle}>
<SidebarIcon name={collapsed ? "expand" : "collapse"} />
</button>
</div>
<nav className="nav-list" aria-label="Hauptnavigation">
{views.map((view) => (
<button
key={view.id}
type="button"
className={activeView === view.id ? "nav-button active" : "nav-button"}
title={collapsed ? view.label : undefined}
aria-label={view.label}
aria-current={activeView === view.id ? "page" : undefined}
onClick={() => onNavigate(view.id)}
>
<SidebarIcon name={view.id} />
{collapsed ? null : <span>{view.label}</span>}
</button>
))}
</nav>
</div>
<div className="sidebar-footer">
{user && !collapsed ? (
<div className="user-card">
<strong>{userLabel}</strong>
<span>{user.role === "admin" ? "Systemzugang" : user.role === "technician" ? "Technikzugang" : "Benutzerzugang"}</span>
</div>
) : null}
<button
className={collapsed ? "icon-button sidebar-account" : "ghost-button compact-button sidebar-account"}
type="button"
title={collapsed ? accountLabel : undefined}
aria-label={accountLabel}
onClick={user ? onLogout : () => onNavigate("settings")}
>
<SidebarIcon name={user ? "logout" : "login"} />
{collapsed ? null : <span>{accountLabel}</span>}
</button>
{collapsed ? null : <SmallFootnote />}
</div>
</aside>
);
}
+145 -203
View File
@@ -1,16 +1,20 @@
import { useEffect, useMemo, useRef, useState } from "react"; import { useMemo, useRef, useState } from "react";
import { jsPDF } from "jspdf"; import { jsPDF } from "jspdf";
import * as XLSX from "xlsx"; import * as XLSX from "xlsx";
import { import {
CartesianGrid, CartesianGrid,
Customized,
Line, Line,
LineChart, LineChart,
ReferenceArea,
ResponsiveContainer, ResponsiveContainer,
Tooltip, Tooltip,
XAxis, XAxis,
YAxis, YAxis,
} from "recharts"; } from "recharts";
import TrendChartSettings from "./TrendChartSettings.jsx";
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";
function downloadBlob(filename, blob) { function downloadBlob(filename, blob) {
const url = URL.createObjectURL(blob); const url = URL.createObjectURL(blob);
@@ -25,43 +29,68 @@ function quoteCell(value) {
return `"${String(value ?? "").replaceAll('"', '""')}"`; return `"${String(value ?? "").replaceAll('"', '""')}"`;
} }
function buildRandomColor(index) {
const hue = Math.round((Math.random() * 360 + index * 41) % 360);
const saturation = 72 + (index % 3) * 4;
const lightness = 46 + (index % 4) * 3;
return `hsl(${hue} ${saturation}% ${lightness}%)`;
}
function getAnalogDomain(rows, visibleSeries) {
const values = [];
rows.forEach((row) => {
visibleSeries.filter((item) => item.kind !== "digital").forEach((item) => {
const value = row[item.key];
if (Number.isFinite(value)) {
values.push(value);
}
});
});
if (!values.length) {
return [0, 1];
}
const min = Math.min(...values);
const max = Math.max(...values);
if (min === max) {
return [min - 1, max + 1];
}
const padding = (max - min) * 0.08;
return [min - padding, max + padding];
}
function formatTrendNumber(value) { function formatTrendNumber(value) {
const numeric = Number(value); const numeric = Number(value);
return Number.isFinite(numeric) ? numeric.toFixed(2) : "--"; return Number.isFinite(numeric) ? numeric.toFixed(2) : "--";
} }
function TimeZoomOverlay({ offset, onZoom }) {
const activeDrag = useRef(null);
const [drag, setDrag] = useState(null);
if (!offset?.width || !offset.height) return null;
function position(event) {
const bounds = event.currentTarget.getBoundingClientRect();
return Math.max(0, Math.min(1, (event.clientX - bounds.left) / bounds.width));
}
function cancel() {
activeDrag.current = null;
setDrag(null);
}
return (
<g>
{drag ? (
<rect
x={offset.left + Math.min(drag.start, drag.end) * offset.width}
y={offset.top}
width={Math.abs(drag.end - drag.start) * offset.width}
height={offset.height}
fill="var(--brand-2)"
fillOpacity={0.2}
pointerEvents="none"
/>
) : null}
<rect
className="trend-zoom-target"
x={offset.left} y={offset.top} width={offset.width} height={offset.height}
fill="transparent"
onPointerDown={(event) => {
if (!event.isPrimary || event.button !== 0) return;
const start = position(event);
event.currentTarget.setPointerCapture(event.pointerId);
activeDrag.current = { start, end: start, pointerId: event.pointerId };
setDrag(activeDrag.current);
}}
onPointerMove={(event) => {
if (activeDrag.current?.pointerId !== event.pointerId) return;
setDrag({ ...activeDrag.current, end: position(event) });
}}
onPointerUp={(event) => {
if (activeDrag.current?.pointerId !== event.pointerId) return;
const { start } = activeDrag.current;
const end = position(event);
if (Math.abs(end - start) * offset.width >= 8) onZoom(start, end);
cancel();
}}
onPointerCancel={cancel}
onLostPointerCapture={cancel}
/>
</g>
);
}
export default function TrendChart({ export default function TrendChart({
result, result,
title = "Trendansicht", title = "Trendansicht",
@@ -73,154 +102,48 @@ export default function TrendChart({
allowFocusMode = true, allowFocusMode = true,
compact = false, compact = false,
lineWidth = 1.8, lineWidth = 1.8,
settings = DEFAULT_CHART_SETTINGS,
onSettingsChange,
onSaveSettings,
savingSettings,
}) { }) {
const wrapperRef = useRef(null);
const chartHostRef = useRef(null); const chartHostRef = useRef(null);
const dragBoxRef = useRef(null);
const domainRef = useRef({ x: [0, 1], y: [0, 1] });
const [selectedKeys, setSelectedKeys] = useState([]); const [selectedKeys, setSelectedKeys] = useState([]);
const [dragBox, setDragBox] = useState(null);
const [zoomDomain, setZoomDomain] = useState(null); const [zoomDomain, setZoomDomain] = useState(null);
const [exportFormat, setExportFormat] = useState("csv"); const [exportFormat, setExportFormat] = useState("csv");
const [transparentBackground, setTransparentBackground] = useState(false); const [transparentBackground, setTransparentBackground] = useState(false);
const series = useMemo(() => { const series = useMemo(() => assignTrendColors(result?.series || [])
const fallbackColors = []; .map((item) => ({
return (result?.series || []).map((item, index) => ({
...item, ...item,
color: item.color || (fallbackColors[index] ||= buildRandomColor(index)),
name: `${item.displayName} · ${item.alias}${item.unit ? ` (${item.unit})` : ""}`, name: `${item.displayName} · ${item.alias}${item.unit ? ` (${item.unit})` : ""}`,
}));
}, [result]);
const rows = useMemo(() => (result?.rows || []).map((row) => ({
...row,
timestampMs: new Date(row.timestamp).getTime(),
})), [result]); })), [result]);
const visibleSeries = selectedKeys.length ? series.filter((item) => selectedKeys.includes(item.key)) : series; const rows = useMemo(() => (result?.rows || [])
const analogSeries = visibleSeries.filter((item) => item.kind !== "digital"); .map((row) => ({ ...row, timestampMs: new Date(row.timestamp).getTime() }))
const digitalSeries = visibleSeries.filter((item) => item.kind === "digital"); .filter((row) => Number.isFinite(row.timestampMs))
.sort((left, right) => left.timestampMs - right.timestampMs), [result]);
const baseXDomain = useMemo(() => { const baseXDomain = rows.length > 1
if (!rows.length) { ? [rows[0].timestampMs, rows.at(-1).timestampMs]
return [0, 1]; : [(rows[0]?.timestampMs ?? 0) - 1000, (rows[0]?.timestampMs ?? 0) + 1000];
} const activeZoom = zoomDomain && zoomDomain.result === result ? zoomDomain.domain : null;
return [rows[0].timestampMs, rows[rows.length - 1].timestampMs]; const xDomain = activeZoom || baseXDomain;
}, [rows]); const axes = useMemo(() => getTrendAxes(series, settings.assignments).map((axis) => ({
...axis,
const baseYDomain = useMemo(() => { scale: getTrendAxisScale(axis, settings.axes[axis.id], rows, activeZoom, settings.divisions),
if (analogSeries.length === 0 && digitalSeries.length > 0) { })), [series, settings.assignments, settings.axes, settings.divisions, rows, activeZoom]);
return [0, 2]; const axisIndex = new Map(axes.map((axis, index) => [axis.id, index]));
} const activeKeys = new Set(series.filter((entry) => selectedKeys.includes(entry.key)).map((entry) => entry.key));
return getAnalogDomain(rows, visibleSeries); const hasFocusSelection = activeKeys.size > 0 && activeKeys.size < series.length;
}, [analogSeries.length, digitalSeries.length, rows, visibleSeries]); const seriesLimited = result?.requestedSeriesCount > result?.maxSeries;
const xDomain = zoomDomain?.x || baseXDomain;
const yDomain = zoomDomain?.y || baseYDomain;
const hasFocusSelection = selectedKeys.length > 0 && selectedKeys.length < series.length;
const normalizedLineWidth = Number.isFinite(Number(lineWidth)) ? Number(lineWidth) : 1.8; const normalizedLineWidth = Number.isFinite(Number(lineWidth)) ? Number(lineWidth) : 1.8;
useEffect(() => { function zoomTime(start, end) {
domainRef.current = { x: xDomain, y: yDomain }; const domain = getTimeZoom(xDomain, start, end);
}, [xDomain, yDomain]); if (domain) setZoomDomain({ result, domain });
const mapDragToDomain = (clientX, clientY) => {
const rect = chartHostRef.current?.getBoundingClientRect() || wrapperRef.current?.getBoundingClientRect();
if (!rect) {
return null;
} }
const activeDomain = domainRef.current;
const xRatio = Math.max(0, Math.min(1, (clientX - rect.left) / rect.width));
const yRatio = Math.max(0, Math.min(1, (clientY - rect.top) / rect.height));
const xValue = activeDomain.x[0] + (activeDomain.x[1] - activeDomain.x[0]) * xRatio;
const yValue = activeDomain.y[1] - (activeDomain.y[1] - activeDomain.y[0]) * yRatio;
return {
xValue,
yValue,
xPixel: clientX - rect.left,
yPixel: clientY - rect.top,
};
};
const handleMouseDown = (event) => {
if (event.button !== 0) {
return;
}
event.preventDefault();
const mapped = mapDragToDomain(event.clientX, event.clientY);
if (!mapped) {
return;
}
const nextDragBox = { start: mapped, end: mapped };
dragBoxRef.current = nextDragBox;
setDragBox(nextDragBox);
};
const updateDragBox = (clientX, clientY) => {
const mapped = mapDragToDomain(clientX, clientY);
if (!mapped) {
return;
}
setDragBox((current) => {
if (!current) {
return current;
}
const nextDragBox = { ...current, end: mapped };
dragBoxRef.current = nextDragBox;
return nextDragBox;
});
};
const finalizeDragBox = (box) => {
if (!box) {
return;
}
const deltaX = Math.abs(box.end.xPixel - box.start.xPixel);
const deltaY = Math.abs(box.end.yPixel - box.start.yPixel);
if (deltaX < 12 && deltaY < 12) {
dragBoxRef.current = null;
setDragBox(null);
return;
}
const currentDomain = domainRef.current;
setZoomDomain({
x: deltaX < 12 ? currentDomain.x : [Math.min(box.start.xValue, box.end.xValue), Math.max(box.start.xValue, box.end.xValue)],
y: deltaY < 12 ? currentDomain.y : [Math.min(box.start.yValue, box.end.yValue), Math.max(box.start.yValue, box.end.yValue)],
});
dragBoxRef.current = null;
setDragBox(null);
};
useEffect(() => {
if (!dragBox) {
return undefined;
}
const handleWindowMouseMove = (event) => {
updateDragBox(event.clientX, event.clientY);
};
const handleWindowMouseUp = () => {
finalizeDragBox(dragBoxRef.current);
};
window.addEventListener("mousemove", handleWindowMouseMove);
window.addEventListener("mouseup", handleWindowMouseUp);
return () => {
window.removeEventListener("mousemove", handleWindowMouseMove);
window.removeEventListener("mouseup", handleWindowMouseUp);
};
}, [dragBox, xDomain, yDomain]);
const resetZoom = () => {
setZoomDomain(null);
};
const clearFocus = () => { const clearFocus = () => {
setSelectedKeys([]); setSelectedKeys([]);
}; };
@@ -365,6 +288,7 @@ export default function TrendChart({
<div className={compact ? "panel chart-panel compact-chart empty-state" : "panel chart-panel empty-state"}> <div className={compact ? "panel chart-panel compact-chart empty-state" : "panel chart-panel empty-state"}>
<h3>{title}</h3> <h3>{title}</h3>
<p>Keine Daten im gewählten Zeitraum.</p> <p>Keine Daten im gewählten Zeitraum.</p>
{seriesLimited ? <small>Diagrammlimit: {result.maxSeries} von {result.requestedSeriesCount} Datenpunkten.</small> : null}
</div> </div>
); );
} }
@@ -374,7 +298,8 @@ export default function TrendChart({
<div className="panel-header compact-header chart-toolbar"> <div className="panel-header compact-header chart-toolbar">
<div> <div>
<h3>{title}</h3> <h3>{title}</h3>
<p>Ziehen mit gedrückter Maustaste zoomt Zeit und Wertebereich gemeinsam.</p> {rows.length > 1 && !compact ? <p>Zum Zeitzoom einen Bereich im Diagramm aufziehen.</p> : null}
{seriesLimited ? <p>Diagrammlimit: {result.maxSeries} von {result.requestedSeriesCount} Datenpunkten.</p> : null}
</div> </div>
<div className="chart-actions"> <div className="chart-actions">
{allowExports ? ( {allowExports ? (
@@ -403,41 +328,68 @@ export default function TrendChart({
<button className="ghost-button" type="button" onClick={handleExport}>Export</button> <button className="ghost-button" type="button" onClick={handleExport}>Export</button>
</> </>
) : null} ) : null}
{zoomDomain ? <button className="ghost-button" type="button" onClick={resetZoom}>Zoom zurück</button> : null} {onSettingsChange ? (
<TrendChartSettings
settings={settings}
onChange={onSettingsChange}
onSave={onSaveSettings}
saving={savingSettings}
axes={axes}
series={series}
/>
) : null}
{!compact && rows.length > 1 ? <button className="ghost-button" type="button" onClick={() => zoomTime(0.25, 0.75)}>Zeitzoom +</button> : null}
{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} {allowFocusMode ? <button className="ghost-button" type="button" onClick={onToggleExpanded}>{expanded ? "Normalansicht" : "Vollbild"}</button> : null}
</div> </div>
</div> </div>
<div <div className={settings.highContrast ? "chart-wrapper high-contrast" : "chart-wrapper"}>
ref={wrapperRef} <div ref={chartHostRef} className="chart-host" style={{ minWidth: 220 + axes.length * 64 }}>
className={dragBox ? "chart-wrapper dragging" : "chart-wrapper"}
onMouseDown={handleMouseDown}
>
<div ref={chartHostRef} className="chart-host">
<ResponsiveContainer width="100%" height={expanded ? 680 : compact ? 280 : 360}> <ResponsiveContainer width="100%" height={expanded ? 680 : compact ? 280 : 360}>
<LineChart data={rows} margin={{ top: 8, right: 18, left: 0, bottom: 8 }}> <LineChart data={rows} margin={{ top: 8, right: 18, left: 0, bottom: 8 }}>
<CartesianGrid strokeDasharray="3 3" stroke="var(--grid)" /> <CartesianGrid
horizontal={settings.grid === "both" || settings.grid === "horizontal"}
vertical={settings.grid === "both" || settings.grid === "vertical"}
horizontalValues={axes[0]?.scale.ticks}
horizontalFill={settings.shadedBands ? ["transparent", "var(--trend-band)"] : []}
strokeDasharray={settings.gridStyle === "dashed" ? "3 3" : undefined}
stroke="var(--trend-grid)"
/>
<XAxis <XAxis
dataKey="timestampMs" dataKey="timestampMs"
type="number" type="number"
scale="time" scale="time"
domain={xDomain} domain={xDomain}
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" })} tickFormatter={(value) => new Date(value).toLocaleString("de-DE", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" })}
minTickGap={28} minTickGap={28}
stroke="var(--muted)" stroke="var(--trend-axis)"
/> />
{analogSeries.length ? <YAxis yAxisId="analog" stroke="var(--muted)" domain={yDomain} width={52} tickFormatter={formatTrendNumber} /> : null} {axes.map((axis, index) => (
{digitalSeries.length ? (
<YAxis <YAxis
yAxisId="digital" key={axis.id}
orientation="right" yAxisId={index}
domain={[0, 2]} orientation={settings.axes[axis.id]?.side || axis.side}
ticks={[0, 1]} domain={axis.scale.domain}
width={46} ticks={axis.scale.ticks}
stroke="var(--muted)" width={64}
allowDecimals={false} stroke="var(--trend-axis)"
allowDataOverflow
interval={0}
tick={{ fontSize: 10 }}
tickFormatter={axis.digital ? String : formatTrendNumber}
label={axis.unit ? {
value: axis.unit,
angle: -90,
position: (settings.axes[axis.id]?.side || axis.side) === "left" ? "insideLeft" : "insideRight",
fill: "var(--trend-axis)",
fontSize: 10,
offset: 2,
} : undefined}
/> />
) : null} ))}
<Tooltip <Tooltip
labelFormatter={(value) => new Date(value).toLocaleString("de-DE")} labelFormatter={(value) => new Date(value).toLocaleString("de-DE")}
formatter={(value, name) => [formatTrendNumber(value), name]} formatter={(value, name) => [formatTrendNumber(value), name]}
@@ -448,35 +400,25 @@ export default function TrendChart({
fontSize: 12, fontSize: 12,
}} }}
/> />
{dragBox ? (
<ReferenceArea
x1={Math.min(dragBox.start.xValue, dragBox.end.xValue)}
x2={Math.max(dragBox.start.xValue, dragBox.end.xValue)}
y1={Math.min(dragBox.start.yValue, dragBox.end.yValue)}
y2={Math.max(dragBox.start.yValue, dragBox.end.yValue)}
strokeOpacity={0.5}
fillOpacity={0.12}
fill="var(--brand-2)"
/>
) : null}
{series.map((entry) => { {series.map((entry) => {
const isolated = selectedKeys.length > 0 && !selectedKeys.includes(entry.key); const isolated = hasFocusSelection && !activeKeys.has(entry.key);
return ( return (
<Line <Line
key={entry.key} key={entry.key}
yAxisId={entry.kind === "digital" ? "digital" : "analog"} yAxisId={axisIndex.get(seriesAxisId(entry, settings.assignments))}
type={entry.kind === "digital" ? "stepAfter" : "linear"} type={entry.kind === "digital" ? "stepAfter" : "linear"}
dataKey={entry.key} dataKey={entry.key}
dot={false} dot={false}
connectNulls connectNulls
strokeWidth={selectedKeys.includes(entry.key) ? normalizedLineWidth + 0.55 : normalizedLineWidth} strokeWidth={normalizedLineWidth + (settings.highContrast ? 0.6 : 0) + (activeKeys.has(entry.key) ? 0.55 : 0)}
stroke={entry.color} stroke={entry.color}
strokeOpacity={isolated ? 0.1 : 1} strokeOpacity={(isolated ? 0.1 : 1) * settings.opacity / 100}
isAnimationActive={false} isAnimationActive={false}
name={entry.name} name={entry.name}
/> />
); );
})} })}
{rows.length > 1 ? <Customized component={TimeZoomOverlay} onZoom={zoomTime} /> : null}
</LineChart> </LineChart>
</ResponsiveContainer> </ResponsiveContainer>
</div> </div>
@@ -485,8 +427,8 @@ export default function TrendChart({
<div className="legend-row"> <div className="legend-row">
<div className="legend-grid"> <div className="legend-grid">
{series.map((entry) => { {series.map((entry) => {
const dimmed = selectedKeys.length > 0 && !selectedKeys.includes(entry.key); const dimmed = hasFocusSelection && !activeKeys.has(entry.key);
const active = selectedKeys.includes(entry.key); const active = activeKeys.has(entry.key);
return ( return (
<button <button
key={entry.key} key={entry.key}
+116
View File
@@ -0,0 +1,116 @@
import { unitAxisId } from "./trend-scales.mjs";
import { CHART_DIVISIONS } from "../../../shared/trend-chart-settings.mjs";
export default function TrendChartSettings({ settings, onChange, onSave, saving, axes, series }) {
function updateAxis(axis, change) {
const current = settings.axes[axis.id] || {};
onChange({
axes: { ...settings.axes, [axis.id]: { ...current, ...change } },
});
}
return (
<details className="trend-settings">
<summary className="ghost-button">Diagramm einstellen</summary>
<div className="trend-settings-popover">
<div className="trend-settings-fields">
<label>
<span>Achseneinteilung</span>
<select value={settings.divisions} onChange={(event) => onChange({ divisions: Number(event.target.value) })}>
{CHART_DIVISIONS.map((divisions) => <option key={divisions} value={divisions}>{divisions} Abschnitte</option>)}
</select>
</label>
<label>
<span>Gitternetz</span>
<select value={settings.grid} onChange={(event) => onChange({ grid: event.target.value })}>
<option value="both">Horizontal und vertikal</option>
<option value="horizontal">Nur horizontal</option>
<option value="vertical">Nur vertikal</option>
<option value="none">Aus</option>
</select>
</label>
<label>
<span>Rasterdarstellung</span>
<select value={settings.shadedBands ? "bands" : settings.gridStyle} onChange={(event) => onChange({
shadedBands: event.target.value === "bands",
gridStyle: event.target.value === "solid" ? "solid" : "dashed",
})}>
<option value="dashed">Gestrichelt</option>
<option value="solid">Durchgezogen</option>
<option value="bands">Mit Hintergrundstreifen</option>
</select>
</label>
<label>
<span>Kontrast</span>
<select value={settings.highContrast ? "high" : "normal"} onChange={(event) => onChange({ highContrast: event.target.value === "high" })}>
<option value="normal">Normal</option>
<option value="high">Hoch</option>
</select>
</label>
<label className="trend-opacity-field">
<span>Transparenz der Linien · {100 - settings.opacity} %</span>
<input type="range" min="20" max="100" value={settings.opacity} onChange={(event) => onChange({ opacity: Number(event.target.value) })} />
</label>
</div>
<fieldset className="trend-settings-group">
<legend>Y-Achsen</legend>
{axes.map((axis) => {
const config = settings.axes[axis.id] || {};
const [min, max] = axis.scale.domain;
return (
<div key={axis.id} className="trend-axis-settings">
<strong>{axis.name}</strong>
<div className="trend-settings-fields">
<label>
<span>Seite</span>
<select value={config.side || axis.side} onChange={(event) => updateAxis(axis, { side: event.target.value })}>
<option value="left">Links</option>
<option value="right">Rechts</option>
</select>
</label>
<label>
<span>Skalierung</span>
<select disabled={axis.digital} value={axis.digital ? "digital" : config.mode || "auto"} onChange={(event) => updateAxis(axis, {
mode: event.target.value, min: config.min ?? Number(min.toPrecision(8)), max: config.max ?? Number(max.toPrecision(8)),
})}>
{axis.digital ? <option value="digital">Digital (0 / 1)</option> : <>
<option value="auto">Automatisch</option>
<option value="manual">Manuell</option>
</>}
</select>
</label>
{!axis.digital && config.mode === "manual" ? <>
<label><span>Minimum</span><input type="number" step="any" value={config.min ?? ""} onChange={(event) => updateAxis(axis, { min: event.target.value })} /></label>
<label><span>Maximum</span><input type="number" step="any" value={config.max ?? ""} onChange={(event) => updateAxis(axis, { max: event.target.value })} /></label>
{axis.scale.invalid ? <small role="status">Minimum muss kleiner als Maximum sein. Bis dahin gilt die Automatik.</small> : null}
</> : null}
</div>
</div>
);
})}
</fieldset>
{onSave ? (
<div className="button-row trend-settings-save">
<button type="button" className="primary-button compact-button" disabled={saving} onClick={onSave}>
{saving ? "Speichert ..." : "Auswahl aktualisieren"}
</button>
</div>
) : null}
<fieldset className="trend-settings-group">
<legend>Datenreihen zuordnen</legend>
{series.map((entry) => (
<label key={entry.key} className="trend-series-setting">
<span>{entry.name}</span>
<select value={settings.assignments[entry.key] || "unit"} onChange={(event) => onChange({
assignments: { ...settings.assignments, [entry.key]: event.target.value },
})}>
<option value="unit">{unitAxisId(entry).slice(5) || "Ohne Einheit"} · gemeinsame Achse</option>
<option value="own">Eigene Achse</option>
</select>
</label>
))}
</fieldset>
</div>
</details>
);
}
+69
View File
@@ -0,0 +1,69 @@
const PALETTE = [
"#0072b2", "#d55e00", "#009e73", "#a03a83", "#b77a00", "#665aca",
"#e03b53", "#167b93", "#3e7b0d", "#87543f", "#d14caa", "#4d6090",
];
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);
if (color.startsWith("#") && /^[0-9a-f]{6}$/i.test(hex)) {
return hex.match(/../g).map((pair) => parseInt(pair, 16));
}
return null;
}
function distance(left, right) {
const [red, green, blue] = left.map((channel, index) => channel - right[index]);
const redMean = (left[0] + right[0]) / 512;
return (2 + redMean) * red ** 2 + 4 * green ** 2 + (3 - redMean) * blue ** 2;
}
function hslColor(hue, saturation, lightness) {
const amplitude = saturation * Math.min(lightness, 1 - lightness);
return "#" + [0, 8, 4].map((offset) => {
const angle = (offset + hue / 30) % 12;
const channel = lightness - amplitude * Math.max(-1, Math.min(angle - 3, 9 - angle, 1));
return Math.round(255 * channel).toString(16).padStart(2, "0");
}).join("");
}
function isAutomaticColor(color) {
return !color || /^(?:black|#0{3}|#0{6}|rgb\(\s*0(?:\s*,\s*|\s+)0(?:\s*,\s*|\s+)0\s*\))$/i.test(color);
}
export function assignTrendColors(series) {
const automatic = series.filter((entry) => isAutomaticColor(entry.color?.trim()));
if (!automatic.length) return series;
const seed = series.reduce((hash, { key }) => {
for (const char of key) hash = (Math.imul(hash, 31) + char.charCodeAt(0)) >>> 0;
return hash;
}, 0);
const offset = seed % PALETTE.length;
const palette = PALETTE.slice(offset).concat(PALETTE.slice(0, offset));
if (series.length > palette.length) {
for (const lightness of [0.39, 0.49, 0.58]) {
for (let hue = seed % 10; hue < 360; hue += 6) palette.push(hslColor(hue, 0.72, lightness));
}
}
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) => ({
color,
rgb: hexRgb(color),
contrast: Infinity,
}));
function compareTo(rgb) {
for (const candidate of candidates) candidate.contrast = Math.min(candidate.contrast, distance(candidate.rgb, rgb));
}
used.forEach(compareTo);
const colors = new Map();
for (const entry of automatic) {
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);
compareTo(chosen.rgb);
}
return series.map((entry) => colors.has(entry.key) ? { ...entry, color: colors.get(entry.key) } : entry);
}
+73
View File
@@ -0,0 +1,73 @@
import { DIGITAL_UNIT, normalizeUnitSymbol } from "../../../shared/engineering-units.mjs";
export function unitAxisId(series) {
return `unit:${series.kind === "digital" ? DIGITAL_UNIT : normalizeUnitSymbol(series.unit)}`;
}
export function seriesAxisId(series, assignments) {
return assignments[series.key] === "own" ? `point:${series.key}` : unitAxisId(series);
}
export function getTrendAxes(series, assignments) {
const groups = new Map();
for (const entry of series) {
const id = seriesAxisId(entry, assignments);
if (!groups.has(id)) {
const digital = entry.kind === "digital";
const unit = digital ? DIGITAL_UNIT : normalizeUnitSymbol(entry.unit);
groups.set(id, {
id,
unit,
digital,
name: id.startsWith("point:") ? `${entry.alias} (${unit || "ohne Einheit"})` : unit || "Ohne Einheit",
side: groups.size % 2 === 0 ? "left" : "right",
series: [],
});
}
groups.get(id).series.push(entry);
}
return [...groups.values()];
}
function findExtent(rows, series, window) {
let min = Infinity;
let max = -Infinity;
for (const row of rows) {
if (window && (row.timestampMs < window[0] || row.timestampMs > window[1])) continue;
for (const entry of series) {
const value = row[entry.key];
if (!Number.isFinite(value)) continue;
if (value < min) min = value;
if (value > max) max = value;
}
}
return [min, max];
}
export function getTrendAxisScale(axis, settings, rows, window, divisions) {
if (axis.digital) return { domain: [0, 2], ticks: [0, 1] };
let [min, max] = findExtent(rows, axis.series, window);
if (min === Infinity && window) [min, max] = findExtent(rows, axis.series);
if (min === Infinity) [min, max] = [0, 1];
const padding = min === max ? Math.abs(min) * 0.05 || 1 : (max - min) * 0.08;
const validManual = settings?.min !== "" && settings?.max !== ""
&& Number.isFinite(Number(settings?.min)) && Number.isFinite(Number(settings?.max))
&& Number(settings.min) < Number(settings.max);
const domain = settings?.mode === "manual" && validManual
? [Number(settings.min), Number(settings.max)]
: [min - padding, max + padding];
return {
domain,
ticks: Array.from({ length: divisions + 1 }, (_, index) => domain[0] + (domain[1] - domain[0]) * index / divisions),
invalid: settings?.mode === "manual" && !validManual,
};
}
export function getTimeZoom(domain, start, end) {
const span = domain[1] - domain[0];
const min = Math.round(domain[0] + span * Math.min(start, end));
const max = Math.round(domain[0] + span * Math.max(start, end));
return max > min && (min > domain[0] || max < domain[1]) ? [min, max] : null;
}
+256 -36
View File
@@ -223,13 +223,14 @@ span {
} }
.app-shell { .app-shell {
--sidebar-width: 188px;
display: grid; display: grid;
grid-template-columns: 188px 1fr; grid-template-columns: var(--sidebar-width) minmax(0, 1fr);
min-height: 100vh; min-height: 100vh;
} }
.app-shell.trend-focus { .app-shell.sidebar-collapsed {
grid-template-columns: 72px 1fr; --sidebar-width: 64px;
} }
.sidebar { .sidebar {
@@ -238,13 +239,12 @@ span {
height: 100vh; height: 100vh;
padding: 0.65rem 0.55rem 0.7rem; padding: 0.65rem 0.55rem 0.7rem;
display: grid; display: grid;
grid-template-rows: auto 1fr auto; grid-template-rows: auto 1fr;
gap: 0.75rem; gap: 0.75rem;
width: 188px; min-width: 0;
overflow: hidden; overflow: auto;
background: var(--sidebar-bg); background: var(--sidebar-bg);
border-right: 1px solid var(--sidebar-border); border-right: 1px solid var(--sidebar-border);
transition: width 160ms ease, padding 160ms ease;
} }
.sidebar::before { .sidebar::before {
@@ -256,23 +256,19 @@ span {
} }
.sidebar.collapsed { .sidebar.collapsed {
width: 64px; padding-inline: 0.55rem;
padding-inline: 0.35rem;
} }
.sidebar.collapsed .sidebar-top { .sidebar.collapsed .sidebar-top,
.sidebar.collapsed .nav-list,
.sidebar.collapsed .sidebar-footer {
justify-items: center; justify-items: center;
align-items: center;
} }
.sidebar.collapsed .sidebar-brand-row { .sidebar.collapsed .sidebar-brand-row {
width: 100%; flex-direction: column;
padding-left: 0; padding-inline: 0;
padding-right: 0;
justify-content: center;
}
.sidebar.collapsed .logo-lockup {
justify-content: center;
} }
.sidebar.collapsed .logo-lockup img { .sidebar.collapsed .logo-lockup img {
@@ -281,16 +277,21 @@ span {
} }
.sidebar.collapsed .nav-list { .sidebar.collapsed .nav-list {
width: 100%; align-self: stretch;
gap: 0.45rem; gap: 0.45rem;
} }
.sidebar.collapsed .nav-button { .sidebar.collapsed .nav-button,
width: 100%; .sidebar.collapsed .sidebar-account,
.sidebar.collapsed .sidebar-toggle {
width: 38px;
min-width: 38px;
height: 38px;
min-height: 38px; min-height: 38px;
justify-content: center; justify-content: center;
justify-self: center;
padding: 0; padding: 0;
font-size: 12px; border-radius: 10px;
} }
.sidebar-top { .sidebar-top {
@@ -331,6 +332,10 @@ span {
border-bottom: 1px solid var(--border); border-bottom: 1px solid var(--border);
} }
.sidebar-toggle {
flex-shrink: 0;
}
.nav-list, .nav-list,
.button-row, .button-row,
.widget-stack, .widget-stack,
@@ -355,9 +360,16 @@ span {
padding: 0.38rem 0.58rem; padding: 0.38rem 0.58rem;
border-radius: 12px; border-radius: 12px;
justify-content: flex-start; justify-content: flex-start;
gap: 0.42rem;
font-size: 12px; font-size: 12px;
} }
.sidebar svg {
width: 18px;
height: 18px;
flex-shrink: 0;
}
.user-card { .user-card {
padding-top: 0.1rem; padding-top: 0.1rem;
} }
@@ -382,19 +394,15 @@ span {
border-top: 1px solid var(--border); border-top: 1px solid var(--border);
} }
.sidebar-logout { .sidebar-account {
justify-self: start;
border-radius: 999px;
padding-inline: 0.7rem;
}
.sidebar-login {
justify-self: start; justify-self: start;
border-radius: 999px; border-radius: 999px;
padding-inline: 0.7rem; padding-inline: 0.7rem;
gap: 0.42rem;
} }
.content { .content {
min-width: 0;
padding: 0.55rem 0.65rem 0.7rem; padding: 0.55rem 0.65rem 0.7rem;
display: grid; display: grid;
gap: 0.55rem; gap: 0.55rem;
@@ -603,14 +611,23 @@ span {
} }
.chart-wrapper { .chart-wrapper {
--trend-axis: var(--muted);
--trend-grid: var(--grid);
--trend-band: color-mix(in srgb, var(--text) 5%, transparent);
width: 100%; width: 100%;
min-height: 320px; min-height: 320px;
user-select: none; user-select: none;
cursor: crosshair; overflow-x: auto;
touch-action: none; touch-action: pan-y;
} }
.chart-wrapper.dragging { .chart-wrapper.high-contrast {
--trend-axis: var(--text);
--trend-grid: color-mix(in srgb, var(--text) 42%, transparent);
--trend-band: color-mix(in srgb, var(--text) 10%, transparent);
}
.trend-zoom-target {
cursor: crosshair; cursor: crosshair;
} }
@@ -620,12 +637,75 @@ span {
.chart-toolbar { .chart-toolbar {
align-items: flex-start; align-items: flex-start;
position: relative;
} }
.chart-actions { .chart-actions {
align-items: center; align-items: center;
} }
.trend-settings > summary {
cursor: pointer;
list-style: none;
}
.trend-settings > summary::-webkit-details-marker {
display: none;
}
.trend-settings-popover {
position: absolute;
z-index: 12;
top: 100%;
right: 0;
width: min(100%, 420px);
max-height: min(64vh, 540px);
overflow: auto;
overscroll-behavior: contain;
background: var(--surface-strong);
border: 1px solid var(--border-strong);
border-radius: 12px;
box-shadow: 0 12px 28px #0003;
padding: 0.8rem;
}
.trend-settings-fields,
.trend-series-setting {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.5rem;
}
.trend-settings-save {
justify-content: flex-end;
margin-top: 0.65rem;
}
.trend-settings-fields > small,
.trend-opacity-field {
grid-column: 1 / -1;
}
.trend-settings-group {
margin: 0.65rem 0 0;
padding: 0.55rem;
min-width: 0;
border: 1px solid var(--border-strong);
border-radius: 8px;
}
.trend-axis-settings + .trend-axis-settings,
.trend-series-setting + .trend-series-setting {
margin-top: 0.55rem;
padding-top: 0.55rem;
border-top: 1px solid var(--border);
}
.trend-series-setting {
align-items: center;
overflow-wrap: anywhere;
}
.chart-check { .chart-check {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
@@ -693,12 +773,123 @@ span {
display: grid; display: grid;
gap: 0.65rem; gap: 0.65rem;
align-content: start; align-content: start;
min-width: 0;
} }
.trend-side { .trend-point-panel,
.trend-point-library {
grid-template-rows: auto auto minmax(0, 1fr);
min-height: 0;
min-width: 0; min-width: 0;
} }
.trend-point-library .point-list {
align-content: start;
grid-auto-rows: max-content;
max-height: min(36dvh, 24rem);
min-height: 0;
overscroll-behavior: contain;
}
.point-item[aria-pressed="true"],
.trend-point-library [aria-pressed="true"] {
border-color: var(--border-strong);
background: color-mix(in srgb, var(--brand-2) 8%, var(--surface-strong));
}
.trend-options {
border: 1px solid var(--border);
border-radius: 10px;
padding: 0.44rem 0.55rem;
}
.trend-options summary {
cursor: pointer;
}
.trend-options summary small {
float: right;
color: var(--muted);
}
.trend-options[open] summary {
margin-bottom: 0.44rem;
}
.trend-selection-save > .primary-button {
margin-top: 0.44rem;
}
@media (min-width: 981px) and (min-height: 560px) {
.content.trend-content {
display: flex;
flex-direction: column;
height: 100dvh;
}
.trend-content .trend-layout {
flex: 1;
min-height: 0;
grid-template-rows: minmax(0, 1fr);
}
.trend-content .trend-side {
align-self: stretch;
align-content: stretch;
min-height: 0;
grid-template-rows: minmax(0, 1fr) auto;
}
.trend-content .trend-point-library .point-list {
max-height: none;
}
}
.unit-table {
width: 100%;
border-collapse: collapse;
text-align: left;
}
.unit-table th,
.unit-table td {
padding: 0.38rem 0.52rem;
border-bottom: 1px solid var(--border);
overflow-wrap: anywhere;
}
.unit-table thead th,
.unit-table small {
color: var(--muted);
}
.unit-table tbody tr:nth-child(even) {
background: color-mix(in srgb, var(--border) 36%, transparent);
}
.unit-table :is(th, td):last-child {
text-align: right;
width: 1%;
overflow-wrap: normal;
white-space: nowrap;
}
.runner-mail-fields {
margin: 0;
padding: 0.5rem 0;
border: 0;
border-top: 1px solid var(--border);
min-width: 0;
}
.runner-mail-fields:disabled {
opacity: 0.55;
}
.runner-mail-fields:disabled input {
cursor: not-allowed;
}
.stat-card, .stat-card,
.gauge-card, .gauge-card,
.user-row { .user-row {
@@ -956,9 +1147,8 @@ span {
} }
@media (max-width: 980px) { @media (max-width: 980px) {
.app-shell, .app-shell {
.app-shell.trend-focus { grid-template-columns: minmax(0, 1fr);
grid-template-columns: 1fr;
} }
.sidebar, .sidebar,
@@ -968,6 +1158,36 @@ span {
height: auto; height: auto;
} }
.sidebar.collapsed {
grid-template-columns: minmax(0, 1fr) auto;
grid-template-rows: auto;
column-gap: 0.4rem;
padding-block: 0.4rem;
}
.sidebar.collapsed .sidebar-top,
.sidebar.collapsed .sidebar-brand-row,
.sidebar.collapsed .nav-list {
display: flex;
flex-direction: row;
align-items: center;
gap: 0.3rem;
}
.sidebar.collapsed .sidebar-top {
flex-wrap: wrap;
}
.sidebar.collapsed .sidebar-brand-row,
.sidebar.collapsed .sidebar-footer {
padding: 0;
border: 0;
}
.sidebar.collapsed .sidebar-footer {
align-self: center;
}
.grid.two, .grid.two,
.form-grid, .form-grid,
.alias-row, .alias-row,
+6
View File
@@ -1,7 +1,13 @@
import { fileURLToPath } from "node:url";
import { defineConfig } from "vite"; import { defineConfig } from "vite";
import react from "@vitejs/plugin-react"; import react from "@vitejs/plugin-react";
export default defineConfig({ export default defineConfig({
plugins: [react()], plugins: [react()],
server: {
fs: {
allow: [fileURLToPath(new URL(".", import.meta.url)), fileURLToPath(new URL("../shared", import.meta.url))],
},
},
}); });