diff --git a/README.md b/README.md index 053df7c..127768b 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,11 @@ The Console theme, light and dark: ![PiMonitor dashboard, Console theme, light](docs/dashboard-console-light.png) ![PiMonitor dashboard, Console theme, dark](docs/dashboard-console-dark.png) +The Berry theme, light and dark: + +![PiMonitor dashboard, Berry theme, light](docs/dashboard-berry-light.png) +![PiMonitor dashboard, Berry theme, dark](docs/dashboard-berry-dark.png) + ## Features - **CPU usage** - overall and per-core percentage, with a trend sparkline @@ -59,7 +64,7 @@ The Console theme, light and dark: metric sampling - **Light/dark mode toggle** - follows the OS setting by default, with a manual override remembered in the browser -- **Choosable themes** - Clear and Console (a monospace, outlined look), picked +- **Choosable themes** - Clear, Console (a monospace, outlined look) and Berry (soft, one accent colour), picked in the Customize dialog, remembered in the browser - **Configurable dashboard layout** - show/hide and reorder metric cards from a settings modal, remembered in the browser diff --git a/docs/areas/dashboard.md b/docs/areas/dashboard.md index 59d74b7..6589afb 100644 --- a/docs/areas/dashboard.md +++ b/docs/areas/dashboard.md @@ -158,7 +158,7 @@ client of the [HTTP API](http-api.md) like any third-party integration and has n - CPU usage, temperature, memory, swap and each filesystem are colored `crit` when the value is greater than or equal to the matching `*_crit` threshold from `/api/v1/config`, otherwise `warn` when greater than or equal to the - `*_warn` threshold, otherwise `ok` — the same comparison the alert engine uses. The levels are the same in every theme; only the color of `ok` differs: green in Clear, `--text` in Console, where color marks only `warn` and `crit` (*Look*, [0043](../decisions/0043-console-colour-only-for-warn-and-crit.md)). + `*_warn` threshold, otherwise `ok` — the same comparison the alert engine uses. The levels are the same in every theme; only the color of `ok` differs: green in Clear, `--text` in Console, where color marks only `warn` and `crit` (*Look*, [0043](../decisions/0043-console-colour-only-for-warn-and-crit.md)); Berry is colored as Clear. - The load-average gauges (1, 5 and 15 min) run from 0 to the CPU core count and are colored against the CPU thresholds scaled to the core count (`cores × cpu_warn_percent / 100`, `cores × cpu_crit_percent / 100`). - Coloring follows the raw value of every poll and is independent of alert state: a value can be colored `crit` @@ -207,7 +207,7 @@ client of the [HTTP API](http-api.md) like any third-party integration and has n ### 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`: Clear, the default (the first entry), and Console (`console`), second. + in `PIMONITOR_THEMES` of `theme-init.js`: Clear, the default (the first entry), Console (`console`), second, and Berry (`berry`), third. - 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 @@ -225,17 +225,27 @@ client of the [HTTP API](http-api.md) like any third-party integration and has n `--shadow` and `--dialog-shadow` are `0 0 0 transparent` instead of `none`, which would make the `box-shadow` list of `.theme-toggle:hover` invalid. Its look beyond tokens is rules in `style.css` whose every selector starts with `:root[data-style="console"]`; only the unit gap `.metric-unit::before` is an unscoped rule. +- Berry (soft, rounded, one accent) has the same three blocks, with a raspberry `--accent` and every `--accent-` + equal to it, and its look beyond tokens is rules whose every selector starts with `:root[data-style="berry"]`, + without `!important`. Its light `--ok-ink` is `#166534`, darker than Clear's, so the Pi-hole pill reaches 4.5:1 + ([0045](../decisions/0045-berry-light-ok-ink-darker-for-pill-contrast.md)); its dark `--shadow` is + `0 0 0 transparent`, like Console's. +- Every palette block of every theme also declares `--card-border` (Clear's and Console's equal their `--border`; + Berry's is transparent in light and `#2c2832` in dark), `--pill-tint` (20 % in Clear and Console), `--gauge-shape` + (`half`) and `--spark-dot-size` (8); the unscoped card, header-button and dialog borders and the badge tints read + them, so Clear and Console look as before. - Reasons: [0038](../decisions/0038-dashboard-mode-and-theme-as-token-overrides.md), [0041](../decisions/0041-theme-choice-per-browser-as-pimonitor-style.md), - [0042](../decisions/0042-theme-registry-in-theme-init-js.md). + [0042](../decisions/0042-theme-registry-in-theme-init-js.md), + [0044](../decisions/0044-berry-one-accent-status-colours-for-values.md). ### Look - The canvas renderers read exactly these custom properties through `themeColor`, `themeNumber` and `themeKeyword` of `theme-init.js`: the colors `--accent`, `--muted`, `--card-bg`, `--track`, `--border`, `--ok-fill`, `--warn` and - `--crit`; the numbers `--spark-fill-alpha` (0 to 1), `--spark-line-width` (0.5 to 6) and `--gauge-width` (1 to - 12); the keywords `--spark-shape` (`line`, `step`), `--spark-fill` (`fade`, `flat`), `--spark-dot` (`ring`, - `none`), `--spark-grid` (`none`, `lines`) and `--gauge-cap` (`round`, `butt`). An empty or unparseable value, a + `--crit`; the numbers `--spark-fill-alpha` (0 to 1), `--spark-line-width` (0.5 to 6), `--gauge-width` (1 to + 12) and `--spark-dot-size` (2 to 16); the keywords `--spark-shape` (`line`, `step`), `--spark-fill` (`fade`, `flat`), `--spark-dot` (`ring`, + `none`), `--spark-grid` (`none`, `lines`), `--gauge-cap` (`round`, `butt`) and `--gauge-shape` (`half`, `ring`). An empty or unparseable value, a number outside its range or a word outside its list 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 @@ -245,21 +255,35 @@ client of the [HTTP API](http-api.md) like any third-party integration and has n - 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 (for `ok`: `--ok` on Clear's bars, `--ok-fill` on the gauge arc and on Console's bars). Text on an accent fill uses `--on-accent`. +- Berry colors status as Clear does (`ok` green, `warn` amber, `crit` red) and only the accent is one color: its + `--ok-fill` equals `--ok`, and no status value, bar or percentage takes `--accent` + ([0044](../decisions/0044-berry-one-accent-status-colours-for-values.md)). - Console colors `ok` text with `--text` (`.metric-ok` and the new-version column of the update list); color appears only for `warn` and `crit`, plus the Pi-hole status dot (green when up to date, amber with an update). The ok fill of the gauge arc and of Console's bars is `--ok-fill`: Clear's green (equal to its `--ok`, which Clear's bars use), Console's `--text` ([0043](../decisions/0043-console-colour-only-for-warn-and-crit.md)). - A bar label shows the percentage emphasised, colored only at `warn` and `crit`, and the byte sizes muted beside it. - The load gauge draws an arc of `--gauge-width` (Clear 9 px with round caps, Console 5 px with butt caps) on the - `--track` color and shows its value inside the arc; the value's font size scales with the gauge width in both - themes. + `--track` color and shows its value inside the arc; the value's font size scales with the gauge width in Clear + and Console. + Berry draws the load gauge as a ring (`--gauge-shape: ring`, read at every draw): a full-circle track of the + smaller canvas side with the same 9 px width and round caps, a value arc clockwise from 12 o'clock over the same + 0 to core-count scale and the same thresholds, nothing drawn at 0 and a closed ring at the maximum; its canvas is + 88 px high, the value is centred in it, and its font (12 to 18 px) shrinks with the gauge so it fits the ring down to + the narrowest gauge. - A sparkline (and the detail chart) is a line of `--spark-line-width` with a fill and, as the theme says, a dot with a ring at the newest point, inset so the dot is never clipped. Clear: a 2 px line, a fill fading towards the bottom and the dot. Console: a 1.5 px stepped line (each point held to the next x), a flat low-opacity fill, a - solid baseline with two dashed lines at 25 % and 62.5 % of the height, and no dot. + solid baseline with two dashed lines at 25 % and 62.5 % of the height, and no dot. Berry: a 2.5 px line, a fade fill + and a 10 px dot (`--spark-dot-size`; 8 px in Clear and Console). The plot is inset by the dot's radius plus its 3 px + ring: 7 px in Clear and Console, 8 px in Berry. - A metric value of CPU usage and temperature is a number element (`.metric-number`) and, when there is a unit, a unit element (`.metric-unit`), built by `createElement` and `textContent`. Clear separates them by a space (`.metric-unit::before`); Console sets the unit 15 px, muted, 4 px apart without the space. +- Berry's cards are 22 px round with no border in light (a soft shadow) and a 1 px border without shadow in dark; + card headings are sentence case, 15 px; values are 38 px; badges and the Pi-hole status are pills tinted with + `--pill-tint`, and the alert badge capitalizes its first letter. The Updates card is a wrapping row with the + button beside the count, and the Pi-hole section and the network rows are inset tiles on `--bg`. - Console's bars are 12 px high and square, drawn as a repeating gradient of 6 px segments with 2 px gaps on the track and on the fill, both from the track's left edge; its card heading is a 44 px strip with a bottom border across the card, and in a clickable card the whole strip is the button. @@ -315,6 +339,8 @@ client of the [HTTP API](http-api.md) like any third-party integration and has n - [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` - [0043](../decisions/0043-console-colour-only-for-warn-and-crit.md): in Console, colour only for `warn` and `crit` +- [0044](../decisions/0044-berry-one-accent-status-colours-for-values.md): Berry has one accent, status colours stay for values +- [0045](../decisions/0045-berry-light-ok-ink-darker-for-pill-contrast.md): Berry's light `--ok-ink` is darker for pill contrast ## Not here diff --git a/docs/dashboard-berry-dark.png b/docs/dashboard-berry-dark.png new file mode 100644 index 0000000..c9e1c07 Binary files /dev/null and b/docs/dashboard-berry-dark.png differ diff --git a/docs/dashboard-berry-light.png b/docs/dashboard-berry-light.png new file mode 100644 index 0000000..b8a8dc4 Binary files /dev/null and b/docs/dashboard-berry-light.png differ 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 1e84898..2f3e1b7 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, issue #218, issue #219 +- **Source:** Issue #217, issue #218, issue #219, issue #220 - **Supersedes:** — ## Context @@ -32,6 +32,10 @@ names, and each design has to be swappable without touching the markup or the sc — no theme ever adds a rule. Cost: Console changes fonts, border styles, bar patterns, heading layout and hidden elements; about thirty more tokens would enter all three blocks of every theme, Clear's included, where most name a property Clear does not use. +6. **A value that differs between a theme's modes as a new token read by the unscoped rule** (considered for Berry, + issue #220, whose card border is invisible in light and a hairline in dark mode, and whose badge tint is 16 % in + light and 18 % in dark mode) — Clear and Console get the token with the value their rule had, so their look stays. + The alternative, a scoped rule per mode, repeats each rule three times (light, explicit dark, OS dark). ## Decision @@ -39,7 +43,9 @@ Option 1. Light/dark is the *mode*; its storage key `pimonitor-theme` and attrib since renaming them would reset every stored choice. The look is described in [Dashboard](../areas/dashboard.md#look); the per-card colours are tokens of the palette blocks like every other colour. What a theme changes beyond a token value (a font family, a dashed border, a segmented bar, a hidden element) -is a rule scoped to `:root[data-style=""]` that uses only tokens (issue #219). +is a rule scoped to `:root[data-style=""]` that uses only tokens (issue #219); a value that differs between a +theme's modes is a token, which an unscoped rule may read when every other theme's blocks give it that rule's former +value (option 6, issue #220). ## Consequences diff --git a/docs/decisions/0044-berry-one-accent-status-colours-for-values.md b/docs/decisions/0044-berry-one-accent-status-colours-for-values.md new file mode 100644 index 0000000..7c76173 --- /dev/null +++ b/docs/decisions/0044-berry-one-accent-status-colours-for-values.md @@ -0,0 +1,39 @@ +# 0044: Berry uses one accent colour; status colours stay reserved for values + +- **Status:** Accepted +- **Date:** 2026-11-30 +- **Area:** Dashboard +- **Source:** Issue #220 +- **Supersedes:** — + +## Context + +The theme Berry (issue #220) is a soft look built around one raspberry accent. Clear gives every card a colour of its +own on its icon chip ([0039](0039-card-colour-only-on-icon-chip.md)), and Console draws the `ok` level in the text +colour ([0043](0043-console-colour-only-for-warn-and-crit.md)). Berry's accent is a red, and so is `crit`: if the +accent also coloured values, bars or gauge arcs, a reader could not tell a healthy value from a critical one by colour. +The levels and thresholds are shared by every theme and must not change. + +## Options considered + +1. **One accent for every piece of chrome, the status colours only for values, fills and arcs, as in Clear** — the + logo, the icon chips, the sparklines, links, the primary buttons and the focus rings take `--accent`; every + `--accent-` token equals it; values, bars and gauge arcs keep Clear's green, amber and red. Cost: the cards + lose the colour cue that tells them apart in Clear. +2. **Clear's per-card colours with Berry's shapes** — keeps the cue. Cost: ten hues beside the accent, the opposite of + the single-accent look the issue asks for. +3. **The accent also for values in the `ok` level, as Console uses its text colour** — the calmest page. Cost: a + raspberry `ok` value beside a red `crit` value differ by hue alone, which the issue forbids. + +## Decision + +Option 1. While Berry is active every chrome element that is coloured takes `--accent`, and values, bar fills and gauge +arcs take the status colour of their level exactly as in Clear; the accent is never the colour of a value, a fill or +an arc. The rules are in [Dashboard](../areas/dashboard.md#look). + +## Consequences + +- The icon-chip rule of 0039 still holds: the chip shows the card's colour token, which in Berry is the accent. +- Wherever `crit` appears in Berry it is carried by text as well (a value, a badge, the banner), so the two reds never + stand alone. +- The sparklines and the openHAB memory chart are drawn in the accent: they show a trend, not a level. diff --git a/docs/decisions/0045-berry-light-ok-ink-darker-for-pill-contrast.md b/docs/decisions/0045-berry-light-ok-ink-darker-for-pill-contrast.md new file mode 100644 index 0000000..ec32522 --- /dev/null +++ b/docs/decisions/0045-berry-light-ok-ink-darker-for-pill-contrast.md @@ -0,0 +1,33 @@ +# 0045: Berry's light `ok` ink is one step darker than the issue's palette + +- **Status:** Accepted +- **Date:** 2026-11-30 +- **Area:** Dashboard +- **Source:** Issue #220 +- **Supersedes:** — + +## Context + +Issue #220 gives Berry's light `--ok-ink` as `#15803d`, Clear's value, and asks for text contrast of at least 4.5:1. +Berry draws the Pi-hole status as a pill: `ok` ink on `--ok` at 16 % inside an inset tile on `--bg`. With `#15803d` +that pair reaches only 3.79:1 (4.20:1 over `--card-bg`), and since `--ok-ink` on plain `--bg` is already 4.47:1, no +lighter tint can fix it. Every other pair of the issue's palette passes. + +## Options considered + +1. **A darker ink, `#166534`, in Berry's light blocks only** — the next darker green of the same family; every `ok` + text pair passes (5.38:1 on the pill tint over `--bg`). Cost: a documented departure from the issue's table for one + token. +2. **The `ok` pill's text in `--text`** — no new value. Cost: the pill's text loses its level colour, unlike the + `warn` pill beside it. +3. **Accept 3.79:1** — the issue's value. Cost: text below the contrast the issue itself requires. + +## Decision + +Option 1, chosen by the Product Manager: Berry's light `--ok-ink` is `#166534`; its dark `--ok-ink` and every other +token keep the issue's values. The palette is in [Dashboard](../areas/dashboard.md#theme). + +## Consequences + +- Clear and Console keep `#15803d`; the contrast test computes Berry's pairs from its own blocks, pill and banner + tints included, so a later palette edit cannot drop below 4.5:1 unnoticed. diff --git a/docs/decisions/README.md b/docs/decisions/README.md index 8c202c6..35d76b2 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -110,4 +110,6 @@ once in the [area document](../areas/README.md) of the record's area, and the re | [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 | | [0043](0043-console-colour-only-for-warn-and-crit.md) | In Console, colour is reserved for `warn` and `crit` | Accepted | 2026-11-29 | +| [0044](0044-berry-one-accent-status-colours-for-values.md) | Berry uses one accent colour; status colours stay reserved for values | Accepted | 2026-11-30 | +| [0045](0045-berry-light-ok-ink-darker-for-pill-contrast.md) | Berry's light `ok` ink is one step darker than the issue's palette | Accepted | 2026-11-30 | diff --git a/internal/web/assets/chart.js b/internal/web/assets/chart.js index 75fef14..6c3ffad 100644 --- a/internal/web/assets/chart.js +++ b/internal/web/assets/chart.js @@ -2,8 +2,11 @@ // vendoring a charting library: the dashboard only needs a handful of // small trend lines, not zoom/pan/tooltip interactivity. +// The ring around the newest-point dot, in px beyond the dot's radius. +const SPARK_DOT_RING = 3; + // sparkStyle reads the sparkline drawing properties of the active theme and -// returns { shape, lineWidth, fill, fillAlpha, dot, grid, cardBg, border }. +// returns { shape, lineWidth, fill, fillAlpha, dot, dotSize, grid, cardBg, border }. function sparkStyle() { return { shape: themeKeyword('--spark-shape', ['line', 'step']), @@ -11,6 +14,7 @@ function sparkStyle() { fill: themeKeyword('--spark-fill', ['fade', 'flat']), fillAlpha: themeNumber('--spark-fill-alpha', 0, 1), dot: themeKeyword('--spark-dot', ['ring', 'none']), + dotSize: themeNumber('--spark-dot-size', 2, 16), grid: themeKeyword('--spark-grid', ['none', 'lines']), cardBg: themeColor('--card-bg'), border: themeColor('--border'), @@ -88,14 +92,15 @@ function fillSparkline(ctx, xy, height, color, style) { } // drawSparkDot draws the newest-point dot at `last` ({ x, y }) with a ring in -// `cardBg`. -function drawSparkDot(ctx, last, color, cardBg) { +// the card colour; `style` is the result of sparkStyle. The dot's diameter is +// style.dotSize, the ring is SPARK_DOT_RING px wider all around. +function drawSparkDot(ctx, last, color, style) { ctx.beginPath(); - ctx.arc(last.x, last.y, 7, 0, 2 * Math.PI); - ctx.fillStyle = cardBg; + ctx.arc(last.x, last.y, style.dotSize / 2 + SPARK_DOT_RING, 0, 2 * Math.PI); + ctx.fillStyle = style.cardBg; ctx.fill(); ctx.beginPath(); - ctx.arc(last.x, last.y, 4, 0, 2 * Math.PI); + ctx.arc(last.x, last.y, style.dotSize / 2, 0, 2 * Math.PI); ctx.fillStyle = color; ctx.fill(); } @@ -128,9 +133,10 @@ function drawSparkline(canvas, points, opts) { max += 1; } - // The plot is inset far enough that the newest-point dot (radius 4 plus a - // 3 px ring) stays inside the canvas at the right, top and bottom edges. - const pad = 7; + // The plot is inset far enough that the newest-point dot (its radius plus + // the 3 px ring) stays inside the canvas at the right, top and bottom edges. + const style = sparkStyle(); + const pad = style.dotSize / 2 + SPARK_DOT_RING; const stepX = (cssWidth - pad * 2) / (points.length - 1); const yFor = v => { @@ -138,7 +144,6 @@ function drawSparkline(canvas, points, opts) { return cssHeight - pad - t * (cssHeight - pad * 2); }; - const style = sparkStyle(); const xy = points.map((p, i) => ({ x: pad + i * stepX, y: yFor(p.v) })); if (style.grid !== 'none') { @@ -154,7 +159,7 @@ function drawSparkline(canvas, points, opts) { ctx.stroke(); if (style.dot !== 'none') { - drawSparkDot(ctx, xy[xy.length - 1], color, style.cardBg); + drawSparkDot(ctx, xy[xy.length - 1], color, style); } } diff --git a/internal/web/assets/gauge.js b/internal/web/assets/gauge.js index cc7f6fb..f5d387a 100644 --- a/internal/web/assets/gauge.js +++ b/internal/web/assets/gauge.js @@ -13,6 +13,31 @@ function gaugeColorVar(colorClass) { return '--ok-fill'; } +// drawGaugeRing draws the ring gauge: a full-circle track and, from 12 o'clock +// clockwise, the value arc over `fraction` (0 to 1) of a full turn. `ring` is +// { width, height, lineWidth, lineCap, trackColor, fillColor }. The ring is +// centred and its outer edge, caps included, touches the smaller canvas side. +// Nothing is drawn for a fraction of 0, so round caps leave no dot. +function drawGaugeRing(ctx, ring, fraction) { + const cx = ring.width / 2; + const cy = ring.height / 2; + const radius = Math.max(1, Math.min(ring.width, ring.height) / 2 - ring.lineWidth / 2); + + ctx.beginPath(); + ctx.arc(cx, cy, radius, 0, 2 * Math.PI); + ctx.lineWidth = ring.lineWidth; + ctx.strokeStyle = ring.trackColor; + ctx.stroke(); + + if (fraction <= 0) return; + ctx.beginPath(); + ctx.arc(cx, cy, radius, -Math.PI / 2, -Math.PI / 2 + 2 * Math.PI * fraction, false); + ctx.lineWidth = ring.lineWidth; + ctx.strokeStyle = ring.fillColor; + ctx.lineCap = ring.lineCap; + ctx.stroke(); +} + function drawGauge(canvas, value, max, colorClass) { const dpr = window.devicePixelRatio || 1; const cssWidth = canvas.clientWidth || 80; @@ -27,6 +52,15 @@ function drawGauge(canvas, value, max, colorClass) { const lineWidth = themeNumber('--gauge-width', 1, 12); const lineCap = themeKeyword('--gauge-cap', ['round', 'butt']); + const shape = themeKeyword('--gauge-shape', ['half', 'ring']); + const trackColor = themeColor('--track'); + const fillColor = themeColor(gaugeColorVar(colorClass)); + const clamped = Math.max(0, Math.min(value / max, 1)); + if (shape === 'ring') { + drawGaugeRing(ctx, { width: cssWidth, height: cssHeight, lineWidth, lineCap, trackColor, fillColor }, clamped); + return; + } + const margin = 4; const cx = cssWidth / 2; const cy = cssHeight - margin - lineWidth / 2; @@ -41,9 +75,6 @@ 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 = themeColor('--track'); - const fillColor = themeColor(gaugeColorVar(colorClass)); - // Background track (full top semicircle). ctx.beginPath(); ctx.arc(cx, cy, radius, startAngle, endAngle, false); @@ -53,8 +84,6 @@ function drawGauge(canvas, value, max, colorClass) { ctx.stroke(); // Value arc (proportional sweep from the left). - const clamped = Math.max(0, Math.min(value / max, 1)); - ctx.beginPath(); ctx.arc(cx, cy, radius, startAngle, startAngle + Math.PI * clamped, false); ctx.lineWidth = lineWidth; diff --git a/internal/web/assets/style.css b/internal/web/assets/style.css index fa01fea..2fa3c2f 100644 --- a/internal/web/assets/style.css +++ b/internal/web/assets/style.css @@ -5,6 +5,7 @@ --text: #171a1f; --muted: #5f6876; --border: #e4e7ec; + --card-border: #e4e7ec; --track: #e8eaef; --accent: #2563eb; --on-accent: #ffffff; @@ -26,6 +27,7 @@ --accent-network: #be185d; --accent-openhab: #0369a1; --chip-tint: 12%; + --pill-tint: 20%; --btn-tint: 8%; --btn-border-tint: 30%; --spark-fill-alpha: 0.28; @@ -43,8 +45,10 @@ --spark-fill: fade; --spark-dot: ring; --spark-grid: none; + --spark-dot-size: 8; --gauge-width: 9; --gauge-cap: round; + --gauge-shape: half; } /* Dark palette. Applied either by an explicit user choice @@ -57,6 +61,7 @@ --text: #e8eaee; --muted: #a0a7b3; --border: #2b2f37; + --card-border: #2b2f37; --track: #2c3039; --accent: #60a5fa; --on-accent: #0b1220; @@ -78,6 +83,7 @@ --accent-network: #f472b6; --accent-openhab: #38bdf8; --chip-tint: 16%; + --pill-tint: 20%; --btn-tint: 14%; --btn-border-tint: 35%; --spark-fill-alpha: 0.30; @@ -95,8 +101,10 @@ --spark-fill: fade; --spark-dot: ring; --spark-grid: none; + --spark-dot-size: 8; --gauge-width: 9; --gauge-cap: round; + --gauge-shape: half; } @media (prefers-color-scheme: dark) { @@ -106,6 +114,7 @@ --text: #e8eaee; --muted: #a0a7b3; --border: #2b2f37; + --card-border: #2b2f37; --track: #2c3039; --accent: #60a5fa; --on-accent: #0b1220; @@ -127,6 +136,7 @@ --accent-network: #f472b6; --accent-openhab: #38bdf8; --chip-tint: 16%; + --pill-tint: 20%; --btn-tint: 14%; --btn-border-tint: 35%; --spark-fill-alpha: 0.30; @@ -144,8 +154,10 @@ --spark-fill: fade; --spark-dot: ring; --spark-grid: none; + --spark-dot-size: 8; --gauge-width: 9; --gauge-cap: round; + --gauge-shape: half; } } @@ -157,6 +169,7 @@ --text: #111418; --muted: #5a626e; --border: #d5d9df; + --card-border: #d5d9df; --track: #dde0e5; --accent: #111418; --on-accent: #ffffff; @@ -178,6 +191,7 @@ --accent-network: #111418; --accent-openhab: #111418; --chip-tint: 0%; + --pill-tint: 20%; --btn-tint: 0%; --btn-border-tint: 100%; --spark-fill-alpha: 0.07; @@ -195,8 +209,10 @@ --spark-fill: flat; --spark-dot: none; --spark-grid: lines; + --spark-dot-size: 8; --gauge-width: 5; --gauge-cap: butt; + --gauge-shape: half; } :root[data-style="console"][data-theme="dark"] { @@ -205,6 +221,7 @@ --text: #e6e8eb; --muted: #98a0ab; --border: #282c33; + --card-border: #282c33; --track: #2b2f36; --accent: #e6e8eb; --on-accent: #121417; @@ -226,6 +243,7 @@ --accent-network: #e6e8eb; --accent-openhab: #e6e8eb; --chip-tint: 0%; + --pill-tint: 20%; --btn-tint: 0%; --btn-border-tint: 100%; --spark-fill-alpha: 0.09; @@ -243,8 +261,10 @@ --spark-fill: flat; --spark-dot: none; --spark-grid: lines; + --spark-dot-size: 8; --gauge-width: 5; --gauge-cap: butt; + --gauge-shape: half; } @media (prefers-color-scheme: dark) { @@ -254,6 +274,7 @@ --text: #e6e8eb; --muted: #98a0ab; --border: #282c33; + --card-border: #282c33; --track: #2b2f36; --accent: #e6e8eb; --on-accent: #121417; @@ -275,6 +296,7 @@ --accent-network: #e6e8eb; --accent-openhab: #e6e8eb; --chip-tint: 0%; + --pill-tint: 20%; --btn-tint: 0%; --btn-border-tint: 100%; --spark-fill-alpha: 0.09; @@ -292,8 +314,170 @@ --spark-fill: flat; --spark-dot: none; --spark-grid: lines; + --spark-dot-size: 8; --gauge-width: 5; --gauge-cap: butt; + --gauge-shape: half; + } +} + +/* Berry theme (`data-style="berry"`): the same three blocks as Clear. Accent, on-accent, the + ok fill and the per-card accents are literals so the contrast checks can read them. */ +:root[data-style="berry"] { + --bg: #f4f1f4; + --card-bg: #ffffff; + --card-border: transparent; + --text: #1d1921; + --muted: #665f6d; + --border: #eee9ef; + --track: #ece6ed; + --accent: #c2255c; + --on-accent: #ffffff; + --ok: #16a34a; + --ok-ink: #166534; + --warn: #d97706; + --warn-ink: #92400e; + --crit: #dc2626; + --crit-ink: #b91c1c; + --shadow: 0 1px 2px rgba(40, 20, 50, 0.05), 0 10px 28px rgba(40, 20, 50, 0.07); + --accent-system: #c2255c; + --accent-updates: #c2255c; + --accent-uptime: #c2255c; + --accent-cpu: #c2255c; + --accent-load: #c2255c; + --accent-temperature: #c2255c; + --accent-memory: #c2255c; + --accent-disks: #c2255c; + --accent-network: #c2255c; + --accent-openhab: #c2255c; + --chip-tint: 11%; + --pill-tint: 16%; + --btn-tint: 8%; + --btn-border-tint: 30%; + --spark-fill-alpha: 0.26; + --dialog-shadow: 0 1px 2px rgba(40, 20, 50, 0.05), 0 10px 28px rgba(40, 20, 50, 0.07); + --backdrop: rgba(0, 0, 0, 0.5); + --radius-card: 22px; + --radius-control: 18px; + --radius-button: 999px; + --radius-chip: 50%; + --card-padding: 10px 22px 22px; + --gap: 20px; + --ok-fill: #16a34a; + --spark-line-width: 2.5; + --spark-shape: line; + --spark-fill: fade; + --spark-dot: ring; + --spark-grid: none; + --spark-dot-size: 10; + --gauge-width: 9; + --gauge-cap: round; + --gauge-shape: ring; +} + +:root[data-style="berry"][data-theme="dark"] { + --bg: #131116; + --card-bg: #1d1a21; + --card-border: #2c2832; + --text: #f0ebf3; + --muted: #a8a0b0; + --border: #2e2a33; + --track: #342f3a; + --accent: #f06595; + --on-accent: #2a0a17; + --ok: #22c55e; + --ok-ink: #4ade80; + --warn: #f59e0b; + --warn-ink: #fbbf24; + --crit: #ef4444; + --crit-ink: #f87171; + --shadow: 0 0 0 transparent; + --accent-system: #f06595; + --accent-updates: #f06595; + --accent-uptime: #f06595; + --accent-cpu: #f06595; + --accent-load: #f06595; + --accent-temperature: #f06595; + --accent-memory: #f06595; + --accent-disks: #f06595; + --accent-network: #f06595; + --accent-openhab: #f06595; + --chip-tint: 15%; + --pill-tint: 18%; + --btn-tint: 14%; + --btn-border-tint: 35%; + --spark-fill-alpha: 0.30; + --dialog-shadow: 0 0 0 transparent; + --backdrop: rgba(0, 0, 0, 0.5); + --radius-card: 22px; + --radius-control: 18px; + --radius-button: 999px; + --radius-chip: 50%; + --card-padding: 10px 22px 22px; + --gap: 20px; + --ok-fill: #22c55e; + --spark-line-width: 2.5; + --spark-shape: line; + --spark-fill: fade; + --spark-dot: ring; + --spark-grid: none; + --spark-dot-size: 10; + --gauge-width: 9; + --gauge-cap: round; + --gauge-shape: ring; +} + +@media (prefers-color-scheme: dark) { + :root[data-style="berry"]:not([data-theme]) { + --bg: #131116; + --card-bg: #1d1a21; + --card-border: #2c2832; + --text: #f0ebf3; + --muted: #a8a0b0; + --border: #2e2a33; + --track: #342f3a; + --accent: #f06595; + --on-accent: #2a0a17; + --ok: #22c55e; + --ok-ink: #4ade80; + --warn: #f59e0b; + --warn-ink: #fbbf24; + --crit: #ef4444; + --crit-ink: #f87171; + --shadow: 0 0 0 transparent; + --accent-system: #f06595; + --accent-updates: #f06595; + --accent-uptime: #f06595; + --accent-cpu: #f06595; + --accent-load: #f06595; + --accent-temperature: #f06595; + --accent-memory: #f06595; + --accent-disks: #f06595; + --accent-network: #f06595; + --accent-openhab: #f06595; + --chip-tint: 15%; + --pill-tint: 18%; + --btn-tint: 14%; + --btn-border-tint: 35%; + --spark-fill-alpha: 0.30; + --dialog-shadow: 0 0 0 transparent; + --backdrop: rgba(0, 0, 0, 0.5); + --radius-card: 22px; + --radius-control: 18px; + --radius-button: 999px; + --radius-chip: 50%; + --card-padding: 10px 22px 22px; + --gap: 20px; + --ok-fill: #22c55e; + --spark-line-width: 2.5; + --spark-shape: line; + --spark-fill: fade; + --spark-dot: ring; + --spark-grid: none; + --spark-dot-size: 10; + --gauge-width: 9; + --gauge-cap: round; + --gauge-shape: ring; } } @@ -370,7 +554,7 @@ header h1 { line-height: 1; background: var(--card-bg); color: var(--text); - border: 1px solid var(--border); + border: 1px solid var(--card-border); border-radius: var(--radius-control); box-shadow: var(--shadow); transition: box-shadow 0.15s ease; @@ -451,7 +635,7 @@ main { .card { --card-accent: var(--accent); background: var(--card-bg); - border: 1px solid var(--border); + border: 1px solid var(--card-border); border-radius: var(--radius-card); box-shadow: var(--shadow); padding: var(--card-padding); @@ -790,7 +974,7 @@ dialog.modal[open] { padding: 0; background: var(--card-bg); color: var(--text); - border: 1px solid var(--border); + border: 1px solid var(--card-border); border-radius: var(--radius-card); width: min(640px, 100%); max-height: 85vh; @@ -1120,7 +1304,7 @@ dialog.modal::backdrop { font-size: 0.75rem; padding: 0.125rem 0.5rem; border-radius: 999px; - background: color-mix(in srgb, var(--warn) 20%, transparent); + background: color-mix(in srgb, var(--warn) var(--pill-tint), transparent); color: var(--warn-ink); } @@ -1140,12 +1324,12 @@ dialog.modal::backdrop { } .alert-badge.metric-warn { - background: color-mix(in srgb, var(--warn) 20%, transparent); + background: color-mix(in srgb, var(--warn) var(--pill-tint), transparent); color: var(--warn-ink); } .alert-badge.metric-crit { - background: color-mix(in srgb, var(--crit) 20%, transparent); + background: color-mix(in srgb, var(--crit) var(--pill-tint), transparent); color: var(--crit-ink); } @@ -1577,3 +1761,320 @@ footer { color: var(--text); text-decoration: underline; } + +/* Berry gauge: the ring canvas and the value box centred in it (the rest of + Berry's look follows in its own rules). */ + +:root[data-style="berry"] .gauge canvas { + height: 88px; +} + +:root[data-style="berry"] .gauge .gauge-value { + top: 0; + bottom: 0; + display: flex; + align-items: center; + justify-content: center; + font-size: clamp(12px, 21cqi, 18px); + font-weight: 750; + letter-spacing: -0.02em; +} + +/* Berry look: page, header, banner, cards, values, bars, Updates row, tiles, + network, badges and dialogs. Every selector is under Berry's scope. */ + +:root[data-style="berry"] body { + font-size: 14px; +} + +:root[data-style="berry"] header { + padding: 22px 28px 8px; +} + +:root[data-style="berry"] main { + padding: 12px 28px 22px; +} + +:root[data-style="berry"] footer { + padding: 0 28px 22px; + font-size: 12px; +} + +:root[data-style="berry"] footer a { + color: var(--accent); +} + +:root[data-style="berry"] header h1 { + font-size: 22px; + font-weight: 750; + letter-spacing: -0.02em; +} + +:root[data-style="berry"] .logo-tile { + width: 48px; + height: 48px; + border-radius: 50%; + background: var(--accent); +} + +:root[data-style="berry"] .logo-tile .icon { + width: 24px; + height: 24px; +} + +:root[data-style="berry"] .theme-toggle, +:root[data-style="berry"] .layout-toggle { + border-radius: 50%; +} + +:root[data-style="berry"] .alert-banner { + margin: 0 28px 20px; + border: 0; + font-weight: 650; +} + +:root[data-style="berry"] .alert-banner-icon { + width: 32px; + height: 32px; + border-radius: 50%; + display: inline-flex; + align-items: center; + justify-content: center; +} + +:root[data-style="berry"] .alert-banner-icon .icon { + width: 17px; + height: 17px; +} + +:root[data-style="berry"] .alert-banner.metric-warn .alert-banner-icon { + background: color-mix(in srgb, var(--warn) 22%, transparent); +} + +:root[data-style="berry"] .alert-banner.metric-crit .alert-banner-icon { + background: color-mix(in srgb, var(--crit) 22%, transparent); +} + +:root[data-style="berry"] .card h2 { + text-transform: none; + font-size: 15px; + font-weight: 650; + color: var(--text); + min-height: 48px; + letter-spacing: -0.01em; +} + +:root[data-style="berry"] .card-icon { + width: 32px; + height: 32px; + color: var(--card-accent); +} + +:root[data-style="berry"] .card-icon .icon { + width: 17px; + height: 17px; +} + +:root[data-style="berry"] .card-header-btn .chevron { + width: 18px; + height: 18px; +} + +:root[data-style="berry"] .kv-row { + font-size: 14px; + padding: 8px 0; +} + +:root[data-style="berry"] .metric-value { + font-size: 38px; + font-weight: 750; + letter-spacing: -0.035em; + line-height: 1; +} + +:root[data-style="berry"] .metric-unit { + font-size: 18px; + font-weight: 650; + margin-left: 4px; +} + +:root[data-style="berry"] .metric-unit::before { + content: none; +} + +:root[data-style="berry"] .metric-sub { + font-size: 13px; + margin-top: 6px; +} + +:root[data-style="berry"] .bar-track { + height: 10px; +} + +:root[data-style="berry"] .bar-label { + font-size: 14px; + margin-bottom: 8px; +} + +:root[data-style="berry"] .bar-pct { + font-weight: 650; +} + +:root[data-style="berry"] .bar-row { + margin-bottom: 16px; +} + +:root[data-style="berry"] .bar-row:last-child { + margin-bottom: 0; +} + +:root[data-style="berry"] .gauge .gauge-label { + font-size: 12px; + margin-top: 8px; +} + +:root[data-style="berry"] #card-updates { + display: flex; + flex-wrap: wrap; + align-items: center; + column-gap: 12px; +} + +:root[data-style="berry"] #card-updates h2 { + flex: 0 0 100%; +} + +:root[data-style="berry"] #updates-count { + flex: 1 1 auto; +} + +:root[data-style="berry"] #updates-show { + order: 1; +} + +:root[data-style="berry"] #updates-checked, +:root[data-style="berry"] #updates-stale, +:root[data-style="berry"] #pihole-section { + order: 2; +} + +:root[data-style="berry"] #updates-checked, +:root[data-style="berry"] #pihole-section { + flex: 0 0 100%; +} + +:root[data-style="berry"] .updates-button { + background: var(--accent); + color: var(--on-accent); + border: 0; + font-size: 14px; + font-weight: 650; + padding: 0 20px; + margin-top: 0; + min-height: 44px; +} + +:root[data-style="berry"] .updates-button:hover { + filter: brightness(1.08); +} + +:root[data-style="berry"] .pihole-section { + background: var(--bg); + border-radius: 14px; + padding: 12px 14px; + margin-top: 16px; + border-top: 0; +} + +:root[data-style="berry"] #pihole-status { + font-size: 12px; + font-weight: 650; + padding: 2px 10px; + border-radius: 999px; +} + +:root[data-style="berry"] #pihole-status.metric-ok { + background: color-mix(in srgb, var(--ok) var(--pill-tint), transparent); +} + +:root[data-style="berry"] #pihole-status.metric-warn { + background: color-mix(in srgb, var(--warn) var(--pill-tint), transparent); +} + +:root[data-style="berry"] .net-row { + background: var(--bg); + border-radius: 14px; + padding: 11px 14px; + margin-bottom: 8px; + border-bottom: 0; +} + +:root[data-style="berry"] .net-row:last-child { + margin-bottom: 0; +} + +:root[data-style="berry"] .net-name { + font-weight: 650; +} + +:root[data-style="berry"] .net-rate:first-child .net-icon { + color: var(--accent); +} + +:root[data-style="berry"] .net-rate:last-child .net-icon { + color: var(--muted); +} + +:root[data-style="berry"] .net-icon { + stroke-width: 2.5; +} + +:root[data-style="berry"] .alert-badge, +:root[data-style="berry"] .stale-badge { + font-size: 12px; + font-weight: 650; + padding: 2px 10px; +} + +:root[data-style="berry"] .alert-badge { + text-transform: none; + letter-spacing: 0; +} + +:root[data-style="berry"] .alert-badge::first-letter { + text-transform: uppercase; +} + +:root[data-style="berry"] .range-button.active, +:root[data-style="berry"] .apikey-submit { + font-weight: 650; +} + +:root[data-style="berry"] .range-button.active { + background: var(--accent); + color: var(--on-accent); +} + +:root[data-style="berry"] .apikey-submit { + background: var(--accent); + color: var(--on-accent); +} + +:root[data-style="berry"] .range-button, +:root[data-style="berry"] .layout-move, +:root[data-style="berry"] .layout-reset, +:root[data-style="berry"] .modal-close { + background: var(--bg); + border-color: transparent; + border-radius: 999px; +} + +:root[data-style="berry"] .range-button:hover, +:root[data-style="berry"] .layout-move:hover:not(:disabled), +:root[data-style="berry"] .layout-reset:hover { + border-color: var(--accent); +} + +:root[data-style="berry"] .apikey-input { + border-radius: 999px; +} diff --git a/internal/web/assets/theme-init.js b/internal/web/assets/theme-init.js index 428bd3b..96d0a8f 100644 --- a/internal/web/assets/theme-init.js +++ b/internal/web/assets/theme-init.js @@ -3,6 +3,7 @@ const PIMONITOR_THEMES = Object.freeze([ Object.freeze({ id: 'clear', name: 'Clear' }), Object.freeze({ id: 'console', name: 'Console' }), + Object.freeze({ id: 'berry', name: 'Berry' }), ]); // Clear's light values of the custom properties the canvas renderers read. @@ -23,6 +24,8 @@ const DRAWING_FALLBACKS = Object.freeze({ '--spark-grid': 'none', '--gauge-width': '9', '--gauge-cap': 'round', + '--gauge-shape': 'half', + '--spark-dot-size': '8', }); // themeValue returns the trimmed computed value of the custom property `name`. diff --git a/internal/web/chart_test.go b/internal/web/chart_test.go index c17fa0a..17a299a 100644 --- a/internal/web/chart_test.go +++ b/internal/web/chart_test.go @@ -8,9 +8,10 @@ import ( ) // sparkDotReach is the distance from the newest point's centre to the edge of -// its ring: radius 4 plus a 3 px ring (plan.md, Approach, and Challenge notes, -// minor 1). The dot must stay inside the canvas, so the plot is inset by at -// least this much. +// its ring for Clear's 8 px dot: radius 4 plus a 3 px ring (plan.md, Approach, +// and Challenge notes, minor 1). The dot must stay inside the canvas, so the +// plot is inset by at least this much in Clear and Console (Berry's 10 px dot +// reaches 8, TestChartJS_BerrySparkline_AC8). const sparkDotReach = 4 + 3 // TestChartJS_Sparkline_AC7 guards the sparkline style of feature 217 as the @@ -35,7 +36,7 @@ func TestChartJS_Sparkline_AC7(t *testing.T) { }) t.Run("AC7 dot stays inside the canvas", func(t *testing.T) { - checkSparklinePad(t, body) + checkSparklinePad(t, js, body) }) } @@ -118,19 +119,46 @@ func checkSparklineGuard(t *testing.T, body string) { } } -// checkSparklinePad checks that the plot inset keeps the dot inside the canvas. -func checkSparklinePad(t *testing.T, body string) { +// sparkDotRing is the file constant SPARK_DOT_RING of chart.js: the 3 px ring around the end dot. +const sparkDotRing = 3 + +var ( + sparkPadRE = regexp.MustCompile(`const pad\s*=\s*style\.dotSize\s*/\s*2\s*\+\s*SPARK_DOT_RING\s*;`) + sparkRingRE = regexp.MustCompile(`(?m)^const SPARK_DOT_RING\s*=\s*(\d+)\s*;`) + sparkLiteralRadiusRE = regexp.MustCompile(`\barc\(\s*last\.x\s*,\s*last\.y\s*,\s*\d`) + sparkDotSizeRE = regexp.MustCompile(`themeNumber\('--spark-dot-size',\s*2,\s*16\)`) +) + +// sparkPad mirrors the inset of drawSparkline for a dot of dotSize px: the dot's radius plus the ring. +func sparkPad(dotSize float64) float64 { return dotSize/2 + sparkDotRing } + +// checkSparklinePad checks that the plot inset is derived from the dot size and +// keeps the dot and its ring inside the canvas: at least 7 px for Clear's 8 px +// dot (radius 4 plus ring 3, as before the dot size was a token) and the dot's +// radius plus the ring for every theme's size (8 px in Clear and Console, 10 px +// in Berry), with the guard of fewer than two points still first. +func checkSparklinePad(t *testing.T, js, body string) { t.Helper() - m := regexp.MustCompile(`const pad\s*=\s*(\d+(?:\.\d+)?)\s*;`).FindStringSubmatch(body) - if m == nil { - t.Fatal("chart.js drawSparkline: expected const pad = ;") + if !sparkPadRE.MatchString(body) { + t.Fatal("chart.js drawSparkline: expected const pad = style.dotSize / 2 + SPARK_DOT_RING; (the inset derives from the dot size)") + } + m := sparkLiteralRadiusRE.FindString(jsFunctionBody(js, "function drawSparkDot(")) + if m != "" { + t.Errorf("chart.js drawSparkDot: %q has a literal radius, want both radii from style.dotSize", m) + } + ring := sparkRingRE.FindStringSubmatch(js) + if ring == nil || ring[1] != strconv.Itoa(sparkDotRing) { + t.Fatalf("chart.js: SPARK_DOT_RING = %v, want a file constant `const SPARK_DOT_RING = %d;`", ring, sparkDotRing) } - pad, err := strconv.ParseFloat(m[1], 64) + if style, pad, guard := strings.Index(body, "const style = sparkStyle();"), strings.Index(body, "const pad"), strings.Index(body, "points.length < 2"); guard < 0 || style < guard || pad < style { + t.Errorf("chart.js drawSparkline: guard at %d, sparkStyle() at %d, pad at %d, want that order (the style is read before the inset, after the guard)", guard, style, pad) + } + fallbackDot, err := strconv.ParseFloat(parseDrawingFallbacks(readAsset(t, "theme-init.js"))["--spark-dot-size"], 64) if err != nil { - t.Fatalf("parse pad %q: %v", m[1], err) + t.Fatalf("theme-init.js: DRAWING_FALLBACKS['--spark-dot-size'] is not a number: %v", err) } - if pad < sparkDotReach { - t.Errorf("chart.js drawSparkline: pad = %v, want at least %d (dot radius 4 plus ring 3), so the dot centre is never closer to an edge than its reach", pad, sparkDotReach) + if got := sparkPad(fallbackDot); got < sparkDotReach { + t.Errorf("chart.js drawSparkline: pad = %v for Clear's %v px dot, want at least %d (dot radius 4 plus ring 3)", got, fallbackDot, sparkDotReach) } checkAssetParts(t, []assetCheck{ {"drawSparkline x range uses pad", body, []string{"cssWidth - pad * 2", "cssHeight - pad * 2", "cssHeight - pad -"}}, @@ -255,3 +283,99 @@ func checkSparkGrid(t *testing.T, grid string) { } } } + +// TestChartJS_BerrySparkline_AC8 guards the Berry sparkline and detail chart +// (feature 220, AC8): the drawing properties Berry declares in all three +// blocks (a 2.5 px accent line, a fade fill at 26 % light and 30 % dark, a 10 px +// ring dot), the dot size read through themeNumber within 2 to 16 with Clear's +// 8 as fallback, and a plot inset derived from the dot size and its 3 px ring, +// so the 10 px dot with its ring is never clipped (8 px for Berry, 7 px for +// Clear and Console as before), while nothing is drawn below two points. +func TestChartJS_BerrySparkline_AC8(t *testing.T) { + js := readAsset(t, "chart.js") + rules := parseCSSRules(readAsset(t, "style.css")) + + t.Run("AC8 Berry declares the line, fill, dot and dot size in every block", func(t *testing.T) { + checkBerrySparkTokens(t, rules) + }) + t.Run("AC8 sparkStyle reads the dot size within 2 to 16 and the style reaches the dot", func(t *testing.T) { + style := jsFunctionBody(js, "function sparkStyle(") + if !sparkDotSizeRE.MatchString(style) || !strings.Contains(style, "dotSize:") { + t.Errorf("chart.js sparkStyle = %q, want dotSize: themeNumber('--spark-dot-size', 2, 16)", style) + } + requireContains(t, "drawSparkline", jsFunctionBody(js, "function drawSparkline("), "drawSparkDot(ctx, xy[xy.length - 1], color, style)") + }) + t.Run("AC8 the dot is drawn at the dot size and its ring 3 px wider in the card colour", func(t *testing.T) { + checkSparkDotDrawing(t, jsFunctionBody(js, "function drawSparkDot(")) + }) + for _, c := range []struct { + theme, selector string + dot, pad float64 + }{ + {"Clear", selLight, 8, 7}, + {"Console", `:root[data-style="console"]`, 8, 7}, + {"Berry", `:root[data-style="berry"]`, 10, 8}, + } { + t.Run("AC8 "+c.theme+" inset keeps its dot and ring inside the canvas", func(t *testing.T) { + checkThemeSparkInset(t, rules, c.theme, c.selector, c.dot, c.pad) + }) + } + t.Run("AC8 the dot size is bounded 2 to 16 and Clear's value is the fallback", func(t *testing.T) { + bounds, ok := numberReads(t)["--spark-dot-size"] + if !ok || bounds != [2]float64{2, 16} { + t.Errorf("chart.js: themeNumber('--spark-dot-size') bounds = %v (read: %v), want [2 16]", bounds, ok) + } + if got := parseDrawingFallbacks(readAsset(t, "theme-init.js"))["--spark-dot-size"]; got != "8" { + t.Errorf("DRAWING_FALLBACKS['--spark-dot-size'] = %q, want Clear's 8", got) + } + }) + t.Run("AC8 fewer than two points draw nothing and the detail chart uses the same style", func(t *testing.T) { + checkSparklineGuard(t, jsFunctionBody(js, "function drawSparkline(")) + requireContains(t, "renderDetailChart", jsFunctionBody(readAsset(t, "app.js"), "function renderDetailChart("), "drawSparkline(") + }) +} + +// checkBerrySparkTokens checks Berry's sparkline tokens, the accent and the card colour in its three blocks. +func checkBerrySparkTokens(t *testing.T, rules []cssRule) { + t.Helper() + light, dark, media := themeSelectors("berry", false) + for sel, alpha := range map[string]string{light: "0.26", dark: "0.30", media: "0.30"} { + block, _ := blockTokens(rules, sel) + want := map[string]string{ + "--spark-line-width": "2.5", "--spark-shape": "line", "--spark-fill": "fade", "--spark-dot": "ring", + "--spark-grid": "none", "--spark-dot-size": "10", "--spark-fill-alpha": alpha, + } + for _, d := range tokenDiffs(sel, block, want) { + t.Error(d) + } + if block["--accent"] == "" || block["--card-bg"] == "" { + t.Errorf("%s: --accent = %q, --card-bg = %q, want both declared (the line and the dot ring are drawn in them)", sel, block["--accent"], block["--card-bg"]) + } + } +} + +// checkSparkDotDrawing checks that drawSparkDot sizes the ring from the dot size and the ring constant and draws it before the dot. +func checkSparkDotDrawing(t *testing.T, dot string) { + t.Helper() + requireContains(t, "drawSparkDot", dot, "style.dotSize", "SPARK_DOT_RING", "style.cardBg") + ring, fillRing, fillCore := strings.Index(dot, "SPARK_DOT_RING"), strings.Index(dot, "style.cardBg"), strings.Index(dot, "= color") + if fillRing < 0 || fillCore < fillRing || ring > fillRing { + t.Errorf("chart.js drawSparkDot: ring radius at %d, ring fill style.cardBg at %d, dot fill `= color` at %d, want the ring sized and drawn first in the card colour, then the dot in the line colour", ring, fillRing, fillCore) + } + if n := strings.Count(dot, "arc("); n != 2 { + t.Errorf("chart.js drawSparkDot: %d arc( calls, want 2 (ring and dot)", n) + } +} + +// checkThemeSparkInset checks a theme's dot size token and the inset derived from it. +func checkThemeSparkInset(t *testing.T, rules []cssRule, theme, selector string, dot, pad float64) { + t.Helper() + block, _ := blockTokens(rules, selector) + size, err := strconv.ParseFloat(block["--spark-dot-size"], 64) + if err != nil || size != dot { + t.Fatalf("%s --spark-dot-size = %q, want %v", selector, block["--spark-dot-size"], dot) + } + if got := sparkPad(size); got != pad { + t.Errorf("%s: inset = %v, want %v (dot radius %v plus the %d px ring)", theme, got, pad, size/2, sparkDotRing) + } +} diff --git a/internal/web/gauge_test.go b/internal/web/gauge_test.go index 50e9b44..370eae1 100644 --- a/internal/web/gauge_test.go +++ b/internal/web/gauge_test.go @@ -239,9 +239,9 @@ func TestGaugeJS_OkFill_AC3(t *testing.T) { } }) - t.Run("AC3 --ok-fill is --text in Console and --ok in Clear, in every block", func(t *testing.T) { + t.Run("AC3 --ok-fill is --text in Console and --ok in Clear and Berry, in every block", func(t *testing.T) { rules := parseCSSRules(readAsset(t, "style.css")) - for _, id := range []string{"clear", "console"} { + for _, id := range []string{"clear", "console", "berry"} { light, dark, media := themeSelectors(id, id == "clear") for _, sel := range []string{light, dark, media} { block, _ := blockTokens(rules, sel) @@ -333,3 +333,271 @@ func TestGaugeJS_ConsoleArc_AC8(t *testing.T) { } }) } + +// ringValueEm is the em width of NN.NN at weight 750 and letter-spacing -0.02em +// in the system stack (plan.md fact 11: 2.755 em measured in Inter, 3.0 used). +const ringValueEm = 3.0 + +// ringWidths are the gauge widths the ring checks run for: the narrowest gauge +// (about 68 px at 320 px viewport, plan.md fact 12) with room below it, the +// width where the ring reaches its 88 px, and wider columns. +var ringWidths = []float64{60, 68, 72, 88, 100, 150, 250, 400} + +// ringOuter mirrors drawGaugeRing for a canvas of w by h px and a stroke of +// lineWidth: the radius is Math.max(1, Math.min(w, h) / 2 - lineWidth / 2), so +// the outer edge, round caps included, is that radius plus half the stroke. +func ringOuter(w, h, lineWidth float64) (radius, outer float64) { + radius = math.Max(1, math.Min(w, h)/2-lineWidth/2) + return radius, radius + lineWidth/2 +} + +// ringProblems checks that a ring in a w by h canvas lies inside it and that a +// value of font px (line-height lineHeight, valueEm wide per em), centred in a +// box that spans the canvas height, fits the ring's inner chord at the top edge +// of that box (the tightest point, as for the half circle). +func ringProblems(w, h, lineWidth, font, lineHeight, valueEm float64) []string { + var out []string + _, outer := ringOuter(w, h, lineWidth) + cx, cy := w/2, h/2 + if cx-outer < 0 || cx+outer > w || cy-outer < 0 || cy+outer > h { + out = append(out, fmt.Sprintf("ring spans x %.2f..%.2f, y %.2f..%.2f, want inside 0..%.0f by 0..%.0f", cx-outer, cx+outer, cy-outer, cy+outer, w, h)) + } + inner := outer - lineWidth + dy := font * lineHeight / 2 // the top edge of the centred box above the ring's centre + if dy >= inner { + return append(out, fmt.Sprintf("value box top at %.2f px above the centre is outside the inner circle (inner radius %.2f)", dy, inner)) + } + if chord := 2 * math.Sqrt(inner*inner-dy*dy); valueEm*font > chord { + out = append(out, fmt.Sprintf("value width %.2f px (font %.2f px) exceeds the inner chord %.2f px at the top of the value box", valueEm*font, font, chord)) + } + return out +} + +// berryGaugeFont evaluates Berry's clamp(px, cqi, px) font size +// for a gauge of width w (1cqi is 1 % of the .gauge width). +func berryGaugeFont(t *testing.T, rules []cssRule, w float64) float64 { + t.Helper() + got, _ := scopedValue(rules, berryScope, "font-size", []string{".gauge .gauge-value"}) + m := regexp.MustCompile(`^clamp\((\d+(?:\.\d+)?)px,\s*(\d+(?:\.\d+)?)cqi,\s*(\d+(?:\.\d+)?)px\)$`).FindStringSubmatch(got) + if m == nil { + t.Fatalf("style.css: Berry .gauge .gauge-value font-size = %q, want clamp(px, cqi, px)", got) + } + lo, _ := strconv.ParseFloat(m[1], 64) + cqi, _ := strconv.ParseFloat(m[2], 64) + hi, _ := strconv.ParseFloat(m[3], 64) + return math.Min(hi, math.Max(lo, cqi*w/100)) +} + +// berryGaugePx returns the px value Berry gives prop of sel, or fails. +func berryGaugePx(t *testing.T, rules []cssRule, sel, prop string) float64 { + t.Helper() + got, ok := scopedValue(rules, berryScope, prop, []string{sel}) + if !ok { + t.Fatalf("style.css: %s { %s } is not declared for Berry", berryScope+" "+sel, prop) + } + n, err := strconv.ParseFloat(strings.TrimSuffix(strings.TrimSpace(got), "px"), 64) + if err != nil { + t.Fatalf("style.css: Berry %s { %s } = %q, want a px number", sel, prop, got) + } + return n +} + +// TestGaugeJS_Ring_AC7 guards Berry's load gauge (issue 220 section 10, spec +// AC7): drawGaugeRing draws a full circle track and a clockwise arc from 12 +// o'clock to value / max of a full turn with the width and caps of the theme, +// nothing at 0 and a closed ring at the maximum; Berry's rules give the canvas +// 88 px and centre the value in it; the ring and the value fit inside the +// canvas from the narrowest gauge on, and the ring is 88 px from 88 px on. +func TestGaugeJS_Ring_AC7(t *testing.T) { + ring := jsFunctionBody(readAsset(t, "gauge.js"), "function drawGaugeRing(") + rules := parseCSSRules(readAsset(t, "style.css")) + + t.Run("AC7 the ring is a centred circle sized by the smaller canvas side and its stroke", func(t *testing.T) { + checkRingForm(t, ring) + }) + t.Run("AC7 the track is a full circle and the arc runs clockwise from 12 o'clock to the fraction", func(t *testing.T) { + checkRingArcs(t, ring) + }) + t.Run("AC7 a fraction of 0 returns after the track, before the value arc, so round caps leave no dot", func(t *testing.T) { + checkRingZeroGuard(t, ring) + }) + t.Run("AC7 Berry gives the canvas 88 px and centres the value in a box spanning it", func(t *testing.T) { + checkBerryGaugeBox(t, rules) + }) + for _, w := range ringWidths { + t.Run("AC7 ring and value fit and the diameter is 88 px at most at "+strconv.FormatFloat(w, 'f', -1, 64)+" px", func(t *testing.T) { + checkRingFits(t, rules, w) + }) + } + t.Run("AC7 the geometry check reports a value wider than the chord", func(t *testing.T) { + if got := ringProblems(60, 88, 9, 30, 1, ringValueEm); len(got) == 0 { + t.Error("ringProblems(60 px gauge, 30 px font) = none, want the value reported as too wide") + } + if got := ringProblems(88, 88, 9, 18, 1, ringValueEm); len(got) != 0 { + t.Errorf("ringProblems(88 px gauge, 18 px font) = %v, want none", got) + } + }) +} + +// checkRingForm checks the centre, the radius and the ring fields of drawGaugeRing. +func checkRingForm(t *testing.T, ring string) { + t.Helper() + if strings.TrimSpace(ring) == "" { + t.Fatal("gauge.js: expected a function drawGaugeRing(ctx, ring, fraction)") + } + requireContains(t, "drawGaugeRing", ring, + "ring.width / 2", "ring.height / 2", + "Math.max(1, Math.min(ring.width, ring.height) / 2 - ring.lineWidth / 2)", + "ring.lineWidth", "ring.lineCap", "ring.trackColor", "ring.fillColor") +} + +// checkRingArcs checks the full-circle track and the clockwise value arc from 12 o'clock. +func checkRingArcs(t *testing.T, ring string) { + t.Helper() + requireContains(t, "drawGaugeRing", ring, "0, 2 * Math.PI", "-Math.PI / 2, -Math.PI / 2 + 2 * Math.PI * fraction") + if strings.Contains(ring, "true)") { + t.Error("gauge.js drawGaugeRing: unexpected anticlockwise arc, the value runs clockwise") + } + if n := strings.Count(ring, "ctx.arc("); n != 2 { + t.Errorf("gauge.js drawGaugeRing: %d ctx.arc( calls, want 2 (track and value arc)", n) + } +} + +// checkRingZeroGuard checks that the track is stroked, then a fraction of 0 returns, then the value arc is drawn. +func checkRingZeroGuard(t *testing.T, ring string) { + t.Helper() + guard := strings.Index(ring, "if (fraction <= 0) return;") + track, value := strings.Index(ring, "ctx.arc("), strings.LastIndex(ring, "ctx.arc(") + if guard < 0 || track < 0 || track > guard || guard > value { + t.Errorf("gauge.js drawGaugeRing: track arc at %d, guard `if (fraction <= 0) return;` at %d, value arc at %d, want that order", track, guard, value) + } + if stroke := strings.Index(ring, "ctx.stroke()"); stroke < 0 || stroke > guard { + t.Errorf("gauge.js drawGaugeRing: the track is stroked at %d, want it before the guard at %d", stroke, guard) + } +} + +// checkBerryGaugeBox checks Berry's canvas height and the value box that spans the dial and centres its text. +func checkBerryGaugeBox(t *testing.T, rules []cssRule) { + t.Helper() + checkWants(t, rules, berryScope, []cssWant{ + {[]string{".gauge canvas"}, "height", "88px"}, + {[]string{".gauge .gauge-value"}, "top", "0"}, + {[]string{".gauge .gauge-value"}, "bottom", "0"}, + {[]string{".gauge .gauge-value"}, "display", "flex"}, + {[]string{".gauge .gauge-value"}, "align-items", "center"}, + {[]string{".gauge .gauge-value"}, "justify-content", "center"}, + }, true) + for prop, want := range map[string]string{"position": "absolute", "left": "0", "right": "0"} { + if got, ok := effectiveValue(rules, berryScope, prop, []string{".gauge .gauge-value"}); !ok || normCSS(got) != want { + t.Errorf("style.css: effective .gauge .gauge-value { %s } for Berry = %q, want %q (the box spans the dial)", prop, got, want) + } + } +} + +// checkRingFits checks the ring and the centred value of a gauge of width w with Berry's values from the stylesheet. +func checkRingFits(t *testing.T, rules []cssRule, w float64) { + t.Helper() + h := berryGaugePx(t, rules, ".gauge canvas", "height") + block, _ := blockTokens(rules, berryScope) + lineWidth, err := strconv.ParseFloat(block["--gauge-width"], 64) + if err != nil { + t.Fatalf("style.css: Berry --gauge-width = %q, want a number", block["--gauge-width"]) + } + lineHeight, _ := effectiveValue(rules, berryScope, "line-height", []string{".gauge .gauge-value"}) + lh, err := strconv.ParseFloat(lineHeight, 64) + if err != nil { + t.Fatalf("style.css: Berry .gauge .gauge-value line-height = %q, want a number", lineHeight) + } + for _, p := range ringProblems(w, h, lineWidth, berryGaugeFont(t, rules, w), lh, ringValueEm) { + t.Errorf("gauge %.0f px: %s", w, p) + } + if _, outer := ringOuter(w, h, lineWidth); 2*outer != math.Min(w, 88) { + t.Errorf("gauge %.0f px: outer diameter %.2f, want %.0f (88 px, smaller only where the gauge is narrower)", w, 2*outer, math.Min(w, 88)) + } +} + +// TestGaugeJS_ShapePerDraw_AC10 guards that the shape of the load gauge is read +// at every draw (feature 220, AC10): a switch between Berry and another theme +// ends in repaintCanvases, which calls drawGauge again, so drawGauge reads +// --gauge-shape inside its body (no module-level cache), after clearing the +// canvas and before drawing, and the ring branch draws on the cleared canvas +// with the colours and the clamped fraction computed before it and returns. +func TestGaugeJS_ShapePerDraw_AC10(t *testing.T) { + js := readAsset(t, "gauge.js") + body := jsFunctionBody(js, "function drawGauge(") + + t.Run("AC10 the shape is read once, inside drawGauge, never at module level", func(t *testing.T) { + if n := strings.Count(js, "'--gauge-shape'"); n != 1 { + t.Errorf("gauge.js: %d mentions of '--gauge-shape', want exactly 1 (the read inside drawGauge)", n) + } + requireContains(t, "drawGauge", body, shapeRead) + }) + t.Run("AC10 the read comes after clearRect and before the first path or arc", func(t *testing.T) { + checkShapeReadOrder(t, body) + }) + t.Run("AC10 the colours and the clamped fraction are computed before the first draw", func(t *testing.T) { + checkComputedBeforeDraw(t, body) + }) + t.Run("AC10 the ring branch hands the context, the ring and the clamped fraction over and returns", func(t *testing.T) { + checkRingBranch(t, body) + }) + t.Run("AC10 the half circle keeps its two cap assignments and the canvas size reads", func(t *testing.T) { + requireContains(t, "drawGauge", body, "canvas.clientWidth", "canvas.clientHeight", "ctx.setTransform(dpr, 0, 0, dpr, 0, 0);") + if n := strings.Count(body, "ctx.lineCap = "); n != 2 { + t.Errorf("gauge.js drawGauge: %d assignments of ctx.lineCap, want 2 (the half circle's track and value arc)", n) + } + }) +} + +// shapeRead is the read of the gauge shape inside drawGauge. +const shapeRead = "themeKeyword('--gauge-shape', ['half', 'ring'])" + +// firstDrawIndex returns the index of the first ctx.beginPath( or ctx.arc( of body, or its length. +func firstDrawIndex(body string) int { + first := len(body) + for _, call := range []string{"ctx.beginPath(", "ctx.arc("} { + if i := strings.Index(body, call); i >= 0 && i < first { + first = i + } + } + return first +} + +// checkShapeReadOrder checks that the shape is read after clearRect and before the first path or arc. +func checkShapeReadOrder(t *testing.T, body string) { + t.Helper() + clearIdx, shape, first := strings.Index(body, "ctx.clearRect("), strings.Index(body, shapeRead), firstDrawIndex(body) + if clearIdx < 0 || shape < clearIdx || shape > first { + t.Errorf("gauge.js drawGauge: clearRect at %d, shape read at %d, first beginPath/arc at %d, want that order", clearIdx, shape, first) + } +} + +// checkComputedBeforeDraw checks that the track and fill colours and the clamped fraction precede the first draw. +func checkComputedBeforeDraw(t *testing.T, body string) { + t.Helper() + first := firstDrawIndex(body) + for _, decl := range []string{"const trackColor = themeColor('--track');", "const fillColor = themeColor(gaugeColorVar(colorClass));", "const clamped = Math.max(0, Math.min(value / max, 1));"} { + if i := strings.Index(body, decl); i < 0 || i > first { + t.Errorf("gauge.js drawGauge: %q at %d, want it before the first draw at %d", decl, i, first) + } + } +} + +// ringBranchRE matches the ring branch of drawGauge: the call and the return. +var ringBranchRE = regexp.MustCompile(`(?s)if \(shape === 'ring'\) \{\s*drawGaugeRing\(ctx, [^;]*, clamped\);\s*return;\s*\}`) + +// checkRingBranch checks the call of drawGaugeRing with the context, the ring and the clamped fraction, the return and the fields of the ring. +func checkRingBranch(t *testing.T, body string) { + t.Helper() + if !ringBranchRE.MatchString(body) { + t.Fatal("gauge.js drawGauge: expected `if (shape === 'ring') { drawGaugeRing(ctx, , clamped); return; }`") + } + for _, field := range []string{"width", "height", "lineWidth", "lineCap", "trackColor", "fillColor"} { + if !regexp.MustCompile(`\b` + field + `\b`).MatchString(body) { + t.Errorf("gauge.js drawGauge: the ring object has no %s, want width, height, lineWidth, lineCap, trackColor and fillColor", field) + } + } + if shape, clearIdx := strings.Index(body, "if (shape === 'ring')"), strings.Index(body, "ctx.clearRect("); shape < clearIdx { + t.Errorf("gauge.js drawGauge: ring branch at %d before clearRect at %d, want the ring drawn on a cleared canvas", shape, clearIdx) + } +} diff --git a/internal/web/look_test.go b/internal/web/look_test.go index 3ad5d56..1087986 100644 --- a/internal/web/look_test.go +++ b/internal/web/look_test.go @@ -438,8 +438,11 @@ func TestStyleCSS_HeaderButtonFocusRing_AC5(t *testing.T) { } // consoleScope is the prefix of every selector of a Console rule (decision -// 0038: Console's look is scoped rules plus tokens). -const consoleScope = `:root[data-style="console"]` +// 0038: Console's look is scoped rules plus tokens); berryScope is Berry's. +const ( + consoleScope = `:root[data-style="console"]` + berryScope = `:root[data-style="berry"]` +) // cssWant is one expectation: the declaration prop (alternatives separated by // "|") of any of the selectors sels (without the scope) has the value want. @@ -461,19 +464,19 @@ func declValue(rules []cssRule, selector, props string) (string, bool) { return "", false } -// consoleValue returns the value a Console-scoped rule gives prop for one of sels. -func consoleValue(rules []cssRule, props string, sels []string) (string, bool) { +// scopedValue returns the value a rule under scope gives prop for one of sels. +func scopedValue(rules []cssRule, scope, props string, sels []string) (string, bool) { for _, sel := range sels { - if v, ok := declValue(rules, consoleScope+" "+sel, props); ok { + if v, ok := declValue(rules, scope+" "+sel, props); ok { return v, true } } return "", false } -// effectiveValue returns the Console-scoped value, else the unscoped one. -func effectiveValue(rules []cssRule, props string, sels []string) (string, bool) { - if v, ok := consoleValue(rules, props, sels); ok { +// effectiveValue returns the value under scope, else the unscoped one. +func effectiveValue(rules []cssRule, scope, props string, sels []string) (string, bool) { + if v, ok := scopedValue(rules, scope, props, sels); ok { return v, true } for _, sel := range sels { @@ -492,33 +495,32 @@ func wantMatches(got, want string) bool { return normCSS(got) == normCSS(want) } -// checkWants checks each want against the Console-scoped value (scopedOnly) or the effective value. -func checkWants(t *testing.T, rules []cssRule, wants []cssWant, scopedOnly bool) { +// checkWants checks each want against the value under scope (scopedOnly) or the effective value. +func checkWants(t *testing.T, rules []cssRule, scope string, wants []cssWant, scopedOnly bool) { t.Helper() for _, w := range wants { - get := effectiveValue + got, ok := effectiveValue(rules, scope, w.prop, w.sels) if scopedOnly { - get = consoleValue + got, ok = scopedValue(rules, scope, w.prop, w.sels) } - got, ok := get(rules, w.prop, w.sels) switch { case !ok: - t.Errorf("style.css: %s { %s } is not declared for Console, want %q", consoleScope+" "+strings.Join(w.sels, " | "), w.prop, w.want) + t.Errorf("style.css: %s { %s } is not declared under the scope, want %q", scope+" "+strings.Join(w.sels, " | "), w.prop, w.want) case !wantMatches(got, w.want): - t.Errorf("style.css: %s { %s } = %q, want %q", consoleScope+" "+strings.Join(w.sels, " | "), w.prop, got, w.want) + t.Errorf("style.css: %s { %s } = %q, want %q", scope+" "+strings.Join(w.sels, " | "), w.prop, got, w.want) } } } -// consoleScoped returns the non-palette rules that have a selector under the Console scope. -func consoleScoped(rules []cssRule) []cssRule { +// scopedRules returns the non-palette rules that have a selector under scope. +func scopedRules(rules []cssRule, scope string) []cssRule { var out []cssRule for _, r := range rules { if isPaletteRule(r) { continue } for _, s := range r.selectors { - if strings.HasPrefix(s, consoleScope) { + if strings.HasPrefix(s, scope) { out = append(out, r) break } @@ -527,9 +529,9 @@ func consoleScoped(rules []cssRule) []cssRule { return out } -// hasConsoleSelector reports whether a Console rule has a selector holding every one of parts. -func hasConsoleSelector(rules []cssRule, parts ...string) bool { - for _, r := range consoleScoped(rules) { +// hasScopedSelector reports whether a rule under scope has a selector holding every one of parts. +func hasScopedSelector(rules []cssRule, scope string, parts ...string) bool { + for _, r := range scopedRules(rules, scope) { for _, s := range r.selectors { if containsAll(s, parts) { return true @@ -576,7 +578,7 @@ func TestStyleCSS_ConsoleMonospace_AC4(t *testing.T) { // monoRules returns the Console rules that declare a font-family. func monoRules(rules []cssRule) []cssRule { var out []cssRule - for _, r := range consoleScoped(rules) { + for _, r := range scopedRules(rules, consoleScope) { for _, d := range r.decls { if d.prop == "font-family" { out = append(out, r) @@ -661,7 +663,7 @@ func TestStyleCSS_ConsoleCards_AC5(t *testing.T) { } }) t.Run("AC5 the heading is a strip with a bottom border", func(t *testing.T) { - checkWants(t, rules, []cssWant{ + checkWants(t, rules, consoleScope, []cssWant{ {[]string{".card h2"}, "min-height", "44px"}, {[]string{".card h2"}, "margin", "0 -14px 12px"}, {[]string{".card h2"}, "padding", "0 14px"}, @@ -674,13 +676,13 @@ func TestStyleCSS_ConsoleCards_AC5(t *testing.T) { }, true) }) t.Run("AC5 in a clickable card the whole strip is the button", func(t *testing.T) { - checkWants(t, rules, []cssWant{ + checkWants(t, rules, consoleScope, []cssWant{ {[]string{".card-clickable h2", ".card-clickable > h2"}, "padding", "re:^0$|^0(px)?0(px)?$"}, {[]string{".card-clickable .card-header-btn", ".card-header-btn"}, "padding", "0 14px"}, }, true) }) t.Run("AC5 icons are muted, chipless and 14 px, the chevron too", func(t *testing.T) { - checkWants(t, rules, []cssWant{ + checkWants(t, rules, consoleScope, []cssWant{ {[]string{".card-icon"}, "color", "var(--muted)"}, {[]string{".card-icon"}, "background", "re:^(none|transparent)$"}, {[]string{".card-icon .icon", ".card-icon"}, "width", "14px"}, @@ -690,7 +692,7 @@ func TestStyleCSS_ConsoleCards_AC5(t *testing.T) { }) t.Run("AC5 the System and Uptime cards have their own body padding", func(t *testing.T) { for _, id := range []string{"#card-system", "#card-uptime"} { - if !hasConsoleSelector(rules, id) { + if !hasScopedSelector(rules, consoleScope, id) { t.Errorf("style.css: no Console rule for %s", id) } } @@ -708,7 +710,7 @@ func TestStyleCSS_ConsoleSegmentedBars_AC6(t *testing.T) { } t.Run("AC6 track and fill are 12 px high and square", func(t *testing.T) { - checkWants(t, rules, []cssWant{ + checkWants(t, rules, consoleScope, []cssWant{ {[]string{".bar-track"}, "height", "12px"}, {[]string{".bar-fill"}, "height", "re:^(12px|100%)$"}, {[]string{".bar-track"}, "border-radius", "0"}, @@ -716,7 +718,7 @@ func TestStyleCSS_ConsoleSegmentedBars_AC6(t *testing.T) { }, true) }) t.Run("AC6 each bar is a gradient of 6 px segments and 2 px gaps in its colour", func(t *testing.T) { - checkWants(t, rules, []cssWant{ + checkWants(t, rules, consoleScope, []cssWant{ {[]string{".bar-track"}, "background", seg("var(--track)")}, {[]string{".bar-fill"}, "background", seg("var(--ok-fill)")}, {[]string{".bar-fill.metric-warn"}, "background", seg("var(--warn)")}, @@ -726,14 +728,14 @@ func TestStyleCSS_ConsoleSegmentedBars_AC6(t *testing.T) { t.Run("AC6 the patterns share the track's left edge", func(t *testing.T) { for _, sel := range []string{".bar-track", ".bar-fill"} { for _, prop := range []string{"padding", "border", "margin", "background-position", "background-size", "background-origin"} { - if v, ok := consoleValue(rules, prop, []string{sel}); ok && !wantMatches(v, "re:^(0|none|0px)$") { + if v, ok := scopedValue(rules, consoleScope, prop, []string{sel}); ok && !wantMatches(v, "re:^(0|none|0px)$") { t.Errorf("style.css: Console %s { %s: %s } would shift a pattern against the other", sel, prop, v) } } } }) t.Run("AC6 bar rows are 12 px apart and labels 12 px", func(t *testing.T) { - checkWants(t, rules, []cssWant{ + checkWants(t, rules, consoleScope, []cssWant{ {[]string{".bar-row"}, "margin-bottom", "12px"}, {[]string{".bar-label"}, "font-size", "12px"}, }, true) @@ -766,7 +768,7 @@ func TestAppJS_MetricValueUnit_AC9(t *testing.T) { } }) t.Run("AC9 Console sets the unit smaller and muted, apart by 4 px and no space", func(t *testing.T) { - checkWants(t, rules, []cssWant{ + checkWants(t, rules, consoleScope, []cssWant{ {[]string{".metric-unit"}, "font-size", "15px"}, {[]string{".metric-unit"}, "font-weight", "500"}, {[]string{".metric-unit"}, "color", "var(--muted)"}, @@ -877,28 +879,379 @@ func TestStyleCSS_ConsoleChrome_AC15(t *testing.T) { rules := parseCSSRules(readAsset(t, "style.css")) t.Run("AC15 the chrome takes the values of sections 4 to 14", func(t *testing.T) { - checkWants(t, rules, consoleChromeWants, false) + checkWants(t, rules, consoleScope, consoleChromeWants, false) }) t.Run("AC15 badges and the banner carry a square dot", func(t *testing.T) { for _, parts := range [][]string{{".alert-badge", "::before"}, {".stale-badge", "::before"}} { - if !hasConsoleSelector(rules, parts...) { + if !hasScopedSelector(rules, consoleScope, parts...) { t.Errorf("style.css: no Console rule for a selector holding %v", parts) } } }) t.Run("AC15 dashed dividers do not return on the last rows", func(t *testing.T) { - checkWants(t, rules, consoleCascadeWants, true) + checkWants(t, rules, consoleScope, consoleCascadeWants, true) }) t.Run("AC15 the checker reports a missing and a wrong declaration", func(t *testing.T) { fixture := parseCSSRules(consoleScope + " .a { color: red; }") - if _, ok := consoleValue(fixture, "color", []string{".a"}); !ok { - t.Error("consoleValue(fixture): want the declared value") + if _, ok := scopedValue(fixture, consoleScope, "color", []string{".a"}); !ok { + t.Error("scopedValue(fixture): want the declared value") } - if _, ok := consoleValue(fixture, "margin", []string{".a"}); ok { - t.Error("consoleValue(fixture): want no value for an undeclared property") + if _, ok := scopedValue(fixture, consoleScope, "margin", []string{".a"}); ok { + t.Error("scopedValue(fixture): want no value for an undeclared property") } if wantMatches("2px", "3px") || !wantMatches(" 2PX ", "2px") || !wantMatches("dashed 1px", "re:dashed") { t.Error("wantMatches: want normalized comparison and regexp wants") } }) } + +// flexShrinkZero reports whether decls forbid shrinking: flex-shrink 0 or a +// flex shorthand whose second value is 0. +func flexShrinkZero(decls map[string]string) bool { + if v, ok := decls["flex-shrink"]; ok && strings.TrimSpace(v) == "0" { + return true + } + if f := strings.Fields(decls["flex"]); len(f) >= 2 && f[1] == "0" { + return true + } + return false +} + +// shrinkProblems names the rules of rules that give selector flex-shrink 0. +func shrinkProblems(rules []cssRule, selector string) []string { + var out []string + for _, r := range rules { + if r.has(selector) && flexShrinkZero(declsFor([]cssRule{r}, selector)) { + out = append(out, strings.Join(r.selectors, ", ")) + } + } + return out +} + +// TestStyleCSS_BerryCards_AC5 guards Berry's cards: a 22 px radius, no border +// and a soft shadow in light, a 1 px border and no shadow in dark, both drawn by +// the unscoped .card through --card-border and --shadow. +func TestStyleCSS_BerryCards_AC5(t *testing.T) { + rules := parseCSSRules(readAsset(t, "style.css")) + light, dark, media := themeSelectors("berry", false) + + t.Run("AC5 the radius is 22px in all three blocks", func(t *testing.T) { + checkBerryRadius(t, rules, []string{light, dark, media}) + }) + t.Run("AC5 light has a transparent border and a shadow", func(t *testing.T) { + checkBerryLightCard(t, rules, light) + }) + t.Run("AC5 dark has a #2c2832 border and no shadow", func(t *testing.T) { + checkBerryDarkCard(t, rules, []string{dark, media}) + }) + t.Run("AC5 the unscoped card draws the border and the shadow tokens", func(t *testing.T) { + checkUnscopedCard(t, rules) + }) +} + +func checkBerryRadius(t *testing.T, rules []cssRule, selectors []string) { + t.Helper() + for _, sel := range selectors { + block, _ := blockTokens(rules, sel) + for _, d := range tokenDiffs(sel, block, map[string]string{"--radius-card": "22px"}) { + t.Error(d) + } + } +} + +func checkBerryLightCard(t *testing.T, rules []cssRule, light string) { + t.Helper() + block, _ := blockTokens(rules, light) + if got := block["--card-border"]; normCSS(got) != "transparent" { + t.Errorf("style.css: %s { --card-border } = %q, want transparent", light, got) + } + if got := normCSS(block["--shadow"]); got == "" || got == "none" || got == "0 0 0 transparent" { + t.Errorf("style.css: %s { --shadow } = %q, want a visible shadow", light, block["--shadow"]) + } +} + +func checkBerryDarkCard(t *testing.T, rules []cssRule, selectors []string) { + t.Helper() + want := map[string]string{"--card-border": "#2c2832", "--shadow": "0 0 0 transparent"} + for _, sel := range selectors { + block, _ := blockTokens(rules, sel) + for _, d := range tokenDiffs(sel, block, want) { + t.Error(d) + } + } +} + +func checkUnscopedCard(t *testing.T, rules []cssRule) { + t.Helper() + d := declsFor(rules, ".card") + if got, want := d["border"], "1px solid var(--card-border)"; normCSS(got) != normCSS(want) { + t.Errorf("style.css: .card { border } = %q, want %q", got, want) + } + if got, want := d["box-shadow"], "var(--shadow)"; got != want { + t.Errorf("style.css: .card { box-shadow } = %q, want %q", got, want) + } + if len(scopedRules(rules, berryScope)) == 0 { + t.Error("style.css: no Berry rule") + } +} + +var ( + berryWordRE = regexp.MustCompile(`(?i)\bberry\b`) + innerHTMLAssignRE = regexp.MustCompile(`innerHTML\s*=\s*([^;\n]*)`) +) + +// berryMarkupFindings lists every Berry-specific word in an asset and every +// innerHTML assignment with non-empty content. +func berryMarkupFindings(text string) []string { + out := berryWordRE.FindAllString(text, -1) + for _, m := range innerHTMLAssignRE.FindAllStringSubmatch(text, -1) { + if v := strings.TrimSpace(m[1]); v != "''" && v != `""` { + out = append(out, "innerHTML = "+v) + } + } + return out +} + +// TestAssets_NoBerryMarkup_AC13 guards that Berry is CSS only: index.html and +// app.js hold no Berry word (so no markup or branch for it), no inline style or +// script and no non-empty innerHTML. +func TestAssets_NoBerryMarkup_AC13(t *testing.T) { + t.Run("AC13 index.html and app.js hold no Berry-specific markup or branch", func(t *testing.T) { + checkNoBerryMarkup(t) + }) + t.Run("AC13 the scanner matches the word only", func(t *testing.T) { + checkBerryScanner(t) + }) +} + +func checkNoBerryMarkup(t *testing.T) { + t.Helper() + for _, name := range []string{"index.html", "app.js"} { + if got := berryMarkupFindings(readAsset(t, name)); len(got) != 0 { + t.Errorf("%s: found %v, want none", name, got) + } + } + if got := inlineFindings(readAsset(t, "index.html")); len(got) != 0 { + t.Errorf("index.html: inline code %v, want none", got) + } +} + +func checkBerryScanner(t *testing.T) { + t.Helper() + for _, clean := range []string{`

