// 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
sets 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 , up to its styles, as the browser runs it before the first paint: the game script at the end // of (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('')); 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('')).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 = /(? 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'); }); // --ink stays near-black at night: it is the outline and the text on bright fills (yellow buttons, warning tags). Text in // it on a card's own fill (--soft, --paper) all but vanishes in the dark look, as the transfer paste box's did (1.5:1): // such text takes --text, as input.t does. test('at night no text is --ink on a card\'s own fill: the transfer paste box reads (AA)', () => { const html = assemble().html, css = html.slice(html.indexOf('')).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"]'); 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).trim(), body: r.slice(i + 1) }; }).filter(Boolean); const prop = (b, p) => { const m = new RegExp(`(?:^|;)\\s*${p}\\s*:\\s*([^;]+)`).exec(b); return m && m[1].trim(); }; const ink = rules.filter((r) => !r.sel.startsWith(':root') && /^var\(--(soft|paper)\)$/.test(prop(r.body, 'background') || '') && prop(r.body, 'color') === 'var(--ink)').map((r) => r.sel); assert.deepEqual(ink, [], '--ink text on --soft or --paper'); const box = rules.find((r) => r.sel === 'textarea.xfer-in'); assert.ok(box, 'the paste box has its rule'); assert.equal(prop(box.body, 'color'), 'var(--text)'); assert.equal(prop(box.body, '-webkit-text-fill-color'), 'var(--text)'); assert.ok(cr(val(dark, 'text'), val(dark, 'soft')) >= 4.5, `--text on --soft: ${cr(val(dark, 'text'), val(dark, 'soft')).toFixed(2)}`); }); 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(); });