From 25653652fc2a863e32f2f4de0e911842759a5460 Mon Sep 17 00:00:00 2001 From: Persian ROss <195442302+QuantIntellect@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:16:19 +0330 Subject: [PATCH] 1.0.3: no Try offer on sites with a dark theme of their own MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Sites whose own dark theme is switched off in their own settings (YouTube set to light, Stack Overflow, Wikipedia) no longer get the "This page is bright · Try" card or the TRY badge. Before offering, the top frame scans the page's readable style sheets, at idle after load (capped at 3 s), for a dark theme rule aimed at the root: html[dark], body.theme-dark, [data-theme=dark] when the root carries data-theme, or root colors in a matching prefers-color-scheme: dark block that the site's setting gates. Dark section styles (.theme-dark on a promo band, .bg-dark) and blocks libraries ship to every site (Bootstrap's [data-bs-theme=dark], DocSearch's html[data-theme=dark]) don't count. The popup says "Site's own dark theme is off" and keeps Try on this page. All bright sites and sites turned on are adapted as before; the check runs only while the system is dark. Tests: 21 unit, 92/92 fixture e2e. Checked live with the extension: YouTube, Stack Overflow, Wikipedia get no card; HN, BBC, Apple iPhone, IKEA, Microsoft, CNN, Nike, Craigslist keep it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0119pSNmC1KsBQ25Q5us1HoS --- CHANGELOG.md | 23 +++ README.md | 13 +- manifest.json | 2 +- package-lock.json | 4 +- package.json | 2 +- src/content/detect.js | 255 +++++++++++++++++++++++++++++- src/content/main.js | 67 ++++++++ src/popup/popup.js | 4 +- test/e2e/run.mjs | 77 ++++++++- test/fixtures/light.html | 4 +- test/fixtures/own-theme.html | 49 ++++++ test/fixtures/section-themes.html | 35 ++++ test/unit/detect.test.js | 115 ++++++++++++++ 13 files changed, 635 insertions(+), 15 deletions(-) create mode 100644 test/fixtures/own-theme.html create mode 100644 test/fixtures/section-themes.html create mode 100644 test/unit/detect.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 56537a3..20d9796 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,28 @@ # Changelog +## 1.0.3 — 2026-11-20 + +Sites that have a dark theme of their own, switched off in their own settings. + +- No **Try** offer on sites that have a dark theme of their own, switched off in the site's own settings: YouTube + set to its light theme (`html[dark]`), Stack Overflow (`body.theme-dark`), Wikipedia + (`html.skin-theme-clientpref-night`), GitHub-style `[data-color-mode=dark]` with the attribute on ``, or root + colors in a `prefers-color-scheme: dark` block that the site's setting gates (the block matches, the rule doesn't + match the root). The card no longer appears there, the toolbar badge shows nothing, and the popup says **Site's own + dark theme is off**, with **Try on this page** still available. **All bright sites** and sites you turned on are + adapted as before. The check runs only while the system is dark: with **Always** on a light system, sites that + follow the system still get the offer, and **Try** uses their own dark CSS. +- Dark *section* styles are not taken for a site theme: `.theme-dark` used on a promo band (Apple, IKEA, + Microsoft), Bootstrap's `.bg-dark`/`.btn-dark`, and blocks that libraries ship to every site using them: Bootstrap + 5.3's `[data-bs-theme=dark]` and Algolia DocSearch's `html[data-theme=dark]` count only when the site sets that + attribute on its root. A dark media block that applies but only restyles a widget doesn't count either. +- The offer card now appears after the page's `load` event (at most 3 s after the first check), when the check for + the site's own theme has seen its style sheets. It used to appear right after DOMContentLoaded. +- Tests: selector-grammar unit tests from real sites, and nine end-to-end checks (five kinds of own theme, the + popup, a page of dark sections and library blocks, a widget-only dark block, and Always on a light system, which + must all still get the offer). The own-theme rule in `light.html` moved into the theme-switch check, since a page + that ships one no longer gets the offer. The offer checks wait for the card instead of a fixed time. + ## 1.0.2 — 2026-11-19 Fixes for the first reports from users, and a tidier popup. Chrome Web Store users update from 1.0.0 to this version diff --git a/README.md b/README.md index 0f4add3..2182b06 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,9 @@ answers, screenshots) is in [store/listing.md](store/listing.md). and remembers the site. The card then offers **Undo** and **All bright sites**. - **⌥⇧D** (Alt+Shift+D) toggles the current site. - Sites that already have a dark theme, or declare `color-scheme: light dark` or `light only`, are never touched. +- Sites with a dark theme of their own that is switched off (YouTube, Stack Overflow or Wikipedia set to light in + their own settings) get no card: their dark theme is one setting away. The popup says so and still has **Try on + this page**. | Popup | Try offer | |---|---| @@ -74,6 +77,7 @@ screenshots, and how each engine mechanism maps to something an extension can do | Runs only in dark mode, only where you allow it | "Follow system" mode, per-site on/off, "Use on all bright sites" | | Leaves sites with their own dark mode alone | `color-scheme: light dark` / `light only` (meta or CSS) → untouched. Author-managed subtrees are excluded. | | Leaves already-dark pages alone | Samples the rendered page after DOMContentLoaded. On sites you turned on it starts at `document_start` (no white flash) unless a cached verdict, recorded per system appearance, says the site is dark, and steps aside if the page turns out dark. | +| No offer where the site has its own dark theme | While the system is dark, before the card appears (after `load`, at idle), the page's readable style sheets are scanned for a dark theme rule aimed at the root: `html[dark]`, `body.theme-dark`, `[data-theme=dark]` when `` carries `data-theme`, or root colors in a `prefers-color-scheme: dark` block the site's setting gates. Dark *section* styles (`.theme-dark` on a promo band, `.bg-dark`) and library blocks shipped to every site (Bootstrap's `[data-bs-theme=dark]`, DocSearch's `html[data-theme=dark]`) don't count. With **All bright sites** or a site you turned on, such pages are still adapted. | | Sites with their own automatic theme keep it | Steps aside when the site turns dark by itself, including themes applied late by an app on a wrapper such as `#app`. The author's `prefers-color-scheme: dark` rules are kept as written. With **Always** on a light system they are switched on, so the site's own dark design is used. | | Light surfaces dark, dark text light, hue kept | A contrast-preserving luminance flip in OKLCH, anchored so white → `#1e1e1e` | | Semantic colors keep their meaning | Vivid badges and buttons stay. Vivid links are lightened just enough. | @@ -104,12 +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 and a page whose body arrives late. Pages that must be left alone +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 are also compared pixel for pixel. | Browser | Mode | Fixture checks | |---|---|---| -| Chrome for Testing 153.0.8010.12 | headless | 83 / 83 (1.0.2) | +| Chrome for Testing 153.0.8010.12 | headless | 92 / 92 (1.0.3) | | 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 @@ -150,6 +155,8 @@ apple.com it was 0.07 to 0.2 s higher. extension can't change the appearance Chrome reports to the page. Set macOS to Dark: the site then uses its own theme and the extension leaves it alone. - **Frames that look dark**, such as some consent dialogs, are not adapted inside. +- **Own dark theme, cross-origin CSS.** The check for a site's own dark theme reads only style sheets the page can + read; it doesn't fetch cross-origin ones. A site whose theme rules live only in such a sheet still gets the offer. - **Timing.** Once on stripe.com (Chrome for Testing 153), a button's text was checked before a late style change settled and stayed white on a light button. It did not happen in the Chrome 157 run. - **Calibration.** Apple's two published screenshots disagree on how dark white becomes. Standard uses `#1e1e1e`, and @@ -171,7 +178,7 @@ src/shared/transform.js the color model, value rewriting, CSS-variable role src/shared/settings.js defaults, per-site policy, built-in quirks src/shared/imageclass.js bitmap histogram and SVG paint classifier src/content/page-hook.js main-world signal for insertRule / adoptedStyleSheets / attachShadow -src/content/detect.js color-scheme opt-out and light/dark page sampling +src/content/detect.js color-scheme opt-out, light/dark page sampling, the site's own dark theme src/content/sheets.js rule-level override engine (media, layers, nesting, @import, cross-origin, shadow roots) src/content/inline.js inline styles and bgcolor / src/content/layout.js backdrop pass: text contrast, small controls, hairlines, SVG, canvas islands diff --git a/manifest.json b/manifest.json index 2a7de29..6c6f224 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.2", + "version": "1.0.3", "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 5811ca2..5912750 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "adaptive-dark-mode", - "version": "1.0.2", + "version": "1.0.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "adaptive-dark-mode", - "version": "1.0.2", + "version": "1.0.3", "devDependencies": { "playwright-core": "^1.56.0" } diff --git a/package.json b/package.json index 484b03c..c45a39b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "adaptive-dark-mode", - "version": "1.0.2", + "version": "1.0.3", "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/detect.js b/src/content/detect.js index 3cb7552..b185aef 100644 --- a/src/content/detect.js +++ b/src/content/detect.js @@ -220,5 +220,258 @@ return { verdict, medianBgY, lightFrac, textY, mediaPoints, samples: bgY.length }; } - ADM.detect = { authorScheme, sampleAppearance, backdropAtPoint, gradientColor, canvasColor, pageSurface, MEDIA_TAGS }; + // --------------------------------------------------------------------------- + // A dark theme of the site's own, switched off right now. + // + // Sites that follow the system appearance are already dark in dark mode, + // and sites that declare color-scheme are left alone (authorScheme). What + // remains are sites with a theme setting of their own, set to light: + // YouTube (html[dark]), Stack Overflow (body.theme-dark), Wikipedia + // (html.skin-theme-clientpref-night), Reddit (:root:not(.theme-light) in a + // dark media block). Offering to darken those is noise: their own dark + // theme is one setting away. + // + // Evidence, from the page's readable style sheets (cross-origin sheets are + // not fetched for this: it only decides whether to offer): + // root a rule for the root itself, keyed on a dark marker: + // html[dark], body.theme-dark, html.dark body, + // :root[data-mode=dark]. A marker with a value + // ([data-mode=dark]) counts only when the root carries that + // attribute: Algolia DocSearch ships html[data-theme=dark] + // to every site that has its search box. + // root-attr a bare [theme-attribute=dark] rule, when or + // carries that attribute. Bootstrap 5.3 ships + // [data-bs-theme=dark] to every site; only a site that sets + // data-bs-theme on its root uses it as a theme. + // root-family a bare dark class that no element has right now, from a + // family the root carries (.theme-dark beside + // body.theme-beta). A .theme-dark with no theme class on the + // root is a style for dark sections (Apple, IKEA), not a + // site theme. + // media-root root colors inside @media (prefers-color-scheme: dark), + // while that query matches, in a rule that doesn't match the + // root: the site's own setting gates them + // (:root:not(.theme-light)). A dark block that applies but + // only restyles a widget is not a theme. + // A rule counts only when it sets colors: two or more, three in a dark + // media block. + // --------------------------------------------------------------------------- + const DARK_WORDS = new Set(['dark', 'night']); + // Words that may stand beside "dark" in a theme marker's name. Anything else + // makes it a component name: .bg-dark, .btn-dark, .navbar-dark, .dark-card. + const THEME_WORDS = new Set(['theme', 'themed', 'mode', 'scheme', 'color', 'colour', 'skin', 'appearance', 'clientpref', 'pref', 'prefers', 'is', 'has', 'use', 'ui', 'app', 'site', 'page', 'v', 't', 'global', 'on', 'active', 'enabled']); + // Words that tie a root class to a theme family (theme-beta ~ theme-dark). + const FAMILY_WORDS = new Set(['theme', 'themed', 'mode', 'scheme', 'skin', 'appearance', 'color', 'colour', 'clientpref']); + const THEME_ATTR = /theme|mode|scheme|appearance|colou?r|skin/i; + const DARK_MEDIA = /prefers-color-scheme\s*:\s*dark/i; + const ROOT_RE = /^(?:html|body|:root)(?![\w-])/i; + const NOT_RE = /:not\((?:[^()]|\([^()]*\))*\)/gi; + const ATTR_RE = /\[\s*([\w-]+)\s*(?:([~|^$*]?=)\s*(?:"([^"]*)"|'([^']*)'|([^\]\s]+))\s*(?:[is]\s*)?)?\]/g; + const PSEUDO_RE = /::?[\w-]+(?:\((?:[^()]|\([^()]*\))*\))?/g; + const CLASS_RE = /\.((?:[\w-]|\\.)+)/g; + const COLORISH = /#[0-9a-f]{3,8}\b|\b(?:rgb|hsl|hwb|lab|lch|oklab|oklch|color)a?\(|^\s*\d+(?:\.\d+)?\s*,\s*\d+(?:\.\d+)?\s*,\s*\d+|^\s*\d+(?:\.\d+)?(?:deg)?\s+\d+(?:\.\d+)?%\s+\d+(?:\.\d+)?%|^\s*(?:black|white)\s*$/i; + + /** "skin-theme-clientpref-night" -> [skin, theme, clientpref, night]; "darkMode" -> [dark, mode]. */ + function nameWords(name) { + return String(name) + .replace(/\\/g, '') + .replace(/([a-z0-9])([A-Z])/g, '$1-$2') + .toLowerCase() + .split(/[-_:]+/) + .filter(Boolean); + } + + function isDarkName(name) { + const w = nameWords(name); + return w.length > 0 && w.length <= 5 && w.some((x) => DARK_WORDS.has(x)) && w.every((x) => DARK_WORDS.has(x) || THEME_WORDS.has(x)); + } + + /** Split at top-level commas (list) or combinators (compounds), outside brackets, parentheses and strings. */ + function splitSelector(sel, compounds) { + const out = []; + let depth = 0; + let quote = null; + let cur = ''; + for (let i = 0; i < sel.length; i++) { + const ch = sel[i]; + if (ch === '\\') { + cur += ch + (sel[i + 1] || ''); + i++; + continue; + } + if (quote) { + cur += ch; + if (ch === quote) quote = null; + continue; + } + if (ch === '"' || ch === "'") quote = ch; + else if (ch === '(' || ch === '[') depth++; + else if (ch === ')' || ch === ']') depth--; + if (depth === 0 && !quote && (compounds ? /[\s>+~]/.test(ch) : ch === ',')) { + if (cur.trim()) out.push(cur.trim()); + cur = ''; + continue; + } + cur += ch; + } + if (cur.trim()) out.push(cur.trim()); + return out; + } + + /** + * One compound selector: { root, bare, marks }. root: it is html, body or + * :root. bare: it holds nothing but the root type, dark markers, theme + * attributes and pseudo-classes. marks: its dark markers. :not() is ignored. + */ + function parseCompound(text) { + let s = text.replace(NOT_RE, ''); + const root = ROOT_RE.test(s); + if (root) s = s.replace(ROOT_RE, ''); + const marks = []; + let other = false; + s = s.replace(ATTR_RE, (_, name, op, v1, v2, v3) => { + const value = v1 ?? v2 ?? v3; + if (THEME_ATTR.test(name)) { + if (op ? nameWords(value).some((w) => DARK_WORDS.has(w)) : isDarkName(name.replace(/^data-/, ''))) marks.push({ kind: 'attr', name, valued: !!op }); + } else if (!op && isDarkName(name.replace(/^data-/, ''))) { + marks.push({ kind: 'flag', name }); // [dark] + } else { + other = true; + } + return ''; + }); + s = s.replace(PSEUDO_RE, ''); + s = s.replace(CLASS_RE, (_, name) => { + if (isDarkName(name)) marks.push({ kind: 'class', name: name.replace(/\\/g, '') }); + else other = true; + return ''; + }); + s = s.trim(); + if (s && s !== '*' && s !== '&') other = true; + return { root, bare: !other, marks }; + } + + /** + * Classify one complex selector (no commas). `page` describes the root: + * { hasAttr(name), family: Set of FAMILY_WORDS on root classes, dormant(className) }. + * Returns 'root' | 'root-attr' | 'root-family' | 'media-root' | null. + */ + function themeSelector(sel, inDarkMedia, page) { + const parts = splitSelector(sel, true).map(parseCompound); + if (!parts.length) return null; + const subject = parts[parts.length - 1]; + // A marker with a value counts only on a root that carries the attribute. + const usable = (m) => m.kind !== 'attr' || !m.valued || page.hasAttr(m.name); + // The root itself: html/body/:root, with only root compounds or bare + // markers before it (html.dark body, .dark body). + if (subject.root && parts.every((p) => p.root || (p.bare && p.marks.length))) { + if (parts.some((p) => p.marks.some(usable))) return 'root'; + if (parts.some((p) => p.marks.length)) return null; + if (inDarkMedia) return 'media-root'; + } + if (parts.length !== 1 || !subject.bare) return null; + for (const m of subject.marks) { + if (m.kind === 'attr' && page.hasAttr(m.name)) return 'root-attr'; + if (m.kind === 'class' && nameWords(m.name).some((w) => page.family.has(w)) && page.dormant(m.name)) return 'root-family'; + } + return null; + } + + function colorCount(style) { + let n = 0; + for (let i = 0; i < style.length; i++) { + const p = style[i]; + const v = style.getPropertyValue(p); + if (p === 'color-scheme') { + if (/dark/i.test(v)) n += 2; + } else if ((p.startsWith('--') || /^(?:background(?:-color)?|color|border(?:-\w+)?-color)$/.test(p)) && COLORISH.test(v)) { + n++; + } + } + return n; + } + + /** Returns { via, selector } when the page ships a dark theme of its own, else null. */ + function ownDarkTheme(budget = 60000) { + const roots = [document.documentElement, document.body].filter(Boolean); + const family = new Set(); + for (const el of roots) for (const c of el.classList) for (const w of nameWords(c)) if (FAMILY_WORDS.has(w)) family.add(w); + const page = { + hasAttr: (name) => roots.some((el) => el.hasAttribute(name)), + family, + dormant: (cls) => document.getElementsByClassName(cls).length === 0, + }; + // A dark media block counts only while it matches (the system is dark). + const darkNow = (media) => { + if (!DARK_MEDIA.test(media)) return false; + try { + return matchMedia(media).matches; + } catch (_) { + return false; + } + }; + const appliesToRoot = (sel) => { + try { + return roots.some((el) => el.matches(sel)); + } catch (_) { + return true; // can't tell: not evidence + } + }; + let found = null; + // darkMedia: inside a (prefers-color-scheme: dark) block that matches now. + const visit = (rules, darkMedia) => { + for (const rule of rules) { + if (found || budget-- <= 0) return; + if (rule instanceof CSSStyleRule) { + const text = rule.selectorText; + if ((darkMedia || /dark|night/i.test(text)) && colorCount(rule.style) >= (darkMedia ? 3 : 2)) { + for (const sel of splitSelector(text, false)) { + const via = themeSelector(sel, darkMedia, page); + if (via === 'media-root' && appliesToRoot(sel)) continue; + if (via) { + found = { via, selector: sel.slice(0, 120) }; + return; + } + } + } + if (rule.cssRules && rule.cssRules.length) visit(rule.cssRules, darkMedia); + } else if (rule instanceof CSSImportRule) { + let inner = null; + try { + inner = rule.styleSheet && rule.styleSheet.cssRules; + } catch (_) { + /* cross-origin import */ + } + if (inner) visit(inner, darkMedia || darkNow(rule.media.mediaText)); + } else if (rule.cssRules) { + visit(rule.cssRules, darkMedia || (rule instanceof CSSMediaRule && darkNow(rule.media.mediaText))); + } + } + }; + for (const sheet of [...document.styleSheets, ...(document.adoptedStyleSheets || [])]) { + let rules; + try { + rules = sheet.cssRules; + } catch (_) { + continue; // cross-origin + } + visit(rules, darkNow(sheet.media ? sheet.media.mediaText : '')); + if (found || budget <= 0) break; + } + return found; + } + + ADM.detect = { + authorScheme, + sampleAppearance, + backdropAtPoint, + gradientColor, + canvasColor, + pageSurface, + ownDarkTheme, + themeSelector, + isDarkName, + splitSelector, + MEDIA_TAGS, + }; })(globalThis); diff --git a/src/content/main.js b/src/content/main.js index 9273b01..efb7248 100644 --- a/src/content/main.js +++ b/src/content/main.js @@ -180,12 +180,78 @@ activate(); return; } + // Not wanted here yet: offer "Try", unless the site has a dark theme of + // its own (switched off right now). Its style sheets keep arriving until + // load, so nothing is offered before that check has run. Only while the + // system is dark: with Always on a light system, a site whose theme + // follows the system can't be switched to its own dark theme, and Try + // uses its own dark CSS (see darkMedia in sheets.js). + if (isTop && darkMQ.matches) { + const own = ownThemeNow(); + if (own === undefined) return deactivate('ask'); + if (own) { + if (offered) ADM.prompt.hide(); + return deactivate('own-theme'); + } + } deactivate('ask'); state = 'offer'; report(); if (isTop && pol.offer && !offered) offer(); } + // --------------------------------------------------------------------------- + // The site's own dark theme (top frame, only on the way to an offer) + // --------------------------------------------------------------------------- + // undefined: not checked yet; null: none found; { via, selector }: found. + // A "none" is checked again at the next decision (a root class or attribute + // change, a navigation, a settings change) after the page's set of style + // sheets has changed. A sheet arriving on its own doesn't trigger one. + let ownTheme; + let ownThemeSheets = ''; + let ownThemePending = false; + const sheetCount = () => `${document.styleSheets.length}/${document.adoptedStyleSheets ? document.adoptedStyleSheets.length : 0}`; + + function ownThemeNow() { + if (ownTheme === undefined || (ownTheme === null && ownThemeSheets !== sheetCount())) checkOwnTheme(); + return ownTheme; + } + + function checkOwnTheme() { + if (ownThemePending) return; + ownThemePending = true; + const run = () => { + ownThemePending = false; + if (engine) return; // adapting now: the next offer decision checks again + const t0 = performance.now(); + try { + ownTheme = ADM.detect.ownDarkTheme(); + } catch (_) { + ownTheme = null; + } + ownThemeSheets = sheetCount(); + timing.ownThemeMs = Math.round((performance.now() - t0) * 10) / 10; + evaluate('own-theme'); + }; + // After load, a beat, and an idle moment: one scan of every rule (about + // 10 ms on YouTube's 12,000) must not compete with the page's start. A + // slow ad or tracker can hold load back for a long time (Stack Overflow), + // so the wait is capped at 3 s from the first decision. + let started = false; + const go = () => { + if (started) return; + started = true; + if (window.requestIdleCallback) requestIdleCallback(run, { timeout: 1000 }); + else setTimeout(run, 0); + }; + if (document.readyState === 'complete') { + setTimeout(go, 300); + } else { + window.addEventListener('load', () => setTimeout(go, 300), { once: true }); + setTimeout(go, 3000); + } + } + function scheduleRetries() { if (retryTimers.length) return; retryTimers = [600, 1500, 3500].map((ms) => setTimeout(() => { @@ -634,6 +700,7 @@ host: location.hostname, siteKey: S.siteKey(location.hostname), sample, + ownTheme: ownTheme || null, stats: { ...stats }, timing: { ...timing, diff --git a/src/popup/popup.js b/src/popup/popup.js index 74349f3..29796a6 100644 --- a/src/popup/popup.js +++ b/src/popup/popup.js @@ -11,6 +11,8 @@ starting: ['Checking page…', ''], 'already-dark': ['Page is already dark', ''], 'declares-dark': ['Site has its own dark mode', ''], + // A theme setting of the site's own, set to light (YouTube, Stack Overflow...). + 'own-theme': ["Site's own dark theme is off", ''], 'declares-light-only': ['Site asks to stay light (light only)', 'warn'], 'system-light': ['System appearance is light', ''], off: ['Turned off', ''], @@ -77,7 +79,7 @@ $('status').textContent = text; $('dot').className = 'dot' + (tone ? ' ' + tone : ''); - const canTry = status && (status.state === 'offer' || (status.state === 'inactive' && status.reason === 'ask')); + const canTry = status && (status.state === 'offer' || (status.state === 'inactive' && (status.reason === 'ask' || status.reason === 'own-theme'))); $('tryBtn').hidden = !canTry; const active = !!status && status.state === 'active'; diff --git a/test/e2e/run.mjs b/test/e2e/run.mjs index f1efaf8..ded84fa 100644 --- a/test/e2e/run.mjs +++ b/test/e2e/run.mjs @@ -172,6 +172,17 @@ async function settle(page, ms = 1200) { await page.waitForTimeout(400); } +/** Poll `fn` until it returns a truthy value or `ms` pass; returns the last value. */ +async function until(fn, ms = 6000) { + const end = Date.now() + ms; + let v = await fn(); + while (!v && Date.now() < end) { + await new Promise((r) => setTimeout(r, 150)); + v = await fn(); + } + return v; +} + // --- main ---------------------------------------------------------------------- const results = []; const check = (name, ok, detail) => { @@ -312,6 +323,13 @@ check('hover dropdown is dark', (await L('.dropdown')) < 0.08, await L('.dropdow await shoot(page, 'light-on-hover', false); console.log('\nre-evaluation stability'); +// The site's own dark theme, switched by a class on . It is added here, +// not shipped in light.html: a site that has one gets no "Try" offer. +await page.evaluate(() => { + const s = document.createElement('style'); + s.textContent = 'html.site-dark body { background: #101418; color: #e6e6e6; }'; + document.head.appendChild(s); +}); await page.evaluate(() => document.getElementById('dark-band').scrollIntoView()); await page.waitForTimeout(300); await page.evaluate(() => document.documentElement.classList.add('scrolled-state')); @@ -481,11 +499,12 @@ console.log('\n"Try" offer (default settings)'); await configure({ scope: 'ask', sites: {}, dismissed: {} }); await sw.evaluate(() => chrome.storage.local.remove('verdicts')); await page.goto(`${base}/light.html`); -await page.waitForTimeout(1500); +// The card appears after load and the check for the site's own dark theme. +const hasOffer = await until(() => page.evaluate(() => !!document.querySelector('adm-offer'))); const offerState = await status(page); -const hasOffer = await page.evaluate(() => !!document.querySelector('adm-offer')); check('bright page shows the Try offer and is not adapted yet', hasOffer && offerState && offerState.state === 'offer', offerState && `${offerState.state}/${offerState.reason}`); -await page.waitForTimeout(400); +// Past the card's entrance (260 ms) and its click guard (500 ms after it appears). +await page.waitForTimeout(800); await shoot(page, 'offer', false); // The card is in a closed shadow root: click the "Try" button by position. await page.mouse.click(1280 - 49, 900 - 44); @@ -496,6 +515,56 @@ check('clicking Try adapts the page and remembers the site', tried && tried.stat await shoot(page, 'offer-applied', false); await configure({ scope: 'all', sites: {} }); +console.log('\nsites with a dark theme of their own (default settings)'); +{ + await configure({ scope: 'ask', sites: {}, dismissed: {} }); + const offerShown = () => page.evaluate(() => !!document.querySelector('adm-offer')); + const decided = async () => { + const s = await status(page); + return s && (s.state === 'offer' || s.reason === 'own-theme') ? s : null; + }; + for (const v of ['flag', 'class', 'attr', 'media', 'late']) { + await sw.evaluate(() => chrome.storage.local.remove('verdicts')); + await page.goto(`${base}/own-theme.html?v=${v}`); + const s = (await until(decided)) || (await status(page)); + const card = await offerShown(); + check(`own dark theme (${v}): no offer`, !card && s && s.state === 'inactive' && s.reason === 'own-theme', s && { state: `${s.state}/${s.reason}`, card, ownTheme: s.ownTheme, ms: s.timing && s.timing.ownThemeMs }); + } + // The popup says why, and still offers Try. + const tabId = await sw.evaluate(async (x) => (await chrome.tabs.query({})).find((t) => t.url === x)?.id, page.url()); + const pop = await context.newPage(); + await pop.emulateMedia({ colorScheme: 'dark' }); + await pop.goto(`chrome-extension://${extensionId}/src/popup/popup.html?tab=${tabId}`); + await pop.waitForTimeout(700); + const popState = await pop.evaluate(() => ({ text: document.getElementById('status').textContent, tryShown: !document.getElementById('tryBtn').hidden })); + await pop.close(); + check('popup: says the site\'s own dark theme is off, and still offers Try', /own dark theme is off/.test(popState.text) && popState.tryShown, popState); + + await sw.evaluate(() => chrome.storage.local.remove('verdicts')); + await page.goto(`${base}/section-themes.html`); + const secCard = await until(offerShown); + const sec = await status(page); + check('dark sections, Bootstrap\'s and DocSearch\'s built-in dark blocks: offer still shown', secCard && sec && sec.state === 'offer', sec && { state: `${sec.state}/${sec.reason}`, card: secCard, ownTheme: sec.ownTheme }); + + // A dark media block in force that only restyles a widget is not a theme. + await page.goto(`${base}/own-theme.html?v=widget`); + const wCard = await until(offerShown); + const w = await status(page); + check('dark media block that only restyles a widget: offer still shown', wCard && w && w.state === 'offer', w && { state: `${w.state}/${w.reason}`, card: wCard, ownTheme: w.ownTheme }); + + // Always on a light system: a site whose theme follows the system can't be + // switched to it, so the offer stays (Try uses the site's own dark CSS). + await configure({ mode: 'always' }); + await page.emulateMedia({ colorScheme: 'light' }); + await page.goto(`${base}/own-theme.html?v=media`); + const aCard = await until(offerShown); + const a = await status(page); + check('Always on a light system: a site that follows the system still gets the offer', aCard && a && a.state === 'offer', a && { state: `${a.state}/${a.reason}`, card: aCard }); + await page.emulateMedia({ colorScheme: 'dark' }); + await page.goto('about:blank'); + await configure({ mode: 'system', scope: 'all', sites: {}, dismissed: {} }); +} + console.log('\npopup'); { const tabIdOf = (u) => sw.evaluate(async (x) => (await chrome.tabs.query({})).find((t) => t.url === x)?.id, u); @@ -514,7 +583,7 @@ console.log('\npopup'); await configure({ scope: 'ask', sites: {}, dismissed: {}, quirks: {} }); await sw.evaluate(() => chrome.storage.local.remove('verdicts')); await page.goto(`${base}/light.html`); - await page.waitForTimeout(1500); + await until(async () => (await status(page))?.state === 'offer'); await openPopup(); const hOffer = await popHeight(); const tryShown = await pop.evaluate(() => !document.getElementById('tryBtn').hidden); diff --git a/test/fixtures/light.html b/test/fixtures/light.html index 15654b0..99b381c 100644 --- a/test/fixtures/light.html +++ b/test/fixtures/light.html @@ -81,8 +81,8 @@ .full { grid-column: 1 / -1; } .ink { color: #222222; } .dark-band { background: #0b0f14; color: #e5e7eb; min-height: 1000px; padding: 40px 24px; } - /* the site's own dark theme, switched by a class on */ - html.site-dark body { background: #101418; color: #e6e6e6; } + /* No dark theme of its own: a site that has one gets no "Try" offer + (own-theme.html). The theme-switch check adds html.site-dark body {...}. */ /* cascade: an unchanged later rule must still win over an earlier transformed one */ .btn-base { --btn-bg: #533afd; background-color: var(--btn-bg); color: #fff; padding: 6px 12px; border-radius: 8px; display: inline-block; } .btn-ghost { background-color: transparent; color: #1f2937; } diff --git a/test/fixtures/own-theme.html b/test/fixtures/own-theme.html new file mode 100644 index 0000000..837a389 --- /dev/null +++ b/test/fixtures/own-theme.html @@ -0,0 +1,49 @@ + + +Own dark theme, switched off + + + +
Streamly · Appearance: Light theme
+
+
Evening mix