Raspberry Pi

`, `el.innerHTML = '';`, `el.innerHTML = "";`} { + if got := berryMarkupFindings(clean); len(got) != 0 { + t.Errorf("scanner on %q: got %v, want none", clean, got) + } + } + for name, text := range map[string]string{ + "lower case word": `if (theme === 'berry') {}`, + "upper case word": `
`, + "filled innerHTML": `el.innerHTML = '' + x;`, + } { + if len(berryMarkupFindings(text)) == 0 { + t.Errorf("%s: scanner reported nothing, want a finding", name) + } + } +} + +// TestStyleCSS_BerryHeadings_AC6 guards Berry's card headings: sentence case at +// 15 px / 650 in the text colour, a 48 px strip and a slight negative tracking. +func TestStyleCSS_BerryHeadings_AC6(t *testing.T) { + rules := parseCSSRules(readAsset(t, "style.css")) + t.Run("AC6 the card heading is 15px, 650, sentence case, in --text", func(t *testing.T) { + checkWants(t, rules, berryScope, []cssWant{ + {[]string{".card h2"}, "text-transform", "none"}, + {[]string{".card h2"}, "font-size", "15px"}, + {[]string{".card h2"}, "font-weight", "650"}, + {[]string{".card h2"}, "color", "var(--text)"}, + {[]string{".card h2"}, "min-height", "48px"}, + {[]string{".card h2"}, "letter-spacing", "-0.01em"}, + }, true) + }) +} + +// berryTileWants are the Updates row, its button, the two tiles (Pi-hole and +// network rows) and the Pi-hole pill of the plan's Approach. +var berryTileWants = []cssWant{ + {[]string{"#card-updates"}, "display", "flex"}, + {[]string{"#card-updates"}, "flex-wrap", "wrap"}, + {[]string{"#card-updates"}, "align-items", "center"}, + {[]string{"#card-updates"}, "column-gap", "12px"}, + {[]string{"#card-updates h2"}, "flex", "0 0 100%"}, + {[]string{"#updates-count"}, "flex", "1 1 auto"}, + {[]string{"#updates-show"}, "order", "1"}, + {[]string{"#updates-checked"}, "order", "2"}, + {[]string{"#updates-stale"}, "order", "2"}, + {[]string{"#pihole-section"}, "order", "2"}, + {[]string{"#updates-checked"}, "flex", "0 0 100%"}, + {[]string{"#pihole-section"}, "flex", "0 0 100%"}, + {[]string{".updates-button"}, "background", "var(--accent)"}, + {[]string{".updates-button"}, "color", "var(--on-accent)"}, + {[]string{".updates-button"}, "border", "re:^(0|none)$"}, + {[]string{".updates-button"}, "font-size", "14px"}, + {[]string{".updates-button"}, "font-weight", "650"}, + {[]string{".updates-button"}, "padding", "0 20px"}, + {[]string{".updates-button"}, "margin-top", "0"}, + {[]string{".updates-button"}, "min-height", "44px"}, + {[]string{".updates-button:hover"}, "filter", "brightness(1.08)"}, + {[]string{".pihole-section"}, "background", "var(--bg)"}, + {[]string{".pihole-section"}, "border-radius", "14px"}, + {[]string{".pihole-section"}, "padding", "12px 14px"}, + {[]string{".pihole-section"}, "margin-top", "16px"}, + {[]string{".pihole-section"}, "border-top", "re:^(0|none)$"}, + {[]string{"#pihole-status"}, "font-size", "12px"}, + {[]string{"#pihole-status"}, "font-weight", "650"}, + {[]string{"#pihole-status"}, "padding", "2px 10px"}, + {[]string{"#pihole-status"}, "border-radius", "999px"}, + {[]string{"#pihole-status.metric-ok", ".kv-val#pihole-status.metric-ok"}, "background", "color-mix(in srgb, var(--ok) var(--pill-tint), transparent)"}, + {[]string{"#pihole-status.metric-warn", ".kv-val#pihole-status.metric-warn"}, "background", "color-mix(in srgb, var(--warn) var(--pill-tint), transparent)"}, + {[]string{".net-row"}, "background", "var(--bg)"}, + {[]string{".net-row"}, "border-radius", "14px"}, + {[]string{".net-row"}, "padding", "11px 14px"}, + {[]string{".net-row"}, "margin-bottom", "8px"}, + {[]string{".net-row"}, "border-bottom", "re:^(0|none)$"}, + {[]string{".net-row:last-child"}, "margin-bottom", "0"}, + {[]string{".net-rate:first-child .net-icon", ".net-rate:first-of-type .net-icon"}, "color", "var(--accent)"}, + {[]string{".net-rate:last-child .net-icon", ".net-rate:last-of-type .net-icon"}, "color", "var(--muted)"}, +} + +// TestStyleCSS_BerryTiles_AC9 guards Berry's Updates row (a wrapping flex row +// with the button beside the count), the inset tiles of Pi-hole and the network +// rows without a divider, and a count that may shrink so that "Not checked yet" +// wraps in a narrow card. +func TestStyleCSS_BerryTiles_AC9(t *testing.T) { + rules := parseCSSRules(readAsset(t, "style.css")) + + t.Run("AC9 the Updates row, the tiles and the pill take the plan's values", func(t *testing.T) { + checkWants(t, rules, berryScope, berryTileWants, true) + }) + t.Run("AC9 the count may shrink", func(t *testing.T) { + if len(scopedRules(rules, berryScope)) == 0 { + t.Fatal("style.css: no Berry rule") + } + if got := shrinkProblems(rules, ":root[data-style=\"berry\"] #updates-count"); len(got) != 0 { + t.Errorf("style.css: %v give #updates-count flex-shrink 0, want it shrinkable", got) + } + if got := shrinkProblems(rules, "#updates-count"); len(got) != 0 { + t.Errorf("style.css: %v give #updates-count flex-shrink 0, want it shrinkable", got) + } + }) + t.Run("AC9 the shrink checker reports flex-shrink 0 in both spellings", func(t *testing.T) { + for _, css := range []string{"#c { flex-shrink: 0; }", "#c { flex: 1 0 auto; }"} { + if got := shrinkProblems(parseCSSRules(css), "#c"); len(got) != 1 { + t.Errorf("shrinkProblems(%q) = %v, want one problem", css, got) + } + } + if got := shrinkProblems(parseCSSRules("#c { flex: 1 1 auto; }"), "#c"); len(got) != 0 { + t.Errorf("shrinkProblems(flex: 1 1 auto) = %v, want none", got) + } + }) +} + +// berryChromeWants are the page, header, banner, card, value, bar, badge and +// dialog declarations of the plan's Approach, each a Berry rule (the gauge box +// is guarded by feature 220's ring tests). +var berryChromeWants = []cssWant{ + {[]string{".range-button:hover"}, "border-color", "var(--accent)"}, + {[]string{".layout-move:hover:not(:disabled)"}, "border-color", "var(--accent)"}, + {[]string{".layout-reset:hover"}, "border-color", "var(--accent)"}, + {[]string{"body"}, "font-size", "14px"}, + {[]string{"header"}, "padding", "22px 28px 8px"}, + {[]string{"main"}, "padding", "12px 28px 22px"}, + {[]string{".alert-banner"}, "margin", "0 28px 20px"}, + {[]string{"footer"}, "padding", "0 28px 22px"}, + {[]string{"footer"}, "font-size", "12px"}, + {[]string{".logo-tile"}, "width", "48px"}, + {[]string{".logo-tile"}, "height", "48px"}, + {[]string{".logo-tile"}, "border-radius", "50%"}, + {[]string{".logo-tile .icon"}, "width", "24px"}, + {[]string{"header h1"}, "font-size", "22px"}, + {[]string{"header h1"}, "font-weight", "750"}, + {[]string{"header h1"}, "letter-spacing", "-0.02em"}, + {[]string{".theme-toggle", ".layout-toggle"}, "border-radius", "50%"}, + {[]string{".alert-banner"}, "border", "re:^(0|none)$"}, + {[]string{".alert-banner"}, "font-weight", "650"}, + {[]string{".alert-banner-icon"}, "width", "32px"}, + {[]string{".alert-banner-icon"}, "height", "32px"}, + {[]string{".alert-banner-icon"}, "border-radius", "50%"}, + {[]string{".alert-banner-icon"}, "display", "re:flex"}, + {[]string{".alert-banner-icon"}, "align-items", "center"}, + {[]string{".alert-banner-icon"}, "justify-content", "center"}, + {[]string{".alert-banner-icon .icon"}, "width", "17px"}, + {[]string{".alert-banner.metric-warn .alert-banner-icon"}, "background", "color-mix(in srgb, var(--warn) 22%, transparent)"}, + {[]string{".alert-banner.metric-crit .alert-banner-icon"}, "background", "color-mix(in srgb, var(--crit) 22%, transparent)"}, + {[]string{".card-icon"}, "width", "32px"}, + {[]string{".card-icon"}, "height", "32px"}, + {[]string{".card-icon .icon"}, "width", "17px"}, + {[]string{".card-header-btn .chevron"}, "width", "18px"}, + {[]string{".kv-row"}, "font-size", "14px"}, + {[]string{".kv-row"}, "padding", "8px 0"}, + {[]string{".metric-value"}, "font-size", "38px"}, + {[]string{".metric-value"}, "font-weight", "750"}, + {[]string{".metric-value"}, "letter-spacing", "-0.035em"}, + {[]string{".metric-value"}, "line-height", "1"}, + {[]string{".metric-unit"}, "font-size", "18px"}, + {[]string{".metric-unit"}, "font-weight", "650"}, + {[]string{".metric-unit"}, "margin-left", "4px"}, + {[]string{".metric-unit::before"}, "content", "none"}, + {[]string{".metric-sub"}, "font-size", "13px"}, + {[]string{".metric-sub"}, "margin-top", "6px"}, + {[]string{".bar-track"}, "height", "10px"}, + {[]string{".bar-label"}, "font-size", "14px"}, + {[]string{".bar-label"}, "margin-bottom", "8px"}, + {[]string{".bar-pct"}, "font-weight", "650"}, + {[]string{".bar-row"}, "margin-bottom", "16px"}, + {[]string{".bar-row:last-child"}, "margin-bottom", "0"}, + {[]string{".gauge .gauge-label"}, "font-size", "12px"}, + {[]string{".gauge .gauge-label"}, "margin-top", "8px"}, + {[]string{".net-name"}, "font-weight", "650"}, + {[]string{".net-icon", ".net-rate .net-icon"}, "stroke-width", "2.5"}, + {[]string{".alert-badge"}, "font-size", "12px"}, + {[]string{".alert-badge"}, "font-weight", "650"}, + {[]string{".alert-badge"}, "padding", "2px 10px"}, + {[]string{".alert-badge"}, "text-transform", "none"}, + {[]string{".alert-badge"}, "letter-spacing", "0"}, + {[]string{".alert-badge::first-letter"}, "text-transform", "uppercase"}, + {[]string{".stale-badge"}, "font-size", "12px"}, + {[]string{".stale-badge"}, "font-weight", "650"}, + {[]string{".stale-badge"}, "padding", "2px 10px"}, + {[]string{".range-button.active"}, "font-weight", "650"}, + {[]string{".apikey-submit"}, "font-weight", "650"}, + {[]string{".range-button"}, "background", "var(--bg)"}, + {[]string{".range-button"}, "border-color", "transparent"}, + {[]string{".range-button"}, "border-radius", "999px"}, + {[]string{".layout-move"}, "background", "var(--bg)"}, + {[]string{".layout-move"}, "border-color", "transparent"}, + {[]string{".layout-move"}, "border-radius", "999px"}, + {[]string{".layout-reset"}, "background", "var(--bg)"}, + {[]string{".layout-reset"}, "border-color", "transparent"}, + {[]string{".layout-reset"}, "border-radius", "999px"}, + {[]string{".modal-close"}, "background", "var(--bg)"}, + {[]string{".modal-close"}, "border-color", "transparent"}, + {[]string{".modal-close"}, "border-radius", "999px"}, + {[]string{".apikey-input"}, "border-radius", "999px"}, +} + +// TestStyleCSS_BerryChrome_AC14 guards the header, banner, cards, values, bars, +// badges and dialogs of Berry: the chrome table takes the plan's values, the +// capital of the alert badge is drawn on the badge only, and no font file is +// added. +func TestStyleCSS_BerryChrome_AC14(t *testing.T) { + css := readAsset(t, "style.css") + rules := parseCSSRules(css) + + t.Run("AC14 the chrome takes the plan's values", func(t *testing.T) { + checkWants(t, rules, berryScope, berryChromeWants, true) + }) + t.Run("AC14 the capital is drawn on the alert badge only", func(t *testing.T) { + if !hasScopedSelector(rules, berryScope, ".alert-badge", "::first-letter") { + t.Error("style.css: no Berry rule for .alert-badge::first-letter") + } + if hasScopedSelector(rules, berryScope, ".stale-badge", "::first-letter") { + t.Error("style.css: a Berry rule for .stale-badge::first-letter, want the capital on .alert-badge only") + } + }) + t.Run("AC14 no font file is added", func(t *testing.T) { + checkNoFontFiles(t, css) + }) +} diff --git a/internal/web/palette_test.go b/internal/web/palette_test.go index 299e686..9697884 100644 --- a/internal/web/palette_test.go +++ b/internal/web/palette_test.go @@ -239,6 +239,12 @@ func expectedTokens(dark bool) map[string]string { "--spark-grid": "none", "--gauge-width": "9", "--gauge-cap": "round", + + // Feature 220: the four tokens every theme declares; Clear's keep its look. + "--card-border": pick("#e4e7ec", "#2b2f37"), + "--pill-tint": "20%", + "--gauge-shape": "half", + "--spark-dot-size": "8", } } @@ -793,6 +799,12 @@ func consoleTokens(dark bool) map[string]string { "--spark-grid": "lines", "--gauge-width": "5", "--gauge-cap": "butt", + + // Feature 220: the four tokens every theme declares; Console's keep its look. + "--card-border": pick("#d5d9df", "#282c33"), + "--pill-tint": "20%", + "--gauge-shape": "half", + "--spark-dot-size": "8", } for _, card := range []string{"system", "updates", "uptime", "cpu", "load", "temperature", "memory", "disks", "network", "openhab"} { tokens["--accent-"+card] = text @@ -800,9 +812,9 @@ func consoleTokens(dark bool) map[string]string { return tokens } -// consoleBlockProblems lists the tokens of block that differ from want and +// blockProblems lists the tokens of block that differ from want and // the keys it has too many or too few. -func consoleBlockProblems(name string, block, want map[string]string) []string { +func blockProblems(name string, block, want map[string]string) []string { out := tokenDiffs(name, block, want) for _, d := range keySetDiff(block, want) { out = append(out, name+": "+d) @@ -835,7 +847,7 @@ func TestStyleCSS_ConsolePalette_AC2(t *testing.T) { dark bool }{{lightSel, light, false}, {darkSel, dark, true}, {mediaSel, media, true}} { t.Run("AC2 "+b.name+" holds the palette and exactly the tokens expected", func(t *testing.T) { - for _, d := range consoleBlockProblems(b.name, b.got, consoleTokens(b.dark)) { + for _, d := range blockProblems(b.name, b.got, consoleTokens(b.dark)) { t.Error(d) } }) @@ -853,11 +865,11 @@ func TestStyleCSS_ConsolePalette_AC2(t *testing.T) { }) } -// consoleContrastFailures checks the AC11 pairs of one Console mode: text +// themeContrastFailures checks the AC11 pairs of one Console mode: text // contrast of at least 4.5:1 for --text, --muted and the three inks against // --card-bg, --text and --muted against --bg, and a graphic contrast of at // least 3:1 for --ok, --warn and --crit against --card-bg. -func consoleContrastFailures(mode string, tokens map[string]string) []string { +func themeContrastFailures(mode string, tokens map[string]string) []string { var out []string check := func(fgName, bgName string, floor float64) { fg, errFg := hexRGB(tokens[fgName]) @@ -888,7 +900,7 @@ func TestStyleCSS_ThemeContrast_AC11(t *testing.T) { tokens := consoleTokens(false) tokens["--muted"] = "#aaaaaa" tokens["--warn"] = "#ffee99" - if got := consoleContrastFailures("fixture", tokens); len(got) < 3 { + if got := themeContrastFailures("fixture", tokens); len(got) < 3 { t.Errorf("failures = %v, want --muted on --card-bg, --muted on --bg and --warn on --card-bg", got) } }) @@ -898,7 +910,7 @@ func TestStyleCSS_ThemeContrast_AC11(t *testing.T) { for _, m := range []struct{ name, selector string }{{"light", lightSel}, {"dark", darkSel}, {"OS dark", mediaSel}} { t.Run("AC11 Console "+m.name+" mode meets 4.5:1 for text and 3:1 for fills", func(t *testing.T) { block, _ := blockTokens(rules, m.selector) - for _, f := range consoleContrastFailures("Console "+m.name, block) { + for _, f := range themeContrastFailures("Console "+m.name, block) { t.Error(f) } }) @@ -915,7 +927,7 @@ func TestStyleCSS_ConsoleColourRule_AC3(t *testing.T) { rules := parseCSSRules(readAsset(t, "style.css")) t.Run("AC3 ok text is --text, the new-version column too", func(t *testing.T) { - checkWants(t, rules, []cssWant{ + checkWants(t, rules, consoleScope, []cssWant{ {[]string{".metric-ok"}, "color", "var(--text)"}, {[]string{".kv-val.metric-ok"}, "color", "var(--text)"}, {[]string{".updates-table td.pkg-new"}, "color", "var(--text)"}, @@ -925,7 +937,7 @@ func TestStyleCSS_ConsoleColourRule_AC3(t *testing.T) { checkOnlyPiholeGreen(t, rules) }) t.Run("AC3 the Pi-hole dot is a 6 px square, green when up to date and amber when an update exists", func(t *testing.T) { - checkWants(t, rules, []cssWant{ + checkWants(t, rules, consoleScope, []cssWant{ {[]string{"#pihole-status::before"}, "width", "6px"}, {[]string{"#pihole-status::before"}, "height", "6px"}, {[]string{"#pihole-status::before"}, "content", "re:^(\"\"|''|\" \")$"}, @@ -934,7 +946,7 @@ func TestStyleCSS_ConsoleColourRule_AC3(t *testing.T) { }, true) }) t.Run("AC3 warn and crit text keep their ink colour", func(t *testing.T) { - for _, r := range consoleScoped(rules) { + for _, r := range scopedRules(rules, consoleScope) { checkLevelInk(t, r) } }) @@ -949,7 +961,7 @@ func TestStyleCSS_ConsoleColourRule_AC3(t *testing.T) { // greenOutsideDot returns the Console declarations that use --ok or --ok-ink outside the Pi-hole dot. func greenOutsideDot(rules []cssRule) []string { var out []string - for _, r := range consoleScoped(rules) { + for _, r := range scopedRules(rules, consoleScope) { dot := true for _, s := range r.selectors { dot = dot && strings.Contains(s, "#pihole-status") @@ -966,7 +978,7 @@ func greenOutsideDot(rules []cssRule) []string { // checkOnlyPiholeGreen reports every Console use of the green tokens outside the Pi-hole dot. func checkOnlyPiholeGreen(t *testing.T, rules []cssRule) { t.Helper() - if len(consoleScoped(rules)) == 0 { + if len(scopedRules(rules, consoleScope)) == 0 { t.Fatal("style.css: no Console-scoped rule") } for _, f := range greenOutsideDot(rules) { @@ -999,21 +1011,21 @@ func TestStyleCSS_ConsoleRulesScoped_AC12(t *testing.T) { rules := parseCSSRules(readAsset(t, "style.css")) t.Run("AC12 Console rules exist and every selector of one is scoped", func(t *testing.T) { - if len(consoleScoped(rules)) == 0 { + if len(scopedRules(rules, consoleScope)) == 0 { t.Fatal("style.css: no Console-scoped rule") } - for _, p := range unscopedMix(rules) { + for _, p := range unscopedMix(rules, consoleScope) { t.Error(p) } }) t.Run("AC12 the mixed-selector check reports a rule", func(t *testing.T) { fixture := parseCSSRules(consoleScope + " .a, .b { color: var(--text); }") - if got := unscopedMix(fixture); len(got) != 1 { - t.Errorf("unscopedMix(fixture) = %v, want one problem", got) + if got := unscopedMix(fixture, consoleScope); len(got) != 1 { + t.Errorf("unscopedMix(fixture, consoleScope) = %v, want one problem", got) } }) t.Run("AC12 no !important and no change of the gauge value box or canvas height", func(t *testing.T) { - for _, p := range consoleBoxProblems(rules) { + for _, p := range scopedBoxProblems(rules, consoleScope, true) { t.Error(p) } }) @@ -1025,12 +1037,12 @@ func TestStyleCSS_ConsoleRulesScoped_AC12(t *testing.T) { }) } -// unscopedMix reports each rule that lists a Console selector together with another one. -func unscopedMix(rules []cssRule) []string { +// unscopedMix reports each rule that lists a selector under scope together with another one. +func unscopedMix(rules []cssRule, scope string) []string { var out []string - for _, r := range consoleScoped(rules) { + for _, r := range scopedRules(rules, scope) { for _, s := range r.selectors { - if !strings.HasPrefix(s, consoleScope) { + if !strings.HasPrefix(s, scope) { out = append(out, fmt.Sprintf("style.css: the rule for %q lists the unscoped selector %q", strings.Join(r.selectors, ", "), s)) } } @@ -1038,11 +1050,11 @@ func unscopedMix(rules []cssRule) []string { return out } -// consoleBoxProblems reports !important and changes of the gauge value box in Console rules. -func consoleBoxProblems(rules []cssRule) []string { +// scopedBoxProblems reports !important in the rules under scope and, when boxLocked, changes of the gauge value box. +func scopedBoxProblems(rules []cssRule, scope string, boxLocked bool) []string { var out []string boxProps := map[string]bool{"font-size": true, "bottom": true, "line-height": true, "height": true} - for _, r := range consoleScoped(rules) { + for _, r := range scopedRules(rules, scope) { gauge := false for _, s := range r.selectors { gauge = gauge || strings.Contains(s, ".gauge-value") || strings.Contains(s, ".gauge canvas") || strings.Contains(s, ".gauge-dial") @@ -1051,7 +1063,7 @@ func consoleBoxProblems(rules []cssRule) []string { if strings.Contains(d.value, "!important") { out = append(out, fmt.Sprintf("style.css: %s { %s: %s } uses !important", strings.Join(r.selectors, ", "), d.prop, d.value)) } - if gauge && boxProps[d.prop] { + if boxLocked && gauge && boxProps[d.prop] { out = append(out, fmt.Sprintf("style.css: %s { %s: %s } changes the gauge box the chord check does not see", strings.Join(r.selectors, ", "), d.prop, d.value)) } } @@ -1074,9 +1086,9 @@ func checkClearUnitRule(t *testing.T, rules []cssRule) { } } -// unitRuleProblems reports the declarations of an unscoped rule for a unit selector other than the gap. +// unitRuleProblems reports the declarations of an unscoped rule (not under any theme scope) for a unit selector other than the gap. func unitRuleProblems(selector string, decls []cssDecl) []string { - if !strings.Contains(selector, ".metric-unit") || strings.HasPrefix(selector, consoleScope) { + if !strings.Contains(selector, ".metric-unit") || strings.HasPrefix(selector, `:root[data-style=`) { return nil } var out []string @@ -1127,3 +1139,561 @@ func checkWantsUnscoped(t *testing.T, rules []cssRule) { } } } + +// berryTokens returns Berry's palette blocks of feature 220 for the light or +// the dark mode: issue 220 section 1 and the tokens the plan fixes. The two +// departures from section 1 are the light --ok-ink `#166534` (decision 0045: +// `#15803d` gives the Pi-hole pill 3.79:1) and the dark --shadow +// `0 0 0 transparent` instead of `none` (spec Q2: `none` inside the hover +// box-shadow list of the header buttons would invalidate the declaration). Every +// per-card accent equals the mode's --accent, --ok-fill equals --ok and +// --dialog-shadow the mode's --shadow. +func berryTokens(dark bool) map[string]string { + pick := func(light, dk string) string { + if dark { + return dk + } + return light + } + accent, ok, shadow := pick("#c2255c", "#f06595"), pick("#16a34a", "#22c55e"), + pick("0 1px 2px rgba(40, 20, 50, 0.05), 0 10px 28px rgba(40, 20, 50, 0.07)", "0 0 0 transparent") + tokens := map[string]string{ + "--bg": pick("#f4f1f4", "#131116"), + "--card-bg": pick("#ffffff", "#1d1a21"), + "--card-border": pick("transparent", "#2c2832"), + "--text": pick("#1d1921", "#f0ebf3"), + "--muted": pick("#665f6d", "#a8a0b0"), + "--border": pick("#eee9ef", "#2e2a33"), + "--track": pick("#ece6ed", "#342f3a"), + "--accent": accent, + "--on-accent": pick("#ffffff", "#2a0a17"), + "--ok": ok, + "--ok-ink": pick("#166534", "#4ade80"), + "--warn": pick("#d97706", "#f59e0b"), + "--warn-ink": pick("#92400e", "#fbbf24"), + "--crit": pick("#dc2626", "#ef4444"), + "--crit-ink": pick("#b91c1c", "#f87171"), + "--shadow": shadow, + + "--chip-tint": pick("11%", "15%"), + "--pill-tint": pick("16%", "18%"), + "--btn-tint": pick("8%", "14%"), + "--btn-border-tint": pick("30%", "35%"), + "--spark-fill-alpha": pick("0.26", "0.30"), + + "--dialog-shadow": shadow, + "--backdrop": "rgba(0, 0, 0, 0.5)", + "--radius-card": "22px", + "--radius-control": "18px", + "--radius-button": "999px", + "--radius-chip": "50%", + "--card-padding": "10px 22px 22px", + "--gap": "20px", + + "--ok-fill": ok, + "--spark-line-width": "2.5", + "--spark-shape": "line", + "--spark-fill": "fade", + "--spark-dot": "ring", + "--spark-grid": "none", + "--spark-dot-size": "10", + "--gauge-width": "9", + "--gauge-cap": "round", + "--gauge-shape": "ring", + } + for _, card := range []string{"system", "updates", "uptime", "cpu", "load", "temperature", "memory", "disks", "network", "openhab"} { + tokens["--accent-"+card] = accent + } + return tokens +} + +// TestStyleCSS_BerryPalette_AC2 guards Berry's three palette blocks: one rule +// each, the values of berryTokens with exactly that key set, the same key set +// as Clear's light block, every per-card accent equal to --accent, --ok-fill +// equal to --ok and identical explicit and OS dark blocks. +func TestStyleCSS_BerryPalette_AC2(t *testing.T) { + rules := parseCSSRules(readAsset(t, "style.css")) + clearTokens, _ := blockTokens(rules, selLight) + lightSel, darkSel, mediaSel := themeSelectors("berry", false) + light, nl := blockTokens(rules, lightSel) + dark, nd := blockTokens(rules, darkSel) + media, nm := blockTokens(rules, mediaSel) + + t.Run("AC2 each block is one rule", func(t *testing.T) { + for sel, n := range map[string]int{lightSel: nl, darkSel: nd, mediaSel: nm} { + if n != 1 { + t.Errorf("style.css: %d rules for %s, want exactly 1", n, sel) + } + } + }) + for _, b := range []struct { + name string + got map[string]string + dark bool + }{{lightSel, light, false}, {darkSel, dark, true}, {mediaSel, media, true}} { + t.Run("AC2 "+b.name+" holds the palette, the key set of Clear's light block and the derived tokens", func(t *testing.T) { + checkBerryBlock(t, b.name, b.got, berryTokens(b.dark), clearTokens) + }) + } + t.Run("AC2 both dark blocks are identical", func(t *testing.T) { + for _, d := range mapDiffs(dark, media) { + t.Errorf("Berry dark blocks differ: %s", d) + } + }) + t.Run("AC2 the two departures from the issue are kept: light ok ink and dark shadow", func(t *testing.T) { + checkBerryDepartures(t, map[string]map[string]string{lightSel: light, darkSel: dark, mediaSel: media}) + }) + t.Run("AC2 the derived-token check reports a card with its own colour and an ok fill that differs", func(t *testing.T) { + fixture := berryTokens(false) + fixture["--accent-cpu"] = "#7c3aed" + fixture["--ok-fill"] = "#000000" + if got := berryDerivedProblems("fixture", fixture); len(got) != 2 { + t.Errorf("berryDerivedProblems(fixture) = %v, want 2 problems", got) + } + }) +} + +// checkBerryDepartures checks the light --ok-ink of decision 0045 and the dark --shadow of spec Q2 in Berry's blocks, keyed by selector. +func checkBerryDepartures(t *testing.T, blocks map[string]map[string]string) { + t.Helper() + for sel, block := range blocks { + want, token := "0 0 0 transparent", "--shadow" + if !strings.Contains(sel, "[data-theme") && !strings.Contains(sel, ":not(") { + want, token = "#166534", "--ok-ink" + } + if got := block[token]; normCSS(got) != normCSS(want) { + t.Errorf("%s %s = %q, want %q (decision 0045, spec Q2)", sel, token, got, want) + } + } +} + +// checkBerryBlock checks one Berry block against its expected tokens, Clear's key set and the derived tokens. +func checkBerryBlock(t *testing.T, name string, got, want, clearTokens map[string]string) { + t.Helper() + for _, d := range blockProblems(name, got, want) { + t.Error(d) + } + for _, d := range keySetDiff(got, clearTokens) { + t.Errorf("%s compared with Clear's light block: %s", name, d) + } + for _, p := range berryDerivedProblems(name, got) { + t.Error(p) + } +} + +// berryDerivedProblems reports each --accent- that is not the block's +// --accent and an --ok-fill that is not the block's --ok. +func berryDerivedProblems(name string, block map[string]string) []string { + var out []string + for _, k := range sortedKeys(block) { + if strings.HasPrefix(k, "--accent-") && block[k] != block["--accent"] { + out = append(out, fmt.Sprintf("%s: %s = %q, want the block's --accent %q", name, k, block[k], block["--accent"])) + } + } + if block["--ok-fill"] != block["--ok"] { + out = append(out, fmt.Sprintf("%s: --ok-fill = %q, want the block's --ok %q", name, block["--ok-fill"], block["--ok"])) + } + return out +} + +// sharedTokenProblems reports the four tokens of feature 220 in one palette +// block of Clear or Console that deviate from the values keeping their look. +func sharedTokenProblems(name string, block map[string]string) []string { + var out []string + if block["--card-border"] == "" || block["--card-border"] != block["--border"] { + out = append(out, fmt.Sprintf("%s: --card-border = %q, want the block's --border %q", name, block["--card-border"], block["--border"])) + } + for prop, want := range map[string]string{"--pill-tint": "20%", "--gauge-shape": "half", "--spark-dot-size": "8"} { + if normCSS(block[prop]) != normCSS(want) { + out = append(out, fmt.Sprintf("%s: %s = %q, want %q", name, prop, block[prop], want)) + } + } + return out +} + +// TestStyleCSS_SharedNewTokens_AC2 guards the four tokens every palette block +// gains: Clear's and Console's six blocks keep their look through them +// (--card-border their --border, --pill-tint 20 %, --gauge-shape half, +// --spark-dot-size 8), and DRAWING_FALLBACKS holds the last two with Clear's +// value. +func TestStyleCSS_SharedNewTokens_AC2(t *testing.T) { + rules := parseCSSRules(readAsset(t, "style.css")) + + for _, id := range []string{"clear", "console"} { + light, dark, media := themeSelectors(id, id == "clear") + for _, sel := range []string{light, dark, media} { + t.Run("AC2 "+id+" block "+sel+" holds the four tokens that keep its look", func(t *testing.T) { + block, _ := blockTokens(rules, sel) + for _, p := range sharedTokenProblems(sel, block) { + t.Error(p) + } + }) + } + } + + t.Run("AC2 DRAWING_FALLBACKS holds the ring word and the dot size with Clear's values", func(t *testing.T) { + fallbacks := parseDrawingFallbacks(readAsset(t, "theme-init.js")) + for prop, want := range map[string]string{"--gauge-shape": "half", "--spark-dot-size": "8"} { + if fallbacks[prop] != want { + t.Errorf("DRAWING_FALLBACKS[%s] = %q, want %q", prop, fallbacks[prop], want) + } + } + }) + + t.Run("AC2 the check reports a missing token, a card border that is not the border and a wrong word", func(t *testing.T) { + fixture := map[string]string{"--border": "#111", "--card-border": "#222", "--pill-tint": "20%", "--gauge-shape": "ring"} + if got := sharedTokenProblems("fixture", fixture); len(got) != 3 { + t.Errorf("sharedTokenProblems(fixture) = %v, want 3 problems (card border, gauge shape, dot size)", got) + } + }) +} + +// tokenRGB parses the hex colour of a token. +func tokenRGB(tokens map[string]string, name string) ([3]float64, error) { + rgb, err := hexRGB(tokens[name]) + if err != nil { + return rgb, fmt.Errorf("%s: %w", name, err) + } + return rgb, nil +} + +// ratioProblem returns a message when fg on bg is below floor. +func ratioProblem(mode, fgName string, fg [3]float64, bgName string, bg [3]float64, floor float64) []string { + if r := contrastRatio(fg, bg); r < floor { + return []string{fmt.Sprintf("%s: %s on %s = %.2f:1, want at least %.1f:1", mode, fgName, bgName, r, floor)} + } + return nil +} + +// berryContrastFailures checks the pairs of feature 220 in one Berry mode: the +// shared pairs of themeContrastFailures, --accent on --card-bg and --bg and +// --on-accent on --accent at 4.5:1, each status ink on its own pill tint +// (--pill-tint of the base colour) over --card-bg and over --bg and on its +// banner tint (14 %) over --bg at 4.5:1. +func berryContrastFailures(mode string, tokens map[string]string) []string { + out := themeContrastFailures(mode, tokens) + card, errCard := tokenRGB(tokens, "--card-bg") + page, errPage := tokenRGB(tokens, "--bg") + accent, errAccent := tokenRGB(tokens, "--accent") + onAccent, errOn := tokenRGB(tokens, "--on-accent") + tint, errTint := strconv.ParseFloat(strings.TrimSuffix(strings.TrimSpace(tokens["--pill-tint"]), "%"), 64) + for _, err := range []error{errCard, errPage, errAccent, errOn} { + if err != nil { + return append(out, mode+": "+err.Error()) + } + } + if errTint != nil { + return append(out, fmt.Sprintf("%s: --pill-tint = %q is not a percentage", mode, tokens["--pill-tint"])) + } + out = append(out, ratioProblem(mode, "--accent", accent, "--card-bg", card, 4.5)...) + out = append(out, ratioProblem(mode, "--accent", accent, "--bg", page, 4.5)...) + out = append(out, ratioProblem(mode, "--on-accent", onAccent, "--accent", accent, 4.5)...) + for _, level := range []string{"ok", "warn", "crit"} { + out = append(out, levelTintFailures(mode, tokens, level, card, page, tint)...) + } + return out +} + +// levelTintFailures checks one status ink on its pill tint over --card-bg and --bg and on its banner tint over --bg. +func levelTintFailures(mode string, tokens map[string]string, level string, card, page [3]float64, tint float64) []string { + base, errBase := tokenRGB(tokens, "--"+level) + ink, errInk := tokenRGB(tokens, "--"+level+"-ink") + if errBase != nil || errInk != nil { + return []string{fmt.Sprintf("%s: --%s or --%s-ink is not a hex colour (%q, %q)", mode, level, level, tokens["--"+level], tokens["--"+level+"-ink"])} + } + name := "--" + level + "-ink" + var out []string + out = append(out, ratioProblem(mode, name, ink, fmt.Sprintf("--%s at %.0f%% over --card-bg", level, tint), mixRGB(base, card, tint/100), 4.5)...) + out = append(out, ratioProblem(mode, name, ink, fmt.Sprintf("--%s at %.0f%% over --bg", level, tint), mixRGB(base, page, tint/100), 4.5)...) + out = append(out, ratioProblem(mode, name, ink, fmt.Sprintf("--%s banner tint 14%% over --bg", level), mixRGB(base, page, 0.14), 4.5)...) + return out +} + +// TestStyleCSS_BerryContrast_AC11 guards the contrast of Berry's tokens in +// both modes, computed from the stylesheet's three blocks: text at 4.5:1 (the +// accent on both surfaces, the on-accent label, every ink on its pill tint and +// banner tint), fills and arcs at 3:1. +func TestStyleCSS_BerryContrast_AC11(t *testing.T) { + t.Run("AC11 the issue's palette with the light ok ink #166534 passes in both modes", func(t *testing.T) { + for _, dark := range []bool{false, true} { + if got := berryContrastFailures(fmt.Sprintf("dark=%v", dark), berryTokens(dark)); len(got) != 0 { + t.Errorf("berryContrastFailures(berryTokens(%v)) = %v, want none", dark, got) + } + } + }) + t.Run("AC11 the issue's light ok ink #15803d fails on the Pi-hole pill tint over --bg", func(t *testing.T) { + fixture := berryTokens(false) + fixture["--ok-ink"] = "#15803d" + got := strings.Join(berryContrastFailures("fixture", fixture), "\n") + if !strings.Contains(got, "--ok-ink on --ok at 16% over --bg = 3.79:1") { + t.Errorf("berryContrastFailures(#15803d) = %q, want the 3.79:1 pill pair over --bg reported", got) + } + }) + t.Run("AC11 a pair below the floor is reported for the accent, the label and the banner", func(t *testing.T) { + fixture := berryTokens(false) + fixture["--accent"] = "#f06595" + fixture["--warn-ink"] = "#d97706" + got := strings.Join(berryContrastFailures("fixture", fixture), "\n") + for _, want := range []string{"--accent on --card-bg", "--accent on --bg", "--on-accent on --accent", "banner tint 14% over --bg"} { + if !strings.Contains(got, want) { + t.Errorf("berryContrastFailures(fixture) = %q, want a report of %q", got, want) + } + } + }) + + rules := parseCSSRules(readAsset(t, "style.css")) + lightSel, darkSel, mediaSel := themeSelectors("berry", false) + for _, m := range []struct{ name, selector string }{{"light", lightSel}, {"dark", darkSel}, {"OS dark", mediaSel}} { + t.Run("AC11 Berry "+m.name+" mode meets 4.5:1 for text and pills and 3:1 for fills", func(t *testing.T) { + checkBerryModeContrast(t, rules, m.name, m.selector) + }) + } +} + +// checkBerryModeContrast reports every contrast failure of the Berry block with selector. +func checkBerryModeContrast(t *testing.T, rules []cssRule, name, selector string) { + t.Helper() + block, n := blockTokens(rules, selector) + if n != 1 { + t.Fatalf("style.css: %d rules for %s, want exactly 1", n, selector) + } + for _, f := range berryContrastFailures("Berry "+name, block) { + t.Error(f) + } +} + +// statusSelectorRE matches the selectors AC4 reserves for the status colours. +var statusSelectorRE = regexp.MustCompile(`\.metric-|\.bar-fill|\.bar-pct`) + +// accentRE matches a use of --accent or a per-card accent token. +var accentRE = regexp.MustCompile(`var\(\s*--accent`) + +// accentOnStatusProblems reports each rule under scope that gives a value, bar +// fill, bar percentage or gauge arc selector a colour or background taken from +// the accent. +func accentOnStatusProblems(rules []cssRule, scope string) []string { + var out []string + colourProps := map[string]bool{"color": true, "background": true, "background-color": true, "border-color": true, "fill": true, "stroke": true} + for _, r := range scopedRules(rules, scope) { + for _, s := range r.selectors { + if !statusSelectorRE.MatchString(s) { + continue + } + for _, d := range r.decls { + if colourProps[d.prop] && accentRE.MatchString(d.value) { + out = append(out, fmt.Sprintf("style.css: %s { %s: %s }: the accent is never the colour of a value, a fill or an arc", s, d.prop, d.value)) + } + } + } + } + return out +} + +// TestStyleCSS_BerryStatusColours_AC4 guards that Berry colours levels as Clear +// does: its --ok-fill (the ok arc and bar fill) is its --ok in every block, and +// no Berry rule colours a value, a bar fill or a percentage with the accent. +// The arcs read --ok-fill, --warn and --crit (TestGaugeJS_OkFill_AC3). +func TestStyleCSS_BerryStatusColours_AC4(t *testing.T) { + rules := parseCSSRules(readAsset(t, "style.css")) + + t.Run("AC4 --ok-fill is --ok in each of Berry's blocks, and none of its status tokens is the accent", func(t *testing.T) { + light, dark, media := themeSelectors("berry", false) + for _, sel := range []string{light, dark, media} { + checkBerryStatusBlock(t, rules, sel) + } + }) + t.Run("AC4 no Berry rule colours a value, a fill or a percentage with the accent", func(t *testing.T) { + for _, p := range accentOnStatusProblems(rules, berryScope) { + t.Error(p) + } + }) + t.Run("AC4 the scan reports a Berry value, fill and percentage coloured by the accent", func(t *testing.T) { + fixture := parseCSSRules(berryScope + " .metric-value { color: var(--accent); }\n" + + berryScope + " .bar-fill { background: var(--accent-cpu); }\n" + + berryScope + " .bar-pct { color: var(--accent); }\n" + + berryScope + " .card-icon { color: var(--accent); }") + if got := accentOnStatusProblems(fixture, berryScope); len(got) != 3 { + t.Errorf("accentOnStatusProblems(fixture) = %v, want 3 problems (not the icon chip)", got) + } + }) +} + +// checkBerryStatusBlock checks that one Berry block keeps --ok-fill equal to --ok and the status colours apart from --accent. +func checkBerryStatusBlock(t *testing.T, rules []cssRule, sel string) { + t.Helper() + block, n := blockTokens(rules, sel) + if n != 1 { + t.Errorf("style.css: %d rules for %s, want exactly 1", n, sel) + } + if block["--ok-fill"] == "" || block["--ok-fill"] != block["--ok"] { + t.Errorf("%s: --ok-fill = %q, want --ok %q", sel, block["--ok-fill"], block["--ok"]) + } + for _, level := range []string{"--ok", "--warn", "--crit"} { + if block[level] == "" || block[level] == block["--accent"] { + t.Errorf("%s: %s = %q, want a status colour distinct from --accent %q", sel, level, block[level], block["--accent"]) + } + } +} + +// checkUnscopedTokenReads pins the unscoped rules that read the two +// mode-dependent tokens of feature 220 (decision 0038, option 6): the border of +// the cards, the header buttons and the dialogs, and the badge tints. +func checkUnscopedTokenReads(t *testing.T, rules []cssRule) { + t.Helper() + for _, sel := range []string{".card", ".theme-toggle", ".layout-toggle", "dialog.modal[open]"} { + if got, want := declsFor(rules, sel)["border"], "1px solid var(--card-border)"; normCSS(got) != normCSS(want) { + t.Errorf("style.css: %s { border } = %q, want %q (a token every theme declares)", sel, got, want) + } + } + if got, want := declsFor(rules, ".card")["box-shadow"], "var(--shadow)"; got != want { + t.Errorf("style.css: .card { box-shadow } = %q, want %q", got, want) + } + for sel, level := range map[string]string{".stale-badge": "warn", ".alert-badge.metric-warn": "warn", ".alert-badge.metric-crit": "crit"} { + want := "color-mix(in srgb, var(--" + level + ") var(--pill-tint), transparent)" + if got := declsFor(rules, sel)["background"]; normCSS(got) != normCSS(want) { + t.Errorf("style.css: %s { background } = %q, want %q", sel, got, want) + } + } +} + +// TestStyleCSS_BerryRulesScoped_AC12 guards that Berry changes only Berry: +// every selector of a Berry rule is under its scope, no Berry rule uses +// !important, Clear's own values stay (the pins of checkWantsUnscoped) and the +// unscoped rules read the border and pill-tint tokens instead of a literal, so +// Clear and Console look as before. +func TestStyleCSS_BerryRulesScoped_AC12(t *testing.T) { + rules := parseCSSRules(readAsset(t, "style.css")) + + t.Run("AC12 Berry rules exist and every selector of one is scoped", func(t *testing.T) { + if len(scopedRules(rules, berryScope)) == 0 { + t.Fatal("style.css: no Berry-scoped rule") + } + for _, p := range unscopedMix(rules, berryScope) { + t.Error(p) + } + }) + t.Run("AC12 the mixed-selector check reports a Berry rule listing an unscoped selector", func(t *testing.T) { + fixture := parseCSSRules(berryScope + " .a, .b { color: var(--text); }") + if got := unscopedMix(fixture, berryScope); len(got) != 1 { + t.Errorf("unscopedMix(fixture, berryScope) = %v, want one problem", got) + } + }) + t.Run("AC12 no Berry rule uses !important", func(t *testing.T) { + for _, p := range scopedBoxProblems(rules, berryScope, false) { + t.Error(p) + } + fixture := parseCSSRules(berryScope + " .a { color: red !important; }") + if got := scopedBoxProblems(fixture, berryScope, false); len(got) != 1 { + t.Errorf("scopedBoxProblems(fixture) = %v, want one problem", got) + } + }) + t.Run("AC12 Clear keeps its look and the only unscoped unit rule is the gap", func(t *testing.T) { + checkWantsUnscoped(t, rules) + checkClearUnitRule(t, rules) + }) + t.Run("AC12 the unscoped rules read the card border and pill tint tokens", func(t *testing.T) { + checkUnscopedTokenReads(t, rules) + }) + t.Run("AC12 no Console rule lists a Berry selector", func(t *testing.T) { + for _, p := range consoleBerryMix(rules) { + t.Error(p) + } + }) +} + +// consoleBerryMix reports each Console rule that lists a Berry selector. +func consoleBerryMix(rules []cssRule) []string { + var out []string + for _, r := range scopedRules(rules, consoleScope) { + for _, s := range r.selectors { + if strings.Contains(s, berryScope) { + out = append(out, fmt.Sprintf("style.css: the Console rule %q lists the Berry selector %q", strings.Join(r.selectors, ", "), s)) + } + } + } + return out +} + +// berryCards are the ten per-card accent tokens (--accent-) of the palette blocks. +var berryCards = []string{"system", "updates", "uptime", "cpu", "load", "temperature", "memory", "disks", "network", "openhab"} + +// berryNamedAccentRules returns the Berry rules (as selector text) that read a +// per-card accent token (var(--accent-)): Berry has one accent, so its +// rules read --accent or --card-accent only. +func berryNamedAccentRules(rules []cssRule) []string { + var out []string + for _, r := range scopedRules(rules, berryScope) { + for _, d := range r.decls { + if strings.Contains(d.value, "var(--accent-") { + out = append(out, strings.Join(r.selectors, ", ")+" { "+d.prop+" }") + } + } + } + return out +} + +// TestStyleCSS_BerryAccent_AC3 guards Berry's single accent: every +// --accent- token of its three blocks equals the block's --accent, the 32 px +// chip keeps var(--card-accent), the logo, the Updates button, the primary +// dialog buttons and the footer link take var(--accent), and no Berry rule +// names an --accent- token. +func TestStyleCSS_BerryAccent_AC3(t *testing.T) { + rules := parseCSSRules(readAsset(t, "style.css")) + + t.Run("AC3 every card accent token of Berry's blocks equals --accent", func(t *testing.T) { + light, dark, media := themeSelectors("berry", false) + for _, sel := range []string{light, dark, media} { + checkAccentBlock(t, rules, sel) + } + }) + t.Run("AC3 the chip keeps the card accent and the accent surfaces take --accent", func(t *testing.T) { + checkWants(t, rules, berryScope, []cssWant{ + {[]string{".card-icon"}, "color", "var(--card-accent)"}, + {[]string{".logo-tile"}, "background", "var(--accent)"}, + {[]string{".updates-button"}, "background", "var(--accent)"}, + {[]string{".apikey-submit"}, "background", "var(--accent)"}, + {[]string{"footer a"}, "color", "var(--accent)"}, + }, false) + }) + t.Run("AC3 the active range button keeps its accent under Berry's secondary-button rule", func(t *testing.T) { + // A Berry rule for .range-button (specificity 0,3,0) beats Clear's + // .range-button.active (0,2,0), so Berry must restate the active pill. + checkWants(t, rules, berryScope, []cssWant{ + {[]string{".range-button.active"}, "background", "var(--accent)"}, + {[]string{".range-button.active"}, "color", "var(--on-accent)"}, + }, true) + }) + t.Run("AC3 no Berry rule names a per-card accent token", func(t *testing.T) { + checkNoNamedAccent(t, rules) + }) + t.Run("AC3 the checker reports a per-card accent read", func(t *testing.T) { + fixture := parseCSSRules(berryScope + " .a { color: var(--accent-cpu); }\n" + berryScope + " .b { color: var(--accent); }") + if got := berryNamedAccentRules(fixture); len(got) != 1 { + t.Errorf("berryNamedAccentRules(fixture) = %v, want one problem", got) + } + }) +} + +func checkAccentBlock(t *testing.T, rules []cssRule, sel string) { + t.Helper() + block, found := blockTokens(rules, sel) + if found == 0 { + t.Errorf("style.css: no block %s", sel) + return + } + for _, card := range berryCards { + if got, want := block["--accent-"+card], block["--accent"]; want == "" || normCSS(got) != normCSS(want) { + t.Errorf("style.css: %s { --accent-%s } = %q, want --accent %q", sel, card, got, want) + } + } +} + +func checkNoNamedAccent(t *testing.T, rules []cssRule) { + t.Helper() + if len(scopedRules(rules, berryScope)) == 0 { + t.Fatal("style.css: no Berry rule") + } + for _, p := range berryNamedAccentRules(rules) { + t.Errorf("style.css: %s reads an --accent- token, want --accent or --card-accent", p) + } +} diff --git a/internal/web/theme_test.go b/internal/web/theme_test.go index d632a68..a851454 100644 --- a/internal/web/theme_test.go +++ b/internal/web/theme_test.go @@ -770,6 +770,8 @@ var newDrawingReads = map[string]string{ "--spark-line-width": "Number", "--gauge-width": "Number", "--spark-shape": "Keyword", "--spark-fill": "Keyword", "--spark-dot": "Keyword", "--spark-grid": "Keyword", "--gauge-cap": "Keyword", + // Feature 220: the ring shape word and the sparkline dot diameter. + "--gauge-shape": "Keyword", "--spark-dot-size": "Number", } // keywordReads returns the allowed words of every themeKeyword read of the canvas scripts, by property. @@ -805,10 +807,10 @@ func numberReads(t *testing.T) map[string][2]float64 { return out } -// themeBlockSelectors returns the light, explicit dark and OS dark selectors of the themes clear and console. +// themeBlockSelectors returns the light, explicit dark and OS dark selectors of the themes clear, console and berry. func themeBlockSelectors() map[string][3]string { out := map[string][3]string{} - for _, id := range []string{"clear", "console"} { + for _, id := range []string{"clear", "console", "berry"} { light, dark, media := themeSelectors(id, id == "clear") out[id] = [3]string{light, dark, media} } @@ -898,7 +900,7 @@ func checkKeywordLists(t *testing.T, rules []cssRule, fallbacks map[string]strin func checkNumberBounds(t *testing.T, rules []cssRule) { t.Helper() numbers := numberReads(t) - for _, prop := range []string{"--spark-line-width", "--gauge-width"} { + for _, prop := range []string{"--spark-line-width", "--gauge-width", "--spark-dot-size"} { bounds, ok := numbers[prop] if !ok { t.Errorf("%s: no themeNumber read found", prop) @@ -955,14 +957,16 @@ func checkOkFillHex(t *testing.T, rules []cssRule, fallbacks map[string]string) // TestThemeRegistry_HasConsole_AC1 guards the registry entry of feature 219: // Console follows Clear with the id the stylesheet and the stored choice use // and the name the picker shows. The picker, the stored-theme and the -// attribute tests run over the registry, so this entry reaches them. +// attribute tests run over the registry, so this entry reaches them. Later +// themes (Berry, feature 220) follow Console; the exact list is +// TestThemeRegistry_HasBerry_AC1's. func TestThemeRegistry_HasConsole_AC1(t *testing.T) { themes := parseThemeRegistry(readAsset(t, "theme-init.js")) t.Run("AC1 Console is the second entry after Clear", func(t *testing.T) { want := []themeEntry{{"clear", "Clear"}, {"console", "Console"}} - if !slices.Equal(themes, want) { - t.Errorf("theme-init.js registry = %v, want %v", themes, want) + if len(themes) < len(want) || !slices.Equal(themes[:len(want)], want) { + t.Errorf("theme-init.js registry = %v, want it to start with %v", themes, want) } }) @@ -973,6 +977,52 @@ func TestThemeRegistry_HasConsole_AC1(t *testing.T) { }) } +// TestThemeRegistry_HasBerry_AC1 guards the registry entry of feature 220 +// (issue 220, AC1): Berry is the third theme, id `berry`, name "Berry". The +// picker and the stored-choice code run over the registry, so the entry makes +// it a radio option and lets a stored `berry` apply before the first paint; a +// stored value that is not exactly a registered id keeps meaning Clear (E8). +func TestThemeRegistry_HasBerry_AC1(t *testing.T) { + initJS := readAsset(t, "theme-init.js") + themes := parseThemeRegistry(initJS) + + t.Run("AC1 the registry is exactly Clear, Console, Berry in that order", func(t *testing.T) { + want := []themeEntry{{"clear", "Clear"}, {"console", "Console"}, {"berry", "Berry"}} + if !slices.Equal(themes, want) { + t.Errorf("theme-init.js registry = %v, want %v", themes, want) + } + }) + + t.Run("AC1 only an exact registered id is applied, so Berry or 'berry ' stays Clear", func(t *testing.T) { + checkExactIDMatch(t, themes, initJS) + }) + + t.Run("AC1 the picker lists every registry entry as a radio option", func(t *testing.T) { + requireContains(t, "buildStylePicker", jsFunctionBody(readAsset(t, "app.js"), "function buildStylePicker("), + "for (const theme of PIMONITOR_THEMES)", "type = 'radio'", "theme.name") + }) +} + +// registeredID reports whether v is exactly the id of a registry entry. +func registeredID(themes []themeEntry, v string) bool { + return slices.ContainsFunc(themes, func(th themeEntry) bool { return th.id == v }) +} + +// checkExactIDMatch checks that only the exact id berry matches the registry and that theme-init.js holds no id literal. +func checkExactIDMatch(t *testing.T, themes []themeEntry, initJS string) { + t.Helper() + for v, want := range map[string]bool{"berry": true, "Berry": false, "berry ": false, " berry": false, "BERRY": false, "": false} { + if got := registeredID(themes, v); got != want { + t.Errorf("registeredID(%q) = %v, want %v", v, got, want) + } + } + iife := themeInitIIFE(initJS) + requireContains(t, "theme-init.js IIFE", iife, "PIMONITOR_THEMES", "dataset.style = ") + if strings.Contains(iife, "'berry'") { + t.Error("theme-init.js IIFE: unexpected 'berry' literal, the stored choice is matched against the registry") + } +} + // TestAppJS_ThemeSwitchRedraws_AC10 guards that switching the theme or the // mode restyles the page through the attributes and redraws every canvas // widget without a reload: both switches end in repaintCanvases, which