seriesoftubes/tests/dark-mode.test.js
jvanvik 27ffa33d7c Dark mode: red text and the market's heat tags read on the dark panels (#80)
Red warning text used var(--bad), 3.8 to 4.8:1 on the dark cards and tints.
Every text use now takes var(--tx-red,var(--bad)): light mode keeps --bad,
dark gets #FF8E9B (5.65:1 or better on paper, soft and every tint). --bad
stays the fill under white letters (buttons, counters, bars).

Lambda Bazaar's Hot and Cool tags kept their light pastel chips at night.
They now use the dark tints (--tint-o, --tint-b) with --tx-amber and a new
--tx-blue, keeping the same colours by day.

The dark-mode test checks the tags, the text tokens on every dark card, that
no tag keeps a bare pastel fill, and that no red text in --bad is left in the
styles or the game's markup.
2026-11-09 23:01:43 +01:00

424 lines
31 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Dark mode (#80): Settings › Theme is Auto (the device's light or dark setting), Light or Dark, a choice kept on the
// device (localStorage sot-theme), never in the save. The page's <head> sets <html data-theme> before the first paint;
// the panels follow through CSS custom properties, and the map paints its sea, land, clouds and labels in the night
// colours in both renderers, painting its cached layers again once when the theme changes (not on every frame).
// jsdom has no matchMedia: the tests lend the page one, before it is parsed (the harness's browser hook) or after.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { JSDOM } = require('jsdom');
const { load, browser, flush } = require('./harness');
const { assemble } = require('../scripts/lib/page');
// A device setting the test can flip: matchMedia('(prefers-color-scheme: dark)') with change listeners.
const device = (dark) => {
const q = { matches: dark, media: '(prefers-color-scheme: dark)', fns: [],
addEventListener(t, f) { if (t === 'change') this.fns.push(f); }, removeEventListener(t, f) { this.fns = this.fns.filter((x) => x !== f); },
set(v) { this.matches = v; for (const f of this.fns.slice()) f({ matches: v }); } };
return { q, attach(w) { w.matchMedia = (m) => (/prefers-color-scheme:\s*dark/.test(m) ? q : { matches: false, addEventListener() {}, removeEventListener() {} }); } };
};
const meta = (doc, n) => doc.querySelector(`meta[name="${n}"]`).getAttribute('content');
// WCAG contrast between two #RRGGBB colours.
const lum = (h) => { h = h.replace('#', ''); const c = [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16) / 255).map((v) => (v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4)); return 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]; };
const cr = (a, b) => { const x = lum(a), y = lum(b); return (Math.max(x, y) + 0.05) / (Math.min(x, y) + 0.05); };
// Only the page's <head>, up to its styles, as the browser runs it before the first paint: the game script at the end
// of <body> (which sets the theme as well, but late) is not there. ls: what window.localStorage gives, or throws.
const headOnly = (dark, ls) => {
const html = assemble().html, head = html.slice(0, html.indexOf('<style>')) + '</head><body></body></html>';
const dom = new JSDOM(head, { runScripts: 'dangerously', url: 'https://tests.invalid/', beforeParse(w) {
device(dark).attach(w);
if (ls) Object.defineProperty(w, 'localStorage', { configurable: true, get: () => ls(w) });
} });
const doc = dom.window.document, r = [doc.documentElement.getAttribute('data-theme'), meta(doc, 'theme-color'), meta(doc, 'color-scheme')];
dom.window.close();
return r;
};
const DARK = ['dark', '#0E2A44', 'dark'], LIGHT = ['light', '#57C4E5', 'light'];
const started = "ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.nextFail=S.nextEvent=1e9;UI.speed=0;closeModal();compute();renderAll();";
test('the choice applies at boot, from the <head>, before the page is painted', () => {
for (const [storage, want, pref] of [[{ 'sot-theme': 'dark' }, 'dark', 'dark'], [{ 'sot-theme': 'light' }, 'light', 'light'], [{}, 'light', 'auto'], [{ 'sot-theme': 'neon' }, 'light', 'auto']]) {
const { dom, ev, errors } = load({ storage });
const doc = dom.window.document;
assert.equal(doc.documentElement.getAttribute('data-theme'), want, JSON.stringify(storage));
assert.equal(meta(doc, 'theme-color'), want === 'dark' ? '#0E2A44' : '#57C4E5', 'the browser bar follows');
assert.equal(meta(doc, 'color-scheme'), want);
assert.equal(ev('THEME.pref'), pref);
assert.equal(ev('THEME.dark'), want === 'dark');
assert.deepEqual(errors, []);
dom.window.close();
}
// The script that sets it sits in the <head>, before the styles: nothing is painted in the wrong colours first. Read
// from the page's HTML (the harness runs script bodies outside the DOM, so a <script>'s text is empty there).
const html = assemble().html, headEnd = html.indexOf('</head>'), st = html.indexOf('<style>');
const scripts = [...html.slice(0, headEnd).matchAll(/<script>([\s\S]*?)<\/script>/g)], s = scripts.find((m) => /sot-theme/.test(m[1]));
assert.ok(s && st >= 0 && st < headEnd && s.index < st, 'the theme script runs before the stylesheet');
// Auto with a dark device: dark from the first paint as well.
const d = device(true), h = load({ browser: d });
assert.equal(h.dom.window.document.documentElement.getAttribute('data-theme'), 'dark');
assert.equal(h.ev('THEME.dark'), true);
assert.deepEqual(h.errors, []);
});
test('the <head> alone sets the theme, and a dark device stays dark when the site\'s storage is blocked', () => {
const saved = (v) => () => ({ getItem: (k) => (k === 'sot-theme' ? v : null) });
assert.deepEqual(headOnly(true), DARK, 'Auto on a dark device');
assert.deepEqual(headOnly(false), LIGHT, 'Auto on a light device');
assert.deepEqual(headOnly(false, saved('dark')), DARK, 'Dark chosen');
assert.deepEqual(headOnly(true, saved('light')), LIGHT, 'Light chosen');
// Cookies and site data blocked (Chrome, sandboxed frames: a SecurityError), storage switched off (Firefox: null),
// or a getItem that throws: the device's setting still decides, before the first paint.
const blocked = [(w) => { throw new w.DOMException('The operation is insecure.', 'SecurityError'); }, () => null, () => ({ getItem() { throw new Error('denied'); } })];
for (const ls of blocked) {
assert.deepEqual(headOnly(true, ls), DARK, `dark device, blocked storage (${ls})`);
assert.deepEqual(headOnly(false, ls), LIGHT, `light device, blocked storage (${ls})`);
}
// The whole page with blocked storage on a dark device: dark, on Auto.
const blockedDevice = { attach(w) { device(true).attach(w); Object.defineProperty(w, 'localStorage', { configurable: true, get() { throw new w.DOMException('The operation is insecure.', 'SecurityError'); } }); } };
const { dom, ev, errors } = load({ browser: blockedDevice });
assert.equal(dom.window.document.documentElement.getAttribute('data-theme'), 'dark');
assert.deepEqual(JSON.parse(ev('JSON.stringify([THEME.pref,THEME.dark])')), ['auto', true]);
assert.deepEqual(errors, []);
dom.window.close();
});
test('Auto follows the device when its setting changes; Light and Dark do not', () => {
const d = device(false), { dom, ev, errors } = load({ browser: d });
const root = dom.window.document.documentElement;
ev(started);
assert.equal(root.getAttribute('data-theme'), 'light');
d.q.set(true);
assert.equal(root.getAttribute('data-theme'), 'dark', 'the device went dark');
assert.equal(ev('THEME.dark'), true);
assert.equal(meta(dom.window.document, 'theme-color'), '#0E2A44');
d.q.set(false);
assert.equal(root.getAttribute('data-theme'), 'light', 'and light again');
ev("ACT.themeSet({v:'dark'})");
d.q.set(true); d.q.set(false);
assert.equal(root.getAttribute('data-theme'), 'dark', 'Dark stays dark whatever the device says');
ev("ACT.themeSet({v:'light'})");
d.q.set(true);
assert.equal(root.getAttribute('data-theme'), 'light', 'Light stays light');
ev("ACT.themeSet({v:'auto'})");
assert.equal(root.getAttribute('data-theme'), 'dark', 'Auto takes the device setting at once');
assert.equal(d.q.fns.length, 1, 'one listener');
assert.deepEqual(errors, []);
});
test('a choice made in one tab reaches the others (the NOC window on a second screen too)', async () => {
const b = browser(), A = load({ browser: b }), B = load({ browser: b });
A.ev("ACT.themeSet({v:'dark'})");
await flush();
assert.equal(B.dom.window.document.documentElement.getAttribute('data-theme'), 'dark');
assert.equal(B.ev('THEME.pref'), 'dark');
A.ev("ACT.themeSet({v:'auto'})");
await flush();
assert.equal(B.dom.window.document.documentElement.getAttribute('data-theme'), 'light');
assert.deepEqual([...A.errors, ...B.errors], []);
for (const h of [A, B]) h.dom.window.close();
});
test('Settings › Theme: three choices, on the title screen and in a game, kept on the device and not in the save', () => {
const { dom, ev, errors } = load();
const doc = dom.window.document, root = doc.documentElement;
const row = () => [...doc.querySelectorAll('#modalCard [data-act="themeSet"]')].map((b) => [JSON.parse(b.dataset.args).v, b.textContent, b.className.includes('pink')]);
// The title screen: no game yet, the button still works.
ev('ACT.settings({})');
assert.deepEqual(row(), [['auto', 'Auto', true], ['light', 'Light', false], ['dark', 'Dark', false]]);
doc.querySelector('#modalCard [data-act="themeSet"][data-args*="dark"]').click();
assert.equal(root.getAttribute('data-theme'), 'dark');
assert.equal(ev("localStorage.getItem('sot-theme')"), 'dark');
assert.deepEqual(row().map((r) => r[2]), [false, false, true], 'the settings show the new choice');
ev("ACT.settingsClose({})");
// In a game: the choice is not part of it.
ev(started);
const before = ev('JSON.stringify(S)');
ev("ACT.settings({});ACT.themeSet({v:'light'})");
assert.equal(root.getAttribute('data-theme'), 'light');
assert.equal(ev("localStorage.getItem('sot-theme')"), 'light');
assert.equal(ev('JSON.stringify(S)'), before, 'the save is untouched');
ev("ACT.themeSet({v:'auto'})");
assert.equal(ev("localStorage.getItem('sot-theme')"), null, 'Auto is the default: nothing kept');
ev("ACT.themeSet({v:'sepia'});ACT.themeSet({})");
assert.equal(ev('THEME.pref'), 'auto', 'anything else is ignored');
// A puzzle keeps its settings working.
assert.ok(ev("PZ_ACTS.has('themeSet')"));
assert.deepEqual(errors, []);
});
test('the map paints sea, land, clouds and labels in the theme\'s colours, in 2D, and paints its cached land again once', () => {
const { ev, errors } = load({ storage: { 'sot-map': '2d' } });
ev(started + "const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;");
// What paintWorld() fills and strokes, on a recording context.
const world = () => JSON.parse(ev(`(()=>{const r={f:[],s:[],save(){},restore(){},translate(){},beginPath(){},moveTo(){},lineTo(){},ellipse(){},setLineDash(){},
fill(){this.f.push(this.fillStyle);},stroke(){this.s.push(this.strokeStyle);}};paintWorld(r,1.4,false);return JSON.stringify({f:[...new Set(r.f)],s:[...new Set(r.s)]});})()`));
const P = JSON.parse(ev('JSON.stringify(MAP_PAL)'));
let w = world();
assert.deepEqual(w.f, [P.light.shadow, P.light.land, P.light.hill, P.light.shine]);
assert.deepEqual(w.s, [P.light.sand, P.light.coast]);
// The sea's gradient, the waves and the clouds of a 2D frame, and the labels' pills.
ev(`window.__sea=[];CTX0.createLinearGradient=()=>({addColorStop:(o,c)=>__sea.push(c)});window.__pills=[];const __p=pill;pill=function(t,f,w,h,r,fill,ink,edge){__pills.push(fill+'/'+ink+'/'+edge);return __p.apply(this,arguments);};
window.__paints=0;const __pw=paintWorld;paintWorld=function(){__paints++;return __pw.apply(this,arguments);};`);
const frame = (t) => JSON.parse(ev(`(()=>{__sea.length=0;__pills.length=0;__paints=0;draw(${t});return JSON.stringify({sea:__sea.slice(),pills:[...new Set(__pills)],paints:__paints,wave:CTX0.strokeStyle});})()`));
let f = frame(1000);
assert.deepEqual(f.sea, [P.light.sea, P.light.sea2]);
assert.ok(f.pills.includes(`${P.light.pill}/${P.light.pillInk}/${P.light.pillEdge}`), 'city labels on white pills');
assert.equal(frame(1000).paints, 0, 'nothing changed: the land is not painted again');
ev("ACT.themeSet({v:'dark'})");
assert.equal(ev('WL.key'), null, 'the land picture is let go');
assert.equal(ev('SPRC.size'), 0, 'and every sprite painted in the old colours');
w = world();
assert.deepEqual(w.f, [P.dark.shadow, P.dark.land, P.dark.hill, P.dark.shine]);
assert.deepEqual(w.s, [P.dark.sand, P.dark.coast]);
f = frame(1016);
assert.deepEqual(f.sea, [P.dark.sea, P.dark.sea2]);
assert.equal(f.paints, 1, 'the land is painted again, once');
assert.ok(f.pills.includes(`${P.dark.pill}/${P.dark.pillInk}/${P.dark.pillEdge}`), 'city labels on dark pills');
assert.ok(!f.pills.includes(`${P.light.pill}/${P.light.pillInk}/${P.light.pillEdge}`), 'no light label left');
assert.ok(f.pills.some((p) => p.startsWith('#FF4F9A/')), 'your POPs keep their pink labels');
assert.equal(frame(1016).paints, 0, 'and not on the next frame');
// Paused and unmoved, the map is drawn again for the theme (mapStill() would otherwise keep the old frame).
ev("FRAME.length=0;mapStill(0,performance.now());UI.drawnAt=performance.now();");
// mapStill() says how the map stands (MAP_MOVING, MAP_AMBIENT, MAP_STILL; 99-loop.js), not just whether it is still.
assert.equal(ev('mapStill(0,performance.now())'), ev('MAP_STILL'), 'an unchanged frame is skipped');
ev("ACT.themeSet({v:'light'})");
assert.equal(ev('mapStill(0,performance.now())'), ev('MAP_MOVING'), 'a theme change draws the map again');
assert.deepEqual(errors, []);
});
// A WebGL2 stand-in that records calls (as tests/webgl-map.test.js).
const STUB = `(()=>{const calls=[];const gl=new Proxy({calls},{get(t,k){if(k in t)return t[k];if(typeof k==='string'&&/^[A-Z_0-9]+$/.test(k))return k;
if(k==='isContextLost')return ()=>false;return (...a)=>{calls.push([k,...a]);return {};};}});
const c=document.getElementById('mapgl'),f=document.getElementById('mapfx');
const P=()=>({p:{},u:{}}),B=()=>({v:{},b:{}});
Object.assign(GLX,{want:true,dead:false,gl,c,f,fx:f.getContext('2d'),line:P(),pk:P(),fill:P(),fan:P(),ell:P(),land:{},circ:P(),tex:{},lv:B(),hv:B(),pv:B(),cb:B(),wv:B(),dv:B(),cl:B(),empty:{},key:[],gpu:'stub'});return gl;})()`;
test('on the graphics card too: the sea, the land and its coastlines in the theme\'s colours, built again once', () => {
const { ev, errors } = load();
ev(started + "const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;");
ev(STUB);
const pm = (s) => JSON.parse(ev(`JSON.stringify(glPm(${JSON.stringify(s)}))`));
const P = JSON.parse(ev('JSON.stringify(MAP_PAL)'));
// The colours sent with uniform4fv (sea, land, hills, clouds) and the coastline colours in the land's buffers.
const frame = (t) => JSON.parse(ev(`(()=>{GLX.gl.calls.length=0;draw(${t});const c=GLX.gl.calls;
const u=c.filter(x=>x[0]==='uniform4fv').map(x=>Array.from(x[2]).map(v=>Math.round(v*1e4)/1e4).join(','));
const lines=c.filter(x=>x[0]==='bufferData'&&x[3]==='STATIC_DRAW'&&x[2]&&x[2].length%LINE_STRIDE===0&&x[2].length>LINE_STRIDE*1000).map(x=>[x[2][9],x[2][10],x[2][11]].map(v=>Math.round(v*1e4)/1e4).join(','));
return JSON.stringify({u:[...new Set(u)],lines,del:c.filter(x=>x[0]==='deleteBuffer').length,land:Object.keys(GLX.land).length});})()`));
const key = (a) => a.map((v) => Math.round(v * 1e4) / 1e4).join(',');
const rgb = (s) => key(JSON.parse(ev(`JSON.stringify(glColor(${JSON.stringify(s)}).slice(0,3))`)));
let f = frame(1000);
assert.equal(ev('glOn()'), true);
for (const k of ['sea', 'sea2', 'land', 'hill', 'shadow', 'cloud']) assert.ok(f.u.includes(key(pm(P.light[k]))), `light ${k} on the card`);
assert.ok(f.lines.includes(rgb(P.light.sand)) && f.lines.includes(rgb(P.light.coast)), 'light sand and coastline in the land buffers');
assert.equal(frame(1016).lines.length, 0, 'an ordinary frame uploads no land');
assert.equal(ev('glPal()===glPal()&&GLP.m===MAP_PAL.light'), true, 'the colours are worked out once, not per frame');
ev("ACT.themeSet({v:'dark'})");
assert.equal(ev('Object.keys(GLX.land).length'), 0, 'the land is let go');
assert.ok(ev("GLX.gl.calls.filter(x=>x[0]==='deleteBuffer').length") > 0, 'its buffers freed');
f = frame(1032);
for (const k of ['sea', 'sea2', 'land', 'hill', 'shadow', 'cloud']) assert.ok(f.u.includes(key(pm(P.dark[k]))), `dark ${k} on the card`);
assert.ok(!f.u.includes(key(pm(P.light.sea))), 'no light sea left');
assert.ok(f.lines.includes(rgb(P.dark.sand)) && f.lines.includes(rgb(P.dark.coast)), 'dark sand and coastline in the new land buffers');
assert.equal(f.land, 1, 'one level of land built for the view');
assert.equal(frame(1048).lines.length, 0, 'and only once');
assert.deepEqual(errors, []);
});
// Two tubes that were nearly lost at night: a dark fiber with no channels lit yet, and a virtual circuit on the ccn
// fabric (thin, dotted, purple). Every tube is drawn over its casing, which the theme gives (MAP_PAL.*.casing).
const TUBES = "S.links.push({id:'unlit',a:'fra',b:'ams',kind:'df',own:false,sys:'dwdm',ch:[],cable:null,km:kmBetween('fra','ams'),sub:false,mo:1000,trench:'t-unlit',ready:0,day:0,cut:0,spares:false},"
+ "{id:'vc',a:'fra',b:'lon',kind:'vxc',prov:'ccn',vt:1,km:kmBetween('fra','lon'),sub:false,mo:0,cut:0,day:0});compute();cam.x=CITY.fra.x;cam.y=CITY.fra.y;cam.z=1.4;";
const tubeCols = (ev) => JSON.parse(ev("JSON.stringify(Object.fromEntries(['unlit','vc'].map(id=>[id,linkLook([S.links.find(l=>l.id===id)],S.day).col])))"));
test('every tube keeps an outline that stands out from the land and the sea, by night as by day', () => {
const { ev, errors } = load({ storage: { 'sot-map': '2d' } });
ev(started + TUBES);
const P = JSON.parse(ev('JSON.stringify(MAP_PAL)')), col = tubeCols(ev);
assert.equal(ev('linkLook([S.links.find(l=>l.id==="unlit")],S.day).dark'), true, 'an unlit dark fiber');
assert.equal(col.vc, ev('FAB.ccn.col'), 'the ccn fabric\'s colour');
// The casing is what parts a tube from the map: 3:1 at least on the land and both ends of the sea, in either theme.
// The cores sit inside it, so they must stand out from it (the unlit fiber and the purple circuit are the darkest).
for (const t of ['light', 'dark']) {
for (const bg of ['land', 'sea', 'sea2']) assert.ok(cr(P[t].casing, P[t][bg]) >= 3, `${t}: the casing on the ${bg}: ${cr(P[t].casing, P[t][bg]).toFixed(2)}`);
for (const [k, c] of Object.entries(col)) assert.ok(cr(c, P[t].casing) >= 2.5, `${t}: the ${k} core in its casing: ${cr(c, P[t].casing).toFixed(2)}`);
}
// In 2D: each core is stroked right over its casing, in the theme's colour, and a switch changes it on the next frame.
ev("window.__st=[];CTX0.stroke=function(){__st.push(this.strokeStyle);};");
const strokes = (t) => JSON.parse(ev(`(()=>{__st.length=0;draw(${t});return JSON.stringify(__st);})()`));
const under = (st, c) => st.flatMap((x, i) => (x === c && i ? [st[i - 1]] : []));
let st = strokes(1000);
for (const c of Object.values(col)) assert.deepEqual([...new Set(under(st, c))], [P.light.casing], `light: ${c} over the light casing`);
ev("ACT.themeSet({v:'dark'})");
st = strokes(1016);
for (const c of Object.values(col)) assert.deepEqual([...new Set(under(st, c))], [P.dark.casing], `dark: ${c} over the dark casing`);
assert.deepEqual(errors, []);
});
test('on the graphics card the tubes\' casing is the theme\'s too (a uniform: the tubes\' buffers are not rebuilt)', () => {
const { ev, errors } = load();
ev(started + TUBES);
ev(STUB);
const P = JSON.parse(ev('JSON.stringify(MAP_PAL)'));
assert.ok(ev('GL_LINE_VS').includes('col=vec4(uCas,1.)'), 'the casing pass takes its colour from uCas');
assert.ok(!ev('GL_LINE_VS').includes('30./255.'), 'no casing colour left in the line shader');
ev("GLX.line.u.uCas='uCas'");
const rgb = (s) => JSON.parse(ev(`JSON.stringify(glColor(${JSON.stringify(s)}).slice(0,3))`)).map((v) => Math.round(v * 1e4) / 1e4).join(',');
const frame = (t) => JSON.parse(ev(`(()=>{GLX.gl.calls.length=0;draw(${t});const c=GLX.gl.calls;
return JSON.stringify({cas:[...new Set(c.filter(x=>x[0]==='uniform3f'&&x[1]==='uCas').map(x=>x.slice(2).map(v=>Math.round(v*1e4)/1e4).join(',')))],
tubes:c.filter(x=>x[0]==='bufferData'&&x[1]===GLX.lv.b).length,seg:GLX.nSeg});})()`));
let f = frame(1000);
assert.equal(ev('glOn()'), true);
assert.ok(f.seg > 0, 'tubes on the card');
assert.deepEqual(f.cas, [rgb(P.light.casing)]);
ev("ACT.themeSet({v:'dark'})");
f = frame(1016);
assert.deepEqual(f.cas, [rgb(P.dark.casing)], 'the dark casing on the next frame');
assert.equal(f.tubes, 0, 'without building the tubes again');
assert.deepEqual(errors, []);
});
test('a puzzle\'s stepping stones keep a dashed ring that reads on the night land and sea', () => {
const { ev, errors } = load();
ev("localStorage.removeItem('sot-puzzles');pzBegin(pzDef('baltic'));closeModal();");
assert.equal(ev("pzKind('hel')"), 'via', 'Helsinki is the stepping stone');
const P = JSON.parse(ev('JSON.stringify(MAP_PAL)'));
// An rgba() ring over a solid background, as the eye sees it.
const over = (rgba, bg) => { const [r, g, b, a] = rgba.match(/[\d.]+/g).map(Number), h = bg.replace('#', '');
return '#' + [r, g, b].map((v, i) => Math.round(v * a + parseInt(h.slice(i * 2, i * 2 + 2), 16) * (1 - a)).toString(16).padStart(2, '0')).join(''); };
for (const t of ['light', 'dark']) for (const bg of ['land', 'sea']) {
const c = cr(over(P[t].via, P[t][bg]), P[t][bg]);
assert.ok(c >= 3, `${t}: the stepping-stone ring on the ${bg}: ${c.toFixed(2)}`);
}
// The ring a frame strokes (dashed 5,5) is the theme's.
ev("window.__st=[];window.__d='';CTX0.setLineDash=function(a){__d=String(a);};CTX0.stroke=function(){__st.push(this.strokeStyle+'|'+__d);};");
const rings = (t) => JSON.parse(ev(`(()=>{__st.length=0;cam.x=CITY.hel.x;cam.y=CITY.hel.y;cam.z=2;draw(${t});return JSON.stringify([...new Set(__st.filter(s=>s.endsWith('|5,5')).map(s=>s.split('|')[0]))]);})()`));
assert.deepEqual(rings(1000), [P.light.via]);
ev("ACT.themeSet({v:'dark'})");
assert.deepEqual(rings(1016), [P.dark.via]);
assert.deepEqual(errors, []);
});
test('the Pie globe starts at night in the dark theme, unless the player picked day or night', () => {
let h = load({ storage: { 'sot-theme': 'dark' } });
assert.equal(h.ev('pgNightPref()'), true);
h.ev("ACT.themeSet({v:'light'})");
assert.equal(h.ev('PG.night'), false, 'it follows the theme while the player has not chosen');
h = load({ storage: { 'sot-theme': 'dark', 'sot-globe': 'day' } });
assert.equal(h.ev('pgNightPref()'), false, 'the player\'s day view stays');
h.ev("ACT.themeSet({v:'light'});ACT.themeSet({v:'dark'})");
assert.equal(h.ev('PG.night'), false);
assert.deepEqual(h.errors, []);
});
test('dark on a phone (360 px): the settings row, the panels and every language', () => {
for (const lang of ['en', 'de', 'fr']) {
const { dom, ev, errors } = load({ lang: lang === 'en' ? undefined : lang, storage: { 'sot-theme': 'dark' } });
const doc = dom.window.document;
ev("window.innerWidth=360;window.innerHeight=740;" + started + "ACT.launchBB({city:S.home});UI.sel={type:'city',id:S.home};renderAll();ACT.settings({});");
const line = doc.querySelector('#modalCard [data-act="themeSet"]').closest('.setline');
assert.ok(line, 'the Theme row is a settings line');
assert.equal(line.querySelectorAll('[data-act="themeSet"]').length, 3);
const names = [...line.querySelectorAll('[data-act="themeSet"]')].map((b) => b.textContent);
if (lang === 'de') assert.deepEqual(names, ['Auto', 'Hell', 'Dunkel']);
if (lang === 'fr') assert.deepEqual(names, ['Auto', 'Clair', 'Sombre']);
ev("ACT.settingsClose({});ACT.dash({})");
for (const id of ['hud', 'panelBody', 'leftBody', 'dashCard', 'tabbar']) {
const t = doc.getElementById(id).textContent;
assert.doesNotMatch(t, /\b(settings|common)\.[a-z0-9_]+\b|undefined|NaN/, `${lang} ${id}`);
}
assert.equal(ev('isPhone()'), true);
assert.equal(doc.documentElement.getAttribute('data-theme'), 'dark');
assert.deepEqual(errors, []);
dom.window.close();
}
});
// The styles: every dark token the panels use is defined, and text on the dark panels passes WCAG AA (4.5:1).
test('the dark look defines every token it is used with, and its text reads (AA)', () => {
const html = assemble().html, css = html.slice(html.indexOf('<style>'), html.indexOf('</style>'));
const block = (sel) => { const i = css.indexOf(sel + '{'); assert.ok(i >= 0, sel); return css.slice(i, css.indexOf('}', i)); };
const dark = block(':root[data-theme="dark"]'), light = block(':root');
const val = (b, k) => { const m = new RegExp(`--${k}:\\s*([^;\\n]+);`).exec(b); return m && m[1].trim(); };
// Every var(--tint-…, light) and var(--tx-…, light) in the styles and the game's own markup has a dark value.
const src = css + fs.readdirSync(path.join(__dirname, '..', 'src', 'game'), { recursive: true }).filter((f) => f.endsWith('.js')).map((f) => fs.readFileSync(path.join(__dirname, '..', 'src', 'game', f), 'utf8')).join('\n');
const used = new Set([...src.matchAll(/var\(--((?:tint|tx)-[a-z]+),\s*#[0-9A-Fa-f]{3,6}\)/g)].map((m) => m[1]));
assert.ok(used.size >= 8, `tints in use (${[...used]})`);
for (const k of used) assert.ok(val(dark, k), `--${k} has a dark value`);
// Every plain var(--x) in the styles is defined for the light look (dark only overrides).
for (const m of css.matchAll(/var\(--([a-z0-9-]+)\)/g)) if (!/^(tabbar|app-h|c|rc|d|x|t|r|dl|pzdock)$/.test(m[1])) assert.ok(val(light, m[1]), `--${m[1]} is defined`);
const bgs = ['paper', 'soft', 'tint-y', 'tint-g', 'tint-r', 'tint-p', 'tint-b', 'tint-v', 'tint-o', 'tint-n'].map((k) => [k, val(dark, k)]);
for (const t of ['text', 'ink2', 'eye']) for (const [k, b] of bgs) assert.ok(cr(val(dark, t), b) >= 4.5, `--${t} on --${k}: ${cr(val(dark, t), b).toFixed(2)}`);
// The text colours of warnings and tags read on every card and tint they sit on, not only on the paper.
for (const t of ['tx-red', 'tx-amber', 'tx-blue']) for (const [k, b] of bgs) assert.ok(cr(val(dark, t), b) >= 4.5, `--${t} on --${k}: ${cr(val(dark, t), b).toFixed(2)}`);
// The outline stays dark in both looks, so text on bright fills (yellow buttons, warning tags) keeps reading.
assert.ok(cr(val(dark, 'ink'), '#FFD23F') >= 7, 'dark ink on the yellow buttons');
// Badge labels (10px, so 4.5:1) on their night cards: each variant's gradient, and the dimmed card of one not earned now.
const rules = css.replace(/\/\*[\s\S]*?\*\//g, '').split('}').map((r) => { const i = r.indexOf('{'); return i < 0 ? null : { sel: r.slice(0, i).split(',').map((x) => x.trim()), body: r.slice(i + 1) }; }).filter(Boolean);
const decl = (sel, prop) => { let v = null; for (const r of rules) if (r.sel.includes(sel)) { const m = new RegExp(`(?:^|;)\\s*${prop}\\s*:\\s*([^;]+)`).exec(r.body); if (m) v = m[1].trim(); } return v; };
const D = ':root[data-theme="dark"] ';
for (const v of ['freeze', 'bgp']) {
const label = decl(D + `.bdg.v-${v} .bv`, 'color') || decl(`.bdg.v-${v} .bv`, 'color'), stops = decl(D + `.bdg.on.v-${v}`, 'background').match(/#[0-9A-Fa-f]{6}/g);
assert.ok(label && stops.length >= 2, v);
for (const b of [...stops, val(dark, 'tint-n')]) assert.ok(cr(label, b) >= 4.5, `the ${v} badge label ${label} on ${b}: ${cr(label, b).toFixed(2)}`);
}
// The dashboard's Demand key is an outline in its line's colour (--text): dark ink by day as before, light at night.
assert.equal(val(light, 'text'), val(light, 'ink'), 'by day the key looks as it always did');
assert.ok(cr(val(dark, 'text'), val(dark, 'paper')) >= 3, 'at night the key\'s outline shows on the card');
});
// Two things that kept their day colours at night: the capacity market's Hot and Cool tags (bright pastel chips on the
// dark dashboard), and red warning text in var(--bad), 3.8 to 4.8:1 on the dark cards. --bad stays the fill under white
// letters (buttons, counters, bars); text takes var(--tx-red,var(--bad)), which by day is --bad as before.
test('at night the market\'s Hot and Cool tags take the dark tints, and red text reads (AA) on every card', () => {
const html = assemble().html, css = html.slice(html.indexOf('<style>'), html.indexOf('</style>')).replace(/\/\*[\s\S]*?\*\//g, '');
const block = (sel) => { const i = css.indexOf(sel + '{'); return css.slice(i, css.indexOf('}', i)); };
const dark = block(':root[data-theme="dark"]'), light = block(':root');
const val = (b, k) => { const m = new RegExp(`--${k}:\\s*([^;\\n]+);`).exec(b); return m && m[1].trim(); };
const rules = css.split('}').map((r) => { const i = r.indexOf('{'); return i < 0 ? null : { sel: r.slice(0, i).split(',').map((x) => x.trim()), body: r.slice(i + 1) }; }).filter(Boolean);
const decl = (sel, prop) => { let v = null; for (const r of rules) if (r.sel.includes(sel)) { const m = new RegExp(`(?:^|;)\\s*${prop}\\s*:\\s*([^;]+)`).exec(r.body); if (m) v = m[1].trim(); } return v; };
// var(--token,fallback) as each look paints it: the dark value, or the fallback (the light look never sets the tint).
const paint = (v, look) => { const m = /^var\(--([a-z-]+),\s*(#[0-9A-Fa-f]{6})\)$/.exec(v); assert.ok(m, `a themed colour: ${v}`); return look === 'dark' ? val(dark, m[1]) : (assert.equal(val(light, m[1]), null, `--${m[1]} is dark-only`), m[2]); };
for (const [tag, bg, fg, was] of [['cmhot', 'tint-o', 'tx-amber', ['#FFE1D6', '#B43A12']], ['cmcool', 'tint-b', 'tx-blue', ['#DDF1FB', '#1E6A8C']]]) {
const b = decl(`.tag.${tag}`, 'background'), c = decl(`.tag.${tag}`, 'color');
assert.ok(b.startsWith(`var(--${bg},`) && c.startsWith(`var(--${fg},`), `.tag.${tag}: ${b} / ${c}`);
assert.deepEqual([paint(b, 'light'), paint(c, 'light')], was, `.tag.${tag} looks as it did by day`);
const r = cr(paint(c, 'dark'), paint(b, 'dark'));
assert.ok(r >= 4.5, `.tag.${tag} at night: ${r.toFixed(2)}`);
}
// No tag keeps a bare pastel fill: it would be a bright patch on the dark panels.
const pale = (h) => lum(h) > 0.5;
for (const r of rules) if (!r.sel.some((s) => s.startsWith(':root')) && r.sel.some((s) => /\.tag\b/.test(s))) {
const m = /(?:^|;)\s*background\s*:\s*(#[0-9A-Fa-f]{6})\b/.exec(r.body);
assert.ok(!(m && pale(m[1])), `${r.sel.join(',')} has a bare pastel background ${m && m[1]}`);
}
// Red as text takes the dark-aware colour everywhere, in the styles and in the game's own markup and HUD (the test
// above checks --tx-red on every card and tint). `color:var(--bad)`, `color:${x?'var(--bad)':…}`, `.style.color=…'var(--bad)'`.
const RED = /(?<![-\w])color\s*(?::|=)\s*(?:\$\{[^}]*?|[^;'"`{}(]*?)'?(?<!--tx-red,)var\(--bad\)/g;
const cssLeft = [...css.matchAll(RED)].map((m) => m[0]);
assert.deepEqual(cssLeft, [], 'red text in the styles in --bad');
const dir = path.join(__dirname, '..', 'src', 'game'), left = [];
for (const f of fs.readdirSync(dir, { recursive: true }).filter((f) => f.endsWith('.js'))) {
const s = fs.readFileSync(path.join(dir, f), 'utf8');
for (const m of s.matchAll(RED)) left.push(`${f}: ${m[0].slice(-60)}`);
}
assert.deepEqual(left, [], 'red text in the game\'s markup in --bad');
// The fills keep --bad (white letters on it): a button, a counter, a bar.
assert.equal(decl('.b.red', 'background'), 'var(--bad)');
assert.equal(decl('.b.red', 'color'), '#fff');
});
test('the dashboard\'s Demand key matches its dashed line, by night too', () => {
const { dom, ev, errors } = load({ storage: { 'sot-theme': 'dark' } });
ev(started + "for(let i=0;i<3;i++)dayTick();ACT.dash({});");
const card = dom.window.document.getElementById('dashCard');
const line = card.querySelector('svg path[stroke-dasharray="5 4"]');
assert.ok(line, 'the dashed Demand line');
const stroke = /stroke:\s*([^;"]+)/.exec(line.getAttribute('style'))[1].trim();
const key = [...card.querySelectorAll('.legend .lg')].find((b) => JSON.parse(b.dataset.args).k === 'dem').querySelector('i');
assert.equal(key.style.borderStyle, 'dashed');
assert.equal(key.style.borderColor, stroke, 'the key is outlined in the line\'s own colour');
assert.equal(stroke, 'var(--text)');
assert.deepEqual(errors, []);
dom.window.close();
});