From 8f82aa1d67151dc89f4b1bb40317fec1894344b6 Mon Sep 17 00:00:00 2001 From: dborup Date: Fri, 27 Nov 2026 12:10:01 +0100 Subject: [PATCH 1/2] feat(live): scope palette and legend window in the customizer (#882 M2) Theme keys scope1-12, scopeNone, scopeUnknown and scopeOther (--scope-*) in THEME_CSS_MAP and THEME_COLOR_KEYS, with light and dark values in every theme preset (the stylesheet palette, so a preset pick changes nothing). Each colourblind preset carries a light and a dark scope palette (--mc-scope--*), read by style.css before the M1 default; a user pick is set inline only when it differs from the default, so a preset pick never hides the colourblind palette. Display > Live scope legend: minutes listed (1-60, default 15) and rows (1-12, default 12), per browser in the liveScope section, by the rule LiveScopeColor.SETTINGS; built with createElement. Live re-reads them on each legend render and retitles "SCOPES (last N min)". The cap of 64 stays fixed. Relates to #882 Co-Authored-By: Claude Opus 5.5 --- docs/CUSTOMIZATION.md | 1 + public/cb-presets.js | 72 ++++- public/customize-v2.js | 236 ++++++++++++++++- public/live-scope-color.js | 45 +++- public/live.js | 33 ++- public/style.css | 95 +++---- scripts/e2e-shards.json | 1 + test-882-m2-scope-customizer-e2e.js | 386 +++++++++++++++++++++++++++ test-882-m2-scope-customizer.js | 395 ++++++++++++++++++++++++++++ test-all.sh | 1 + test-live-scope-color.js | 14 +- 11 files changed, 1205 insertions(+), 74 deletions(-) create mode 100644 test-882-m2-scope-customizer-e2e.js create mode 100644 test-882-m2-scope-customizer.js diff --git a/docs/CUSTOMIZATION.md b/docs/CUSTOMIZATION.md index 27676fd6f..28034575f 100644 --- a/docs/CUSTOMIZATION.md +++ b/docs/CUSTOMIZATION.md @@ -208,6 +208,7 @@ Some of the customizer's Display settings belong to an optional map layer and on - **Ancient Monuments**: the protected ancient monuments overlay and its Path profile warning. See [ancient-monuments.md](ancient-monuments.md). - **Live Moments**: the Live page's moment cards, only while the operator has `moments.enabled`. `moments.enabled` (default `true`) is whether the Live page starts with them (a `?moments=` link and your own last choice on the Live page still win until Reset All); `moments.visibleCards` (1 to 5, default 3, desktop only: a phone shows one); `moments.dwellSeconds` (3 to 30, default 8) is how long a card stays; `moments.showNewNode`, `showBackOnline`, `showRecordLink` and `showBusiest` (default `true`) switch a kind off. The operator sets the defaults with `moments.display` in `config.json` (see above). The card fill and the four kind accents are the theme keys `momentCardBg`, `momentNewNode`, `momentBackOnline`, `momentRecordLink` and `momentBusiest` (CSS `--moment-*`), and the accents follow the colourblind preset. The operator's thresholds and rate stay in `config.json`. See [moments.md](moments.md). - **Live kiosk**: how a TV or wall screen running `#/live?kiosk=1` looks in this browser. `kiosk.scale` is the text and tile size: `auto` (the default: picked by the screen's size, 1 up to 2) or a fixed `1`, `1.25`, `1.5` or `2`. `kiosk.safeInsetVmin` is the margin kept clear at the screen edges for TV overscan, in % of the screen's short side, 0 to 10 (default 3). Set them once in the screen's own browser, outside kiosk, before opening the kiosk link (a kiosk screen hides the customizer). Your browser's value wins over the operator's `kiosk` preset in `config.json` (below), which wins over the defaults; a value equal to the operator's is not stored. A running kiosk takes a change at once. In an exported file this section is per browser: placed on a server as `theme.json` it is ignored there, so put the operator's values in `config.json`. +- **Live scope legend**: the SCOPES list on the Live page with "Color by scope" on (always offered). `liveScope.windowMinutes` (1 to 60, default 15) is how long a scope stays listed, and keeps its colour slot, after its last packet; `liveScope.legendRows` (1 to 12, default 12) is how many of the most recent scopes are listed, the rest showing as "+N more". They apply to this browser only. The colours are the theme keys `scope1` to `scope12` (the 12 slots a scope name is given), `scopeNone` (no scope), `scopeUnknown` (scoped, region not known) and `scopeOther` (beyond 12 active scopes), CSS `--scope-*`, under Theme → **Live scope colours** with a light and a dark value. Every theme preset keeps the default palette; a colourblind preset brings its own for each mode, and your own colour wins over both. - **Oblique Photos**: how the oblique aerial photo (Skråfoto) viewer opens, only while the server offers the photos. `skraafoto.direction` is the first photo: `auto` (the default: across the line when opened from a Path profile, otherwise north), `north`, `east`, `south`, `west` or `nadir`; a shared link's direction still wins. `skraafoto.zoom` is `zoomed` (the default: each new photo opens on the crop around the point, where the point is in the photo, otherwise on the whole photo) or `overview` (the whole photo first). `skraafoto.lineOfSight` (default `true`) draws the line of sight from a Path profile; this row is shown only with the Path profile tool. These are viewer settings; the server's `map.skraafoto` config is not part of the customizer. - **Predicted reach**: the default environment loss of the Map's Predicted reach panel (#968), only while the server offers the predicted reach. `reach.environmentLossDb` (0 to 60 dB, empty by default) is the buildings, trees and other clutter the terrain model does not include. Empty means the operator's `map.coverage.environmentLossDb` in `config.json` (default 25 dB). A link's own value (`renv`) still wins, and the panel's Reset returns to your default. It stays in the browser: it is never sent to the server and changes no request. Like the other sections here it is a per-browser value: a `theme.json` on the server ignores it, so operators set theirs in `config.json`. diff --git a/public/cb-presets.js b/public/cb-presets.js index 266ddafa3..a75245a08 100644 --- a/public/cb-presets.js +++ b/public/cb-presets.js @@ -22,6 +22,8 @@ var DATA_ATTR = 'data-cb-preset'; var MOMENT_KINDS = ['newNode', 'backOnline', 'recordLink', 'busiest']; // newNode -> --mc-moment-new-node + // #882 M2 — Live scope colours: --mc-scope-{light|dark}-{1..12|none|unknown|other}. + var SCOPE_SUFFIXES = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', 'none', 'unknown', 'other']; function _momentVar(k) { return '--mc-moment-' + k.replace(/[A-Z]/g, function (c) { return '-' + c.toLowerCase(); }); } // ── Palettes ──────────────────────────────────────────────────────────── @@ -56,7 +58,16 @@ routeRamp: ['#440154', '#3b528b', '#21918c', '#5ec962', '#fde725'], // #881 M3 — the Live Moments kind accents (icon + stripe), each >= 3:1 // against the light and the dark card (test-881-m3-theme-tokens.js). - momentAccents: { newNode: '#009E73', backOnline: '#2E86C1', recordLink: '#B8578A', busiest: '#D55E00' } + momentAccents: { newNode: '#009E73', backOnline: '#2E86C1', recordLink: '#B8578A', busiest: '#D55E00' }, + // #882 M2 — Live scope colours, slots 1-12 then none / unknown / other, + // one list per base-map mode: the stylesheet palette (Okabe-Ito based), so this preset changes nothing. + // Each slot >= 3:1 on the map tile (test-882-m2-scope-customizer.js). + scopePalette: { + light: ['#0072b2', '#009e73', '#b35c00', '#7e3fa0', '#a8780b', '#00838f', '#b0306f', '#4b5eaa', '#5e8b2f', '#8b4513', '#c026d3', '#6d6d00', + '#a1a1aa', '#57534e', '#111827'], + dark: ['#3d8bfd', '#3fd7a5', '#f0a03c', '#c49be0', '#e6c34a', '#4dd0e1', '#f06292', '#8c9eff', '#a5d66b', '#d7a07a', '#e879f9', '#dce775', + '#6b7280', '#c4b5a5', '#f8fafc'] + } }, { id: 'deut', @@ -85,7 +96,16 @@ routeRamp: ['#0d0887', '#7e03a8', '#cc4778', '#f89540', '#f0f921'], // #881 M3 — the Live Moments kind accents (icon + stripe), each >= 3:1 // against the light and the dark card (test-881-m3-theme-tokens.js). - momentAccents: { newNode: '#785EF0', backOnline: '#648FFF', recordLink: '#DC267F', busiest: '#FE6100' } + momentAccents: { newNode: '#785EF0', backOnline: '#648FFF', recordLink: '#DC267F', busiest: '#FE6100' }, + // #882 M2 — Live scope colours, slots 1-12 then none / unknown / other, + // one list per base-map mode: blue / orange / purple / amber axes, lightness-separated (red-green safe). + // Each slot >= 3:1 on the map tile (test-882-m2-scope-customizer.js). + scopePalette: { + light: ['#2F5FD0', '#C25000', '#6A3FC8', '#8F6400', '#B0175E', '#1D3D8F', '#6E4300', '#4B2A8A', '#C2338A', '#00607A', '#7D4F94', '#A33500', + '#a1a1aa', '#57534e', '#111827'], + dark: ['#648FFF', '#FE6100', '#A08CFF', '#FFB000', '#DC267F', '#9DB8FF', '#FFD27A', '#C9B8FF', '#FF8CC6', '#5CC8E6', '#E0A3FF', '#FF9E7A', + '#6b7280', '#c4b5a5', '#f8fafc'] + } }, { id: 'prot', @@ -112,7 +132,16 @@ routeRamp: ['#0d0887', '#7e03a8', '#cc4778', '#f89540', '#f0f921'], // #881 M3 — the Live Moments kind accents (icon + stripe), each >= 3:1 // against the light and the dark card (test-881-m3-theme-tokens.js). - momentAccents: { newNode: '#785EF0', backOnline: '#648FFF', recordLink: '#DC267F', busiest: '#FE6100' } + momentAccents: { newNode: '#785EF0', backOnline: '#648FFF', recordLink: '#DC267F', busiest: '#FE6100' }, + // #882 M2 — Live scope colours, slots 1-12 then none / unknown / other, + // one list per base-map mode: the deut palette: the same blue / orange / purple / amber axes. + // Each slot >= 3:1 on the map tile (test-882-m2-scope-customizer.js). + scopePalette: { + light: ['#2F5FD0', '#C25000', '#6A3FC8', '#8F6400', '#B0175E', '#1D3D8F', '#6E4300', '#4B2A8A', '#C2338A', '#00607A', '#7D4F94', '#A33500', + '#a1a1aa', '#57534e', '#111827'], + dark: ['#648FFF', '#FE6100', '#A08CFF', '#FFB000', '#DC267F', '#9DB8FF', '#FFD27A', '#C9B8FF', '#FF8CC6', '#5CC8E6', '#E0A3FF', '#FF9E7A', + '#6b7280', '#c4b5a5', '#f8fafc'] + } }, { id: 'trit', @@ -147,7 +176,16 @@ routeRamp: ['#440154', '#3b528b', '#21918c', '#5ec962', '#fde725'], // #881 M3 — the Live Moments kind accents (icon + stripe), each >= 3:1 // against the light and the dark card (test-881-m3-theme-tokens.js). - momentAccents: { newNode: '#2A8F4C', backOnline: '#C04F7F', recordLink: '#B45AA6', busiest: '#CC6677' } + momentAccents: { newNode: '#2A8F4C', backOnline: '#C04F7F', recordLink: '#B45AA6', busiest: '#CC6677' }, + // #882 M2 — Live scope colours, slots 1-12 then none / unknown / other, + // one list per base-map mode: Tol muted extended: rose / green / wine / teal (blue-yellow safe). + // Each slot >= 3:1 on the map tile (test-882-m2-scope-customizer.js). + scopePalette: { + light: ['#AA3344', '#117733', '#882255', '#7A6A00', '#AA4499', '#44706A', '#5E6B00', '#332288', '#006E8A', '#994455', '#666633', '#B8572A', + '#a1a1aa', '#57534e', '#111827'], + dark: ['#EE8899', '#44BB99', '#CC6699', '#DDCC77', '#DD88CC', '#88CCCC', '#BBCC33', '#9988EE', '#66CCEE', '#EEAA88', '#CCCC88', '#E0B0FF', + '#6b7280', '#c4b5a5', '#f8fafc'] + } }, { id: 'achromat', @@ -195,7 +233,16 @@ routeRamp: ['#222222', '#555555', '#888888', '#bbbbbb', '#eeeeee'], // #881 M3 — the Live Moments kind accents (icon + stripe), each >= 3:1 // against the light and the dark card (test-881-m3-theme-tokens.js). - momentAccents: { newNode: '#777777', backOnline: '#858585', recordLink: '#6f6f6f', busiest: '#8f8f8f' } + momentAccents: { newNode: '#777777', backOnline: '#858585', recordLink: '#6f6f6f', busiest: '#8f8f8f' }, + // #882 M2 — Live scope colours, slots 1-12 then none / unknown / other, + // one list per base-map mode: a luminance ramp, darkest first on light tiles, lightest first on dark. + // Each slot >= 3:1 on the map tile (test-882-m2-scope-customizer.js). + scopePalette: { + light: ['#000000', '#1a1a1a', '#2b2b2b', '#3a3a3a', '#474747', '#525252', '#5c5c5c', '#666666', '#6e6e6e', '#767676', '#7e7e7e', '#858585', + '#a1a1aa', '#57534e', '#111827'], + dark: ['#ffffff', '#f0f0f0', '#e0e0e0', '#d1d1d1', '#c2c2c2', '#b3b3b3', '#a6a6a6', '#999999', '#8c8c8c', '#808080', '#757575', '#6b6b6b', + '#6b7280', '#c4b5a5', '#f8fafc'] + } } ]; @@ -303,6 +350,15 @@ if (ma[k]) style.setProperty(_momentVar(k), ma[k]); else style.removeProperty(_momentVar(k)); }); + // #882 M2 — Live scope colours per mode; style.css reads them through + // --scope-* so a customizer colour still wins. + var sp = p.scopePalette; + ['light', 'dark'].forEach(function (mode) { + SCOPE_SUFFIXES.forEach(function (sx, i) { + if (sp && sp[mode] && sp[mode][i]) style.setProperty('--mc-scope-' + mode + '-' + sx, sp[mode][i]); + else style.removeProperty('--mc-scope-' + mode + '-' + sx); + }); + }); // #1407 — ROLE_COLORS / ROLE_STYLE are now live getters in roles.js // that read --mc-role-* directly, so no explicit sync is needed. The // pre-#1407 code path kept them in sync as a workaround for the static @@ -354,6 +410,9 @@ for (var hj = 1; hj <= 5; hj++) style.removeProperty('--mc-heat-' + mode + '-' + hj); }); MOMENT_KINDS.forEach(function (k) { style.removeProperty(_momentVar(k)); }); + ['light', 'dark'].forEach(function (mode) { + SCOPE_SUFFIXES.forEach(function (sx) { style.removeProperty('--mc-scope-' + mode + '-' + sx); }); + }); } if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof window.CustomEvent === 'function') { try { window.dispatchEvent(new window.CustomEvent('cb-preset-changed', { detail: { id: null } })); } catch (e) {} @@ -397,7 +456,8 @@ TILE_LIGHT: TILE_LIGHT, TILE_DARK: TILE_DARK }, - STORAGE_KEY: STORAGE_KEY + STORAGE_KEY: STORAGE_KEY, + SCOPE_SUFFIXES: SCOPE_SUFFIXES }; if (typeof window !== 'undefined') window.MeshCorePresets = api; if (typeof module !== 'undefined') module.exports = api; diff --git a/public/customize-v2.js b/public/customize-v2.js index ecb878cde..d6d4377e7 100644 --- a/public/customize-v2.js +++ b/public/customize-v2.js @@ -36,8 +36,8 @@ 'meshcore-live-heatmap-opacity' ]; - var VALID_SECTIONS = ['branding', 'theme', 'themeDark', 'nodeColors', 'typeColors', 'home', 'timestamps', 'heatmapOpacity', 'liveHeatmapOpacity', 'distanceUnit', 'favorites', 'myNodes', 'markerStroke', 'terrain', 'masts', 'dhmOverlays', 'heritage', 'skraafoto', 'moments', 'reach', 'kiosk']; - var OBJECT_SECTIONS = ['branding', 'theme', 'themeDark', 'nodeColors', 'typeColors', 'home', 'timestamps', 'markerStroke', 'terrain', 'masts', 'dhmOverlays', 'heritage', 'skraafoto', 'moments', 'reach', 'kiosk']; + var VALID_SECTIONS = ['branding', 'theme', 'themeDark', 'nodeColors', 'typeColors', 'home', 'timestamps', 'heatmapOpacity', 'liveHeatmapOpacity', 'distanceUnit', 'favorites', 'myNodes', 'markerStroke', 'terrain', 'masts', 'dhmOverlays', 'heritage', 'skraafoto', 'moments', 'reach', 'kiosk', 'liveScope']; + var OBJECT_SECTIONS = ['branding', 'theme', 'themeDark', 'nodeColors', 'typeColors', 'home', 'timestamps', 'markerStroke', 'terrain', 'masts', 'dhmOverlays', 'heritage', 'skraafoto', 'moments', 'reach', 'kiosk', 'liveScope']; var SCALAR_SECTIONS = ['heatmapOpacity', 'liveHeatmapOpacity']; var DISTANCE_UNIT_VALUES = ['km', 'mi', 'auto']; @@ -75,6 +75,12 @@ momentBusiest: '--moment-busiest', // #883 M2 — the Live kiosk big-number tiles: the fill and the numbers. kioskTileBg: '--kiosk-tile-bg', kioskNumber: '--kiosk-number', + // #882 M2 — the Live "Color by scope" palette: 12 slots, then no scope, + // unknown scope and the overflow colour (public/live-scope-color.js). + scope1: '--scope-1', scope2: '--scope-2', scope3: '--scope-3', scope4: '--scope-4', + scope5: '--scope-5', scope6: '--scope-6', scope7: '--scope-7', scope8: '--scope-8', + scope9: '--scope-9', scope10: '--scope-10', scope11: '--scope-11', scope12: '--scope-12', + scopeNone: '--scope-none', scopeUnknown: '--scope-unknown', scopeOther: '--scope-other', font: '--font', mono: '--mono' }; @@ -110,11 +116,31 @@ }); } + // #882 M2 — the scope palette. A value that differs from the stylesheet + // default for the mode is set on , so it wins over style.css and a + // colourblind preset (--mc-scope-*). One equal to the default (every theme + // preset's own) or none is removed, so the stylesheet chain decides and a + // cleared pick goes back without a reload. + function _applyScopeCSS(root, themeSection, dark) { + var defs = SCOPE_PRESET_COLORS[dark ? 'themeDark' : 'theme']; + SCOPE_COLOR_KEYS.forEach(function (k, i) { + var v = themeSection && themeSection[k]; + if (v && String(v).toLowerCase() !== defs[i]) root.setProperty(THEME_CSS_MAP[k], v); + else root.removeProperty(THEME_CSS_MAP[k]); + }); + } + // #881 M3 — likewise: the kind accents follow the colourblind preset // (cb-presets.js momentAccents), not the theme preset. var MOMENTS_COLOR_KEYS = ['momentCardBg', 'momentNewNode', 'momentBackOnline', 'momentRecordLink', 'momentBusiest']; // #883 M2 — likewise outside preset detection: no preset defines them. var KIOSK_COLOR_KEYS = ['kioskTileBg', 'kioskNumber']; + // #882 M2 — the Live scope palette. Unlike the groups above these ARE in + // THEME_COLOR_KEYS: every theme preset carries a light and a dark value + // (SCOPE_PRESET_COLORS, below PRESETS). A colourblind preset's palette + // comes through style.css (--mc-scope-*), see _applyScopeCSS. + var SCOPE_COLOR_KEYS = ['scope1', 'scope2', 'scope3', 'scope4', 'scope5', 'scope6', 'scope7', 'scope8', + 'scope9', 'scope10', 'scope11', 'scope12', 'scopeNone', 'scopeUnknown', 'scopeOther']; var THEME_COLOR_KEYS = Object.keys(THEME_CSS_MAP).filter(function (k) { return k !== 'font' && k !== 'mono' && TERRAIN_COLOR_KEYS.indexOf(k) === -1 && MASTS_COLOR_KEYS.indexOf(k) === -1 && @@ -367,6 +393,25 @@ } }; + // #882 M2 — the Live scope palette of every theme preset, light and dark. + // One palette for all of them: it is the stylesheet's (style.css --scope-*, + // Okabe-Ito based), so picking a theme preset leaves the scope colours as + // they were, and _applyScopeCSS keeps a value equal to it off , where + // it would hide a colourblind preset's palette. The order is + // SCOPE_COLOR_KEYS; test-882-m2-scope-customizer.js pins it to style.css. + var SCOPE_PRESET_COLORS = { + theme: ['#0072b2', '#009e73', '#b35c00', '#7e3fa0', '#a8780b', '#00838f', '#b0306f', '#4b5eaa', + '#5e8b2f', '#8b4513', '#c026d3', '#6d6d00', '#a1a1aa', '#57534e', '#111827'], + themeDark: ['#3d8bfd', '#3fd7a5', '#f0a03c', '#c49be0', '#e6c34a', '#4dd0e1', '#f06292', '#8c9eff', + '#a5d66b', '#d7a07a', '#e879f9', '#dce775', '#6b7280', '#c4b5a5', '#f8fafc'] + }; + Object.keys(PRESETS).forEach(function (id) { + ['theme', 'themeDark'].forEach(function (sec) { + if (!PRESETS[id][sec]) PRESETS[id][sec] = {}; + SCOPE_COLOR_KEYS.forEach(function (k, i) { PRESETS[id][sec][k] = SCOPE_PRESET_COLORS[sec][i]; }); + }); + }); + // ── Labels, hints, emojis (carried from v1) ── var THEME_LABELS = { @@ -388,6 +433,9 @@ momentCardBg: 'Card Fill', momentNewNode: 'New Node', momentBackOnline: 'Back Online', momentRecordLink: 'Record Link', momentBusiest: 'Busiest Repeater', kioskTileBg: 'Tile Fill', kioskNumber: 'Numbers', + scope1: 'Scope 1', scope2: 'Scope 2', scope3: 'Scope 3', scope4: 'Scope 4', scope5: 'Scope 5', scope6: 'Scope 6', + scope7: 'Scope 7', scope8: 'Scope 8', scope9: 'Scope 9', scope10: 'Scope 10', scope11: 'Scope 11', scope12: 'Scope 12', + scopeNone: 'No Scope', scopeUnknown: 'Unknown Scope', scopeOther: 'Other Scopes', font: 'Body Font', mono: 'Mono Font' }; @@ -428,6 +476,16 @@ momentBusiest: 'Live: the icon and stripe of a busiest-repeater moment', kioskTileBg: 'Live kiosk (TV mode): the background of the big-number tiles', kioskNumber: 'Live kiosk (TV mode): the big numbers in the tiles', + scope1: 'Live, Color by scope: one of 12 colours a scope name is given (lines, feed stripe, legend)', + scope2: 'Live, Color by scope: palette slot 2', scope3: 'Live, Color by scope: palette slot 3', + scope4: 'Live, Color by scope: palette slot 4', scope5: 'Live, Color by scope: palette slot 5', + scope6: 'Live, Color by scope: palette slot 6', scope7: 'Live, Color by scope: palette slot 7', + scope8: 'Live, Color by scope: palette slot 8', scope9: 'Live, Color by scope: palette slot 9', + scope10: 'Live, Color by scope: palette slot 10', scope11: 'Live, Color by scope: palette slot 11', + scope12: 'Live, Color by scope: palette slot 12', + scopeNone: 'Live, Color by scope: packets without a scope (plain flood and direct)', + scopeUnknown: 'Live, Color by scope: scoped packets whose region is not known (T?)', + scopeOther: 'Live, Color by scope: scopes beyond the 12 slots while all are in use', font: 'System font stack for body text', mono: 'Monospace font for hex, code, hashes' }; @@ -685,6 +743,31 @@ else setOverride('moments', key, v); } + // ── #882 M2 — Live "Color by scope": the legend window ── + // liveScope.windowMinutes and liveScope.legendRows, per browser. The keys, + // defaults and bounds are the rule in public/live-scope-color.js + // (LiveScopeColor.SETTINGS), which the Live page reads back on + // theme-changed. That file loads after this one, hence the lazy lookup; + // without it no value is accepted. + function _liveScopeRule() { + var R = window.LiveScopeColor && window.LiveScopeColor.SETTINGS; + return R && typeof R.resolve === 'function' && typeof R.valid === 'function' ? R : null; + } + + function isValidLiveScopeSetting(key, val) { + var R = _liveScopeRule(); + return !!R && R.KEYS.indexOf(key) >= 0 && R.valid(key, val); + } + + /** The effective legend window (this section over the defaults), or null + * without the rule. */ + function liveScopeSettings(effectiveConfig) { + var R = _liveScopeRule(); + if (!R) return null; + var sec = effectiveConfig && effectiveConfig.liveScope; + return R.resolve(sec && typeof sec === 'object' ? sec : {}); + } + // ── #968 M2 — Live kiosk: the screen's text size and edge margin ── // kiosk.scale and kiosk.safeInsetVmin, per browser. The keys, steps and // bounds are the kiosk's own rule (public/live-kiosk.js, @@ -1059,6 +1142,16 @@ else console.warn('[customizer-v2] Invalid Moments setting rejected:', 'moments.' + mok, moIn[mok]); } if (Object.keys(moOut).length) clean[key] = moOut; + } else if (key === 'liveScope' && typeof delta[key] === 'object' && delta[key] !== null) { + // #882 M2 — the scope legend window, by the module's rule. + var lsIn = delta[key], lsOut = {}, lsRule = _liveScopeRule(), lsKeys = lsRule ? lsRule.KEYS : []; + for (var lsi = 0; lsi < lsKeys.length; lsi++) { + var lsk = lsKeys[lsi]; + if (!_own(lsIn, lsk) || lsIn[lsk] == null) continue; + if (isValidLiveScopeSetting(lsk, lsIn[lsk])) lsOut[lsk] = lsIn[lsk]; + else console.warn('[customizer-v2] Invalid Live scope setting rejected:', 'liveScope.' + lsk, lsIn[lsk]); + } + if (Object.keys(lsOut).length) clean[key] = lsOut; } else if (key === 'kiosk' && typeof delta[key] === 'object' && delta[key] !== null) { // #968 M2 — the kiosk scale and inset, by the kiosk's rule; the // operator-only keys (tour, tiles, …) are never the viewer's. @@ -1210,9 +1303,11 @@ // Apply theme color/font CSS variables for (var key in THEME_CSS_MAP) { if (HEAT_COLOR_KEYS.indexOf(key) !== -1) continue; // _applyHeatCSS + if (SCOPE_COLOR_KEYS.indexOf(key) !== -1) continue; // _applyScopeCSS if (themeSection[key]) root.setProperty(THEME_CSS_MAP[key], themeSection[key]); } _applyHeatCSS(root, effectiveConfig, userOverrides, dark); + _applyScopeCSS(root, themeSection, dark); // Logo brand colors mirror --accent / --accent-hover ONLY when an // operator has actually overridden them via the customizer. We check @@ -1710,6 +1805,20 @@ } } } + // #882 M2 — liveScope: two bounded whole numbers. + if (key === 'liveScope' && typeof obj[key] === 'object' && obj[key] !== null) { + var lsrule = _liveScopeRule(); + for (var lssk in obj[key]) { + if (!_own(obj[key], lssk)) continue; + if (lsrule && lsrule.KEYS.indexOf(lssk) === -1) { + console.warn('[customizer-v2] Unknown liveScope key in import:', lssk); + } else if (!isValidLiveScopeSetting(lssk, obj[key][lssk])) { + var lslim = lsrule && lsrule.LIMITS[lssk]; + errors.push('Invalid Live scope setting: liveScope.' + lssk + ' = "' + obj[key][lssk] + '" \u2014 must be ' + + (lslim ? 'a whole number ' + lslim[0] + '-' + lslim[1] : 'unavailable without the Live page')); + } + } + } // #968 M2 — kiosk: a scale step and a bounded inset. if (key === 'kiosk' && typeof obj[key] === 'object' && obj[key] !== null) { var krule = _kioskRule(); @@ -1971,7 +2080,7 @@ { id: 'theme', glyph: 'ph:palette', title: 'Theme', badge: _tabBadge(isDarkMode() ? 'themeDark' : 'theme') }, { id: 'nodes', glyph: 'ph:target', title: 'Colors', badge: (function () { var n = _countOverrides('nodeColors') + _countOverrides('typeColors'); return n ? ' ' + n + '' : ''; })() }, { id: 'home', glyph: 'ph:house', title: 'Home', badge: _tabBadge('home') }, - { id: 'display', glyph: 'ph:monitor', title: 'Display', badge: (function () { var n = _countOverrides('timestamps') + _countOverrides('terrain') + _countOverrides('masts') + _countOverrides('dhmOverlays') + _countOverrides('heritage') + _countOverrides('skraafoto') + _countOverrides('reach') + _countOverrides('moments') + _countOverrides('kiosk') + (_isOverridden(null, 'distanceUnit') ? 1 : 0); return n ? ' ' + n + '' : ''; })() }, + { id: 'display', glyph: 'ph:monitor', title: 'Display', badge: (function () { var n = _countOverrides('timestamps') + _countOverrides('terrain') + _countOverrides('masts') + _countOverrides('dhmOverlays') + _countOverrides('heritage') + _countOverrides('skraafoto') + _countOverrides('reach') + _countOverrides('moments') + _countOverrides('kiosk') + _countOverrides('liveScope') + (_isOverridden(null, 'distanceUnit') ? 1 : 0); return n ? ' ' + n + '' : ''; })() }, { id: 'geofilter', glyph: 'ph:map-trifold', title: 'GeoFilter' }, { id: 'export', glyph: 'ph:download-simple', title: 'Export' } ]; @@ -2208,6 +2317,13 @@ var kck = KIOSK_COLOR_KEYS[kci]; kioskRows += _renderColorRow(kck, section, current[kck] || _cssVarValue(kck), serverCurrent[kck]); } + // #882 M2 — no server default here either: show what the page draws + // with (a colourblind preset's palette included). + var scopeRows = ''; + for (var sci = 0; sci < SCOPE_COLOR_KEYS.length; sci++) { + var sck = SCOPE_COLOR_KEYS[sci]; + scopeRows += _renderColorRow(sck, section, current[sck] || _cssVarValue(sck), serverCurrent[sck]); + } return '
' + _renderPresets() + @@ -2220,6 +2336,7 @@ '
Heat map (' + HEAT_COLOR_KEYS.length + ' options)' + heatRows + '
' + '
Live moments cards (' + MOMENTS_COLOR_KEYS.length + ' options)' + momentsRows + '
' + '
Live kiosk tiles (' + KIOSK_COLOR_KEYS.length + ' options)' + kioskRows + '
' + + '
Live scope colours (' + SCOPE_COLOR_KEYS.length + ' options)' + scopeRows + '
' + '
Fonts' + fontRows + '
' + '
'; } @@ -2487,6 +2604,7 @@ _renderReachSettings() + _renderMomentsSettings() + _renderKioskSettings() + + '
' + ''; } @@ -2810,6 +2928,81 @@ ''; } + // ── #882 M2 Live scope legend ── + // The window of the SCOPES legend on the Live page ("Color by scope"). + // Built with createElement/textContent and mounted by _renderPanel into + // the Display panel's [data-cv2-live-scope-mount], before _bindEvents wires + // the inputs and the override dots. doc: the document (a fake in tests). + function _buildLiveScopeSettings(doc) { + var R = _liveScopeRule(); + if (!R) return null; + var cur = liveScopeSettings(_getEffective()); + var el = function (tag, cls, text) { + var n = doc.createElement(tag); + if (cls) n.className = cls; + if (text) n.textContent = text; + return n; + }; + var dot = function (key) { + if (!_isOverridden('liveScope', key)) return null; + var d = el('span', 'cv2-override-dot'); + d.setAttribute('data-reset-s', 'liveScope'); + d.setAttribute('data-reset-k', key); + d.setAttribute('title', 'Reset to default'); + if (typeof doc.createElementNS === 'function') { + var NS = 'http://www.w3.org/2000/svg'; + var svg = doc.createElementNS(NS, 'svg'); + svg.setAttribute('class', 'ph-icon'); + svg.setAttribute('aria-hidden', 'true'); + var use = doc.createElementNS(NS, 'use'); + use.setAttribute('href', '/icons/phosphor-sprite.svg#ph-circle-fill'); + svg.appendChild(use); + d.appendChild(svg); + } + return d; + }; + var row = function (key, label, hint) { + var id = 'cv2-live-scope-' + key, lim = R.LIMITS[key]; + var r = el('div', 'cust-terrain-row'); + var left = el('div'); + var lab = el('label', null, label); + lab.setAttribute('for', id); + var d = dot(key); + if (d) lab.appendChild(d); + left.appendChild(lab); + left.appendChild(el('div', 'cust-hint', hint)); + var inp = el('input'); + inp.setAttribute('type', 'number'); + inp.setAttribute('id', id); + inp.setAttribute('min', String(lim[0])); + inp.setAttribute('max', String(lim[1])); + inp.setAttribute('step', '1'); + inp.setAttribute('inputmode', 'numeric'); + inp.setAttribute('data-cv2-live-scope', key); + inp.value = String(cur[key]); + r.appendChild(left); + r.appendChild(inp); + return r; + }; + var sec = el('div'); + sec.setAttribute('data-cv2-live-scope-section', ''); + var title = el('p', 'cust-section-title', 'Live scope legend'); + title.style.fontSize = '14px'; + title.style.margin = '16px 0 8px'; + var intro = el('p', 'cust-hint', 'The SCOPES list on the Live page with \u201cColor by scope\u201d on. ' + + 'The colours are under Theme \u2192 Live scope colours. These apply to this browser only.'); + intro.style.fontSize = '12px'; + intro.style.marginBottom = '8px'; + sec.appendChild(title); + sec.appendChild(intro); + var wl = R.LIMITS.windowMinutes, rl = R.LIMITS.legendRows; + sec.appendChild(row('windowMinutes', 'Minutes a scope stays listed', + 'A scope leaves the list, and frees its colour, this long after its last packet (' + wl[0] + '\u2013' + wl[1] + ', default ' + R.DEFAULTS.windowMinutes + ')')); + sec.appendChild(row('legendRows', 'Scopes listed at most', + 'The most recent ones; the rest show as \u201c+N more\u201d (' + rl[0] + '\u2013' + rl[1] + ', default ' + R.DEFAULTS.legendRows + ')')); + return sec; + } + // ── #737 Oblique photo viewer defaults ── // Shown only while the server offers the photos (its skraafoto block); // the line-of-sight row only where the Path profile tool is offered too. @@ -3450,6 +3643,9 @@ _renderGeoFilter() + _renderExport() + ''; + var lsMount = container.querySelector('[data-cv2-live-scope-mount]'); + var lsEl = lsMount ? _buildLiveScopeSettings(document) : null; + if (lsEl) lsMount.appendChild(lsEl); _bindEvents(container); } @@ -3734,6 +3930,24 @@ }); }); + // #882 M2 — Live scope legend window. A value back at its default is a + // cleared override; a bad one is put back. The Live page re-reads it on + // theme-changed (every pipeline run). + container.querySelectorAll('[data-cv2-live-scope]').forEach(function (inp) { + var key = inp.dataset.cv2LiveScope; + inp.addEventListener('change', function () { + var R = _liveScopeRule(); + if (!R) return; + var v = /^[0-9]{1,3}$/.test(inp.value) ? Number(inp.value) : undefined; + if (v === undefined || !isValidLiveScopeSetting(key, v)) { + inp.value = String(liveScopeSettings(_getEffective())[key]); + return; + } + if (v === R.DEFAULTS[key]) clearOverride('liveScope', key); + else setOverride('liveScope', key, v); + }); + }); + // #737 — oblique photo viewer defaults. A value back at its default is // a cleared override; a bad one is put back. The next viewer reads it. container.querySelectorAll('[data-cv2-skraafoto]').forEach(function (inp) { @@ -4372,6 +4586,12 @@ }); for (var ri = 0; ri < 5; ri++) rs.removeProperty('--mc-rt-ramp-' + ri); ['new-node', 'back-online', 'record-link', 'busiest'].forEach(function (k) { rs.removeProperty('--mc-moment-' + k); }); + // #882 M2 — the colourblind preset's scope palette, both modes. + ['light', 'dark'].forEach(function (mode) { + ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', 'none', 'unknown', 'other'].forEach(function (sx) { + rs.removeProperty('--mc-scope-' + mode + '-' + sx); + }); + }); ['light', 'dark'].forEach(function (mode) { for (var hn = 1; hn <= 5; hn++) rs.removeProperty('--mc-heat-' + mode + '-' + hn); }); @@ -4525,6 +4745,14 @@ // v0.2.9 review nit (#825 N1) — exposed for tests; see // test-issue-734-customizer-overlays.js (Display badge and order). renderTabs: _renderTabs, - renderDisplay: _renderDisplay + renderDisplay: _renderDisplay, + // #882 M2 — exposed for tests; see test-882-m2-scope-customizer.js. + PRESETS: PRESETS, + THEME_COLOR_KEYS: THEME_COLOR_KEYS, + SCOPE_COLOR_KEYS: SCOPE_COLOR_KEYS, + renderTheme: _renderTheme, + isValidLiveScopeSetting: isValidLiveScopeSetting, + liveScopeSettings: liveScopeSettings, + buildLiveScopeSettings: _buildLiveScopeSettings }; })(); diff --git a/public/live-scope-color.js b/public/live-scope-color.js index a763e3f8c..79a080c4a 100644 --- a/public/live-scope-color.js +++ b/public/live-scope-color.js @@ -14,8 +14,9 @@ * one. With all 12 slots held by active scopes, the next one shares the * "other" colour. The registry is an LRU capped at CAP entries. * - * Hardcoded for now (window, rows, cap); exposing them and the palette in the - * customizer is M2 (AGENTS.md rule 8). + * The legend window (minutes, rows) is a per-browser customizer setting + * (#882 M2: SETTINGS below, section liveScope); the cap stays fixed, it + * bounds memory. The palette is the --scope-* theme keys. */ 'use strict'; @@ -25,6 +26,26 @@ var WINDOW_MS = 15 * 60000; var LEGEND_ROWS = 12; var OTHER = -1; + // #882 M2 — the legend window, by the customizer's liveScope section. + // The defaults are the M0 plan; rows cannot exceed the palette slots. + var SETTINGS_DEFAULTS = { windowMinutes: 15, legendRows: LEGEND_ROWS }; + var SETTINGS_LIMITS = { windowMinutes: [1, 60], legendRows: [1, SLOTS] }; + var SETTINGS_KEYS = Object.keys(SETTINGS_DEFAULTS); + function settingValid(key, val) { + var lim = SETTINGS_LIMITS[key]; + return !!lim && typeof val === 'number' && Math.floor(val) === val && val >= lim[0] && val <= lim[1]; + } + // A section object → { windowMinutes, legendRows }, each key valid or its default. + function resolveSettings(sec) { + var out = {}; + for (var i = 0; i < SETTINGS_KEYS.length; i++) { + var k = SETTINGS_KEYS[i]; + out[k] = sec && typeof sec === 'object' && settingValid(k, sec[k]) ? sec[k] : SETTINGS_DEFAULTS[k]; + } + return out; + } + var SETTINGS = { KEYS: SETTINGS_KEYS, DEFAULTS: SETTINGS_DEFAULTS, LIMITS: SETTINGS_LIMITS, valid: settingValid, resolve: resolveSettings }; + var PALETTE_VARS = []; for (var i = 1; i <= SLOTS; i++) PALETTE_VARS.push('--scope-' + i); PALETTE_VARS.push('--scope-none', '--scope-unknown', '--scope-other'); @@ -53,12 +74,17 @@ // Session registry: Map in LRU order (oldest first), // plus slotOwner[slot] = name. Every operation is O(1) or O(SLOTS); legend() - // is O(CAP log CAP), called at most once a second. - function createRegistry() { + // is O(CAP log CAP), called at most once a second. settings: the legend + // window ({ windowMinutes, legendRows }, see SETTINGS); configure() swaps + // it at run time. + function createRegistry(settings) { var entries = new Map(); var slotOwner = new Array(SLOTS); + var cfg, windowMs; + function configure(s) { cfg = resolveSettings(s); windowMs = cfg.windowMinutes * 60000; } + configure(settings); - function active(e, now) { return !!e && now - e.lastTs <= WINDOW_MS; } + function active(e, now) { return !!e && now - e.lastTs <= windowMs; } function slotFreeFor(slot, name, now) { var owner = slotOwner[slot]; @@ -104,15 +130,16 @@ var act = []; entries.forEach(function (e, name) { if (active(e, now)) act.push({ name: name, slot: e.slot, lastTs: e.lastTs }); }); act.sort(function (a, b) { return b.lastTs - a.lastTs; }); - var rows = act.slice(0, LEGEND_ROWS).map(function (x) { return { name: x.name, slot: x.slot }; }); + var rows = act.slice(0, cfg.legendRows).map(function (x) { return { name: x.name, slot: x.slot }; }); rows.sort(function (a, b) { return a.name < b.name ? -1 : a.name > b.name ? 1 : 0; }); var more = act.length - rows.length; var sig = rows.map(function (r) { return r.name + '\u0000' + r.slot; }).join('\u0001') + '\u0002' + more; - return { rows: rows, more: more, sig: sig }; + return { rows: rows, more: more, sig: sig, windowMinutes: cfg.windowMinutes }; } return { - touch: touch, slotOf: slotOf, legend: legend, + touch: touch, slotOf: slotOf, legend: legend, configure: configure, + settings: function () { return { windowMinutes: cfg.windowMinutes, legendRows: cfg.legendRows }; }, size: function () { return entries.size; }, has: function (n) { return entries.has(n); }, }; @@ -152,7 +179,7 @@ window.LiveScopeColor = { SLOTS: SLOTS, CAP: CAP, WINDOW_MS: WINDOW_MS, LEGEND_ROWS: LEGEND_ROWS, OTHER: OTHER, - PALETTE_VARS: PALETTE_VARS, + PALETTE_VARS: PALETTE_VARS, SETTINGS: SETTINGS, STORAGE_KEY: 'meshcore-color-packets-by-scope', SCOPED_STORAGE_KEY: 'live-scoped-only', COLOR_PARAM: 'color', SCOPED_PARAM: 'scoped', diff --git a/public/live.js b/public/live.js index 4d83fa002..3fe5564a2 100644 --- a/public/live.js +++ b/public/live.js @@ -92,8 +92,14 @@ // One registry per page load, so a scope keeps its colour while the // viewer stays (session-sticky). Bounded by LiveScopeColor.CAP. let _scopeRegistry = null; + // #882 M2 — the legend window (minutes, rows) is the customizer's + // per-browser liveScope section, validated by LiveScopeColor.SETTINGS. + function scopeLegendSettings() { + const cfg = window.SITE_CONFIG && window.SITE_CONFIG.liveScope; + return window.LiveScopeColor.SETTINGS.resolve(cfg); + } function scopeRegistry() { - if (!_scopeRegistry) _scopeRegistry = window.LiveScopeColor.createRegistry(); + if (!_scopeRegistry) _scopeRegistry = window.LiveScopeColor.createRegistry(scopeLegendSettings()); return _scopeRegistry; } // The canvas needs concrete colour strings: the --scope-* variables are @@ -111,6 +117,14 @@ return _scopePalette; } function invalidateScopePalette() { _scopePalette = null; } + // A customizer change ('theme-changed'): new colours for the next lines + // (drawn lines keep theirs), the legend redrawn with the window re-read + // (its swatches are var(--scope-*), so they follow at once). + function onScopeThemeChanged() { + invalidateScopePalette(); + _scopeLegendSig = ''; + renderScopeLegend(); + } let _scopeThemeListening = false; // Scope colour of one transmission, or null when "Color by scope" is off. // touch: register the scope in the legend (live packets only; a VCR @@ -139,7 +153,7 @@ return null; } - // Legend section "SCOPES (last 15 min)": re-rendered at most once a second + // Legend section "SCOPES (last N min)": re-rendered at most once a second // while packets arrive, on the shared 60 s tick (expiry) and on a toggle, // and only touches the DOM when its rows changed. Names are untrusted // (node/config strings), so rows are built with textContent. @@ -172,13 +186,22 @@ const menu = document.getElementById('scopeLegendMenu'); const menuList = document.getElementById('scopeLegendMenuList'); if (!S || !sec || !list) return; + // The window follows the customizer even when its 'theme-changed' came + // before this page listened (boot order): re-read on every render + // (<= 1/s, two keys). The registry's touch() uses it from then on. + scopeRegistry().configure(scopeLegendSettings()); sec.hidden = !colorByScope; if (menu) menu.hidden = !colorByScope; if (!colorByScope) { _scopeLegendSig = ''; return; } const L = scopeRegistry().legend(Date.now()); - const sig = L.sig + '|' + scopedOnly; + const sig = L.sig + '|' + scopedOnly + '|' + L.windowMinutes; if (sig === _scopeLegendSig) return; _scopeLegendSig = sig; + const title = 'SCOPES (last ' + L.windowMinutes + ' min)'; + [sec, menu].forEach(function(box) { + const h = box && box.querySelector('.legend-title'); + if (h) h.textContent = title; + }); const frag = document.createDocumentFragment(); if (!L.rows.length) frag.appendChild(scopeLegendRow(null, 'No named scopes yet', 'live-scope-empty')); for (const r of L.rows) frag.appendChild(scopeLegendRow(S.paletteVar({ kind: 'named' }, r.slot), r.name)); @@ -3327,7 +3350,7 @@ // One shared 60 s tick: nodes also age out of the "Last heard" filter // here (#660), with no timer of its own. _pruneInterval = setInterval(() => { pruneStaleNodes(); applyHeardFilter(); renderScopeLegend(); }, 60000); - if (!_scopeThemeListening) { window.addEventListener('theme-changed', invalidateScopePalette); _scopeThemeListening = true; } + if (!_scopeThemeListening) { window.addEventListener('theme-changed', onScopeThemeChanged); _scopeThemeListening = true; } // Refresh relative timestamps in feed every 10 seconds (#701) _feedTimestampInterval = setInterval(function() { @@ -6343,7 +6366,7 @@ if (_heardReapplyTimer) { clearTimeout(_heardReapplyTimer); _heardReapplyTimer = null; } if (_scopeLegendTimer) { clearTimeout(_scopeLegendTimer); _scopeLegendTimer = null; } _scopeLegendSig = ''; - if (_scopeThemeListening) { window.removeEventListener('theme-changed', invalidateScopePalette); _scopeThemeListening = false; } + if (_scopeThemeListening) { window.removeEventListener('theme-changed', onScopeThemeChanged); _scopeThemeListening = false; } if (_feedTimestampInterval) { clearInterval(_feedTimestampInterval); _feedTimestampInterval = null; } stopAffinityRefresh(); // Unsubscribe rather than close: the socket belongs to app.js and the rest diff --git a/public/style.css b/public/style.css index fa8809469..af2c139d3 100644 --- a/public/style.css +++ b/public/style.css @@ -484,22 +484,25 @@ /* #882 — Live "Color by scope" palette (public/live-scope-color.js). * 12 qualitative slots, kept off pure red (foreign-origin red wins), plus * two greys that differ from each other: no scope (FLOOD/DIRECT) and - * unknown scope (route 0/3, region not resolved). Customizer: #882 M2. */ - --scope-1: #0072b2; - --scope-2: #009e73; - --scope-3: #b35c00; - --scope-4: #7e3fa0; - --scope-5: #a8780b; - --scope-6: #00838f; - --scope-7: #b0306f; - --scope-8: #4b5eaa; - --scope-9: #5e8b2f; - --scope-10: #8b4513; - --scope-11: #c026d3; - --scope-12: #6d6d00; - --scope-none: #a1a1aa; - --scope-unknown: #57534e; - --scope-other: #111827; + * unknown scope (route 0/3, region not resolved). #882 M2: a colourblind + * preset's palette for this mode (--mc-scope-light-*, cb-presets.js) wins + * over these defaults; a customizer colour (Theme > Live scope colours) + * is set inline on and wins over both. */ + --scope-1: var(--mc-scope-light-1, #0072b2); + --scope-2: var(--mc-scope-light-2, #009e73); + --scope-3: var(--mc-scope-light-3, #b35c00); + --scope-4: var(--mc-scope-light-4, #7e3fa0); + --scope-5: var(--mc-scope-light-5, #a8780b); + --scope-6: var(--mc-scope-light-6, #00838f); + --scope-7: var(--mc-scope-light-7, #b0306f); + --scope-8: var(--mc-scope-light-8, #4b5eaa); + --scope-9: var(--mc-scope-light-9, #5e8b2f); + --scope-10: var(--mc-scope-light-10, #8b4513); + --scope-11: var(--mc-scope-light-11, #c026d3); + --scope-12: var(--mc-scope-light-12, #6d6d00); + --scope-none: var(--mc-scope-light-none, #a1a1aa); + --scope-unknown: var(--mc-scope-light-unknown, #57534e); + --scope-other: var(--mc-scope-light-other, #111827); /* #880 — Live "Follow a packet". Built on theme tokens, so both dark * blocks follow without their own copies. Customizer mapping: #880 M3. */ --follow-ring: var(--accent); @@ -623,21 +626,21 @@ --shadow: rgba(0,0,0,0.5); --trace-ghost-color: #94a3b8; /* #882 — Live scope palette, dark (keep both dark blocks in sync). */ - --scope-1: #3d8bfd; - --scope-2: #3fd7a5; - --scope-3: #f0a03c; - --scope-4: #c49be0; - --scope-5: #e6c34a; - --scope-6: #4dd0e1; - --scope-7: #f06292; - --scope-8: #8c9eff; - --scope-9: #a5d66b; - --scope-10: #d7a07a; - --scope-11: #e879f9; - --scope-12: #dce775; - --scope-none: #6b7280; - --scope-unknown: #c4b5a5; - --scope-other: #f8fafc; + --scope-1: var(--mc-scope-dark-1, #3d8bfd); + --scope-2: var(--mc-scope-dark-2, #3fd7a5); + --scope-3: var(--mc-scope-dark-3, #f0a03c); + --scope-4: var(--mc-scope-dark-4, #c49be0); + --scope-5: var(--mc-scope-dark-5, #e6c34a); + --scope-6: var(--mc-scope-dark-6, #4dd0e1); + --scope-7: var(--mc-scope-dark-7, #f06292); + --scope-8: var(--mc-scope-dark-8, #8c9eff); + --scope-9: var(--mc-scope-dark-9, #a5d66b); + --scope-10: var(--mc-scope-dark-10, #d7a07a); + --scope-11: var(--mc-scope-dark-11, #e879f9); + --scope-12: var(--mc-scope-dark-12, #dce775); + --scope-none: var(--mc-scope-dark-none, #6b7280); + --scope-unknown: var(--mc-scope-dark-unknown, #c4b5a5); + --scope-other: var(--mc-scope-dark-other, #f8fafc); --section-bg: #1e1e34; } } @@ -728,21 +731,21 @@ --shadow: rgba(0,0,0,0.5); --trace-ghost-color: #94a3b8; /* #882 — Live scope palette, dark (keep both dark blocks in sync). */ - --scope-1: #3d8bfd; - --scope-2: #3fd7a5; - --scope-3: #f0a03c; - --scope-4: #c49be0; - --scope-5: #e6c34a; - --scope-6: #4dd0e1; - --scope-7: #f06292; - --scope-8: #8c9eff; - --scope-9: #a5d66b; - --scope-10: #d7a07a; - --scope-11: #e879f9; - --scope-12: #dce775; - --scope-none: #6b7280; - --scope-unknown: #c4b5a5; - --scope-other: #f8fafc; + --scope-1: var(--mc-scope-dark-1, #3d8bfd); + --scope-2: var(--mc-scope-dark-2, #3fd7a5); + --scope-3: var(--mc-scope-dark-3, #f0a03c); + --scope-4: var(--mc-scope-dark-4, #c49be0); + --scope-5: var(--mc-scope-dark-5, #e6c34a); + --scope-6: var(--mc-scope-dark-6, #4dd0e1); + --scope-7: var(--mc-scope-dark-7, #f06292); + --scope-8: var(--mc-scope-dark-8, #8c9eff); + --scope-9: var(--mc-scope-dark-9, #a5d66b); + --scope-10: var(--mc-scope-dark-10, #d7a07a); + --scope-11: var(--mc-scope-dark-11, #e879f9); + --scope-12: var(--mc-scope-dark-12, #dce775); + --scope-none: var(--mc-scope-dark-none, #6b7280); + --scope-unknown: var(--mc-scope-dark-unknown, #c4b5a5); + --scope-other: var(--mc-scope-dark-other, #f8fafc); --section-bg: #1e1e34; } diff --git a/scripts/e2e-shards.json b/scripts/e2e-shards.json index 2820cd854..a936dca55 100644 --- a/scripts/e2e-shards.json +++ b/scripts/e2e-shards.json @@ -287,6 +287,7 @@ {"file":"test-issue-189-group-caret-e2e.js","shard":3,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":1.742,"secondsByExecution":[1.542,1.622,1.648,2.362,1.606,1.669]}, {"file":"test-issue-1128-multi-viewport-e2e.js","shard":3,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":7.251,"secondsByExecution":[6.193,8.864,8.099,8.362,5.889,6.097]}, {"file":"test-live-scope-color-e2e.js","shard":3,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":45,"measurementNote":"New suite; #882 M1 Live Color by scope and Scoped only with stubbed /api/nodes and stubbed WS packets of every class (named scope on route 0 and 3, unknown scope, FLOOD, DIRECT, foreign origin): route and feed-stripe colours from the --scope-* variables, foreign red wins, legend rows sorted with a hostile name rendered as text, Scoped only hides FLOOD/DIRECT and keeps unknown scope, scope off restores the hash checkbox and the type colour, ?color= and ?scoped= deep links and storage, the dark palette after a theme switch, and a real-tap walk at 375x560 where the SCOPES list is read in the settings panel. About 40s locally; no CI duration measured yet. Assigned to shard 3, the lightest by meanSeconds.","secondsByExecution":[]}, + {"file":"test-882-m2-scope-customizer-e2e.js","shard":1,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":0,"measurementNote":"New suite; #882 M2 the Live scope palette and legend window in the customizer, with stubbed /api/nodes and stubbed WS packets: defaults unchanged and a theme preset leaving --scope-* alone; a light and a dark colour pick recolouring the legend swatch and the next line; a colourblind preset for unpicked slots; Display window and rows retitling and capping the legend with out-of-range input put back; reload and export round trip; a cold-start 375x560 touch phone in light and dark reaching both sections by real taps and Live with Color by scope by a real tap. About 75s locally; no CI duration measured yet. Assigned to shard 1, the lightest by meanSeconds.","secondsByExecution":[]}, {"file":"test-live-heard-filter-e2e.js","shard":3,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":12.567,"secondsByExecution":[10.986,14.496,13.579,14.234,10.485,11.624]}, {"file":"test-issue-1147-section-order-e2e.js","shard":3,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":1.787,"secondsByExecution":[1.512,1.63,1.605,1.546,2.495,1.933]}, {"file":"test-logo-rebrand-e2e.js","shard":3,"env":{"CHROMIUM_REQUIRE":"1","BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":2.453,"secondsByExecution":[2.059,2.913,2.767,2.838,2.045,2.095]}, diff --git a/test-882-m2-scope-customizer-e2e.js b/test-882-m2-scope-customizer-e2e.js new file mode 100644 index 000000000..5a34a5ccd --- /dev/null +++ b/test-882-m2-scope-customizer-e2e.js @@ -0,0 +1,386 @@ +/** + * E2E (#882 M2): the Live scope palette and the scope legend window in the + * customizer, and what they do to the Live page. + * + * 1. Defaults unchanged: a fresh page draws with the stylesheet palette; + * picking a theme preset (Ocean) leaves every --scope-* as it was. + * 2. Light: Theme -> Live scope colours, a new colour for the slot a scope + * holds recolours its legend swatch at once and the next line drawn; + * the pick is saved per browser. + * 3. Dark: the same tab edits the dark palette; the dark pick draws in + * dark, the light pick again after switching back. + * 4. A colourblind preset recolours the slots nobody picked; a pick wins. + * 5. Display -> Live scope legend: 5 min and 3 rows retitle the legend and + * cap it ("+N more"); out-of-range input is put back; reload keeps it. + * 6. Export / import round trip through the Export tab's JSON. + * 7. Phone 375x560, cold start, touch: More -> Customize, Display and + * Theme sections reached by real taps inside the screen, in light and + * dark; then Live with "Color by scope" (real tap) draws the new colour. + * + * /api/nodes is served by request interception so the two route endpoints + * are known nodes at the viewport centre (as in test-live-scope-color-e2e.js). + * + * Usage: BASE_URL=http://localhost:13581 node test-882-m2-scope-customizer-e2e.js + */ +'use strict'; +const { chromium } = require('playwright'); + +const BASE = process.env.BASE_URL || 'http://localhost:13581'; +if (!['localhost', '127.0.0.1', '[::1]'].includes(new URL(BASE).hostname)) throw new Error('local server only'); +const SHOTS = process.env.E2E_SHOT_DIR || ''; + +let passed = 0, failed = 0; +let curPage = null; // for a screenshot of a failed step (E2E_SHOT_DIR) +async function step(name, fn) { + try { await fn(); passed++; console.log(' ✓ ' + name); } + catch (e) { + failed++; console.error(' ✗ ' + name + ': ' + (e && e.stack || e)); + if (SHOTS && curPage) await curPage.screenshot({ path: SHOTS + '/fail-' + failed + '.png' }).catch(() => {}); + } +} +function assert(c, m) { if (!c) throw new Error(m || 'assertion failed'); } + +const A = 'e2e882m2' + 'a'.repeat(56); +const B = 'e2e882m2' + 'b'.repeat(56); +const VIEW = 'lat=50.5&lon=10.5&zoom=11'; +const KEY = (slot) => 'scope' + (slot + 1); + +function nodesBody() { + const now = new Date().toISOString(); + const node = (pk, name, lat, lon) => ({ public_key: pk, name, role: 'repeater', lat, lon, last_seen: now, last_heard: now, first_seen: now, advert_count: 3 }); + const nodes = [node(A, 'E2E-882M2 A', 50.5, 10.5), node(B, 'E2E-882M2 B', 50.51, 10.52)]; + return JSON.stringify({ nodes, total: nodes.length, counts: {} }); +} + +async function open(browser, opts) { + opts = opts || {}; + const ctx = await browser.newContext(Object.assign({ viewport: opts.viewport || { width: 1400, height: 900 } }, opts.touch ? { hasTouch: true, isMobile: true } : {})); + await ctx.addInitScript((theme) => { + try { + if (!sessionStorage.getItem('e2e882m2')) { + localStorage.removeItem('live-legend-hidden'); + // Live auto-hides the top nav after 4 s (#62); pinned, the palette + // button stays where a viewer would reach for it. + localStorage.setItem('live-nav-pinned', 'true'); + localStorage.setItem('meshcore-theme', theme); + sessionStorage.setItem('e2e882m2', '1'); + } + } catch (_) { /* storage off */ } + }, opts.theme || 'light'); + const page = await ctx.newPage(); + curPage = page; + const h = { ctx, page, errors: [] }; + page.on('pageerror', (e) => h.errors.push(String(e.stack || e.message).split('\n').slice(0, 3).join(' | '))); + await page.route(/\/api\/nodes\?/, (route) => route.fulfill({ status: 200, contentType: 'application/json', body: nodesBody() })); + h.ready = async () => { + await page.waitForFunction((k) => { + const m = window._liveNodeMarkers && window._liveNodeMarkers(); + return !!(window._liveWSHandler && window._liveWSHandler()) && m && m[k]; + }, A, { timeout: 20000 }); + await page.waitForFunction(() => window._customizerV2 && window._customizerV2.initDone, null, { timeout: 15000 }); + }; + h.goto = async (query) => { + await page.goto(BASE + '/?r=' + Date.now() + '#/live?' + (query ? query + '&' : '') + VIEW, { waitUntil: 'domcontentloaded' }); + await h.ready(); + }; + let seq = 0; + h.send = async (scope) => { + const hash = 'e2e882m2' + (++seq) + 'x' + Date.now().toString(16); + await page.evaluate((a) => window._liveWSHandler()({ type: 'packet', data: { + id: 882200 + a.seq, hash: a.hash, raw_hex: '1500', route_type: 0, payload_type: 5, + scope_name: a.scope, path_json: '["E2","E2"]', resolved_path: [a.a, a.b], + observer_id: 'e2e-882m2', observer_name: 'e2e-882m2', timestamp: new Date().toISOString(), snr: 5, rssi: -90, + decoded: { header: { payloadTypeName: 'GRP_TXT' }, payload: { text: 'x' }, path: { hops: [] } }, + } }), { seq, hash, scope, a: A, b: B }); + return hash; + }; + h.routeColor = async (hash) => { + await page.waitForFunction((x) => window._liveClickablePaths.some((e) => e.hash === x), hash, { timeout: 8000 }); + return page.evaluate((x) => window._liveClickablePaths.find((e) => e.hash === x).color, hash); + }; + h.cssVar = (n) => page.evaluate((v) => getComputedStyle(document.documentElement).getPropertyValue(v).trim(), n); + h.slot = (name) => page.evaluate((n) => window._liveScopeRegistry().slotOf(n), name); + h.legend = async () => { + await page.waitForTimeout(1300); // the legend re-render is coalesced to <= 1/s + return page.evaluate(() => ({ + title: document.querySelector('#scopeLegendSection .legend-title').textContent, + rows: [...document.querySelectorAll('#scopeLegendList li')].map((li) => { + const sw = li.querySelector('.live-scope-swatch'); + return { text: li.textContent.trim(), sw: sw ? getComputedStyle(sw).backgroundColor : null }; + }), + })); + }; + // The palette button, or on a phone the More sheet, then Customize, then a tab. + h.openTab = async (tab, phone) => { + if (!(await page.$('.cust-overlay:not(.hidden)'))) { + if (phone) { + await page.tap('[data-bottom-nav-tab="more"]'); + await page.waitForSelector('[data-mpa-mirror="customizeToggle"]', { state: 'visible', timeout: 5000 }); + await page.tap('[data-mpa-mirror="customizeToggle"]'); + } else await page.click('#customizeToggle'); + await page.waitForSelector('.cust-overlay:not(.hidden)', { timeout: 5000 }); + } + if (phone) await page.tap('.cust-tab[data-tab="' + tab + '"]'); else await page.click('.cust-tab[data-tab="' + tab + '"]'); + await page.waitForSelector('.cust-panel[data-panel="' + tab + '"].active', { timeout: 4000 }); + }; + h.openScopeColours = async (phone) => { + await h.openTab('theme', phone); + const open = await page.$eval('.cust-scope-colors', (d) => d.open); + if (!open) { + const sum = page.locator('.cust-scope-colors > summary'); + await sum.scrollIntoViewIfNeeded(); + if (phone) await sum.tap(); else await sum.click(); + } + }; + // A native colour picker cannot be driven, so the value is filled; the + // change event is the one the picker fires when it closes. + h.pickColour = async (section, key, hex) => { + const sel = '[data-cv2-field="' + section + '.' + key + '"]'; + await page.locator(sel).scrollIntoViewIfNeeded(); + await page.fill(sel, hex); + await page.dispatchEvent(sel, 'change'); + await page.waitForTimeout(700); // the debounced write + }; + h.setNum = async (key, v) => { + const sel = '[data-cv2-live-scope="' + key + '"]'; + await page.fill(sel, String(v)); + await page.dispatchEvent(sel, 'change'); + await page.waitForTimeout(700); + }; + h.closePanel = async (phone) => { + if (!(await page.$('.cust-overlay:not(.hidden)'))) return; + if (phone) await page.tap('.cust-close'); else await page.click('.cust-close'); + await page.waitForTimeout(200); + }; + h.scopeOn = async () => { + if (!(await page.$eval('#liveColorScopeToggle', (e) => e.checked))) throw new Error('scope mode not on'); + }; + h.overrides = () => page.evaluate(() => JSON.parse(localStorage.getItem('cs-theme-overrides') || '{}')); + return h; +} + +function rgb(hex) { + const n = parseInt(hex.slice(1), 16); + return 'rgb(' + (n >> 16) + ', ' + ((n >> 8) & 255) + ', ' + (n & 255) + ')'; +} + +const M1_LIGHT_1 = '#0072b2', M1_DARK_1 = '#3d8bfd'; + +(async () => { + const browser = await chromium.launch({ + headless: true, + executablePath: process.env.CHROMIUM_PATH || undefined, + args: ['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage'], + }); + console.log('\n=== #882 M2 scope palette + legend window in the customizer, against ' + BASE + ' ==='); + try { + const h = await open(browser); + const st = {}; + + await step('defaults unchanged: stylesheet palette; a theme preset (Ocean) leaves --scope-* alone', async () => { + await h.goto('color=scope'); + await h.scopeOn(); + const before = {}; + for (const v of ['--scope-1', '--scope-7', '--scope-none', '--scope-unknown', '--scope-other']) before[v] = await h.cssVar(v); + assert(before['--scope-1'] === M1_LIGHT_1, 'default --scope-1 ' + before['--scope-1']); + const title = (await h.legend()).title; + assert(title === 'SCOPES (last 15 min)', 'default title ' + title); + await h.openTab('theme'); + await h.page.click('.cust-preset-btn[data-preset="ocean"]'); + await h.page.waitForTimeout(400); + for (const v of Object.keys(before)) assert(await h.cssVar(v) === before[v], v + ' moved with the Ocean preset'); + assert(await h.page.evaluate(() => !document.documentElement.style.getPropertyValue('--scope-1')), 'Ocean stamped --scope-1 inline'); + assert(await h.page.evaluate(() => window._customizerV2.detectActivePreset()) === 'ocean', 'Ocean not detected'); + // Back to Default (clears every override). + await h.page.click('.cust-preset-btn[data-preset="default"]'); + await h.page.waitForTimeout(400); + await h.closePanel(); + }); + + await step('light: a new colour for a scope\'s slot recolours its swatch at once and the next line', async () => { + const first = await h.send('#dk'); + st.slot = await h.slot('#dk'); + st.var = '--scope-' + (st.slot + 1); + const old = await h.routeColor(first); + assert(old === await h.cssVar(st.var), 'line before ' + old); + await h.openScopeColours(); + const rows = await h.page.$$eval('.cust-scope-colors [data-cv2-field]', (els) => els.map((e) => e.getAttribute('data-cv2-field'))); + assert(rows.length === 15 && rows.every((r) => r.startsWith('theme.')), 'rows ' + JSON.stringify(rows)); + await h.pickColour('theme', KEY(st.slot), '#123456'); + assert(await h.cssVar(st.var) === '#123456', st.var + ' = ' + await h.cssVar(st.var)); + await h.closePanel(); + const L = await h.legend(); + const dk = L.rows.find((r) => r.text === '#dk'); + assert(dk && dk.sw === rgb('#123456'), 'swatch ' + JSON.stringify(L.rows)); + const next = await h.routeColor(await h.send('#dk')); + assert(next === '#123456', 'next line ' + next); + assert(await h.routeColor(first) === old, 'a drawn line was recoloured (not expected: lines keep their colour)'); + const ov = await h.overrides(); + assert(ov.theme && ov.theme[KEY(st.slot)] === '#123456', 'not saved: ' + JSON.stringify(ov)); + }); + + await step('dark: the tab edits the dark palette; each theme draws its own pick', async () => { + await h.page.evaluate(() => document.documentElement.setAttribute('data-theme', 'dark')); + await h.page.waitForTimeout(300); + // A light pick with no dark one carries over, as for every theme key. + assert(await h.cssVar(st.var) === '#123456', 'dark before its own pick: ' + await h.cssVar(st.var)); + assert(await h.cssVar('--scope-unknown') === '#c4b5a5', 'dark default unknown ' + await h.cssVar('--scope-unknown')); + await h.openScopeColours(); + assert(await h.page.$('.cust-scope-colors [data-cv2-field="themeDark.' + KEY(st.slot) + '"]'), 'dark mode does not edit themeDark'); + await h.pickColour('themeDark', KEY(st.slot), '#abcdef'); + await h.closePanel(); + assert(await h.routeColor(await h.send('#dk')) === '#abcdef', 'dark line'); + const L = await h.legend(); + assert(L.rows.find((r) => r.text === '#dk').sw === rgb('#abcdef'), 'dark swatch'); + if (SHOTS) await h.page.screenshot({ path: SHOTS + '/desktop-dark-legend.png' }); + await h.page.evaluate(() => document.documentElement.setAttribute('data-theme', 'light')); + await h.page.waitForTimeout(300); + assert(await h.routeColor(await h.send('#dk')) === '#123456', 'light line after switching back'); + const ov = await h.overrides(); + assert(ov.themeDark && ov.themeDark[KEY(st.slot)] === '#abcdef', 'dark pick not saved'); + if (SHOTS) await h.page.screenshot({ path: SHOTS + '/desktop-light-legend.png' }); + }); + + await step('a colourblind preset recolours the slots nobody picked; a pick still wins', async () => { + const other = st.slot === 0 ? 1 : 0; + const before = await h.cssVar('--scope-' + (other + 1)); + await h.page.evaluate(() => window.MeshCorePresets.applyPreset('deut', { skipPersist: true })); + await h.page.waitForTimeout(300); + const deut = await h.page.evaluate((i) => window.MeshCorePresets.list.find((p) => p.id === 'deut').scopePalette.light[i], other); + assert((await h.cssVar('--scope-' + (other + 1))).toLowerCase() === deut.toLowerCase(), 'deut slot ' + (other + 1) + ': ' + await h.cssVar('--scope-' + (other + 1)) + ' want ' + deut + ' (was ' + before + ')'); + assert(await h.cssVar(st.var) === '#123456', 'the pick lost to the preset'); + await h.page.evaluate(() => window.MeshCorePresets.clearPreset()); + await h.page.waitForTimeout(300); + assert(await h.cssVar('--scope-' + (other + 1)) === before, 'clearPreset did not restore'); + }); + + await step('Display -> Live scope legend: 5 min and 3 rows retitle and cap the legend; bad input is put back', async () => { + for (let i = 0; i < 6; i++) await h.send('#w' + i); + await h.openTab('display'); + const sec = h.page.locator('[data-cv2-live-scope-section]'); + assert(await sec.count() === 1, 'no Live scope legend section'); + assert(await h.page.inputValue('[data-cv2-live-scope="windowMinutes"]') === '15', 'window default'); + assert(await h.page.inputValue('[data-cv2-live-scope="legendRows"]') === '12', 'rows default'); + await h.setNum('windowMinutes', 5); + await h.setNum('legendRows', 3); + await h.setNum('legendRows', 40); + assert(await h.page.inputValue('[data-cv2-live-scope="legendRows"]') === '3', 'an out-of-range value stayed'); + const ov = await h.overrides(); + assert(ov.liveScope && ov.liveScope.windowMinutes === 5 && ov.liveScope.legendRows === 3, 'stored ' + JSON.stringify(ov.liveScope)); + await h.closePanel(); + const L = await h.legend(); + assert(L.title === 'SCOPES (last 5 min)', 'title ' + L.title); + const named = L.rows.filter((r) => r.text.startsWith('#')); + assert(named.length === 3, 'rows ' + JSON.stringify(L.rows)); + assert(L.rows.some((r) => /^\+\d+ more$/.test(r.text)), 'no +N more: ' + JSON.stringify(L.rows)); + }); + + await step('reload keeps the palette and the window', async () => { + await h.goto('color=scope'); + assert(await h.cssVar(st.var) === '#123456', 'pick lost on reload'); + await h.send('#dk'); + const L = await h.legend(); + assert(L.title === 'SCOPES (last 5 min)', 'window lost on reload: ' + L.title); + await h.openTab('display'); + assert(await h.page.inputValue('[data-cv2-live-scope="windowMinutes"]') === '5', 'input after reload'); + assert(await h.page.$$eval('[data-cv2-live-scope-section] .cv2-override-dot', (d) => d.length) === 2, 'an override dot per changed key'); + await h.closePanel(); + }); + + await step('export / import round trip (Export tab JSON)', async () => { + const exported = await h.page.evaluate(() => JSON.parse(JSON.stringify(window._customizerV2.readOverrides()))); + assert(exported.liveScope && exported.theme[KEY(st.slot)] === '#123456', 'export ' + JSON.stringify(exported)); + const h2 = await open(browser); + await h2.goto('color=scope'); + const res = await h2.page.evaluate((d) => window._customizerV2.validateShape(d), exported); + assert(res.valid, 'import rejected: ' + JSON.stringify(res.errors)); + await h2.page.evaluate((d) => window._customizerV2.writeOverrides(d), exported); + await h2.goto('color=scope'); + assert(await h2.cssVar(st.var) === '#123456', 'imported colour'); + await h2.send('#dk'); + assert((await h2.legend()).title === 'SCOPES (last 5 min)', 'imported window'); + assert(!h2.errors.length, h2.errors.join('; ')); + await h2.ctx.close(); + }); + assert(!h.errors.length, h.errors.join('; ')); + await h.ctx.close(); + + for (const theme of ['light', 'dark']) { + await step('phone 375x560 (' + theme + '), cold start, real taps: Display and Theme sections, then Live by scope', async () => { + const p = await open(browser, { viewport: { width: 375, height: 560 }, touch: true, theme }); + const pg = p.page; + await pg.goto(BASE + '/?r=' + Date.now() + '#/', { waitUntil: 'domcontentloaded' }); + await pg.waitForSelector('[data-bottom-nav-tab="live"]', { state: 'visible', timeout: 20000 }); + await pg.evaluate(() => localStorage.setItem('live-map-view', JSON.stringify({ lat: 50.5, lng: 10.5, zoom: 11 }))); + await pg.tap('[data-bottom-nav-tab="live"]'); + await p.ready(); + assert(await pg.evaluate(() => document.documentElement.getAttribute('data-theme')) === theme, 'theme'); + const inScreen = async (selector) => { + const loc = pg.locator(selector).first(); + await loc.scrollIntoViewIfNeeded(); + const b = await loc.boundingBox(); + assert(b && b.x >= 0 && b.x + b.width <= 375 && b.y >= 0 && b.y + b.height <= 560, selector + ' off screen ' + JSON.stringify(b)); + return b; + }; + await p.openTab('display', true); + const tapType = async (key, value) => { + const sel = '[data-cv2-live-scope="' + key + '"]'; + const b = await inScreen(sel); + assert(b.height >= 40, key + ' input ' + b.height + ' px'); + await pg.tap(sel); + await pg.keyboard.press('ControlOrMeta+A'); + await pg.keyboard.press('Backspace'); + await pg.keyboard.type(String(value)); + const t = pg.locator('[data-cv2-live-scope-section] .cust-section-title'); + await t.scrollIntoViewIfNeeded(); + await t.tap(); + await pg.waitForTimeout(700); + assert(await pg.inputValue(sel) === String(value), key + ' did not take ' + value); + }; + await tapType('windowMinutes', 10); + await tapType('legendRows', 4); + // The section survives the panel's re-render after the write. + await inScreen('[data-cv2-live-scope-section] .cust-section-title'); + assert(await pg.inputValue('[data-cv2-live-scope="legendRows"]') === '4', 'rows after re-render'); + if (SHOTS) await pg.screenshot({ path: SHOTS + '/phone-' + theme + '-display.png' }); + const ov = await p.overrides(); + assert(ov.liveScope && ov.liveScope.windowMinutes === 10 && ov.liveScope.legendRows === 4, 'stored ' + JSON.stringify(ov)); + assert(await pg.evaluate(() => document.documentElement.scrollWidth - innerWidth) <= 0, 'sideways scroll (display)'); + // Theme tab: the group opens by a real tap; every row inside the screen. + await p.openScopeColours(true); + const sec = theme === 'dark' ? 'themeDark' : 'theme'; + for (const k of ['scope1', 'scope12', 'scopeOther']) await inScreen('[data-cv2-field="' + sec + '.' + k + '"]'); + await pg.tap('[data-cv2-field="' + sec + '.scope1"]'); // a real tap opens the native picker + await pg.keyboard.press('Escape'); + await p.pickColour(sec, 'scope1', '#cc0077'); + if (SHOTS) await pg.screenshot({ path: SHOTS + '/phone-' + theme + '-theme.png' }); + assert(await pg.evaluate(() => document.documentElement.scrollWidth - innerWidth) <= 0, 'sideways scroll (theme)'); + await p.closePanel(true); + // Live: Color by scope by a real tap, then a scope on slot 1. + if (await pg.$eval('#liveControlsToggle', (e) => e.getAttribute('aria-expanded')) !== 'true') await pg.tap('#liveControlsToggle'); + await pg.waitForSelector('#liveColorScopeToggle', { state: 'visible' }); + await pg.$eval('#liveColorScopeToggle', (e) => e.scrollIntoView({ block: 'nearest' })); + await pg.tap('#liveColorScopeToggle'); + await p.scopeOn(); + // A name whose preferred slot is 0, found by the module's own hash. + const name = await pg.evaluate(() => { for (let i = 0; i < 1000; i++) { const n = '#p' + i; if (window.LiveScopeColor.preferredSlot(n) === 0) return n; } return null; }); + const hash = await p.send(name); + assert(await p.slot(name) === 0, 'slot'); + assert(await p.routeColor(hash) === '#cc0077', 'phone line ' + await p.routeColor(hash)); + await pg.waitForTimeout(1300); + const menu = await pg.evaluate(() => ({ title: document.querySelector('#scopeLegendMenu .legend-title').textContent, + sw: [...document.querySelectorAll('#scopeLegendMenu li')].map((li) => { const s = li.querySelector('.live-scope-swatch'); return li.textContent.trim() + '=' + (s ? getComputedStyle(s).backgroundColor : ''); }) })); + assert(menu.title === 'SCOPES (last 10 min)', 'phone title ' + menu.title); + assert(menu.sw.includes(name + '=' + rgb('#cc0077')), 'phone swatch ' + JSON.stringify(menu.sw)); + await pg.$eval('#scopeLegendMenu', (e) => e.scrollIntoView({ block: 'nearest' })); + if (SHOTS) await pg.screenshot({ path: SHOTS + '/phone-' + theme + '-live.png' }); + assert(!p.errors.length, p.errors.join('; ')); + await p.ctx.close(); + }); + } + } finally { + await browser.close(); + } + console.log('\n' + passed + ' passed, ' + failed + ' failed'); + process.exit(failed ? 1 : 0); +})(); diff --git a/test-882-m2-scope-customizer.js b/test-882-m2-scope-customizer.js new file mode 100644 index 000000000..227862585 --- /dev/null +++ b/test-882-m2-scope-customizer.js @@ -0,0 +1,395 @@ +/** + * #882 M2 (AGENTS rule 8) — the Live scope palette and the scope legend + * window in the customizer. + * + * The real public/customize-v2.js, public/live-scope-color.js and + * public/cb-presets.js run in vm sandboxes; nothing is copied. + * 1. palette keys: THEME_CSS_MAP and THEME_COLOR_KEYS carry the 15 scope + * keys; every theme preset has a light and a dark value for each; the + * Default preset is the stylesheet (no change at the defaults); + * 2. applyCSS: a pick reaches --scope-N; a value equal to the stylesheet + * default leaves the cascade to style.css (and a colourblind preset); + * 3. colourblind presets: a light and a dark palette in every preset, + * >= 3:1 against the map tile, 12 distinct slots; clearPreset and + * style.css wiring; + * 4. legend window rule (LiveScopeColor.SETTINGS): keys, defaults, + * bounds; the registry follows it; + * 5. the liveScope section: storage, import validation, export round + * trip, the Display badge, the controls (createElement, bounded inputs). + * Usage: node test-882-m2-scope-customizer.js + */ +'use strict'; +const fs = require('fs'); +const path = require('path'); +const vm = require('vm'); +const assert = require('assert'); +const { loadCustomizer } = require('./tests/customizer-sandbox'); + +let passed = 0, failed = 0; +const tests = []; +function test(name, fn) { tests.push([name, fn]); } +const plain = (v) => JSON.parse(JSON.stringify(v === undefined ? null : v)); +const eq = (a, b, m) => assert.deepStrictEqual(plain(a), b, m); + +const SCOPE_KEYS = ['scope1', 'scope2', 'scope3', 'scope4', 'scope5', 'scope6', 'scope7', 'scope8', 'scope9', + 'scope10', 'scope11', 'scope12', 'scopeNone', 'scopeUnknown', 'scopeOther']; +const VAR = (k) => (k === 'scopeNone' ? '--scope-none' : k === 'scopeUnknown' ? '--scope-unknown' : k === 'scopeOther' ? '--scope-other' : '--scope-' + k.slice(5)); +const SUFFIX = (k) => VAR(k).replace('--scope-', ''); +const HEX = /^#[0-9a-f]{6}$/i; + +const css = fs.readFileSync(path.join(__dirname, 'public/style.css'), 'utf8'); + +// The stylesheet's default for one scope variable: the fallback of the +// first declaration (light :root) or of the dark blocks. +function cssDefaults(mode) { + const out = {}; + SCOPE_KEYS.forEach((k) => { + const s = SUFFIX(k); + const re = new RegExp('^\\s*' + VAR(k) + ':\\s*var\\(--mc-scope-' + mode + '-' + s + ',\\s*(#[0-9a-f]{6})\\);', 'gim'); + const all = [...css.matchAll(re)].map((m) => m[1].toLowerCase()); + out[k] = all; + }); + return out; +} + +function load(o) { + o = o || {}; + return loadCustomizer({ theme: o.theme, scripts: o.noRule ? [] : ['live-scope-color.js'], setup: o.setup }); +} + +// ── 1. Palette keys ───────────────────────────────────────────────────────── + +test('THEME_CSS_MAP maps the 15 scope keys; all are THEME_COLOR_KEYS (preset detection)', () => { + const { api } = load(); + SCOPE_KEYS.forEach((k) => assert.strictEqual(api.THEME_CSS_MAP[k], VAR(k), k)); + eq(api.SCOPE_COLOR_KEYS, SCOPE_KEYS); + SCOPE_KEYS.forEach((k) => assert.ok(api.THEME_COLOR_KEYS.indexOf(k) >= 0, k + ' not in THEME_COLOR_KEYS')); +}); + +test('every theme preset has a light and a dark value for every scope key', () => { + const { api } = load(); + const ids = Object.keys(api.PRESETS); + assert.ok(ids.length >= 8, 'presets: ' + ids); + ids.forEach((id) => { + const p = api.PRESETS[id]; + SCOPE_KEYS.forEach((k) => { + assert.ok(HEX.test(p.theme[k] || ''), id + ' light ' + k + ' = ' + p.theme[k]); + assert.ok(HEX.test(p.themeDark[k] || ''), id + ' dark ' + k + ' = ' + p.themeDark[k]); + }); + }); +}); + +test('no change at the defaults: style.css keeps the M1 values, the Default preset is the stylesheet', () => { + const M1_LIGHT = ['#0072b2', '#009e73', '#b35c00', '#7e3fa0', '#a8780b', '#00838f', '#b0306f', '#4b5eaa', '#5e8b2f', '#8b4513', '#c026d3', '#6d6d00', '#a1a1aa', '#57534e', '#111827']; + const M1_DARK = ['#3d8bfd', '#3fd7a5', '#f0a03c', '#c49be0', '#e6c34a', '#4dd0e1', '#f06292', '#8c9eff', '#a5d66b', '#d7a07a', '#e879f9', '#dce775', '#6b7280', '#c4b5a5', '#f8fafc']; + const L = cssDefaults('light'), D = cssDefaults('dark'); + const { api } = load(); + SCOPE_KEYS.forEach((k, i) => { + eq(L[k], [M1_LIGHT[i]], 'style.css light ' + k); + eq(D[k], [M1_DARK[i], M1_DARK[i]], 'style.css dark blocks ' + k); + assert.strictEqual(api.PRESETS.default.theme[k], M1_LIGHT[i], 'Default preset light ' + k); + assert.strictEqual(api.PRESETS.default.themeDark[k], M1_DARK[i], 'Default preset dark ' + k); + }); +}); + +test('preset detection: a pre-M2 preset pick (no scope keys) still matches, a recoloured scope does not', () => { + const { api, ctx } = load(); + const p = api.PRESETS.ocean; + const strip = (o) => { const c = Object.assign({}, o); SCOPE_KEYS.forEach((k) => delete c[k]); return c; }; + ctx.window.SITE_CONFIG = { theme: strip(p.theme), themeDark: strip(p.themeDark) }; + assert.strictEqual(api.detectActivePreset(), 'ocean'); + ctx.window.SITE_CONFIG = { theme: Object.assign({}, p.theme), themeDark: Object.assign({}, p.themeDark) }; + assert.strictEqual(api.detectActivePreset(), 'ocean', 'a full M2 preset pick'); + ctx.window.SITE_CONFIG = { theme: Object.assign({}, p.theme, { scope3: '#123456' }), themeDark: Object.assign({}, p.themeDark) }; + assert.strictEqual(api.detectActivePreset(), null); +}); + +test('Theme tab: a "Live scope colours" group with a row per key, for the mode being edited', () => { + const { api } = load(); + const html = api.renderTheme(); + const m = html.match(/
/); + assert.ok(m, 'no cust-scope-colors group'); + SCOPE_KEYS.forEach((k) => assert.ok(m[0].includes('data-cv2-field="theme.' + k + '"'), k)); + assert.ok(/Live scope colours \(15 options\)/.test(m[0]), 'summary'); + const dark = load({ theme: 'dark' }).api.renderTheme(); + assert.ok(dark.includes('data-cv2-field="themeDark.scope1"'), 'dark mode edits themeDark'); +}); + +// ── 2. applyCSS ───────────────────────────────────────────────────────────── + +test('applyCSS: a pick reaches --scope-N, light and dark', () => { + const c = load(); + c.api.init({}); + c.api.writeOverrides({ theme: { scope3: '#112233', scopeNone: '#445566' } }); + c.api.applyCSS(c.api.computeEffective({}, c.api.readOverrides()), c.api.readOverrides()); + assert.strictEqual(c.rootStyle._props['--scope-3'], '#112233'); + assert.strictEqual(c.rootStyle._props['--scope-none'], '#445566'); + const d = load({ theme: 'dark' }); + d.api.init({}); + d.api.writeOverrides({ themeDark: { scope3: '#abcdef' } }); + d.api.applyCSS(d.api.computeEffective({}, d.api.readOverrides()), d.api.readOverrides()); + assert.strictEqual(d.rootStyle._props['--scope-3'], '#abcdef'); +}); + +test('applyCSS: a value equal to the stylesheet default (a preset pick) leaves --scope-N to style.css; a cleared pick is removed', () => { + const c = load(); + c.api.init({}); + const p = c.api.PRESETS.ocean; + c.api.writeOverrides({ theme: Object.assign({}, p.theme), themeDark: Object.assign({}, p.themeDark) }); + c.api.applyCSS(c.api.computeEffective({}, c.api.readOverrides()), c.api.readOverrides()); + SCOPE_KEYS.forEach((k) => assert.strictEqual(c.rootStyle._props[VAR(k)], undefined, k + ' stamped inline: a colourblind preset could not win')); + c.api.writeOverrides({ theme: { scope1: '#010203' } }); + c.api.applyCSS(c.api.computeEffective({}, c.api.readOverrides()), c.api.readOverrides()); + assert.strictEqual(c.rootStyle._props['--scope-1'], '#010203'); + c.api.writeOverrides({}); + c.api.applyCSS(c.api.computeEffective({}, c.api.readOverrides()), c.api.readOverrides()); + assert.strictEqual(c.rootStyle._props['--scope-1'], undefined, 'a cleared pick stays inline'); +}); + +// ── 3. Colourblind presets ────────────────────────────────────────────────── + +function loadPresets() { + const props = {}; + const style = { setProperty: (k, v) => { props[k] = v; }, removeProperty: (k) => { delete props[k]; }, getPropertyValue: (k) => props[k] || '' }; + const ctx = { window: { dispatchEvent() {}, CustomEvent: class {}, addEventListener() {} }, document: { body: { setAttribute() {}, removeAttribute() {} }, documentElement: { style } }, + localStorage: { getItem: () => null, setItem() {}, removeItem() {} }, console }; + vm.createContext(ctx); + vm.runInContext(fs.readFileSync(path.join(__dirname, 'public/cb-presets.js'), 'utf8'), ctx, { filename: 'cb-presets.js' }); + return { MCP: ctx.window.MeshCorePresets, props }; +} +const CB_IDS = ['default', 'deut', 'prot', 'trit', 'achromat']; + +test('cb-presets: every preset sets a light and a dark value for all 15 scope colours; clearPreset removes them', () => { + const { MCP, props } = loadPresets(); + CB_IDS.forEach((id) => { + assert.ok(MCP.applyPreset(id, { skipPersist: true }), id); + ['light', 'dark'].forEach((mode) => SCOPE_KEYS.forEach((k) => { + const v = props['--mc-scope-' + mode + '-' + SUFFIX(k)]; + assert.ok(HEX.test(v || ''), id + ' ' + mode + ' ' + k + ' = ' + v); + })); + }); + MCP.clearPreset(); + eq(Object.keys(props).filter((k) => /scope/.test(k)), []); +}); + +test('cb-presets: the Default (Wong) preset is the stylesheet palette', () => { + const { MCP, props } = loadPresets(); + MCP.applyPreset('default', { skipPersist: true }); + const L = cssDefaults('light'), D = cssDefaults('dark'); + SCOPE_KEYS.forEach((k) => { + assert.strictEqual(props['--mc-scope-light-' + SUFFIX(k)].toLowerCase(), L[k][0], 'light ' + k); + assert.strictEqual(props['--mc-scope-dark-' + SUFFIX(k)].toLowerCase(), D[k][0], 'dark ' + k); + }); +}); + +test('cb-presets: tuned palettes have 12 distinct slots, each >= 3:1 on the map tile of its mode (WCAG 1.4.11)', () => { + const { MCP, props } = loadPresets(); + const C = MCP.wcag.contrast; + ['deut', 'prot', 'trit', 'achromat'].forEach((id) => { + MCP.applyPreset(id, { skipPersist: true }); + ['light', 'dark'].forEach((mode) => { + const tile = mode === 'light' ? MCP.wcag.TILE_LIGHT : MCP.wcag.TILE_DARK; + const slots = SCOPE_KEYS.slice(0, 12).map((k) => props['--mc-scope-' + mode + '-' + SUFFIX(k)].toLowerCase()); + assert.strictEqual(new Set(slots).size, 12, id + ' ' + mode + ' slots repeat'); + slots.forEach((c, i) => assert.ok(C(c, tile) >= 3, id + ' ' + mode + ' slot ' + (i + 1) + ' ' + c + ' ' + C(c, tile).toFixed(2))); + const n = props['--mc-scope-' + mode + '-none'], u = props['--mc-scope-' + mode + '-unknown']; + assert.notStrictEqual(n.toLowerCase(), u.toLowerCase(), id + ' ' + mode + ' none = unknown'); + }); + }); +}); + +test('style.css: each --scope-* reads the colourblind preset hook of its mode, once per block', () => { + const L = cssDefaults('light'), D = cssDefaults('dark'); + SCOPE_KEYS.forEach((k) => { + assert.strictEqual(L[k].length, 1, VAR(k) + ' light declarations: ' + L[k].length); + assert.strictEqual(D[k].length, 2, VAR(k) + ' dark declarations (media + [data-theme=dark]): ' + D[k].length); + const plainDecl = css.split('\n').filter((l) => new RegExp('^\\s*' + VAR(k) + ':\\s*#').test(l)); + eq(plainDecl, [], VAR(k) + ' still has a bare hex declaration'); + }); +}); + +test('Reset All strips the colourblind scope variables too', () => { + const c = load(); + c.api.init({}); + c.rootStyle.setProperty('--mc-scope-light-3', '#000000'); + c.rootStyle.setProperty('--mc-scope-dark-none', '#000000'); + c.api.resetAll(); + assert.strictEqual(c.rootStyle._props['--mc-scope-light-3'], undefined); + assert.strictEqual(c.rootStyle._props['--mc-scope-dark-none'], undefined); +}); + +// ── 4. The legend window rule ─────────────────────────────────────────────── + +function loadScope() { + const ctx = { window: {}, console }; + vm.createContext(ctx); + vm.runInContext(fs.readFileSync(path.join(__dirname, 'public/live-scope-color.js'), 'utf8'), ctx, { filename: 'live-scope-color.js' }); + return ctx.window.LiveScopeColor; +} + +test('SETTINGS: the M0 window (15 min, 12 rows) is the default; cap 64 stays fixed', () => { + const S = loadScope(); + const R = S.SETTINGS; + eq(R.KEYS, ['windowMinutes', 'legendRows']); + eq(R.DEFAULTS, { windowMinutes: 15, legendRows: 12 }); + eq(R.LIMITS, { windowMinutes: [1, 60], legendRows: [1, 12] }); + assert.strictEqual(S.CAP, 64); + assert.strictEqual(S.WINDOW_MS, 15 * 60000); + assert.strictEqual(S.LEGEND_ROWS, 12); + eq(R.resolve({}), plain(R.DEFAULTS)); + eq(R.resolve(null), plain(R.DEFAULTS)); +}); + +test('SETTINGS.valid: whole numbers inside the bounds only', () => { + const R = loadScope().SETTINGS; + [[1, true], [60, true], [15, true], [0, false], [61, false], [2.5, false], ['15', false], [null, false], [NaN, false], [Infinity, false], [true, false]] + .forEach(([v, ok]) => assert.strictEqual(R.valid('windowMinutes', v), ok, 'windowMinutes ' + v)); + [[1, true], [12, true], [0, false], [13, false], [6.5, false], ['6', false]] + .forEach(([v, ok]) => assert.strictEqual(R.valid('legendRows', v), ok, 'legendRows ' + v)); + assert.strictEqual(R.valid('cap', 10), false, 'an unknown key'); + eq(R.resolve({ windowMinutes: 5, legendRows: 99, extra: 1 }), { windowMinutes: 5, legendRows: 12 }); +}); + +test('registry: the window and the row count follow configure(), defaults unchanged', () => { + const S = loadScope(); + const r = S.createRegistry(); + const t0 = 1e9; + for (let i = 0; i < 14; i++) r.touch('#s' + i, t0 + i * 60000); // one a minute + const now = t0 + 13 * 60000; + let L = r.legend(now); + eq([L.rows.length, L.more, L.windowMinutes], [12, 2, 15]); + r.configure({ windowMinutes: 5, legendRows: 3 }); + L = r.legend(now); + // A 5 min window (inclusive) keeps the 6 scopes seen at minutes 8..13. + eq([L.rows.length, L.more, L.windowMinutes], [3, 3, 5]); + eq(L.rows.map((x) => x.name), ['#s11', '#s12', '#s13'], 'the most recent rows'); + r.configure(null); + eq([r.legend(now).rows.length, r.legend(now).more], [12, 2], 'configure(null) restores the defaults'); +}); + +test('registry: a shorter window frees colour slots sooner; a bad configure() keeps the defaults', () => { + const S = loadScope(); + const r = S.createRegistry({ windowMinutes: 2, legendRows: 12 }); + const t0 = 1e9; + r.touch('#a', t0); + const L = r.legend(t0 + 3 * 60000); + eq([L.rows.length, L.windowMinutes], [0, 2], 'a scope older than the window is still listed'); + r.configure({ windowMinutes: 'x', legendRows: 0 }); + eq(r.settings(), { windowMinutes: 15, legendRows: 12 }); +}); + +// ── 5. The liveScope section ──────────────────────────────────────────────── + +test('liveScope is a known object section; values by the module rule', () => { + const c = load(); + assert.ok(c.api.VALID_SECTIONS.indexOf('liveScope') >= 0); + eq(c.api.liveScopeSettings({}), { windowMinutes: 15, legendRows: 12 }); + c.api.writeOverrides({ liveScope: { windowMinutes: 30, legendRows: 13, cap: 10 } }); + eq(c.api.readOverrides(), { liveScope: { windowMinutes: 30 } }); + assert.ok(c.warnings.some((w) => /liveScope\.legendRows/.test(w)), 'a rejected value is logged'); + eq(c.api.liveScopeSettings(c.api.computeEffective({}, c.api.readOverrides())), { windowMinutes: 30, legendRows: 12 }); +}); + +test('without the module on the page no value is accepted', () => { + const c = load({ noRule: true }); + c.api.writeOverrides({ liveScope: { windowMinutes: 30 } }); + eq(c.api.readOverrides(), {}); + assert.strictEqual(c.api.liveScopeSettings({}), null); +}); + +test('validateShape names each bad value and its range; unknown keys only warn', () => { + const { api, warnings } = load(); + const res = api.validateShape({ liveScope: { windowMinutes: 0, legendRows: 2.5, cap: 64 } }); + assert.strictEqual(res.valid, false); + const txt = res.errors.join('\n'); + assert.ok(/liveScope\.windowMinutes = "0".*1-60/.test(txt), txt); + assert.ok(/liveScope\.legendRows = "2.5".*1-12/.test(txt), txt); + assert.ok(!/cap/.test(txt), 'an unknown key is not an error'); + assert.ok(warnings.some((w) => /Unknown liveScope key.*cap/.test(w))); + assert.strictEqual(api.validateShape({ liveScope: 'on' }).valid, false); + assert.strictEqual(api.validateShape({ liveScope: { windowMinutes: 5 } }).valid, true); +}); + +test('export / import round trip: palette and window', () => { + const delta = { theme: { scope1: '#102030', scopeUnknown: '#405060' }, themeDark: { scope12: '#a0b0c0' }, liveScope: { windowMinutes: 45, legendRows: 6 } }; + const a = load(); + a.api.writeOverrides(delta); + const exported = JSON.parse(JSON.stringify(a.api.readOverrides())); + eq(exported, delta); + const b = load(); + assert.strictEqual(b.api.validateShape(exported).valid, true, JSON.stringify(b.api.validateShape(exported).errors)); + b.api.writeOverrides(exported); + eq(b.api.readOverrides(), delta); + b.api.init({}); + b.api.applyCSS(b.api.computeEffective({}, b.api.readOverrides()), b.api.readOverrides()); + assert.strictEqual(b.rootStyle._props['--scope-1'], '#102030'); + assert.strictEqual(b.rootStyle._props['--scope-unknown'], '#405060'); + assert.ok(b.api.validateShape({ theme: { scope2: 'red;}' } }).valid === false, 'a bad colour is accepted on import'); +}); + +test('persistence: the section is stored per browser in cs-theme-overrides', () => { + const c = load(); + c.api.writeOverrides({ liveScope: { legendRows: 4 } }); + eq(JSON.parse(c.localStorage.getItem('cs-theme-overrides')), { liveScope: { legendRows: 4 } }); +}); + +test('the Display badge counts the section', () => { + const c = load(); + const before = c.api.countOverrides('liveScope'); + c.api.writeOverrides({ liveScope: { windowMinutes: 5, legendRows: 3 } }); + c.ctx.window.SITE_CONFIG = c.api.computeEffective({}, c.api.readOverrides()); + eq([before, c.api.countOverrides('liveScope')], [0, 2]); + assert.ok(/data-tab="display"[^>]*>[\s\S]*?cv2-tab-badge">2 x.toUpperCase())] = String(v); }, + getAttribute(n) { return n in this.attrs ? this.attrs[n] : null; }, + addEventListener() {}, + set innerHTML(v) { throw new Error('innerHTML used: ' + v); }, + }; + } + return { createElement: el, createElementNS: (_ns, tag) => el(tag) }; +} +function walk(n, fn) { fn(n); (n.children || []).forEach((c) => walk(c, fn)); } + +test('Display section: built with createElement, one bounded number input per key, the current value', () => { + const c = load(); + c.api.writeOverrides({ liveScope: { legendRows: 7 } }); + c.ctx.window.SITE_CONFIG = c.api.computeEffective({}, c.api.readOverrides()); + const root = c.api.buildLiveScopeSettings(fakeDoc()); + const inputs = [], texts = []; + walk(root, (n) => { if (n.tagName === 'INPUT') inputs.push(n); if (n.textContent) texts.push(n.textContent); }); + const by = {}; + inputs.forEach((i) => { by[i.attrs['data-cv2-live-scope']] = i; }); + eq(Object.keys(by).sort(), ['legendRows', 'windowMinutes']); + eq([by.windowMinutes.attrs.type, by.windowMinutes.attrs.min, by.windowMinutes.attrs.max, by.windowMinutes.value], ['number', '1', '60', '15']); + eq([by.legendRows.attrs.min, by.legendRows.attrs.max, by.legendRows.value], ['1', '12', '7']); + assert.ok(texts.some((t) => /Live scope legend/.test(t)), 'section title'); + assert.ok(root.attrs['data-cv2-live-scope-section'] !== undefined, 'section hook'); + assert.strictEqual(c.api.buildLiveScopeSettings(fakeDoc()) !== null, true); + assert.strictEqual(load({ noRule: true }).api.buildLiveScopeSettings(fakeDoc()), null, 'shown without the module'); +}); + +test('Display panel: a mount point for the section, after the other Live sections', () => { + const html = load().api.renderDisplay(); + assert.ok(/
<\/div>/.test(html), 'no mount point'); +}); + +test('CUSTOMIZATION.md names both window keys with their bounds and every palette key', () => { + const doc = fs.readFileSync(path.join(__dirname, 'docs/CUSTOMIZATION.md'), 'utf8'); + assert.ok(/`liveScope\.windowMinutes` \(1 to 60, default 15\)/.test(doc), 'windowMinutes'); + assert.ok(/`liveScope\.legendRows` \(1 to 12, default 12\)/.test(doc), 'legendRows'); + ['scope1', 'scope12', 'scopeNone', 'scopeUnknown', 'scopeOther'].forEach((k) => assert.ok(doc.includes('`' + k + '`'), k)); +}); + +for (const [name, fn] of tests) { + try { fn(); passed++; console.log(' ✅ ' + name); } catch (e) { failed++; console.log(' ❌ ' + name + ': ' + e.message); } +} +console.log('\n' + passed + ' passed, ' + failed + ' failed'); +process.exit(failed ? 1 : 0); diff --git a/test-all.sh b/test-all.sh index 722ace113..1d1d89790 100755 --- a/test-all.sh +++ b/test-all.sh @@ -122,6 +122,7 @@ run test-live-heard-filter.js run test-live-scope-color.js run test-881-live-moments.js run test-881-m3-customizer-moments.js +run test-882-m2-scope-customizer.js run test-883-kiosk-params.js run test-883-kiosk-tour.js run test-883-kiosk-numbers.js diff --git a/test-live-scope-color.js b/test-live-scope-color.js index 855713d61..393d75fef 100644 --- a/test-live-scope-color.js +++ b/test-live-scope-color.js @@ -230,7 +230,7 @@ test('perf: 30 000 classify+touch calls over 50 names < 50 ms, registry bounded' assert.ok(r.size() <= S.CAP); }); -test('style.css defines all 15 --scope-* variables in light and both dark blocks, dark blocks in sync', () => { +test('style.css defines all 15 --scope-* variables in light and both dark blocks (behind the colourblind hook of the mode), dark blocks in sync', () => { const css = fs.readFileSync(path.join(__dirname, 'public', 'style.css'), 'utf8'); function block(startRe) { const m = startRe.exec(css); @@ -244,7 +244,13 @@ test('style.css defines all 15 --scope-* variables in light and both dark blocks const out = {}; const re = /(--scope-[a-z0-9]+)\s*:\s*([^;]+);/g; let m; - while ((m = re.exec(text))) out[m[1]] = m[2].trim(); + // #882 M2: each value reads a colourblind preset hook first, + // var(--mc-scope--, #default); the default is what counts here. + while ((m = re.exec(text))) { + const v = m[2].trim(); + const hook = /^var\(--mc-scope-(light|dark)-([a-z0-9]+),\s*(#[0-9a-f]{6})\)$/.exec(v); + out[m[1]] = hook && '--scope-' + hook[2] === m[1] ? hook[1] + ':' + hook[3] : v; + } return out; } // The light block is the :root that holds --trace-ghost-color (no nesting). @@ -253,8 +259,8 @@ test('style.css defines all 15 --scope-* variables in light and both dark blocks const media = vars(block(/@media \(prefers-color-scheme: dark\)\s*\{\s*:root:not\(\[data-theme="light"\]\)/)); const manual = vars(block(/\n\[data-theme="dark"\]\s*\{\s*\n\s*color-scheme: dark;/)); for (const v of S.PALETTE_VARS) { - assert.ok(/^#[0-9a-f]{6}$/.test(light[v] || ''), 'light ' + v + ' = ' + light[v]); - assert.ok(/^#[0-9a-f]{6}$/.test(media[v] || ''), 'media dark ' + v + ' = ' + media[v]); + assert.ok(/^light:#[0-9a-f]{6}$/.test(light[v] || ''), 'light ' + v + ' = ' + light[v]); + assert.ok(/^dark:#[0-9a-f]{6}$/.test(media[v] || ''), 'media dark ' + v + ' = ' + media[v]); assert.strictEqual(manual[v], media[v], 'dark blocks differ on ' + v); } const distinct = (o) => new Set(S.PALETTE_VARS.map((v) => o[v])).size; From 5d926634aa98cc411160af3aebd6fb59ff163f29 Mon Sep 17 00:00:00 2001 From: dborup Date: Sat, 28 Nov 2026 11:33:21 +0100 Subject: [PATCH 2/2] reviewfix(live): dark-mode and case tests, achromat neutrals, one palette copy less (#882 M2) Review of #999: - test the dark half of _applyScopeCSS (a preset pick in dark mode stays off ) and its case-insensitive default comparison (mutants O1, O5); - setLiveScopeSetting(): the legend window's store rule, out of the change handler, like setFollowSetting; a default typed back clears the override (mutant O3), now unit-tested; - achromat scope palette: 14 even luminance steps (slots, unknown, other), each >= 1.13:1 from the next; "no scope" below 3:1 on the tile and >= 1.79:1 from every slot (was 1.02-1.05 against the nearest slot); - the Default colourblind preset no longer repeats the style.css palette, and Reset All derives the 15 hook names from SCOPE_COLOR_KEYS. Co-Authored-By: Claude Opus 5.5 --- docs/CUSTOMIZATION.md | 2 +- public/cb-presets.js | 26 +++++------- public/customize-v2.js | 22 ++++++---- test-882-m2-scope-customizer.js | 72 +++++++++++++++++++++++++++++---- 4 files changed, 90 insertions(+), 32 deletions(-) diff --git a/docs/CUSTOMIZATION.md b/docs/CUSTOMIZATION.md index 05cd182cd..81c3479f0 100644 --- a/docs/CUSTOMIZATION.md +++ b/docs/CUSTOMIZATION.md @@ -209,7 +209,7 @@ Some of the customizer's Display settings belong to an optional map layer and on - **Live Moments**: the Live page's moment cards, only while the operator has `moments.enabled`. `moments.enabled` (default `true`) is whether the Live page starts with them (a `?moments=` link and your own last choice on the Live page still win until Reset All); `moments.visibleCards` (1 to 5, default 3, desktop only: a phone shows one); `moments.dwellSeconds` (3 to 30, default 8) is how long a card stays; `moments.showNewNode`, `showBackOnline`, `showRecordLink` and `showBusiest` (default `true`) switch a kind off. The operator sets the defaults with `moments.display` in `config.json` (see above). The card fill and the four kind accents are the theme keys `momentCardBg`, `momentNewNode`, `momentBackOnline`, `momentRecordLink` and `momentBusiest` (CSS `--moment-*`), and the accents follow the colourblind preset. The operator's thresholds and rate stay in `config.json`. See [moments.md](moments.md). - **Live Map** (Follow a packet): how the replay of one followed packet plays in this browser, from the next follow. `follow.speed` is `0.5`, `1` (default) or `2` and divides every hop step; `follow.targetSeconds` (3 to 15 whole seconds, default 6) is the replay length aimed for at 1× (each hop step stays between 0.35 s and 1.5 s, so a very short or very deep path takes less or more); `follow.settleSeconds` (0 to 30 whole seconds, or empty) is how long following a just-heard packet waits for late observations before it loads. Empty is the server's `liveMap.propagationBufferMs` (5 s unless the operator changed it), and a value equal to it is not stored. A deep link, or a packet heard longer ago than the delay, loads at once. The colours are the theme keys `followRing` (rings, origin and card accent), `followRelay`, `followObserver` and `followFlag` (the unreliable-clock flag), CSS `--follow-*`, in light and dark; a colourblind preset sets the relay and observer pair. - **Live kiosk**: how a TV or wall screen running `#/live?kiosk=1` looks in this browser. `kiosk.scale` is the text and tile size: `auto` (the default: picked by the screen's size, 1 up to 2) or a fixed `1`, `1.25`, `1.5` or `2`. `kiosk.safeInsetVmin` is the margin kept clear at the screen edges for TV overscan, in % of the screen's short side, 0 to 10 (default 3). Set them once in the screen's own browser, outside kiosk, before opening the kiosk link (a kiosk screen hides the customizer). Your browser's value wins over the operator's `kiosk` preset in `config.json` (below), which wins over the defaults; a value equal to the operator's is not stored. A running kiosk takes a change at once. In an exported file this section is per browser: placed on a server as `theme.json` it is ignored there, so put the operator's values in `config.json`. -- **Live scope legend**: the SCOPES list on the Live page with "Color by scope" on (always offered). `liveScope.windowMinutes` (1 to 60, default 15) is how long a scope stays listed, and keeps its colour slot, after its last packet; `liveScope.legendRows` (1 to 12, default 12) is how many of the most recent scopes are listed, the rest showing as "+N more". They apply to this browser only. The colours are the theme keys `scope1` to `scope12` (the 12 slots a scope name is given), `scopeNone` (no scope), `scopeUnknown` (scoped, region not known) and `scopeOther` (beyond 12 active scopes), CSS `--scope-*`, under Theme → **Live scope colours** with a light and a dark value. Every theme preset keeps the default palette; a colourblind preset brings its own for each mode, and your own colour wins over both. +- **Live scope legend**: the SCOPES list on the Live page with "Color by scope" on (always offered). `liveScope.windowMinutes` (1 to 60, default 15) is how long a scope stays listed, and keeps its colour slot, after its last packet; `liveScope.legendRows` (1 to 12, default 12) is how many of the most recent scopes are listed, the rest showing as "+N more". They apply to this browser only. The colours are the theme keys `scope1` to `scope12` (the 12 slots a scope name is given), `scopeNone` (no scope), `scopeUnknown` (scoped, region not known) and `scopeOther` (beyond 12 active scopes), CSS `--scope-*`, under Theme → **Live scope colours** with a light and a dark value. Every theme preset keeps the default palette; a colourblind preset other than Default brings its own for each mode (achromatopsia keeps no scope, unknown and other apart from every slot by luminance), and your own colour wins over both. - **Oblique Photos**: how the oblique aerial photo (Skråfoto) viewer opens, only while the server offers the photos. `skraafoto.direction` is the first photo: `auto` (the default: across the line when opened from a Path profile, otherwise north), `north`, `east`, `south`, `west` or `nadir`; a shared link's direction still wins. `skraafoto.zoom` is `zoomed` (the default: each new photo opens on the crop around the point, where the point is in the photo, otherwise on the whole photo) or `overview` (the whole photo first). `skraafoto.lineOfSight` (default `true`) draws the line of sight from a Path profile; this row is shown only with the Path profile tool. These are viewer settings; the server's `map.skraafoto` config is not part of the customizer. - **Predicted reach**: the default environment loss of the Map's Predicted reach panel (#968), only while the server offers the predicted reach. `reach.environmentLossDb` (0 to 60 dB, empty by default) is the buildings, trees and other clutter the terrain model does not include. Empty means the operator's `map.coverage.environmentLossDb` in `config.json` (default 25 dB). A link's own value (`renv`) still wins, and the panel's Reset returns to your default. It stays in the browser: it is never sent to the server and changes no request. Like the other sections here it is a per-browser value: a `theme.json` on the server ignores it, so operators set theirs in `config.json`. diff --git a/public/cb-presets.js b/public/cb-presets.js index 7cf80ba1b..46cf52206 100644 --- a/public/cb-presets.js +++ b/public/cb-presets.js @@ -62,16 +62,9 @@ momentAccents: { newNode: '#009E73', backOnline: '#2E86C1', recordLink: '#B8578A', busiest: '#D55E00' }, // #880 M3 — Live "Follow a packet" relay / observer dots, each >= 3:1 // on the light and the dark card (test-880-m3-follow-customizer.js). - followAccents: { relay: '#D55E00', observer: '#2E86C1' }, - // #882 M2 — Live scope colours, slots 1-12 then none / unknown / other, - // one list per base-map mode: the stylesheet palette (Okabe-Ito based), so this preset changes nothing. - // Each slot >= 3:1 on the map tile (test-882-m2-scope-customizer.js). - scopePalette: { - light: ['#0072b2', '#009e73', '#b35c00', '#7e3fa0', '#a8780b', '#00838f', '#b0306f', '#4b5eaa', '#5e8b2f', '#8b4513', '#c026d3', '#6d6d00', - '#a1a1aa', '#57534e', '#111827'], - dark: ['#3d8bfd', '#3fd7a5', '#f0a03c', '#c49be0', '#e6c34a', '#4dd0e1', '#f06292', '#8c9eff', '#a5d66b', '#d7a07a', '#e879f9', '#dce775', - '#6b7280', '#c4b5a5', '#f8fafc'] - } + followAccents: { relay: '#D55E00', observer: '#2E86C1' } + // #882 M2 — no scopePalette: the Live scope colours are the stylesheet's + // (style.css --scope-*, Okabe-Ito based), so this preset changes nothing. }, { id: 'deut', @@ -252,12 +245,15 @@ followAccents: { relay: '#8f8f8f', observer: '#6f6f6f' }, // #882 M2 — Live scope colours, slots 1-12 then none / unknown / other, // one list per base-map mode: a luminance ramp, darkest first on light tiles, lightest first on dark. - // Each slot >= 3:1 on the map tile (test-882-m2-scope-customizer.js). + // Luminance is the only cue, so the ramp is 14 even steps from black (white) to just above + // 3:1 on the tile: slots 1-12, then unknown and other, each step >= 1.13:1 from the next. + // "No scope" (most traffic) sits below 3:1, as in the stylesheet's light palette, and + // >= 1.79:1 from every slot. Each slot >= 3:1 on the map tile (test-882-m2-scope-customizer.js). scopePalette: { - light: ['#000000', '#1a1a1a', '#2b2b2b', '#3a3a3a', '#474747', '#525252', '#5c5c5c', '#666666', '#6e6e6e', '#767676', '#7e7e7e', '#858585', - '#a1a1aa', '#57534e', '#111827'], - dark: ['#ffffff', '#f0f0f0', '#e0e0e0', '#d1d1d1', '#c2c2c2', '#b3b3b3', '#a6a6a6', '#999999', '#8c8c8c', '#808080', '#757575', '#6b6b6b', - '#6b7280', '#c4b5a5', '#f8fafc'] + light: ['#000000', '#151515', '#222222', '#2c2c2c', '#363636', '#3f3f3f', '#484848', '#505050', '#595959', '#626262', '#6b6b6b', '#757575', + '#a2a2a2', '#7f7f7f', '#898989'], + dark: ['#ffffff', '#f0f0f0', '#e1e1e1', '#d3d3d3', '#c6c6c6', '#b9b9b9', '#adadad', '#a2a2a2', '#979797', '#8d8d8d', '#828282', '#797979', + '#525252', '#6f6f6f', '#666666'] } } ]; diff --git a/public/customize-v2.js b/public/customize-v2.js index 4d0d9a551..324038d28 100644 --- a/public/customize-v2.js +++ b/public/customize-v2.js @@ -829,6 +829,16 @@ return R.resolve(sec && typeof sec === 'object' ? sec : {}); } + /** Stores a viewer's legend window value. The default is a cleared + * override (no stale dot or badge); a bad value is refused (false). */ + function setLiveScopeSetting(key, val) { + var R = _liveScopeRule(); + if (!R || !isValidLiveScopeSetting(key, val)) return false; + if (val === R.DEFAULTS[key]) clearOverride('liveScope', key); + else setOverride('liveScope', key, val); + return true; + } + // ── #968 M2 — Live kiosk: the screen's text size and edge margin ── // kiosk.scale and kiosk.safeInsetVmin, per browser. The keys, steps and // bounds are the kiosk's own rule (public/live-kiosk.js, @@ -4162,12 +4172,7 @@ var R = _liveScopeRule(); if (!R) return; var v = /^[0-9]{1,3}$/.test(inp.value) ? Number(inp.value) : undefined; - if (v === undefined || !isValidLiveScopeSetting(key, v)) { - inp.value = String(liveScopeSettings(_getEffective())[key]); - return; - } - if (v === R.DEFAULTS[key]) clearOverride('liveScope', key); - else setOverride('liveScope', key, v); + if (v === undefined || !setLiveScopeSetting(key, v)) inp.value = String(liveScopeSettings(_getEffective())[key]); }); }); @@ -4811,8 +4816,8 @@ ['new-node', 'back-online', 'record-link', 'busiest'].forEach(function (k) { rs.removeProperty('--mc-moment-' + k); }); // #882 M2 — the colourblind preset's scope palette, both modes. ['light', 'dark'].forEach(function (mode) { - ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', 'none', 'unknown', 'other'].forEach(function (sx) { - rs.removeProperty('--mc-scope-' + mode + '-' + sx); + SCOPE_COLOR_KEYS.forEach(function (k) { + rs.removeProperty(THEME_CSS_MAP[k].replace('--scope-', '--mc-scope-' + mode + '-')); }); }); ['light', 'dark'].forEach(function (mode) { @@ -4985,6 +4990,7 @@ renderTheme: _renderTheme, isValidLiveScopeSetting: isValidLiveScopeSetting, liveScopeSettings: liveScopeSettings, + setLiveScopeSetting: setLiveScopeSetting, buildLiveScopeSettings: _buildLiveScopeSettings }; })(); diff --git a/test-882-m2-scope-customizer.js b/test-882-m2-scope-customizer.js index 227862585..07f9a1e23 100644 --- a/test-882-m2-scope-customizer.js +++ b/test-882-m2-scope-customizer.js @@ -146,6 +146,30 @@ test('applyCSS: a value equal to the stylesheet default (a preset pick) leaves - assert.strictEqual(c.rootStyle._props['--scope-1'], undefined, 'a cleared pick stays inline'); }); +test('applyCSS, dark mode: a preset pick is compared with the dark stylesheet defaults and stays off ', () => { + const d = load({ theme: 'dark' }); + d.api.init({}); + const p = d.api.PRESETS.ocean; + d.api.writeOverrides({ theme: Object.assign({}, p.theme), themeDark: Object.assign({}, p.themeDark) }); + d.api.applyCSS(d.api.computeEffective({}, d.api.readOverrides()), d.api.readOverrides()); + SCOPE_KEYS.forEach((k) => assert.strictEqual(d.rootStyle._props[VAR(k)], undefined, k + ' stamped inline in dark mode: a colourblind preset could not win')); + const D = cssDefaults('dark'); + assert.notStrictEqual(D.scope1[0], cssDefaults('light').scope1[0], 'the modes must differ for this test to mean anything'); + d.api.writeOverrides({ themeDark: { scope1: cssDefaults('light').scope1[0] } }); + d.api.applyCSS(d.api.computeEffective({}, d.api.readOverrides()), d.api.readOverrides()); + assert.strictEqual(d.rootStyle._props['--scope-1'], cssDefaults('light').scope1[0], 'the light default is a real pick in dark mode'); +}); + +test('applyCSS: the default comparison ignores case (an imported #0072B2 is still the default)', () => { + const c = load(); + c.api.init({}); + const up = {}; + SCOPE_KEYS.forEach((k) => { up[k] = cssDefaults('light')[k][0].toUpperCase(); }); + c.api.writeOverrides({ theme: up }); + c.api.applyCSS(c.api.computeEffective({}, c.api.readOverrides()), c.api.readOverrides()); + SCOPE_KEYS.forEach((k) => assert.strictEqual(c.rootStyle._props[VAR(k)], undefined, k + ' ' + up[k] + ' stamped inline')); +}); + // ── 3. Colourblind presets ────────────────────────────────────────────────── function loadPresets() { @@ -159,9 +183,9 @@ function loadPresets() { } const CB_IDS = ['default', 'deut', 'prot', 'trit', 'achromat']; -test('cb-presets: every preset sets a light and a dark value for all 15 scope colours; clearPreset removes them', () => { +test('cb-presets: every tuned preset sets a light and a dark value for all 15 scope colours; clearPreset removes them', () => { const { MCP, props } = loadPresets(); - CB_IDS.forEach((id) => { + CB_IDS.filter((id) => id !== 'default').forEach((id) => { assert.ok(MCP.applyPreset(id, { skipPersist: true }), id); ['light', 'dark'].forEach((mode) => SCOPE_KEYS.forEach((k) => { const v = props['--mc-scope-' + mode + '-' + SUFFIX(k)]; @@ -172,14 +196,12 @@ test('cb-presets: every preset sets a light and a dark value for all 15 scope co eq(Object.keys(props).filter((k) => /scope/.test(k)), []); }); -test('cb-presets: the Default (Wong) preset is the stylesheet palette', () => { +test('cb-presets: the Default (Wong) preset carries no scope palette, so the stylesheet decides; it clears a tuned one', () => { const { MCP, props } = loadPresets(); + assert.strictEqual(MCP.list.find((p) => p.id === 'default').scopePalette, undefined, 'a second copy of the style.css palette'); + MCP.applyPreset('achromat', { skipPersist: true }); MCP.applyPreset('default', { skipPersist: true }); - const L = cssDefaults('light'), D = cssDefaults('dark'); - SCOPE_KEYS.forEach((k) => { - assert.strictEqual(props['--mc-scope-light-' + SUFFIX(k)].toLowerCase(), L[k][0], 'light ' + k); - assert.strictEqual(props['--mc-scope-dark-' + SUFFIX(k)].toLowerCase(), D[k][0], 'dark ' + k); - }); + eq(Object.keys(props).filter((k) => /scope/.test(k)), []); }); test('cb-presets: tuned palettes have 12 distinct slots, each >= 3:1 on the map tile of its mode (WCAG 1.4.11)', () => { @@ -198,6 +220,24 @@ test('cb-presets: tuned palettes have 12 distinct slots, each >= 3:1 on the map }); }); +// Luminance is the achromat palette's only cue: no scope, unknown and other +// must not draw like a named slot (review of #999, finding 3). +test('cb-presets: achromat keeps none / unknown / other >= 1.13:1 in luminance from every slot and from each other', () => { + const { MCP, props } = loadPresets(); + const C = MCP.wcag.contrast; + MCP.applyPreset('achromat', { skipPersist: true }); + ['light', 'dark'].forEach((mode) => { + const col = (k) => props['--mc-scope-' + mode + '-' + SUFFIX(k)]; + const slots = SCOPE_KEYS.slice(0, 12).map(col); + const neutrals = ['scopeNone', 'scopeUnknown', 'scopeOther']; + neutrals.forEach((k) => slots.forEach((sl, i) => assert.ok(C(col(k), sl) >= 1.13, + mode + ' ' + k + ' ' + col(k) + ' vs slot ' + (i + 1) + ' ' + sl + ' = ' + C(col(k), sl).toFixed(2)))); + for (let a = 0; a < 3; a++) for (let b = a + 1; b < 3; b++) { + assert.ok(C(col(neutrals[a]), col(neutrals[b])) >= 1.13, mode + ' ' + neutrals[a] + ' vs ' + neutrals[b]); + } + }); +}); + test('style.css: each --scope-* reads the colourblind preset hook of its mode, once per block', () => { const L = cssDefaults('light'), D = cssDefaults('dark'); SCOPE_KEYS.forEach((k) => { @@ -327,6 +367,22 @@ test('export / import round trip: palette and window', () => { assert.ok(b.api.validateShape({ theme: { scope2: 'red;}' } }).valid === false, 'a bad colour is accepted on import'); }); +test('setLiveScopeSetting: the default is a cleared override, a bad value is refused', () => { + const c = load(); + c.api.init({}); + assert.strictEqual(c.api.setLiveScopeSetting('windowMinutes', 5), true); + assert.strictEqual(c.api.setLiveScopeSetting('legendRows', 3), true); + eq(c.api.readOverrides().liveScope, { windowMinutes: 5, legendRows: 3 }); + assert.strictEqual(c.api.setLiveScopeSetting('windowMinutes', 15), true); + assert.strictEqual(c.api.setLiveScopeSetting('legendRows', 12), true); + assert.strictEqual(c.api.countOverrides('liveScope'), 0, 'a default typed back left an override (stale dot and badge)'); + eq(c.api.readOverrides().liveScope || null, null); + assert.strictEqual(c.api.setLiveScopeSetting('legendRows', 40), false); + assert.strictEqual(c.api.setLiveScopeSetting('nope', 1), false); + assert.strictEqual(c.api.countOverrides('liveScope'), 0); + assert.strictEqual(load({ noRule: true }).api.setLiveScopeSetting('legendRows', 3), false, 'accepted without the module'); +}); + test('persistence: the section is stored per browser in cs-theme-overrides', () => { const c = load(); c.api.writeOverrides({ liveScope: { legendRows: 4 } });