diff --git a/CHANGELOG.md b/CHANGELOG.md index 20d9796..169b98a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,37 @@ # Changelog +## 1.0.4 — 2026-11-27 + +Fixes for pages that froze, and for the quirk form on the options page. + +- Fixed ([#5](https://github.com/QuantIntellect/adaptive-dark-mode/issues/5)): pages could stop responding. Four + ways the extension could end up answering its own changes, found on an Oracle careers page and in tests: + - An inline `!important` color was transformed again on every pass, and transforms don't settle (a border color + keeps changing). With nothing else to adjust on the element, each pass was a new style change that the extension + then answered, in microtasks, so the page never painted or took input again. One element with + `style="border-color: #f0f0f0 !important"` was enough. Now the original value is kept and only transformed once, + and it is put back when the mode turns off (unless the page changed it in the meantime). + - Text over a large background photo was checked again on every frame, because the photo is never classified + (photos are left alone) and the "classified, look again" step ran anyway. On the Oracle page that rewrote the + same attributes 60 times a second, and the site's UI library (Oracle JET) re-renders components when attributes + under them change. Text is now checked again only when the image actually got a verdict. + - Adjustments are written only when their value changes. A write of the same value still reaches the page's own + observers, and some re-render on any change. + - Attribute changes that leave the value as it was (a framework re-applying the same classes) are ignored. +- A safety net for loops not covered above. Within one task an element is handled a few times at most. After 100 + observer callbacks in one task, the rest waits for the next task, and if that happens three tasks in a row the + work is dropped until things calm down. Elements that keep coming back to the layout pass on every frame are looked + at again a second later. When this happens, the popup's statistics line says "loops stopped". +- Fixed ([#4](https://github.com/QuantIntellect/adaptive-dark-mode/issues/4)): after one invalid selector in the + options page's quirk form, every selector was rejected as "Not a valid CSS selector" until the page was reloaded + (the message stayed set on the field and blocked the form). The message now clears as soon as the field is edited, + and it names the selector that's wrong. The placeholders no longer read like part of the value ("Invert, e.g. + .chart img, .logo"). +- Tests: a fixture with the loops above (an inline `!important` border, text over a photo, a component that + re-applies its children's classes, and one that re-renders fresh children whenever an attribute under it changes), + checked for a page that still answers, no attribute rewritten while idle, a stable border and colors restored on + turning off. Three checks for the quirk form. + ## 1.0.3 — 2026-11-20 Sites that have a dark theme of their own, switched off in their own settings. diff --git a/README.md b/README.md index 2182b06..0c585f5 100644 --- a/README.md +++ b/README.md @@ -108,13 +108,13 @@ handles what rules can't: text contrast against the real backdrop, small dark co All checks run against the project's own fixtures in `test/fixtures/`: a recipe-site page that exercises every rule case, opt-out pages, an already-dark page, a late-rendering SPA, stacked drawing canvases, a consent -dialog, a page whose body arrives late, sites with a dark theme of their own (no offer) and pages of dark sections -(offer kept). Pages that must be left alone +dialog, a page whose body arrives late, sites with a dark theme of their own (no offer), pages of dark sections +(offer kept) and pages that answer the extension's changes (no feedback loop). Pages that must be left alone are also compared pixel for pixel. | Browser | Mode | Fixture checks | |---|---|---| -| Chrome for Testing 153.0.8010.12 | headless | 92 / 92 (1.0.3) | +| Chrome for Testing 153.0.8010.12 | headless | 104 / 104 (1.0.4) | | Google Chrome 157.0.8103.40 (macOS) | headed | 65 / 66 (1.0.0, before the six auto-theme checks). The miss is the pixel-identical "turned off" comparison. About 2,200 pixels around the two scaled product images differ, by 1 level out of 255 (15 in an earlier run). The separate "nothing left behind" check (0 attributes, 0 custom properties, 0 sheets) passed. The cause has not been isolated. | Real sites, with the extension on (text elements sampled after scrolling). Google Chrome 157 and Chrome for Testing 153 gave the diff --git a/manifest.json b/manifest.json index 6c6f224..8bb507f 100644 --- a/manifest.json +++ b/manifest.json @@ -2,7 +2,7 @@ "manifest_version": 3, "name": "Adaptive Dark Mode", "short_name": "Adaptive Dark", - "version": "1.0.3", + "version": "1.0.4", "description": "Presents light websites as dark while you browse in dark mode, keeping hue, contrast, logos and images right.", "homepage_url": "https://github.com/QuantIntellect/adaptive-dark-mode", "minimum_chrome_version": "121", diff --git a/package-lock.json b/package-lock.json index 5912750..5465b7d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "adaptive-dark-mode", - "version": "1.0.3", + "version": "1.0.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "adaptive-dark-mode", - "version": "1.0.3", + "version": "1.0.4", "devDependencies": { "playwright-core": "^1.56.0" } diff --git a/package.json b/package.json index c45a39b..cd5d650 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "adaptive-dark-mode", - "version": "1.0.3", + "version": "1.0.4", "private": true, "description": "Light websites presented as dark while you browse in dark mode. A Chrome extension modelled on Safari 27.3 Adaptive Dark Mode.", "license": "MIT", diff --git a/src/content/images.js b/src/content/images.js index 5c174f8..8e086e8 100644 --- a/src/content/images.js +++ b/src/content/images.js @@ -21,7 +21,8 @@ constructor(ctx) { this.ctx = ctx; // { model, settings, stats, classifyRemote(url), fetchText(url) } this.verdicts = new Map(); // url -> Promise - this.seen = new WeakMap(); // element -> url handled + this.seen = new WeakMap(); // -> url handled + this.bgJobs = new WeakMap(); // element -> { url, promise } background image looked at this.meta = new WeakMap(); // element -> verdict (for text-over-image decisions) } @@ -59,14 +60,26 @@ } } - /** Small icon element painted with a background image, or a big tiled texture. */ - async processBackground(el, cs) { - if (!this.ctx.settings.images) return; + /** + * Small icon element painted with a background image, or a big tiled + * texture. Resolves once that image has been looked at; calls for the + * same element and image share the one look. Afterwards verdictFor(el) + * is set only if the image was classified (most backgrounds, photos and + * artwork, are left alone and never are). + */ + processBackground(el, cs) { + if (!this.ctx.settings.images) return Promise.resolve(); const m = /url\(\s*["']?([^"')]+)["']?\s*\)/.exec(cs.backgroundImage); - if (!m) return; + if (!m) return Promise.resolve(); const url = m[1]; - if (this.seen.get(el) === url) return; - this.seen.set(el, url); + const job = this.bgJobs.get(el); + if (job && job.url === url) return job.promise; + const promise = this.lookAtBackground(el, cs, url).catch(() => {}); + this.bgJobs.set(el, { url, promise }); + return promise; + } + + async lookAtBackground(el, cs, url) { const rect = el.getBoundingClientRect(); const iconLike = rect.width <= 96 && rect.height <= 96 && el.childElementCount === 0 && !el.textContent.trim(); const large = rect.width * rect.height > 100000; diff --git a/src/content/inline.js b/src/content/inline.js index ff05cea..e77cfb5 100644 --- a/src/content/inline.js +++ b/src/content/inline.js @@ -58,7 +58,7 @@ class InlineEngine { constructor(ctx) { this.ctx = ctx; // { model, stats } - this.important = new WeakMap(); // el -> { prop: [value, priority] } originals we replaced + this.important = new WeakMap(); // el -> { prop: { original, written } } !important declarations we swapped } processTree(node) { @@ -78,6 +78,7 @@ const want = new Map(); // custom prop -> value const ctx = { base: document.baseURI }; let pending = false; + let swapped = false; for (let i = 0; i < style.length; i++) { const prop = style[i]; @@ -94,17 +95,24 @@ pending = true; continue; } - const t = model.transformValue(value, role, ctx); - if (t === value) continue; if (style.getPropertyPriority(prop) === 'important') { // Inline !important beats every author sheet, so we have to swap the - // declaration itself (restored on shutdown). + // declaration itself (restored on shutdown). Never transform our own + // output again: transforms aren't idempotent (a border color drifts + // on every pass), and each pass would be a style write our observer + // sees, which froze pages (#5). const saved = this.important.get(el) || {}; - if (!saved[prop]) saved[prop] = value; - this.important.set(el, saved); + if (saved[prop] && saved[prop].written === value) continue; // ours, untouched since + const t = model.transformValue(value, role, ctx); + if (t === value) continue; style.setProperty(prop, t, 'important'); + saved[prop] = { original: value, written: style.getPropertyValue(prop) }; + this.important.set(el, saved); + swapped = true; continue; } + const t = model.transformValue(value, role, ctx); + if (t === value) continue; const tok = TOKEN_OF[prop]; if (!tok) continue; tokens.push(tok); @@ -154,29 +162,35 @@ if (!want.has(p)) stale.push(p); } } - if (!tokens.length && !want.size && !stale.length && !el.hasAttribute('data-adm-i')) return; + if (!swapped && !tokens.length && !want.size && !stale.length && !el.hasAttribute('data-adm-i')) return; + // Write only what changed. A write of the same value is still reported + // to the page's observers, and some re-render on any change (#5). for (const p of stale) style.removeProperty(p); for (const [p, v] of want) if (style.getPropertyValue(p) !== v) style.setProperty(p, v); - if (tokens.length) el.setAttribute('data-adm-i', tokens.join(' ')); - else el.removeAttribute('data-adm-i'); + const list = tokens.join(' '); + if (list && el.getAttribute('data-adm-i') !== list) el.setAttribute('data-adm-i', list); + else if (!list && el.hasAttribute('data-adm-i')) el.removeAttribute('data-adm-i'); if (tokens.length) this.ctx.stats.inline = (this.ctx.stats.inline || 0) + 1; D.mark(el); } - restore(el) { + /** Put back the author's !important declarations we swapped (if the page hasn't replaced them since). */ + unswap(el) { const saved = this.important.get(el); - if (saved) { - for (const [prop, value] of Object.entries(saved)) el.style.setProperty(prop, value, 'important'); - this.important.delete(el); + if (!saved) return; + for (const [prop, s] of Object.entries(saved)) { + if (el.style.getPropertyValue(prop) === s.written) el.style.setProperty(prop, s.original, 'important'); } + this.important.delete(el); + } + + restore(el) { + this.unswap(el); D.clean(el); } restoreAll() { - for (const el of D.touched) { - const saved = this.important.get(el); - if (saved) for (const [prop, value] of Object.entries(saved)) el.style.setProperty(prop, value, 'important'); - } + for (const el of D.touched) this.unswap(el); } } diff --git a/src/content/layout.js b/src/content/layout.js index 6c45284..b2af7a8 100644 --- a/src/content/layout.js +++ b/src/content/layout.js @@ -36,6 +36,10 @@ this.observed = new WeakSet(); this.surfaceSeen = new WeakMap(); // surface -> pass id this.pass = 0; + this.frame = 0; // flush count + this.runs = new WeakMap(); // element -> { frame, run }: consecutive frames it was processed on + this.parked = new Set(); // elements held back from a re-queue loop, looked at again later + this.parkTimer = 0; this.running = true; this.visible = new Set(); this.io = new IntersectionObserver((entries) => { @@ -82,6 +86,8 @@ stop() { this.running = false; this.io.disconnect(); + clearTimeout(this.parkTimer); + this.parked.clear(); this.queue.clear(); this.visible.clear(); this.offscreen.clear(); @@ -143,9 +149,21 @@ flush() { this.scheduled = false; if (!this.running) return; + const frame = ++this.frame; const start = performance.now(); for (const el of this.queue) { this.queue.delete(el); + // Back in the queue on every frame for half a second: something + // (possibly its own processing) keeps re-queueing it. Park it and + // look again a second later, after the churn. + const r = this.runs.get(el); + const run = r && r.frame === frame - 1 ? r.run + 1 : 1; + this.runs.set(el, { frame, run }); + if (run > 30) { + if (run === 31) this.ctx.stats.loopGuard = (this.ctx.stats.loopGuard || 0) + 1; + this.park(el); + continue; + } try { this.process(el); } catch (_) { @@ -156,6 +174,18 @@ if (this.queue.size) this.schedule(); } + park(el) { + this.parked.add(el); + if (this.parkTimer) return; + this.parkTimer = setTimeout(() => { + this.parkTimer = 0; + if (!this.running) return; + for (const p of this.parked) if (p.isConnected) this.queue.add(p); + this.parked.clear(); + this.schedule(); + }, 1000); + } + // ------------------------------------------------------------------------- process(el) { if (!el.isConnected || el.closest('[data-adm-x]')) return; @@ -217,9 +247,11 @@ const v = this.ctx.images.verdictFor(node); if (!v) { // Unclassified background image: classify it (it may be a light - // texture we remove), then look at this text again. + // texture we remove), then look at this text again, but only if + // that gave a verdict. Photos and artwork are never classified, + // and re-queueing on those re-checked the text on every frame (#5). this.ctx.images.processBackground(node, cs).then(() => { - if (el.isConnected) { + if (el.isConnected && this.ctx.images.verdictFor(node)) { this.queue.add(el); this.schedule(); } @@ -285,7 +317,9 @@ setFg(el, base, fixed) { if (fixed) { if (!el.hasAttribute('data-adm-fg')) this.ctx.stats.text = (this.ctx.stats.text || 0) + 1; - el.dataset.admBase = C.format(base); + // Same value, no write: the page's observers hear about every write. + const b = C.format(base); + if (el.dataset.admBase !== b) el.dataset.admBase = b; D.setAdjust(el, 'data-adm-fg', '--adm-fg', C.format(fixed)); } else if (el.hasAttribute('data-adm-fg')) { delete el.dataset.admBase; @@ -407,7 +441,7 @@ if (!model.isVivid(p.c) && (invertAll || C.contrast(p.c, back) < 3)) next = model.flip(p.c); const key = p.prop === 'fill' ? 'admFill' : 'admStroke'; if (next) { - p.sh.dataset[key] = C.format(p.c); + if (p.sh.dataset[key] !== C.format(p.c)) p.sh.dataset[key] = C.format(p.c); D.setAdjust(p.sh, p.attr, p.cprop, C.format(next)); changed++; } else if (p.sh.hasAttribute(p.attr)) { diff --git a/src/content/main.js b/src/content/main.js index efb7248..5f1e868 100644 --- a/src/content/main.js +++ b/src/content/main.js @@ -417,6 +417,7 @@ subtree: true, characterData: true, attributes: true, + attributeOldValue: true, attributeFilter: ['style', 'class', 'bgcolor', 'color', 'text', 'media', 'disabled', 'rel', 'data-theme', 'data-color-mode', 'data-bs-theme', 'data-mode', 'theme', 'dark', 'content'], }); engine.observers.set(r, mo); @@ -440,8 +441,60 @@ if (node.querySelectorAll) for (const el of node.querySelectorAll('*')) visit(el); } + // Loop guard. MutationObserver callbacks run as microtasks: if what we write + // comes back to us (a page observer that re-renders whatever changes under + // it, as Oracle JET's child tracking does), the two can call each other + // forever and the page never paints or takes input again (#5). + // - Within one task an element is handled a few times at most. + // - After LOOP_ROUNDS callbacks in one task, the rest waits for the next + // task (the page gets to paint and take input in between). If that + // happens LOOP_TASKS tasks in a row, it's a loop: drop the work until a + // task goes by without it. + // The counts reset once the event loop moves on to another task. + const LOOP_ROUNDS = 100; + const LOOP_PER_ELEMENT = 8; + const LOOP_TASKS = 3; + let loopRounds = 0; + let loopSeen = new Map(); + let loopResetQueued = false; + let loopHotTasks = 0; + let loopDeferred = []; + let loopDeferQueued = false; + function loopRound() { + if (!loopResetQueued) { + loopResetQueued = true; + setTimeout(() => { + loopResetQueued = false; + if (loopRounds <= LOOP_ROUNDS) loopHotTasks = 0; + loopRounds = 0; + loopSeen = new Map(); + }, 0); + } + return ++loopRounds <= LOOP_ROUNDS; + } + function loopDefer(muts) { + if (loopRounds === LOOP_ROUNDS + 1 && ++loopHotTasks === LOOP_TASKS) stats.loopGuard = (stats.loopGuard || 0) + 1; + if (loopHotTasks >= LOOP_TASKS) return; + for (const m of muts) loopDeferred.push(m); + if (loopDeferQueued) return; + loopDeferQueued = true; + // Queued after this task's counter reset, so it runs with a fresh count. + setTimeout(() => { + loopDeferQueued = false; + const list = loopDeferred; + loopDeferred = []; + onMutations(list); + }, 0); + } + function loopAllows(el) { + const n = (loopSeen.get(el) || 0) + 1; + loopSeen.set(el, n); + return n <= LOOP_PER_ELEMENT; + } + function onMutations(muts) { if (!engine) return; + if (!loopRound()) return loopDefer(muts); let sheetDirty = false; let rootChanged = false; const added = new Set(); @@ -466,6 +519,9 @@ if (target.parentNode && target.parentNode.nodeName === 'STYLE') sheetDirty = true; } else if (m.type === 'attributes') { const name = m.attributeName; + // Written with the value it already had (a framework re-applying + // classes): nothing changed. Answering it is how loops start. + if (m.oldValue === target.getAttribute(name)) continue; if (name === 'media' || name === 'disabled' || name === 'rel') { sheetDirty = true; continue; @@ -483,6 +539,7 @@ } if (sheetDirty) engine.sheets.scheduleSync(); for (const n of added) { + if (!loopAllows(n)) continue; engine.inline.processTree(n); engine.layout.observeTree(n); markExclusions(n); @@ -491,7 +548,7 @@ } let budget = 150; for (const el of restyled) { - if (!el.isConnected) continue; + if (!el.isConnected || !loopAllows(el)) continue; engine.inline.process(el); // A class/style change can change this element's own color: drop our // fix so the new authored color is visible, and re-check right away diff --git a/src/options/options.html b/src/options/options.html index c1533f2..ac0dc4a 100644 --- a/src/options/options.html +++ b/src/options/options.html @@ -39,8 +39,8 @@

