Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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 `<html>`, 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
Expand Down
13 changes: 10 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
|---|---|
Expand Down Expand Up @@ -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 `<html>` 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. |
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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 / <font color>
src/content/layout.js backdrop pass: text contrast, small controls, hairlines, SVG, canvas islands
Expand Down
2 changes: 1 addition & 1 deletion manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
255 changes: 254 additions & 1 deletion src/content/detect.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 <html> or <body>
// 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);
Loading
Loading