From 77b6e39b842095e771de87361e980265d128feea Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 6 Nov 2026 14:29:22 +0000 Subject: [PATCH 01/17] ci(e2e): run the end-to-end suite in CI, on Linux and Windows The E2E against pymodbus only ever ran locally. A new e2e job runs it on ubuntu-24.04 and windows-latest after the other jobs pass. - Linux: WebKitWebDriver, Xvfb and socat come through the linux-deps action, which takes an `extra` package list included in its cache key. - Windows: msedgedriver matching the runner's WebView2, installed with msedgedriver-tool and put on PATH, as the Tauri WebDriver CI guide does. The app binary is modbus-tool.exe and the interpreter is python. - Windows has no socat, so its run has no serial checks: the run prints which checks it did not run instead of counting them as passed. The reference server's serial port is optional for the same reason. Local Linux run: 88/88, unchanged. The Windows run is new and will be measured on the first CI run. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013Rdii6QU3MVeyCefPEk5AL --- .github/actions/linux-deps/action.yml | 9 ++++- .github/workflows/ci.yml | 53 +++++++++++++++++++++++++++ e2e/helpers.mjs | 9 ++++- e2e/reference_servers.py | 13 ++++--- e2e/run.mjs | 31 ++++++++++------ e2e/types.mjs | 3 +- 6 files changed, 99 insertions(+), 19 deletions(-) diff --git a/.github/actions/linux-deps/action.yml b/.github/actions/linux-deps/action.yml index 29c8051..284d525 100644 --- a/.github/actions/linux-deps/action.yml +++ b/.github/actions/linux-deps/action.yml @@ -5,13 +5,20 @@ description: >- cached: on a hit they are installed with dpkg, with no apt-get update and no mirror at all. The key includes the runner image version, so the cached .deb files always match the base system. On a miss apt runs with time limits and retries, and the packages it downloaded are saved. +inputs: + extra: + description: More packages for this job (e.g. the E2E's WebKitWebDriver, Xvfb, socat). + required: false + default: "" runs: using: composite steps: - id: key shell: bash + env: + EXTRA: ${{ inputs.extra }} run: | - packages="libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libudev-dev" + packages="libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libudev-dev $EXTRA" echo "packages=$packages" >> "$GITHUB_OUTPUT" echo "dir=$HOME/.cache/linux-deps" >> "$GITHUB_OUTPUT" hash=$(printf '%s' "$packages" | sha256sum | cut -c1-16) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6d27f6f..3343c3b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -121,3 +121,56 @@ jobs: src-tauri/target/release/bundle/deb/*.deb src-tauri/target/release/bundle/appimage/*.AppImage if-no-files-found: error + + # The real app against pymodbus (e2e/run.mjs), on both desktop platforms Tauri can drive. + # Windows has no socat, so its run has no serial checks and says so in its output. + e2e: + needs: [rust, frontend, file-size] + strategy: + fail-fast: false + matrix: + os: [ubuntu-24.04, windows-latest] + runs-on: ${{ matrix.os }} + timeout-minutes: 60 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 + with: + node-version-file: .node-version + cache: npm + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + with: + python-version: "3.12" + - run: python -m pip install pymodbus==3.16.2 + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable + - uses: Swatinem/rust-cache@e9d7b9f1e587218970671bac74e5511ed9506e6a # v2 + with: + workspaces: src-tauri + shared-key: e2e + save-if: ${{ github.ref == 'refs/heads/master' }} + - name: System dependencies + if: runner.os == 'Linux' + uses: ./.github/actions/linux-deps + timeout-minutes: 30 + with: + extra: webkit2gtk-driver xvfb socat + - run: cargo install tauri-driver --locked --version 2.1.0 + # tauri-driver drives Edge WebView2 through msedgedriver, whose version must match the + # WebView2 on the runner (https://v2.tauri.app/develop/tests/webdriver/ci/). + - name: Edge driver matching WebView2 + if: runner.os == 'Windows' + shell: pwsh + run: | + cargo install --git https://github.com/chippers/msedgedriver-tool + & "$HOME/.cargo/bin/msedgedriver-tool.exe" + $PWD.Path >> $env:GITHUB_PATH + - run: npm ci + - run: npx tauri build --debug --no-bundle + - name: E2E (Linux) + if: runner.os == 'Linux' + run: xvfb-run -a node e2e/run.mjs + - name: E2E (Windows) + if: runner.os == 'Windows' + run: node e2e/run.mjs diff --git a/e2e/helpers.mjs b/e2e/helpers.mjs index 38b5c1b..c3f84df 100644 --- a/e2e/helpers.mjs +++ b/e2e/helpers.mjs @@ -8,6 +8,13 @@ import { join, resolve } from "node:path"; import { setTimeout as sleep } from "node:timers/promises"; export const root = resolve(import.meta.dirname, ".."); +/** Windows names the interpreter `python`; elsewhere `python3` is the one with pymodbus. */ +export const python = process.platform === "win32" ? "python" : "python3"; +/** + * Serial checks need socat's pty pairs, which Windows does not have: there they are not run, and + * the run says so, rather than counting them as passed. + */ +export const serial = process.platform !== "win32"; export const tmp = mkdtempSync(join(tmpdir(), "modbustool-e2e-")); export const results = []; let currentBrowser = null; @@ -18,7 +25,7 @@ export function track(browser) { } export function reference(...args) { - const out = execFileSync("python3", [join(root, "e2e/reference_client.py"), ...args.map(String)], { + const out = execFileSync(python, [join(root, "e2e/reference_client.py"), ...args.map(String)], { encoding: "utf8", }); return JSON.parse(out.trim().split("\n").pop()); diff --git a/e2e/reference_servers.py b/e2e/reference_servers.py index 5f28327..47d5be7 100644 --- a/e2e/reference_servers.py +++ b/e2e/reference_servers.py @@ -1,6 +1,7 @@ """Independent reference: pymodbus servers the app's master talks to during E2E. -Usage: python3 reference_servers.py +Usage: python3 reference_servers.py [serial_device] +Without a serial device (Windows has no socat ptys) only the network servers run. Unit 1: holding register n = 111 * (n + 1), input register n = 1000 + n, even coils ON. pymodbus data blocks start at 1 for protocol address 0. """ @@ -24,14 +25,16 @@ def context() -> ModbusServerContext: async def main() -> None: - tcp, udp, rtu_over_tcp, serial = int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]), sys.argv[4] + tcp, udp, rtu_over_tcp = int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]) shared = context() - await asyncio.gather( + servers = [ StartAsyncTcpServer(shared, address=("127.0.0.1", tcp)), StartAsyncUdpServer(shared, address=("127.0.0.1", udp)), StartAsyncTcpServer(shared, address=("127.0.0.1", rtu_over_tcp), framer=FramerType.RTU), - StartAsyncSerialServer(shared, port=serial, framer=FramerType.ASCII, baudrate=19200), - ) + ] + if len(sys.argv) > 4: + servers.append(StartAsyncSerialServer(shared, port=sys.argv[4], framer=FramerType.ASCII, baudrate=19200)) + await asyncio.gather(*servers) asyncio.run(main()) diff --git a/e2e/run.mjs b/e2e/run.mjs index 1b8b874..6856103 100644 --- a/e2e/run.mjs +++ b/e2e/run.mjs @@ -1,9 +1,11 @@ -// End-to-end run of the real app (tauri-driver + WebKitWebDriver) against pymodbus as an -// independent reference implementation. Linux only (tauri-driver has no macOS driver). +// End-to-end run of the real app (tauri-driver) against pymodbus as an independent reference +// implementation, on Linux (WebKitWebDriver) and Windows (msedgedriver matching WebView2). +// tauri-driver has no macOS driver. // // npx tauri build --debug --no-bundle && node e2e/run.mjs [screenshot-dir] // -// Needs: tauri-driver, WebKitWebDriver, socat, python3 with pymodbus, an X display. +// Needs: tauri-driver, the platform's WebDriver, python with pymodbus; on Linux also socat (the +// serial checks) and an X display. Windows runs every check but the serial ones. import { remote } from "webdriverio"; import { spawn } from "node:child_process"; @@ -22,10 +24,12 @@ import { gridValues, labelled, panel, + python, reference, results, root, saveDialog, + serial, setField, tmp, track, @@ -33,6 +37,7 @@ import { import { dashboardScenario } from "./dashboard.mjs"; import { typesMaster, typesSlave } from "./types.mjs"; +const APP = process.platform === "win32" ? "modbus-tool.exe" : "modbus-tool"; const shots = process.argv[2] ? resolve(process.argv[2]) : null; const children = []; @@ -129,7 +134,7 @@ async function masterScenario(browser, ports, serialRef) { const others = [ ["UDP", "Modbus UDP", { Port: ports.udp }], ["RTU over TCP", "RTU over TCP", { Port: ports.rtuOverTcp }], - ["ASCII serial", "ASCII · serial", { "Serial port": serialRef, "Data bits": "8" }], + ...(serial ? [["ASCII serial", "ASCII · serial", { "Serial port": serialRef, "Data bits": "8" }]] : []), ]; for (const [name, protocol, fields] of others) { await check(`${name}: read once FC04 matches the reference`, async () => { @@ -215,7 +220,7 @@ async function slaveScenario(browser, ports, slaveSerial, clientSerial) { { Port: ports.slaveRtuOverTcp }, ["rtuovertcp", `127.0.0.1:${ports.slaveRtuOverTcp}`], ], - ["RTU serial", "RTU · serial", { "Serial port": slaveSerial }, ["rtu", clientSerial]], + ...(serial ? [["RTU serial", "RTU · serial", { "Serial port": slaveSerial }, ["rtu", clientSerial]]] : []), ]; for (const [name, protocol, fields, client] of others) { await check(`${name}: reference reads FC03 from the slave`, async () => { @@ -285,15 +290,19 @@ async function main() { const ports = { tcp: 15020, udp: 15022, rtuOverTcp: 15021, slaveTcp: 15030, slaveUdp: 15031, slaveRtuOverTcp: 15032 }; const pty = (a, b) => background("socat", [`pty,raw,echo=0,link=${join(tmp, a)}`, `pty,raw,echo=0,link=${join(tmp, b)}`]); - pty("refA", "refB"); - pty("slaveA", "slaveB"); - await sleep(800); - background("python3", [ + if (serial) { + pty("refA", "refB"); + pty("slaveA", "slaveB"); + await sleep(800); + } else { + console.log("Not run on this platform (no socat): ASCII serial master, RTU serial slave\n"); + } + background(python, [ join(root, "e2e/reference_servers.py"), ports.tcp, ports.udp, ports.rtuOverTcp, - join(tmp, "refA"), + ...(serial ? [join(tmp, "refA")] : []), ]); background("tauri-driver", []); await sleep(2000); @@ -302,7 +311,7 @@ async function main() { hostname: "127.0.0.1", port: 4444, logLevel: "error", - capabilities: { "tauri:options": { application: join(root, "src-tauri/target/debug/modbus-tool") } }, + capabilities: { "tauri:options": { application: join(root, "src-tauri/target/debug", APP) } }, }); track(browser); try { diff --git a/e2e/types.mjs b/e2e/types.mjs index ca00dde..3882f06 100644 --- a/e2e/types.mjs +++ b/e2e/types.mjs @@ -12,12 +12,13 @@ import { eventually, expectEqual, gridValues, + python, reference, root, setField, } from "./helpers.mjs"; -const groups = JSON.parse(execFileSync("python3", [join(root, "e2e/typed_values.py")], { encoding: "utf8" })); +const groups = JSON.parse(execFileSync(python, [join(root, "e2e/typed_values.py")], { encoding: "utf8" })); function shows(text, expect) { if (expect.kind === "text") return text === expect.text; From c0639caca7862ead1525e6002a3a480494ca0590 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 6 Nov 2026 14:40:50 +0000 Subject: [PATCH 02/17] feat(dashboards): a colour for each variable, fixed or custom The user asked for a proper colour picker with fixed and custom colours (spec D22). A variable's colour sets its trend line, its bar or its lit lamp. The fixed colours are five Aura tokens that follow the theme: ring, success, warning, danger, text-muted. accent nearly disappears on the dark theme, and info equals ring on the light one. A custom colour is a #rrggbb picked with color-picker-svelte 2.0.4 (MIT, Svelte 5, one MIT dependency). Without a colour the automatic palette works as before. Saved files without colours are read as automatic. color-picker-svelte 2.0.4 always opens its popup below on Position.Auto: ColorPicker's showAbove never returns its result. Below the last variable the dialog clipped the popup. The field now chooses above or below from the room in the dialog. E2E 88/88: the lamp set to Red lights in the computed --color-danger. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013Rdii6QU3MVeyCefPEk5AL --- CHANGELOG.md | 8 ++ .../plans/2026-11-06-dashboards.md | 6 + .../specs/2026-11-06-dashboards-design.md | 6 + .../verification/2026-11-06-dashboards.md | 17 +++ e2e/dashboard.mjs | 15 ++- messages/en.json | 8 ++ messages/it.json | 8 ++ package-lock.json | 22 +++ package.json | 1 + src/lib/colors.test.ts | 23 ++++ src/lib/colors.ts | 25 ++++ src/lib/components/ColorField.svelte | 127 ++++++++++++++++++ src/lib/components/PanelBody.svelte | 19 ++- src/lib/components/PanelForm.svelte | 6 +- src/lib/components/TrendChart.svelte | 21 ++- src/lib/components/VariableFields.svelte | 12 +- src/lib/dashboards.test.ts | 17 ++- src/lib/dashboards.ts | 7 +- src/lib/dashboardsFile.ts | 11 +- 19 files changed, 330 insertions(+), 29 deletions(-) create mode 100644 src/lib/colors.test.ts create mode 100644 src/lib/colors.ts create mode 100644 src/lib/components/ColorField.svelte diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f667fc..35e04ad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,14 @@ Notable changes to ModbusTool, newest first. Each section is also the text of it [GitHub release](https://github.com/chetto1983/ModbusTool/releases): the Release workflow publishes the section whose heading matches the pushed `vX.Y.Z` tag. The full history is in git. +## Unreleased + +### Added + +- A colour for each dashboard variable: trend line, bar and lamp. Pick one of five theme colours + that follow the light and dark themes, or any custom colour with a colour picker + (color-picker-svelte). Without one, the automatic colours stay as before. + ## v3.3.1 — 2026-11-06 Dashboards read neighbouring variables in one request, far less traffic on the device. diff --git a/docs/superpowers/plans/2026-11-06-dashboards.md b/docs/superpowers/plans/2026-11-06-dashboards.md index 0c602d2..38acace 100644 --- a/docs/superpowers/plans/2026-11-06-dashboards.md +++ b/docs/superpowers/plans/2026-11-06-dashboards.md @@ -64,3 +64,9 @@ lo storico non cresce senza limite; gridstack e Svelte non si contendono il DOM. - [x] **T11 Blocchi di lettura**: blocchi di variabili contigue per unit, tabella e periodo; un poll del backend per blocco; valori e storico di ogni variabile presi dal suo blocco; test (blocchi, limiti 125/2000, nessun buco letto); misura delle richieste prima e dopo contro pymodbus. + +## Colore delle variabili (spec D22) + +- [x] **T12 Colore**: `colour` sulla variabile (validazione, conversione dei file senza), colori + fissi dai token e personalizzato con color-picker-svelte; trend, barre e lampada; test; E2E + (lampada accesa nel colore scelto). diff --git a/docs/superpowers/specs/2026-11-06-dashboards-design.md b/docs/superpowers/specs/2026-11-06-dashboards-design.md index 634bfde..b5afd9d 100644 --- a/docs/superpowers/specs/2026-11-06-dashboards-design.md +++ b/docs/superpowers/specs/2026-11-06-dashboards-design.md @@ -63,6 +63,12 @@ Si riprende il modello d'uso, non il codice (React). |---|---|---| | D21 | Le variabili con stessa unit, tabella e periodo, **contigue o sovrapposte**, si leggono in **un'unica richiesta** (al massimo 125 registri o 2000 bit, i limiti di FC03/04 e FC01/02, Modbus Application Protocol 1.1b3 §6.1–6.4). Non si leggono indirizzi che nessuna variabile chiede: un dispositivo con un buco nella mappa risponde con l'eccezione 02 all'intero blocco | Calcolo dalla specifica: in RTU a 9600 baud un carattere dura 11/9600 s ≈ 1,15 ms e la pausa tra frame 3,5 caratteri ≈ 4 ms (Modbus over Serial Line 1.02 §2.5.1.1). Una lettura di un registro (8 + 7 byte) costa ≈ 25 ms, quindi 30 variabili ≈ 750 ms, più di un periodo da 200 ms. Misurato solo il numero di richieste e la correttezza dei valori: le pty di socat non hanno i tempi della seriale | +## Colore delle variabili (2026-11-06, richiesta utente) + +| # | Decisione | Fonte | +|---|---|---| +| D22 | Ogni variabile può avere un **colore**: linea del trend, barra, lampada accesa. **Fissi**: cinque token Aura che seguono il tema (ring, success, warning, danger, text-muted; accent è quasi invisibile sul tema scuro, info coincide con ring sul chiaro). **Personalizzato**: un esadecimale scelto con `color-picker-svelte` 2.0.4 (MIT, Svelte 5, dipendenza `@ctrl/tinycolor` MIT). Nessun colore: la palette automatica per posizione, come prima. Nel file: `null`, il nome del token o `#rrggbb` | Richiesta utente con il playground di `color-picker-svelte`; inventario del pacchetto pubblicato | + ## Cosa NON è dimostrato - Prestazioni con molti pannelli e poll veloci: da misurare (obiettivo: 20 pannelli, poll 200 ms). diff --git a/docs/superpowers/verification/2026-11-06-dashboards.md b/docs/superpowers/verification/2026-11-06-dashboards.md index f2f291b..9b8794f 100644 --- a/docs/superpowers/verification/2026-11-06-dashboards.md +++ b/docs/superpowers/verification/2026-11-06-dashboards.md @@ -81,8 +81,25 @@ Data: 2026-11-06. Spec: `docs/superpowers/specs/2026-11-06-dashboards-design.md` - posizione di ogni variabile nel suo blocco; - un'eccezione sul blocco segna come non aggiornate tutte le sue variabili. +## Colore delle variabili (D22), misurato il 2026-11-06 + +- **E2E** 88/88: la lampada "Running" impostata su Rosso si accende col colore calcolato del + token `--color-danger`. +- **Screenshot** dell'editor (tema scuro): + - campioni Automatico e cinque colori fissi, con il selezionato evidenziato; + - il personalizzato apre il selettore di color-picker-svelte con l'esadecimale. + + Il primo screenshot ha trovato un difetto del pacchetto 2.0.4: con `Position.Auto` il popup si + apre sempre sotto, perché `showAbove` non restituisce il risultato. Veniva tagliato dal fondo + della finestra di modifica. Ora la posizione si sceglie in base allo spazio nella finestra, e lo + screenshot dopo la correzione mostra il popup sopra, intero. +- **Unit test**: colori accettati e rifiutati nel file, risoluzione token/esadecimale/automatico, + colore conservato quando lo stato segue il target. + ## Cosa NON dimostra +- Il colore delle linee del trend e delle barre: verificato solo a vista nell'editor; l'E2E + controlla la lampada. - Il gauge nel tema scuro e su WebView2: provato solo in WebKitGTK, tema chiaro. - WebView2 su Windows: trascinamento, selettore e input numerico vanno provati a mano. - Il ridimensionamento dei pannelli (nessun controllo E2E). diff --git a/e2e/dashboard.mjs b/e2e/dashboard.mjs index 83bdaf5..14f68fa 100644 --- a/e2e/dashboard.mjs +++ b/e2e/dashboard.mjs @@ -93,7 +93,10 @@ export async function dashboardScenario(browser, target) { await period.clearValue(); await period.setValue("200"); await addPanel(browser, "Value", { Title: "Pressure", Address: 2, "Unit of measure": "bar", Decimals: 0 }); - await addPanel(browser, "Lamp", { Title: "Running", "Read from": "Coils", Address: 0 }); + await click(browser, button("", "Add panel")); + await click(browser, button(dialog, "Lamp")); + await click(browser, `${dialog}//button[@aria-label='Red']`); + await saveDialog(browser, { Title: "Running", "Read from": "Coils", Address: 0 }); await addPanel(browser, "Button", { Title: "Set 4242", Address: 5, "Value to write": "4242" }); // The state of a command is read at first from the address it writes. await addPanel(browser, "Switch", { Title: "Valve 7" }, 7); @@ -151,6 +154,16 @@ export async function dashboardScenario(browser, target) { await eventually(async () => { if (!(await lamp.getAttribute("class")).includes("on")) throw new Error("lamp off"); }, "lamp"); + // Lit in the colour chosen for its variable: the theme's danger red. + const [lit, red] = await browser.execute((el) => { + const probe = document.createElement("i"); + probe.style.color = "var(--color-danger)"; + document.body.append(probe); + const colours = [getComputedStyle(el).backgroundColor, getComputedStyle(probe).color]; + probe.remove(); + return colours; + }, lamp); + expectEqual(lit, red, "lamp colour"); }); await check("Dashboard: a button writes its value (FC06) to the reference", async () => { diff --git a/messages/en.json b/messages/en.json index c590cb3..96af790 100644 --- a/messages/en.json +++ b/messages/en.json @@ -101,6 +101,14 @@ "scaling_eng_max": "Engineering max", "scaling_clamp": "Keep to the engineering range", "scaling_same_ends": "The two ends must differ", + "colour_label": "Colour", + "colour_auto": "Automatic", + "colour_custom": "Custom", + "colour_blue": "Blue", + "colour_green": "Green", + "colour_amber": "Amber", + "colour_red": "Red", + "colour_grey": "Grey", "panel_options": "Options", "panel_option_label": "Label", "panel_add_option": "Add option", diff --git a/messages/it.json b/messages/it.json index 7b8d343..05ea6d5 100644 --- a/messages/it.json +++ b/messages/it.json @@ -101,6 +101,14 @@ "scaling_eng_max": "Ingegneristico max", "scaling_clamp": "Limita all'intervallo ingegneristico", "scaling_same_ends": "I due estremi devono essere diversi", + "colour_label": "Colore", + "colour_auto": "Automatico", + "colour_custom": "Personalizzato", + "colour_blue": "Blu", + "colour_green": "Verde", + "colour_amber": "Ambra", + "colour_red": "Rosso", + "colour_grey": "Grigio", "panel_options": "Opzioni", "panel_option_label": "Etichetta", "panel_add_option": "Aggiungi opzione", diff --git a/package-lock.json b/package-lock.json index 987cdac..e9dc1d5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14,6 +14,7 @@ "@tauri-apps/plugin-fs": "^2.7.1", "@tauri-apps/plugin-process": "^2.4.0", "@tauri-apps/plugin-updater": "^2.14.1", + "color-picker-svelte": "^2.0.4", "gridstack": "^14.0.0", "svelte-gauge": "^2.0.2", "uplot": "^1.6.32" @@ -1536,6 +1537,15 @@ "node": ">=0.1.90" } }, + "node_modules/@ctrl/tinycolor": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@ctrl/tinycolor/-/tinycolor-4.2.2.tgz", + "integrity": "sha512-9rQHijqB2Rq6qOEC/xHaA6aPlsKGi5kmCQW50O1asn9g63XFeD5NmBwysriistW5Xx0JPafyD/TA7yk2S3pXGQ==", + "license": "MIT", + "engines": { + "node": ">=14" + } + }, "node_modules/@emnapi/core": { "version": "1.11.2", "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.2.tgz", @@ -5715,6 +5725,18 @@ "dev": true, "license": "MIT" }, + "node_modules/color-picker-svelte": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/color-picker-svelte/-/color-picker-svelte-2.0.4.tgz", + "integrity": "sha512-dbNw4xpmA03eADeZJlY0+b/Gm6eJgnrZTuaPZgjA7DxHOcEWfIf3nOz/Kv/FBZ45odDZQe/nZKKB62HpH3Okyg==", + "license": "MIT", + "dependencies": { + "@ctrl/tinycolor": "^4.0.0" + }, + "peerDependencies": { + "svelte": "^5.0.0" + } + }, "node_modules/colors": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/colors/-/colors-1.4.0.tgz", diff --git a/package.json b/package.json index e999c9b..9fc6b8f 100644 --- a/package.json +++ b/package.json @@ -55,6 +55,7 @@ "@tauri-apps/plugin-fs": "^2.7.1", "@tauri-apps/plugin-process": "^2.4.0", "@tauri-apps/plugin-updater": "^2.14.1", + "color-picker-svelte": "^2.0.4", "gridstack": "^14.0.0", "svelte-gauge": "^2.0.2", "uplot": "^1.6.32" diff --git a/src/lib/colors.test.ts b/src/lib/colors.test.ts new file mode 100644 index 0000000..f49a759 --- /dev/null +++ b/src/lib/colors.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from "vitest"; +import { colourCss, colourValue, FIXED_COLOURS, isColour } from "./colors"; + +describe("variable colours", () => { + it("accepts automatic, the fixed theme colours and a custom #rrggbb, nothing else", () => { + for (const ok of [null, ...FIXED_COLOURS, "#1a2B3c"]) expect(isColour(ok), String(ok)).toBe(true); + for (const bad of ["accent", "#abc", "#12345g", "red", 3, undefined]) + expect(isColour(bad), String(bad)).toBe(false); + }); + + it("draws a fixed colour from the theme, a custom one as is, none by its position", () => { + expect(colourCss("danger", 0)).toBe("var(--color-danger)"); + expect(colourCss("#112233", 4)).toBe("#112233"); + expect(colourCss(null, 1)).toBe("var(--color-success)"); + expect(colourCss(null, FIXED_COLOURS.length)).toBe("var(--color-ring)"); + }); + + it("reads a token's value from the page for a canvas", () => { + document.documentElement.style.setProperty("--color-warning", "#fdd663"); + expect(colourValue("warning", 0)).toBe("#fdd663"); + expect(colourValue("#010203", 0)).toBe("#010203"); + }); +}); diff --git a/src/lib/colors.ts b/src/lib/colors.ts new file mode 100644 index 0000000..4813a5d --- /dev/null +++ b/src/lib/colors.ts @@ -0,0 +1,25 @@ +// Colours of dashboard variables (docs/superpowers/specs/2026-11-06-dashboards-design.md, D22): a +// fixed Aura token that follows the theme, a custom #rrggbb, or null for the automatic palette. + +/** The fixed colours, as Aura token names (--color-), in the automatic palette's order. */ +export const FIXED_COLOURS = ["ring", "success", "warning", "danger", "text-muted"] as const; +export type FixedColour = (typeof FIXED_COLOURS)[number]; + +const HEX = /^#[0-9a-f]{6}$/i; + +export const isColour = (v: unknown): boolean => + v === null || (typeof v === "string" && (HEX.test(v) || FIXED_COLOURS.includes(v as FixedColour))); + +/** A CSS colour for a variable's colour, the automatic one by its position when it has none. */ +export function colourCss(colour: string | null, index: number): string { + if (colour !== null && HEX.test(colour)) return colour; + const token = colour ?? FIXED_COLOURS[index % FIXED_COLOURS.length]; + return `var(--color-${token})`; +} + +/** The same colour as a value a canvas can draw with: a token is read from the page's theme. */ +export function colourValue(colour: string | null, index: number): string { + const css = colourCss(colour, index); + const token = /^var\((--[a-z-]+)\)$/.exec(css)?.[1]; + return token ? getComputedStyle(document.documentElement).getPropertyValue(token).trim() : css; +} diff --git a/src/lib/components/ColorField.svelte b/src/lib/components/ColorField.svelte new file mode 100644 index 0000000..7ea799f --- /dev/null +++ b/src/lib/components/ColorField.svelte @@ -0,0 +1,127 @@ + + +
+ {m.colour_label()} + + {#each FIXED_COLOURS as fixed (fixed)} + + {/each} +
+ +
+
+ + diff --git a/src/lib/components/PanelBody.svelte b/src/lib/components/PanelBody.svelte index 44decbd..24e21b7 100644 --- a/src/lib/components/PanelBody.svelte +++ b/src/lib/components/PanelBody.svelte @@ -5,6 +5,7 @@ import ValueView from "./ValueView.svelte"; import { setpointRegisters, variableLabel, writeTarget } from "../dashboardActions.svelte"; import type { Panel, SelectOption, SelectPanel, Variable } from "../dashboards"; + import { colourCss } from "../colors"; import { sameEngineering } from "../scaling"; import { master, readKey, variableScaling, variableStale, variableValue } from "../state.svelte"; @@ -66,6 +67,8 @@ const largest = Math.max(1e-9, ...values.map((v) => Math.abs(v ?? 0))); return panel.variables.map((variable, i) => ({ label: variableLabel(variable), + // One hue for every bar unless a variable has its own: colour tells them apart only on demand. + colour: colourCss(variable.colour ?? "ring", 0), value: values[i], stale: stale(variable), share: Math.abs(values[i] ?? 0) / largest, @@ -79,6 +82,7 @@ key: readKey(variable), label: variableLabel(variable), scaling: variableScaling(variable), + colour: variable.colour, }))} windowS={panel.windowS} interpolation={panel.interpolation} @@ -91,7 +95,7 @@ {#each bars as bar, i (i)}
{bar.label} - + {bar.value ?? "—"}
{:else} @@ -100,7 +104,11 @@ {:else if panel.kind === "lamp"}
- +
{:else if panel.kind === "button"}
@@ -214,9 +222,9 @@ background: var(--color-surface-3); } .lamp.on { - border-color: var(--color-success); - background: var(--color-success); - box-shadow: 0 0 0 6px color-mix(in oklab, var(--color-success) 22%, transparent); + border-color: var(--lamp); + background: var(--lamp); + box-shadow: 0 0 0 6px color-mix(in oklab, var(--lamp) 22%, transparent); } .command { min-width: 60%; @@ -311,7 +319,6 @@ .track i { display: block; height: 100%; - background: var(--color-accent); } .number { min-width: 5ch; diff --git a/src/lib/components/PanelForm.svelte b/src/lib/components/PanelForm.svelte index 94555a8..14d0bd9 100644 --- a/src/lib/components/PanelForm.svelte +++ b/src/lib/components/PanelForm.svelte @@ -54,7 +54,7 @@ {#snippet variableList(variables: Variable[])} {#each variables as _, i (i)} - + {#snippet actions()} {/snippet} @@ -126,7 +126,7 @@
{/if} {:else if panel.kind === "lamp"} - + {:else}
{/if} + {#if coloured} + + {/if}