forked from darkreader/darkreader
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdetector.ts
More file actions
210 lines (185 loc) · 7.4 KB
/
Copy pathdetector.ts
File metadata and controls
210 lines (185 loc) · 7.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
import type {DetectorHint} from '../definitions';
import {getSRGBLightness, parseColorWithCache} from '../utils/color';
import {isSystemDarkModeEnabled} from '../utils/media-query';
const COLOR_SCHEME_META_SELECTOR = 'meta[name="color-scheme"]';
function hasBuiltInDarkTheme() {
const rootStyle = getComputedStyle(document.documentElement);
if (rootStyle.filter.includes('invert(1)')) {
return true;
}
const CELL_SIZE = 256;
const MAX_ROW_COUNT = 4;
const winWidth = innerWidth;
const winHeight = innerHeight;
const stepX = Math.floor(winWidth / Math.min(MAX_ROW_COUNT, Math.ceil(winWidth / CELL_SIZE)));
const stepY = Math.floor(winHeight / Math.min(MAX_ROW_COUNT, Math.ceil(winHeight / CELL_SIZE)));
const processedElements = new Set<Element>();
for (let y = Math.floor(stepY / 2); y < winHeight; y += stepY) {
for (let x = Math.floor(stepX / 2); x < winWidth; x += stepX) {
const element = document.elementFromPoint(x, y);
if (!element || processedElements.has(element)) {
continue;
}
processedElements.add(element);
const style = element === document.documentElement ? rootStyle : getComputedStyle(element);
const bgColor = parseColorWithCache(style.backgroundColor)!;
if (bgColor.r === 24 && bgColor.g === 26 && bgColor.b === 27) {
// For some websites changes to CSSStyleSheet.disabled and HTMLStyleElement.textContent
// are not being applied synchronously. For example https://zorin.com/
// Probably a browser bug. Treat as not having a dark theme.
return false;
}
if (bgColor.a === 1) {
const bgLightness = getSRGBLightness(bgColor.r, bgColor.g, bgColor.b);
if (bgLightness > 0.5) {
return false;
}
} else {
const textColor = parseColorWithCache(style.color)!;
const textLightness = getSRGBLightness(textColor.r, textColor.g, textColor.b);
if (textLightness < 0.5) {
return false;
}
}
}
}
const rootColor = parseColorWithCache(rootStyle.backgroundColor)!;
const bodyColor = document.body ? parseColorWithCache(getComputedStyle(document.body).backgroundColor)! : {r: 0, g: 0, b: 0, a: 0};
const rootLightness = (1 - rootColor.a!) + rootColor.a! * getSRGBLightness(rootColor.r, rootColor.g, rootColor.b);
const finalLightness = (1 - bodyColor.a!) * rootLightness + bodyColor.a! * getSRGBLightness(bodyColor.r, bodyColor.g, bodyColor.b);
return finalLightness < 0.5;
}
function runCheck(callback: (hasDarkTheme: boolean) => void) {
const colorSchemeMeta = document.querySelector(COLOR_SCHEME_META_SELECTOR) as HTMLMetaElement;
if (colorSchemeMeta) {
const isMetaDark = colorSchemeMeta.content === 'dark' || (colorSchemeMeta.content.includes('dark') && isSystemDarkModeEnabled());
callback(isMetaDark);
return;
}
const drSheets = Array.from(document.styleSheets).filter((s) => (s.ownerNode as HTMLElement)?.classList.contains('darkreader'));
drSheets.forEach((sheet) => sheet.disabled = true);
const darkThemeDetected = hasBuiltInDarkTheme();
drSheets.forEach((sheet) => sheet.disabled = false);
callback(darkThemeDetected);
}
function hasSomeStyle() {
if (document.querySelector(COLOR_SCHEME_META_SELECTOR) != null) {
return true;
}
if (document.documentElement.style.backgroundColor || (document.body && document.body.style.backgroundColor)) {
return true;
}
for (const style of document.styleSheets) {
if (style && style.ownerNode && !((style.ownerNode as HTMLElement).classList && (style.ownerNode as HTMLElement).classList.contains('darkreader'))) {
return true;
}
}
return false;
}
let observer: MutationObserver | null;
let readyStateListener: (() => void) | null;
function canCheckForStyle() {
return (
document.body &&
document.body.scrollHeight > 0 &&
document.body.clientHeight > 0 &&
hasSomeStyle()
);
}
export function runDarkThemeDetector(callback: (hasDarkTheme: boolean) => void, hints: DetectorHint[]): void {
stopDarkThemeDetector();
if (hints && hints.length > 0) {
const hint = hints[0];
if (hint.noDarkTheme) {
callback(false);
return;
}
if (hint.systemTheme && isSystemDarkModeEnabled()) {
callback(true);
return;
}
detectUsingHint(hint, () => callback(true));
return;
}
if (canCheckForStyle()) {
runCheck(callback);
return;
}
observer = new MutationObserver(() => {
if (canCheckForStyle()) {
stopDarkThemeDetector();
runCheck(callback);
}
});
observer.observe(document.documentElement, {childList: true});
if (document.readyState !== 'complete') {
readyStateListener = () => {
if (document.readyState === 'complete') {
stopDarkThemeDetector();
runCheck(callback);
}
};
// readystatechange event is not cancellable and does not bubble
document.addEventListener('readystatechange', readyStateListener);
}
}
export function stopDarkThemeDetector(): void {
if (observer) {
observer.disconnect();
observer = null;
}
if (readyStateListener) {
document.removeEventListener('readystatechange', readyStateListener);
readyStateListener = null;
}
stopDetectingUsingHint();
}
let hintTargetObserver: MutationObserver;
let hintMatchObserver: MutationObserver;
function detectUsingHint(hint: DetectorHint, success: () => void) {
stopDetectingUsingHint();
const matchSelector = (hint.match || []).join(', ');
function checkMatch(target: Element) {
if (target.matches?.(matchSelector)) {
stopDetectingUsingHint();
success();
return true;
}
return false;
}
function setupMatchObserver(target: Element) {
hintMatchObserver?.disconnect();
if (checkMatch(target)) {
return;
}
hintMatchObserver = new MutationObserver(() => checkMatch(target));
hintMatchObserver.observe(target, {attributes: true});
}
const target = document.querySelector(hint.target);
if (target) {
setupMatchObserver(target);
} else {
hintTargetObserver = new MutationObserver((mutations) => {
const handledTargets = new Set<Node>();
for (const mutation of mutations) {
if (handledTargets.has(mutation.target)) {
continue;
}
handledTargets.add(mutation.target);
if (mutation.target instanceof Element) {
const target = mutation.target.querySelector(hint.target);
if (target) {
hintTargetObserver.disconnect();
setupMatchObserver(target);
break;
}
}
}
});
hintTargetObserver.observe(document.documentElement, {childList: true, subtree: true});
}
}
function stopDetectingUsingHint() {
hintTargetObserver?.disconnect();
hintMatchObserver?.disconnect();
}