mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-12-01 04:16:24 -05:00
The PathInput overlap could not have been caught by jest -- jsdom computes no layout -- so the only guard was a grep for one spelling of one mistake. This adds the layer that can actually see it, and it found a real bug immediately. ui-layout.cy.js mounts library components in a real browser through a new cy.mountUI(), which supplies Mantine's provider and a stamped data-theme and nothing else. That spartan setup is the point: these components read no ambient state, so a spec can assert what jsdom cannot compute -- real geometry, resolved custom properties, applied filters -- across all four themes. It reproduces the leftSectionWidth='auto' overlap on purpose and asserts it still overlaps, because a geometry check that has never gone red is indistinguishable from one that cannot fail. The bug it found: the rule resetting `filter` on leaf media inside a `.media` wrapper scored (0,2,2) against the (0,3,1) rule it was correcting, so it lost every time and never applied to anything. Every image inside a filtered wrapper has been through the luminance matrix twice since that rule landed -- markedly darker than its surroundings, which is exactly what it was written to prevent. tokens.test.js asserted only that the rule's text was present, and so stayed green throughout; it now compares the two selectors' specificity, which is computable without a browser and goes red on the old selector. Three guards in ui.test.js keep the library mock-free by construction rather than by habit: no jest.mock in its own tests, no fetch in any library file, and no useContext outside the theme controls, whose job is to read the theme. All three were verified red against planted violations. 959 jest tests, 14 new browser tests, clean cache-busted build. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
176 lines
8.3 KiB
JavaScript
176 lines
8.3 KiB
JavaScript
import fs from 'fs';
|
|
import path from 'path';
|
|
import {themeNames, themeSessionKey} from '../components/Theme';
|
|
import {mediaFilterSessionKey, themeMediaFilter} from './names';
|
|
|
|
const readFile = (...parts) => fs.readFileSync(path.join(__dirname, ...parts), 'utf8');
|
|
|
|
const tokensCss = readFile('tokens.css');
|
|
const fontsCss = readFile('fonts.css');
|
|
const indexHtml = readFile('..', '..', 'public', 'index.html');
|
|
|
|
/** The custom properties declared in the block for one theme. */
|
|
const themeTokens = (theme) => {
|
|
// Light doubles as the fallback, so its block is a grouped selector.
|
|
const pattern = theme === 'light'
|
|
? /:root,\s*html\[data-theme="light"]\s*{([^}]*)}/
|
|
: new RegExp(`html\\[data-theme="${theme}"]\\s*{([^}]*)}`);
|
|
const match = tokensCss.match(pattern);
|
|
expect(match).not.toBeNull();
|
|
return new Set([...match[1].matchAll(/(--[\w-]+)\s*:/g)].map(m => m[1]));
|
|
};
|
|
|
|
describe('theme tokens', () => {
|
|
it('declares a block for every theme', () => {
|
|
themeNames.forEach(theme => expect(themeTokens(theme).size).toBeGreaterThan(0));
|
|
});
|
|
|
|
it('defines the same tokens in every theme', () => {
|
|
// A token missing from one theme inherits the light value, which is how a stray
|
|
// white or blue ends up in night mode.
|
|
const light = themeTokens('light');
|
|
themeNames.filter(theme => theme !== 'light').forEach(theme => {
|
|
const missing = [...light].filter(token => !themeTokens(theme).has(token)
|
|
// Fonts are a role assignment, not a color; only amber overrides one.
|
|
&& !token.startsWith('--font-'));
|
|
expect({theme, missing}).toEqual({theme, missing: []});
|
|
});
|
|
});
|
|
|
|
it('uses only red hues in the night theme', () => {
|
|
// Night's whole purpose is that no non-red pixel reaches the eye.
|
|
const hexes = [...tokensCss.match(/html\[data-theme="night"]\s*{([^}]*)}/)[1]
|
|
.matchAll(/#([0-9a-f]{6})/gi)].map(m => m[1]);
|
|
expect(hexes.length).toBeGreaterThan(10);
|
|
hexes.forEach(hex => {
|
|
const [r, g, b] = [0, 2, 4].map(i => parseInt(hex.slice(i, i + 2), 16));
|
|
expect({hex, redDominant: r >= g && r >= b, neutralGreenBlue: g === b}).toEqual(
|
|
{hex, redDominant: true, neutralGreenBlue: true}
|
|
);
|
|
});
|
|
});
|
|
|
|
it('resolves fonts through role tokens only', () => {
|
|
expect(fontsCss).toMatch(/--font-body:/);
|
|
expect(fontsCss).toMatch(/--font-mono:/);
|
|
// Nothing may hardcode a family: a theme swaps the role, not the rule.
|
|
expect(tokensCss).toMatch(/font-family:\s*var\(--font-body\)/);
|
|
expect(tokensCss).not.toMatch(/font-family:(?!\s*var\()/);
|
|
});
|
|
});
|
|
|
|
describe('pre-paint theme script', () => {
|
|
// The inline script in index.html duplicates the theme names and storage key so the
|
|
// first paint matches the saved theme. These assertions fail if either side is renamed.
|
|
it('reads the same localStorage key as ThemeProvider', () => {
|
|
expect(indexHtml).toContain(`localStorage.getItem('${themeSessionKey}')`);
|
|
});
|
|
|
|
it('recognizes every theme name', () => {
|
|
themeNames.forEach(theme => expect(indexHtml).toContain(`'${theme}'`));
|
|
});
|
|
|
|
it('stamps data-theme before the bundle loads', () => {
|
|
const head = indexHtml.slice(0, indexHtml.indexOf('</head>'));
|
|
expect(head).toContain("document.documentElement.setAttribute('data-theme'");
|
|
});
|
|
|
|
it('stamps the media filter before the bundle loads too', () => {
|
|
// Otherwise night mode paints a screen of unfiltered thumbnails while the bundle
|
|
// arrives, which costs the user the dark adaptation the theme exists to protect.
|
|
const head = indexHtml.slice(0, indexHtml.indexOf('</head>'));
|
|
expect(head).toContain("document.documentElement.setAttribute('data-media-filter'");
|
|
expect(head).toContain(`localStorage.getItem('${mediaFilterSessionKey}')`);
|
|
});
|
|
|
|
it('duplicates the same filter ids and defaults the app uses', () => {
|
|
// The script cannot import from names.ts, so it restates both. These assertions
|
|
// fail if a theme's filter id or default changes on only one side.
|
|
themeNames.forEach(theme => {
|
|
const filter = themeMediaFilter(theme);
|
|
if (!filter) return;
|
|
expect(indexHtml).toContain(`${theme}: '${filter.id}'`);
|
|
expect(indexHtml).toContain(`${theme}: ${filter.defaultOn}`);
|
|
});
|
|
});
|
|
});
|
|
|
|
describe('media filter rules', () => {
|
|
it('keys on the filter, not on the theme', () => {
|
|
// Filtering is a per-theme setting the user controls, so a rule keyed on
|
|
// `data-theme` could not be turned off.
|
|
const filterRules = [...tokensCss.matchAll(/^html\[([^\]]+)][^{]*{\s*filter:/gm)]
|
|
.map(match => match[1]);
|
|
|
|
expect(filterRules.length).toBeGreaterThan(0);
|
|
// With or without a value: the reset rule for nested media keys on the bare
|
|
// attribute. What matters is that no filter rule keys on `data-theme`.
|
|
filterRules.forEach(selector => expect(selector).toMatch(/^data-media-filter/));
|
|
});
|
|
|
|
it('has a rule for every filter a theme offers', () => {
|
|
themeNames.forEach(theme => {
|
|
const filter = themeMediaFilter(theme);
|
|
if (!filter) return;
|
|
expect(tokensCss).toContain(`html[data-media-filter="${filter.id}"]`);
|
|
// Restated for native fullscreen, where an ancestor's filter stops applying.
|
|
expect(tokensCss).toMatch(
|
|
new RegExp(`html\\[data-media-filter="${filter.id}"] :fullscreen`));
|
|
});
|
|
});
|
|
|
|
it('does not filter leaf media twice inside a filtered wrapper', () => {
|
|
/*
|
|
* A `.media` wrapper filters its subtree as a unit; the img/video inside it also
|
|
* matches the element-type rule, and two passes of the matrix take the luminance of
|
|
* an already-red pixel, leaving that image much darker than its surroundings.
|
|
*
|
|
* This used to assert only that the reset rule's text was present, and so it passed
|
|
* for as long as the rule existed -- including the whole time the rule lost on
|
|
* specificity and never applied to anything. Presence is not effect. What has to
|
|
* hold is that the reset outranks the rule it is correcting, which is computable
|
|
* from the selectors themselves. ui-layout.cy.js measures the resulting `filter` in
|
|
* a real browser, which is the only place the effect itself is observable.
|
|
*/
|
|
const specificity = (selector) => {
|
|
// Enough of the algorithm for these selectors: :is() and :not() contribute the
|
|
// highest specificity among their arguments.
|
|
let classes = 0, elements = 0;
|
|
const counted = selector.replace(/:(is|not)\(([^)]*)\)/g, (_, __, args) => {
|
|
const best = args.split(',')
|
|
.map(arg => specificity(arg.trim()))
|
|
.sort((a, b) => (b.classes - a.classes) || (b.elements - a.elements))[0];
|
|
classes += best.classes;
|
|
elements += best.elements;
|
|
return ' ';
|
|
});
|
|
classes += (counted.match(/\.[\w-]+|\[[^\]]*]|:[\w-]+/g) || []).length;
|
|
elements += (counted.match(/(^|[\s>+~])[a-z][\w-]*/gi) || []).length;
|
|
return {classes, elements};
|
|
};
|
|
const rank = (selector) => {
|
|
const {classes, elements} = specificity(selector);
|
|
return classes * 1000 + elements;
|
|
};
|
|
|
|
const selectorFor = (needle) => {
|
|
const match = tokensCss.split('}')
|
|
.map(block => block.split('{')[0].trim())
|
|
.filter(Boolean)
|
|
.find(selector => selector.includes(needle));
|
|
if (!match) throw new Error(`tokens.css has no rule matching ${needle}`);
|
|
return match.split('\n').pop().trim();
|
|
};
|
|
|
|
const reset = selectorFor('.media :is(img');
|
|
const filtered = selectorFor('[data-media-filter="night-red"] :is(img');
|
|
|
|
expect(rank(reset)).toBeGreaterThan(rank(filtered));
|
|
});
|
|
|
|
it('never filters an ancestor, only leaf media', () => {
|
|
// A CSS filter creates a containing block, which would break `position: fixed`
|
|
// descendants — the nav bar and every modal.
|
|
expect(tokensCss).not.toMatch(/data-media-filter="[^"]+"]\s*{\s*filter:/);
|
|
});
|
|
});
|