Quirks

- - + +
diff --git a/src/options/options.js b/src/options/options.js index c20db6f..5b2154d 100644 --- a/src/options/options.js +++ b/src/options/options.js @@ -84,6 +84,7 @@ function editQuirk(host) { const q = settings.quirks[host] || {}; + for (const id of ['qInvert', 'qPreserve']) $(id).setCustomValidity(''); $('qHost').value = host; $('qDisable').checked = !!q.disable; $('qInvert').value = q.forceInvert || ''; @@ -91,14 +92,46 @@ $('qHost').focus(); } - function validSelector(sel) { - if (!sel) return true; + const parses = (sel) => { try { document.createDocumentFragment().querySelector(sel); return true; } catch (_) { return false; } + }; + + // Split a selector list at its top-level commas (not inside :is(...), + // [attr="a,b"] or quotes). + function splitList(list) { + const out = []; + let depth = 0; + let quote = ''; + let from = 0; + for (let i = 0; i < list.length; i++) { + const ch = list[i]; + if (quote) { + if (ch === '\\') i++; + else if (ch === quote) quote = ''; + } else if (ch === '"' || ch === "'") quote = ch; + else if (ch === '\\') i++; + else if (ch === '(' || ch === '[') depth++; + else if ((ch === ')' || ch === ']') && depth) depth--; + else if (ch === ',' && !depth) { + out.push(list.slice(from, i)); + from = i + 1; + } + } + out.push(list.slice(from)); + return out.map((s) => s.trim()); + } + + /** '' when the list is valid, or a message that names the selector that isn't. */ + function selectorError(list) { + if (!list || parses(list)) return ''; + const bad = splitList(list).find((s) => !s || !parses(s)); + if (bad === '') return 'Empty selector: remove the extra comma.'; + return bad ? `Not a valid CSS selector: ${bad}` : 'Not a valid CSS selector list.'; } function bind() { @@ -110,6 +143,10 @@ save((s) => (s.sites[host] = v)); $('addHost').value = ''; }); + // A message set on a field blocks the form's submit until it is cleared, + // so it must go as soon as the field is edited. Otherwise one bad entry + // made every later selector look invalid until a reload (#4). + for (const id of ['qInvert', 'qPreserve']) $(id).addEventListener('input', (e) => e.target.setCustomValidity('')); $('addQuirk').addEventListener('submit', (e) => { e.preventDefault(); const host = normalizeHost($('qHost').value); @@ -117,7 +154,7 @@ const forceInvert = $('qInvert').value.trim(); const preserve = $('qPreserve').value.trim(); for (const [input, sel] of [[$('qInvert'), forceInvert], [$('qPreserve'), preserve]]) { - input.setCustomValidity(validSelector(sel) ? '' : 'Not a valid CSS selector'); + input.setCustomValidity(selectorError(sel)); if (!input.reportValidity()) return; } const q = {}; diff --git a/src/popup/popup.js b/src/popup/popup.js index 29796a6..e32f574 100644 --- a/src/popup/popup.js +++ b/src/popup/popup.js @@ -98,6 +98,7 @@ `${st.svg || 0} SVG`, ]; if (st.controls) parts.push(`${st.controls} controls`); + if (st.loopGuard) parts.push(`loops stopped ${st.loopGuard}`); const t = status.timing || {}; $('stats').textContent = parts.join(' · ') + (t.startMs != null ? ` · start ${t.startMs} ms` : ''); } diff --git a/test/e2e/run.mjs b/test/e2e/run.mjs index ded84fa..abff7c2 100644 --- a/test/e2e/run.mjs +++ b/test/e2e/run.mjs @@ -634,6 +634,94 @@ console.log('\npopup'); await configure({ scope: 'all', sites: {}, quirks: {}, dismissed: {} }); } +console.log('\nfeedback loops (#5)'); +{ + // Each case once kept the extension busy forever: microtask ping-pong froze + // the page, a frame loop burned CPU. A fresh tab, so a freeze here can't + // take the other checks down with it. + const lp = await context.newPage(); + await lp.setViewportSize({ width: 1280, height: 900 }); + await lp.emulateMedia({ colorScheme: 'dark' }); + await configure({ mode: 'system', scope: 'all', sites: {}, quirks: {}, dismissed: {} }); + const answer = (fn, ms = 3000) => Promise.race([lp.evaluate(fn).catch((e) => 'error: ' + e.message.split('\n')[0]), new Promise((r) => setTimeout(() => r('TIMEOUT'), ms))]); + lp.goto(`${base}/loops.html`).catch(() => {}); + await new Promise((r) => setTimeout(r, 2500)); + const alive = await answer(() => document.readyState); + check('page with loop triggers still answers', alive === 'complete', alive); + if (alive === 'complete') { + const st = await status(lp); + check('mode is on there', st && st.state === 'active', st && `${st.state}/${st.reason}`); + const imp = () => answer(() => getComputedStyle(document.getElementById('imp-border')).borderTopColor); + const b1 = await imp(); + await new Promise((r) => setTimeout(r, 800)); + const b2 = await imp(); + check('inline !important border transformed once and stable', b1 === b2 && b1 !== 'rgb(240, 240, 240)' && /^rgb/.test(b1), { b1, b2 }); + // Idle: nothing may keep rewriting attributes (Oracle: data-adm-base 60 times a second). + const idle = await answer(() => new Promise((resolve) => { + let n = 0; + const seen = {}; + const mo = new MutationObserver((ms) => { + for (const m of ms) { + n++; + const k = `${m.target.id || m.target.localName} ${m.attributeName}`; + seen[k] = (seen[k] || 0) + 1; + } + }); + mo.observe(document.body, { attributes: true, subtree: true }); + const r0 = window.__trackerRounds; + setTimeout(() => { + mo.disconnect(); + resolve({ n, seen, tracker: window.__trackerRounds - r0 }); + }, 1500); + }), 5000); + check('idle page: no attribute keeps being rewritten', idle && idle.n === 0, idle); + const rounds = await answer(() => window.__trackerRounds); + check('child-tracking component settles', typeof rounds === 'number' && rounds < 20, rounds); + const rr1 = await answer(() => window.__rerenders); + await new Promise((r) => setTimeout(r, 1000)); + const rr2 = await answer(() => window.__rerenders); + check('re-rendering component: the loop guard ends the ping-pong', typeof rr1 === 'number' && rr1 === rr2 && rr1 < 1000, { rr1, rr2 }); + check('text over the unclassified photo keeps its authored color', (await answer(() => document.getElementById('art-text').hasAttribute('data-adm-fg'))) === true); + check('inline-colored child of the tracking component adapted', await answer(() => document.getElementById('tracked').hasAttribute('data-adm-i'))); + await configure({ mode: 'off' }); + await new Promise((r) => setTimeout(r, 600)); + const restored = await answer(() => { + const s = document.getElementById('imp-border').style; + return [s.getPropertyValue('border-top-color'), s.getPropertyPriority('border-top-color'), document.getElementById('imp-bg').style.backgroundColor]; + }); + check('inline !important colors restored when the mode turns off', JSON.stringify(restored) === JSON.stringify(['rgb(240, 240, 240)', 'important', 'rgb(250, 250, 250)']), restored); + await configure({ mode: 'system' }); + } + await lp.close().catch(() => {}); +} + +console.log('\noptions page: quirk selectors (#4)'); +{ + const op = await context.newPage(); + await op.goto(`chrome-extension://${extensionId}/src/options/options.html`); + const quirks = async () => (await sw.evaluate(async () => (await chrome.storage.local.get('settings')).settings.quirks)) || {}; + const save = async (host, inv, pre) => { + await op.fill('#qHost', host); + await op.fill('#qInvert', inv); + await op.fill('#qPreserve', pre); + await op.click('#addQuirk button[type=submit]'); + await op.waitForTimeout(250); + return op.evaluate(() => ['qInvert', 'qPreserve'].map((id) => document.getElementById(id).validationMessage)); + }; + await configure({ quirks: {} }); + const bad = await save('quirks.example', '', 'Preserve: .map'); + check('invalid selector rejected, naming it', /Preserve: \.map/.test(bad[1]) && !(await quirks())['quirks.example'], bad); + const msgs = await save('quirks.example', '', '.standard-apply-flow, [dir] .standard'); + const q1 = (await quirks())['quirks.example']; + check('valid selectors accepted after a rejected one', q1 && q1.preserve === '.standard-apply-flow, [dir] .standard', { msgs, q1 }); + await save('quirks2.example', 'a,', ''); + await save('quirks2.example', ':is(.chart, .graph) img, .logo', ''); + const q2 = (await quirks())['quirks2.example']; + check('the other field recovers too (commas inside :is() are fine)', q2 && q2.forceInvert === ':is(.chart, .graph) img, .logo', q2); + await configure({ quirks: {} }); + await op.close(); +} + if (withSites) { console.log('\nreal sites'); const sites = [ diff --git a/test/fixtures/loops.html b/test/fixtures/loops.html new file mode 100644 index 0000000..d5f70d9 --- /dev/null +++ b/test/fixtures/loops.html @@ -0,0 +1,68 @@ + + + + +Feedback loops + + + +
+

Pages that answer back

+

Each block below once kept the extension busy forever. A bright page with plenty of ordinary text, so that it + samples as light and the mode turns on.

+

Issue #5 was an Oracle careers page that stopped responding with the mode on.

+ + +
Inline !important border
+
Inline !important background
+ + +

Text over a photo background

+ + + + Inline-colored child + Plain child + + + + +
+ + +