Twelve tracks for a quiet night in.

+
Workshop recording

Three hours of building a cabinet from scratch.

+
Race highlights

The final laps, from the onboard cameras.

+
How harbours work

Cranes, tides and the people who schedule them.

+
Studio session

A live take, recorded in one pass.

+
Weekend cooking

Slow food for a long Sunday.

+
+ diff --git a/test/fixtures/section-themes.html b/test/fixtures/section-themes.html new file mode 100644 index 0000000..ce0ea2c --- /dev/null +++ b/test/fixtures/section-themes.html @@ -0,0 +1,35 @@ + + +Dark sections, no dark theme + + + +
+
Rain shells

Seam-sealed, packable, and cut for layering.

+
Trail shoes

Grippy soles for wet rock and loose gravel.

+
Camp kitchen

Stoves, pots and a kettle that nests inside.

+
Night hike kit

Headlamps and reflective layers. Shop

+
Repairs

Send it back; we patch it and post it home.

+
Members

Free returns and early sales.

+
+ diff --git a/test/unit/detect.test.js b/test/unit/detect.test.js new file mode 100644 index 0000000..213f5cb --- /dev/null +++ b/test/unit/detect.test.js @@ -0,0 +1,115 @@ +// Unit tests for the own-dark-theme selector grammar (src/content/detect.js). +// The selectors are taken from real sites (2026-11-20): the ones that ship a +// dark theme behind a setting of their own, and the ones whose "dark" classes +// style a section or a component, not the site. +const test = require('node:test'); +const assert = require('node:assert/strict'); + +require('../../src/shared/color.js'); +require('../../src/content/detect.js'); + +const { detect: D } = globalThis.ADM; + +// A root with no attributes or classes, where every class is unused. +const bare = { hasAttr: () => false, family: new Set(), dormant: () => true }; +const page = (over) => ({ ...bare, ...over }); + +test('dark theme rules for the root itself', () => { + for (const sel of [ + 'html[dark]', // YouTube + 'html:not(.style-scope)[dark]', // YouTube + 'body:not(.theme-highcontrast).theme-dark', // Stack Overflow + 'html.skin-theme-clientpref-night', // Wikipedia + ':root.dark', // Cloudflare + 'html.dark', + 'html.site-dark body', + '.dark body', + 'html.darkMode', + 'html[dark-theme]', + ]) { + assert.equal(D.themeSelector(sel, false, bare), 'root', sel); + } +}); + +test('a theme attribute with a value counts on the root only when the root carries it', () => { + // Algolia DocSearch ships html[data-theme=dark] { --docsearch-... } to every + // site with its search box (react.dev and vuejs.org don't set data-theme). + assert.equal(D.themeSelector('html[data-theme="dark"]', false, bare), null); + assert.equal(D.themeSelector(':root[data-mode="dark"]', false, bare), null); + // Docusaurus and others: . + const docs = page({ hasAttr: (n) => n === 'data-theme' }); + assert.equal(D.themeSelector('html[data-theme="dark"]', false, docs), 'root'); + assert.equal(D.themeSelector('html[data-theme="dark"] body', false, docs), 'root'); + // A marked root rule whose marker doesn't count is not a dark media root rule either. + assert.equal(D.themeSelector('html[data-theme="dark"]', true, bare), null); +}); + +test('dark styles for sections and components are not a site theme', () => { + for (const sel of [ + 'html[dark] #guide-skeleton', // a component under the theme, not the theme + '.theme-dark #globalnav', // Apple + '#globalnav.globalnav-dark', + 'html.globalheader-dark', + '.bg-dark', // Bootstrap utilities + '.btn-dark', + '.navbar-dark', + '.navbar[data-bs-theme="dark"]', + '.table-dark', + '.dark-card', + '.dark-band', + '.ytSpecButtonShapeNextOverlayDark', // YouTube button variant + '.homepage--dark', + 'html[darker-dark-theme] #home-chips', + '.prose:where(.dark, .dark *)', // Tailwind utility under the variant + 'body:not(.theme-dark)', + ':root', + 'body', + ]) { + assert.equal(D.themeSelector(sel, false, bare), null, sel); + } +}); + +test('a bare theme attribute counts only when the root carries it', () => { + // Bootstrap 5.3 ships [data-bs-theme=dark] to every site. + assert.equal(D.themeSelector('[data-bs-theme="dark"]', false, bare), null); + const bs = page({ hasAttr: (n) => n === 'data-bs-theme' }); + assert.equal(D.themeSelector('[data-bs-theme="dark"]', false, bs), 'root-attr'); + // GitHub + const gh = page({ hasAttr: (n) => ['data-color-mode', 'data-light-theme', 'data-dark-theme'].includes(n) }); + assert.equal(D.themeSelector('[data-color-mode="dark"][data-dark-theme="dark"]', false, gh), 'root-attr'); + assert.equal(D.themeSelector('[data-color-mode][data-color-mode="auto"][data-dark-theme="dark_high_contrast"]', false, gh), 'root-attr'); + // A component carrying the attribute is not the root. + assert.equal(D.themeSelector('.navbar[data-bs-theme="dark"]', false, bs), null); +}); + +test('a bare dark class counts only when unused and from a family the root carries', () => { + // Reddit: body.theme-beta, and .theme-dark defined but on no element. + const reddit = page({ family: new Set(['theme']) }); + assert.equal(D.themeSelector('.theme-dark', false, reddit), 'root-family'); + // Apple, IKEA, Microsoft: no theme class on the root. + assert.equal(D.themeSelector('.theme-dark', false, bare), null); + assert.equal(D.themeSelector('.theme-night', false, bare), null); + // In use on a section of this page: a section style. + assert.equal(D.themeSelector('.theme-dark', false, page({ family: new Set(['theme']), dormant: () => false })), null); + // .dark has no family word to tie it to the root. + assert.equal(D.themeSelector('.dark', false, reddit), null); +}); + +test('root colors inside a dark media block', () => { + assert.equal(D.themeSelector(':root:not(.theme-light)', true, bare), 'media-root'); // Reddit + assert.equal(D.themeSelector(':root:not([data-theme="light"])', true, bare), 'media-root'); + assert.equal(D.themeSelector('html body', true, bare), 'media-root'); + assert.equal(D.themeSelector('.highlight .k', true, bare), null); + assert.equal(D.themeSelector(':root', false, bare), null); +}); + +test('marker names', () => { + for (const n of ['dark', 'dark-mode', 'darkMode', 'theme-dark', 'theme--dark', 'v-theme--dark', 'is-dark', 'night', 'site-dark', 'skin-theme-clientpref-night']) assert.ok(D.isDarkName(n), n); + for (const n of ['bg-dark', 'btn-dark', 'text-dark', 'dark-card', 'globalnav-dark', 'darker', 'darken', 'nightlife-banner']) assert.ok(!D.isDarkName(n), n); +}); + +test('selector splitting keeps brackets, parentheses, strings and escapes together', () => { + assert.deepEqual(D.splitSelector('html[dark], :root:is(.a, .b), [x="a,b"]', false), ['html[dark]', ':root:is(.a, .b)', '[x="a,b"]']); + assert.deepEqual(D.splitSelector('html.dark > body .a\\:b', true), ['html.dark', 'body', '.a\\:b']); + assert.deepEqual(D.splitSelector('li:nth-child(2n + 1) ~ [data-a="x y"]', true), ['li:nth-child(2n + 1)', '[data-a="x y"]']); +});