diff --git a/README.md b/README.md index 734d9c3..bed2f11 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,8 @@ automation systems like openHAB). Runs as a systemd service. metric sampling - **Light/dark mode toggle** - follows the OS setting by default, with a manual override remembered in the browser +- **Choosable themes** - picked in the Customize dialog once more than one + theme is available (only Clear today), remembered in the browser - **Configurable dashboard layout** - show/hide and reorder metric cards from a settings modal, remembered in the browser - A versioned REST API (`/api/v1/...`) for third-party consumers, with diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 70623fe..1869a8d 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -23,7 +23,7 @@ under [`areas/`](areas/README.md); this document links them instead of repeating - [HTTP API](areas/http-api.md) — routes and when they are registered, authentication, compression, caching, the concurrency limit, security headers, `/healthz`, Prometheus, server stats, TLS and timeouts. - [Dashboard](areas/dashboard.md) — asset serving and caching, polling, the history merge, API key handling, - rendering, coloring, alert badges, layout, mode and look. + rendering, coloring, alert badges, layout, mode, theme and look. - [openHAB](areas/openhab.md) — detecting a local openHAB, its states and values, the poll cadence, the loopback-only requests and the handling of its API token. - [Configuration](areas/configuration.md) — sources and their precedence, every option with its default and valid diff --git a/docs/areas/dashboard.md b/docs/areas/dashboard.md index 995d3da..b4528e2 100644 --- a/docs/areas/dashboard.md +++ b/docs/areas/dashboard.md @@ -4,7 +4,7 @@ The web UI served at `/`: how its assets are delivered, which API endpoints it reads and how often, how it handles a configured API key, failures and hidden tabs, how it renders server data, colors values and shows alerts, and the -per-browser preferences (mode, card layout) it keeps. The user viewing the Pi in a browser relies on it; it is a +per-browser preferences (mode, theme, card layout) it keeps. The user viewing the Pi in a browser relies on it; it is a client of the [HTTP API](http-api.md) like any third-party integration and has no server-side state of its own. ## Behavior @@ -201,11 +201,37 @@ client of the [HTTP API](http-api.md) like any third-party integration and has n control to return to following the operating system. - A stored choice is applied before the first paint, so the page never flashes the other palette. Charts and gauges are redrawn in the new palette immediately on a switch. +- The button's accessible name is "Switch to dark mode" in light mode and "Switch to light mode" in dark mode; the + word "theme" names the choice of [Theme](#theme), never the mode. + +### Theme + +- A theme is a named set of palette tokens, chosen independently of the mode. The registered themes are listed once, + in `PIMONITOR_THEMES` of `theme-init.js`; today only Clear exists, and it is the default (the first entry). +- The default is the absence of the `data-style` attribute on ``; any other theme sets `data-style` to its id. +- The choice is stored in `localStorage` under `pimonitor-style` (the theme's id). A stored value that is no + registered id (unknown, differently cased, unreadable) means Clear; it is kept in storage unchanged, never + rewritten or removed. +- A stored theme is applied before the first paint by the synchronous `theme-init.js`, together with the mode, and + is independent of it: switching the mode keeps the theme and choosing a theme keeps the mode. +- The Customize dialog starts with a Theme group of radio buttons, one per registered theme in registry order, the + active one checked. Choosing one applies and stores it at once, redraws charts and gauges and leaves the dialog + open. With fewer than two registered themes the group is hidden. "Reset to default" does not touch the theme. +- All themes are in the one `style.css`, one DOM. A theme other than Clear has three palette blocks + (`:root[data-style=""]`, with `[data-theme="dark"]`, and inside `prefers-color-scheme: dark` with + `:not([data-theme])`), each with the same token set as Clear's. +- Reasons: [0041](../decisions/0041-theme-choice-per-browser-as-pimonitor-style.md), + [0042](../decisions/0042-theme-registry-in-theme-init-js.md). ### Look +- The canvas renderers read exactly these custom properties through `themeColor`/`themeNumber` of `theme-init.js`: + `--accent`, `--muted`, `--card-bg`, `--track`, `--ok`, `--warn`, `--crit` and `--spark-fill-alpha`. An empty or + unparseable value, or a `--spark-fill-alpha` outside 0 to 1, is replaced by Clear's light value; any valid value, + `0` included, is used as is. - Every color comes from a token of the palette blocks of `style.css` (light, explicit dark and OS dark, the two - dark blocks identical); no rule outside them holds a color literal. Both the text and the fills of the page use + dark blocks identical); every palette block of every theme, Clear's three included, declares the same token keys, + and no rule outside them holds a color literal. Both the text and the fills of the page use these tokens, so a mode switch changes tokens only. - Status text (values, percentages, badges, the alert banner, the API-key error) uses the `*-ink` variant of `ok`/`warn`/`crit`; bar fills and the card border of an alerting card use the base color. Text on an accent fill @@ -239,12 +265,13 @@ client of the [HTTP API](http-api.md) like any third-party integration and has n hidden preference keeps it hidden in every state. - With `network_enabled` false the Network card's visibility checkbox is disabled and labelled "(disabled on server)"; the card can still be moved. +- The dialog's first section is the Theme group of [Theme](#theme); the layout reset leaves it unchanged. - Cards flow in three columns, two at a viewport width of 1100 px or less and one at 720 px or less. ### Browser storage -- The dashboard stores exactly four `localStorage` entries: `pimonitor-api-key`, `pimonitor-theme`, - `pimonitor-layout` and `pimonitor-openhab-things` (the value `open` while the openHAB card's list of not-online +- The dashboard stores exactly five `localStorage` entries: `pimonitor-api-key`, `pimonitor-theme`, + `pimonitor-style`, `pimonitor-layout` and `pimonitor-openhab-things` (the value `open` while the openHAB card's list of not-online Things is expanded; the entry is absent otherwise). When storage is unavailable (private browsing, blocked storage) every feature keeps working for the current page with defaults, and nothing is stored. @@ -263,6 +290,8 @@ client of the [HTTP API](http-api.md) like any third-party integration and has n - [0038](../decisions/0038-dashboard-mode-and-theme-as-token-overrides.md): mode and theme as token overrides - [0039](../decisions/0039-card-colour-only-on-icon-chip.md): card colour only on the icon chip - [0040](../decisions/0040-dashboard-icons-inline-svg.md): inline SVG icons +- [0041](../decisions/0041-theme-choice-per-browser-as-pimonitor-style.md): theme choice per browser +- [0042](../decisions/0042-theme-registry-in-theme-init-js.md): theme registry in `theme-init.js` ## Not here diff --git a/docs/decisions/0038-dashboard-mode-and-theme-as-token-overrides.md b/docs/decisions/0038-dashboard-mode-and-theme-as-token-overrides.md index 9f3a41f..94b49fe 100644 --- a/docs/decisions/0038-dashboard-mode-and-theme-as-token-overrides.md +++ b/docs/decisions/0038-dashboard-mode-and-theme-as-token-overrides.md @@ -3,7 +3,7 @@ - **Status:** Accepted - **Date:** 2026-11-28 - **Area:** Dashboard -- **Source:** Issue #217 +- **Source:** Issue #217, issue #218 - **Supersedes:** — ## Context @@ -24,6 +24,10 @@ names, and each design has to be swappable without touching the markup or the sc key and the attribute keep a name that no longer matches the user-facing concept of the milestone's issues. 3. **One stylesheet per design** — each design free in its rules. Cost: three copies of every layout rule to keep in step, more embedded bytes on a Pi Zero, and a design switch that reloads a stylesheet. +4. **Each further theme's override blocks in a file of its own, linked statically after `style.css`** (issue #218) + — a theme is reviewed in one file. Cost: one more request revalidated on every load per theme, a link and asset + tests per file, and the token key set test reads several files; the blocks are short, so `style.css` keeps them + after Clear's palette. ## Decision @@ -34,5 +38,11 @@ colour. ## Consequences -- A later theme only adds override blocks; `style.css` holds no colour literal outside the palette blocks. +- A later theme only adds override blocks — light, explicit dark and OS dark under its `data-style` value + ([0041](0041-theme-choice-per-browser-as-pimonitor-style.md)) — to `style.css`, after Clear's palette; `style.css` + holds no colour literal outside the palette blocks. The page has one DOM for every theme: no per-theme markup and + no per-theme HTML rendering in `app.js`. +- Canvas widgets take a theme's differences only from custom properties; every one they read is a palette token in + every block of every theme, so all blocks share one token key set (issue #218, + [0042](0042-theme-registry-in-theme-init-js.md)). - The stored key keeps the old word: code and documentation say "mode" and name the key as it is. diff --git a/docs/decisions/0041-theme-choice-per-browser-as-pimonitor-style.md b/docs/decisions/0041-theme-choice-per-browser-as-pimonitor-style.md new file mode 100644 index 0000000..13101d7 --- /dev/null +++ b/docs/decisions/0041-theme-choice-per-browser-as-pimonitor-style.md @@ -0,0 +1,40 @@ +# 0041: The theme choice is a per-browser preference, stored as `pimonitor-style` and applied as `data-style` + +- **Status:** Accepted +- **Date:** 2026-11-28 +- **Area:** Dashboard +- **Source:** Issue #218 +- **Supersedes:** — + +## Context + +v1.5.0 lets the user choose the dashboard's theme (Clear, later Console and Berry) independently of the light/dark +mode ([0038](0038-dashboard-mode-and-theme-as-token-overrides.md)). The mode already occupies the names that would +suit the theme: the `localStorage` key `pimonitor-theme` and the attribute `data-theme` on ``. Renaming them +would reset every stored mode on upgrade. Mode and layout are per-browser preferences without server-side state, and +the page applies the stored mode before the first paint from `theme-init.js` under `script-src 'self'`. + +## Options considered + +1. **Per browser, a new key `pimonitor-style` and attribute `data-style`; the default theme is the absence of the + attribute** — mode and theme stay two independent values, and the page without script, with unreadable storage or + with an unknown stored value is Clear by the unscoped palette. Cost: the code says "style" where the user reads + "theme". +2. **One combined value in `pimonitor-theme`** (`clear-dark`, …) — one key. Cost: changes the key's format, so a + stored mode is lost or needs a migration, and an older version reading the new value forgets the mode. +3. **A server-side default theme (`config.yaml` option, an API field)** — one look for every browser. Cost: a new + configuration and API surface, and per-user choice still needs browser storage; the issue leaves it out of scope. +4. **Default as an explicit `data-style="clear"`** — every theme scoped the same way. Cost: two representations of + Clear (absent before the script runs, explicit after), and Clear's palette, unscoped since #217, would move. + +## Decision + +Option 1. The theme id is stored per browser under `pimonitor-style`; a registered non-default id is applied as +`data-style=""` on ``, and Clear is the absence of the attribute. The rules (fallback, storage entries) +are in [Dashboard](../areas/dashboard.md#theme). + +## Consequences + +- An unknown stored value (downgrade, removed theme) means Clear and is kept, so an upgrade back restores the choice. +- Code names the theme "style" and the mode "theme" (`applyTheme`, `THEME_KEY`); comments say which is which. +- A server-side default would need its own decision and a new configuration option. diff --git a/docs/decisions/0042-theme-registry-in-theme-init-js.md b/docs/decisions/0042-theme-registry-in-theme-init-js.md new file mode 100644 index 0000000..9dfe11a --- /dev/null +++ b/docs/decisions/0042-theme-registry-in-theme-init-js.md @@ -0,0 +1,43 @@ +# 0042: The theme registry and the canvas token readers live once in `theme-init.js` + +- **Status:** Accepted +- **Date:** 2026-11-28 +- **Area:** Dashboard +- **Source:** Issue #218 +- **Supersedes:** — + +## Context + +Two scripts need the list of known themes: `theme-init.js`, which validates the stored id before the first paint, +and `app.js`, which builds the selector after the page loaded. The issue allows a second copy of the list in `app.js` +if a test keeps the two identical, as the fallback threshold keys are kept in step with the server. Three scripts +(`chart.js`, `gauge.js`, `app.js`) also read custom properties for canvas drawing, each with its own inline fallback +literal today, one of which turns a valid `0` into `0.28` and one of which has no fallback at all. + +## Options considered + +1. **One registry as a global constant in `theme-init.js`, read by `app.js`; the token readers and Clear's fallback + values as one map and two functions in the same file** — `theme-init.js` loads first, synchronously in ``, + so every later script sees them; nothing is duplicated, and a test only checks that `app.js` keeps no list and + that the fallback map equals Clear's light block. Cost: two more page-wide names, and `theme-init.js` is more than + a pre-paint snippet. +2. **A copy of the id list in `app.js`, kept equal by a Go test** — the issue's suggestion. Cost: two lists to edit + per theme, and a test that only exists to keep them in step. +3. **A JSON registry asset fetched by both scripts** — one file. Cost: a fetch cannot run before the first paint + without blocking, so `theme-init.js` would still need its own copy. +4. **Readers and fallbacks in `chart.js`** — loaded before `gauge.js` and `app.js`. Cost: `chart.js` is a drawing + library; the fallbacks belong next to the theme list they describe. + +## Decision + +Option 1. `theme-init.js` declares the registry `PIMONITOR_THEMES` (id and display name, default first), the map +`DRAWING_FALLBACKS` of every custom property a canvas renderer reads with Clear's light value, and the readers +`themeColor` and `themeNumber`; `app.js`, `chart.js` and `gauge.js` use only these. The rules are in +[Dashboard](../areas/dashboard.md#theme). + +## Consequences + +- Adding a theme is one registry entry plus its palette blocks; a new drawing property is one map entry plus a + token in every palette block (guarded by the token key set test). +- `app.js`, `chart.js` and `gauge.js` depend on `theme-init.js` having run, as `app.js` already depends on the + drawing functions of `chart.js` and `gauge.js`. diff --git a/docs/decisions/README.md b/docs/decisions/README.md index 75da1e0..da72155 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -102,4 +102,6 @@ once in the [area document](../areas/README.md) of the record's area, and the re | [0038](0038-dashboard-mode-and-theme-as-token-overrides.md) | Dashboard "mode" is light or dark, a "theme" is a set of custom-property overrides | Accepted | 2026-11-28 | | [0039](0039-card-colour-only-on-icon-chip.md) | The per-card colour appears only on the icon chip; status colours have a fill and an ink variant | Accepted | 2026-11-28 | | [0040](0040-dashboard-icons-inline-svg.md) | Dashboard icons are inline stroke SVG in the page, not emoji | Accepted | 2026-11-28 | +| [0041](0041-theme-choice-per-browser-as-pimonitor-style.md) | The theme choice is a per-browser preference, stored as `pimonitor-style` and applied as `data-style` | Accepted | 2026-11-28 | +| [0042](0042-theme-registry-in-theme-init-js.md) | The theme registry and the canvas token readers live once in `theme-init.js` | Accepted | 2026-11-28 | diff --git a/internal/web/assets/app.js b/internal/web/assets/app.js index f52da6c..8b1fcc8 100644 --- a/internal/web/assets/app.js +++ b/internal/web/assets/app.js @@ -29,7 +29,9 @@ let latestSnapshot = null; let latestHistory = null; + // THEME_KEY stores the mode (light/dark); STYLE_KEY stores the theme (registered style id). const THEME_KEY = 'pimonitor-theme'; + const STYLE_KEY = 'pimonitor-style'; const API_KEY_STORAGE = 'pimonitor-api-key'; function storedAPIKey() { @@ -83,7 +85,7 @@ if (!btn) return; const dark = effectiveTheme() === 'dark'; // The icon of the mode the button switches to is shown by CSS. - btn.setAttribute('aria-label', dark ? 'Switch to light theme' : 'Switch to dark theme'); + btn.setAttribute('aria-label', dark ? 'Switch to light mode' : 'Switch to dark mode'); btn.setAttribute('aria-pressed', String(dark)); } @@ -94,11 +96,69 @@ delete document.documentElement.dataset.theme; } updateThemeToggle(); - // Repaint canvas widgets that cached the previous palette's colors. + repaintCanvases(); + } + + // activeStyle returns the id of the theme in effect: the registered + // data-style value, else the default (first) theme. + function activeStyle() { + const id = document.documentElement.dataset.style; + return PIMONITOR_THEMES.some(t => t.id === id) ? id : PIMONITOR_THEMES[0]?.id; + } + + // repaintCanvases redraws the canvas widgets that cached the previous + // palette's colors (canvases read the custom properties at draw time). + function repaintCanvases() { if (latestSnapshot) renderMetrics(latestSnapshot); if (latestHistory) renderHistory(latestHistory); } + // applyStyle shows the theme with the given id; the default theme is the + // absence of data-style. + function applyStyle(id) { + if (id === PIMONITOR_THEMES[0]?.id) { + delete document.documentElement.dataset.style; + } else { + document.documentElement.dataset.style = id; + } + repaintCanvases(); + } + + // selectStyle stores and applies the theme with the given id. + function selectStyle(id) { + if (!PIMONITOR_THEMES.some(t => t.id === id)) return; + try { + localStorage.setItem(STYLE_KEY, id); + } catch (e) { + console.warn('failed to persist theme style', e); + } + applyStyle(id); + } + + // buildStylePicker fills the theme picker of the layout dialog from the + // registry; it stays hidden while fewer than two themes exist. + function buildStylePicker() { + const picker = document.getElementById('style-picker'); + const options = document.getElementById('style-options'); + if (!picker || !options) return; + picker.classList.toggle('hidden', PIMONITOR_THEMES.length < 2); + options.innerHTML = ''; + for (const theme of PIMONITOR_THEMES) { + const label = document.createElement('label'); + label.className = 'style-option'; + const input = document.createElement('input'); + input.type = 'radio'; + input.name = 'style-choice'; + input.value = theme.id; + input.checked = theme.id === activeStyle(); + input.addEventListener('change', () => selectStyle(theme.id)); + const text = document.createElement('span'); + text.textContent = theme.name; + label.append(input, text); + options.appendChild(label); + } + } + function toggleTheme() { const next = effectiveTheme() === 'dark' ? 'light' : 'dark'; try { @@ -844,6 +904,7 @@ } function openLayoutModal() { + buildStylePicker(); buildLayoutList(); openModal(document.getElementById('layout-modal')); } @@ -1409,16 +1470,15 @@ const to = Math.max(...times); const intervalSeconds = Math.max(1, latestOpenHAB?.poll_interval_seconds || 60); const markers = (hist?.openhab_restarts || []).map(pointTime).filter(t => t >= from && t <= to); - const css = getComputedStyle(document.documentElement); const colors = { 'openhab_rss_bytes': '--accent', 'openhab_heap_used_bytes': '--muted' }; drawTimeChart(canvas, lines.map(line => ({ points: line.points, - color: css.getPropertyValue(colors[line.key]).trim() || '#2563eb', + color: themeColor(colors[line.key]), })), { from, to, gapMs: 1.5 * intervalSeconds * 1000, markers, - markerColor: css.getPropertyValue('--warn').trim() || '#d97706', + markerColor: themeColor('--warn'), }); } diff --git a/internal/web/assets/chart.js b/internal/web/assets/chart.js index 7c9f4f4..7fb1bfe 100644 --- a/internal/web/assets/chart.js +++ b/internal/web/assets/chart.js @@ -3,7 +3,7 @@ // small trend lines, not zoom/pan/tooltip interactivity. function drawSparkline(canvas, points, opts) { opts = opts || {}; - const color = opts.color || getComputedStyle(document.documentElement).getPropertyValue('--accent').trim() || '#2563eb'; + const color = opts.color || themeColor('--accent'); const dpr = window.devicePixelRatio || 1; const cssWidth = canvas.clientWidth || 260; const cssHeight = canvas.clientHeight || 48; @@ -39,9 +39,8 @@ function drawSparkline(canvas, points, opts) { return cssHeight - pad - t * (cssHeight - pad * 2); }; - const rootStyle = getComputedStyle(document.documentElement); - const fillAlpha = Number.parseFloat(rootStyle.getPropertyValue('--spark-fill-alpha')) || 0.28; - const cardBg = rootStyle.getPropertyValue('--card-bg').trim() || '#ffffff'; + const fillAlpha = themeNumber('--spark-fill-alpha', 0, 1); + const cardBg = themeColor('--card-bg'); const lastX = pad + (points.length - 1) * stepX; const lastY = yFor(points[points.length - 1].v); diff --git a/internal/web/assets/gauge.js b/internal/web/assets/gauge.js index 53e92f4..3eb93a2 100644 --- a/internal/web/assets/gauge.js +++ b/internal/web/assets/gauge.js @@ -40,8 +40,8 @@ function drawGauge(canvas, value, max, colorClass) { const startAngle = Math.PI; // left (9 o'clock) const endAngle = 2 * Math.PI; // right (3 o'clock), via the top - const trackColor = getComputedStyle(document.documentElement).getPropertyValue('--track').trim() || '#e8eaef'; - const fillColor = getComputedStyle(document.documentElement).getPropertyValue(gaugeColorVar(colorClass)).trim(); + const trackColor = themeColor('--track'); + const fillColor = themeColor(gaugeColorVar(colorClass)); // Background track (full top semicircle). ctx.beginPath(); diff --git a/internal/web/assets/index.html b/internal/web/assets/index.html index 1373ad6..b411df4 100644 --- a/internal/web/assets/index.html +++ b/internal/web/assets/index.html @@ -19,7 +19,7 @@

PiMonitor