forked from darkreader/darkreader
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
338 lines (309 loc) · 12.7 KB
/
Copy pathindex.ts
File metadata and controls
338 lines (309 loc) · 12.7 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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
import {createOrUpdateStyle, removeStyle} from './style';
import {createOrUpdateSVGFilter, removeSVGFilter} from './svg-filter';
import {runDarkThemeDetector, stopDarkThemeDetector} from './detector';
import {createOrUpdateDynamicTheme, removeDynamicTheme, cleanDynamicThemeCache} from './dynamic-theme';
import {logWarn, logInfoCollapsed} from './utils/log';
import {isSystemDarkModeEnabled, runColorSchemeChangeDetector, stopColorSchemeChangeDetector, emulateColorScheme} from '../utils/media-query';
import {collectCSS} from './dynamic-theme/css-collection';
import type {DebugMessageBGtoCS, MessageBGtoCS, MessageCStoBG, MessageCStoUI, MessageUItoCS} from '../definitions';
import {DebugMessageTypeBGtoCS, MessageTypeBGtoCS, MessageTypeCStoBG, MessageTypeCStoUI, MessageTypeUItoCS} from '../utils/message';
import {generateUID} from '../utils/uid';
declare const __DEBUG__: boolean;
declare const __TEST__: boolean;
let unloaded = false;
let darkReaderDynamicThemeStateForTesting: 'loading' | 'ready' = 'loading';
declare const __CHROMIUM_MV2__: boolean;
declare const __CHROMIUM_MV3__: boolean;
declare const __THUNDERBIRD__: boolean;
declare const __FIREFOX_MV2__: boolean;
// Identifier for this particular script instance. It is used as an alternative to chrome.runtime.MessageSender.documentId
const scriptId = generateUID();
function cleanup() {
unloaded = true;
removeEventListener('pagehide', onPageHide);
removeEventListener('freeze', onFreeze);
removeEventListener('resume', onResume);
cleanDynamicThemeCache();
stopDarkThemeDetector();
stopColorSchemeChangeDetector();
}
function sendMessageForTesting(uuid: string) {
document.dispatchEvent(new CustomEvent('test-message', {detail: uuid}));
}
function sendMessage(message: MessageCStoBG | MessageCStoUI) {
if (unloaded) {
return;
}
const responseHandler = (response: MessageBGtoCS | 'unsupportedSender' | undefined) => {
// Vivaldi bug workaround. See TabManager for details.
if (response === 'unsupportedSender') {
removeStyle();
removeSVGFilter();
removeDynamicTheme();
cleanup();
}
};
try {
if (__CHROMIUM_MV3__) {
const promise = chrome.runtime.sendMessage<MessageCStoBG | MessageCStoUI, MessageBGtoCS | 'unsupportedSender'>(message);
promise.then(responseHandler).catch(cleanup);
} else {
chrome.runtime.sendMessage<MessageCStoBG | MessageCStoUI, 'unsupportedSender' | undefined>(message, responseHandler);
}
} catch (error) {
/*
* We get here if Background context is unreachable which occurs when:
* - extension was disabled
* - extension was uninstalled
* - extension was updated and this is the old instance of content script
*
* Any async operations can be ignored here, but sync ones should run to completion.
*
* Regular message passing errors are returned via rejected promise or runtime.lastError.
*/
if (error.message === 'Extension context invalidated.') {
console.log('Dark Reader: instance of old CS detected, cleaning up.');
cleanup();
} else {
console.log('Dark Reader: unexpected error during message passing.');
}
}
}
function onMessage(message: MessageBGtoCS | MessageUItoCS | DebugMessageBGtoCS) {
if (__DEBUG__ && message.type === DebugMessageTypeBGtoCS.RELOAD) {
logWarn('Cleaning up before update');
cleanup();
return;
}
if ((message as MessageBGtoCS).scriptId !== scriptId && message.type !== MessageTypeUItoCS.EXPORT_CSS) {
return;
}
logInfoCollapsed(`onMessage[${message.type}]`, message);
switch (message.type) {
case MessageTypeBGtoCS.ADD_CSS_FILTER:
case MessageTypeBGtoCS.ADD_STATIC_THEME: {
const {css, detectDarkTheme, detectorHints} = message.data;
removeDynamicTheme();
createOrUpdateStyle(css, message.type === MessageTypeBGtoCS.ADD_STATIC_THEME ? 'static' : 'filter');
if (detectDarkTheme) {
runDarkThemeDetector((hasDarkTheme) => {
if (hasDarkTheme) {
removeStyle();
onDarkThemeDetected();
}
}, detectorHints);
}
break;
}
case MessageTypeBGtoCS.ADD_SVG_FILTER: {
const {css, svgMatrix, svgReverseMatrix, detectDarkTheme, detectorHints} = message.data;
removeDynamicTheme();
createOrUpdateSVGFilter(svgMatrix, svgReverseMatrix);
createOrUpdateStyle(css, 'filter');
if (detectDarkTheme) {
runDarkThemeDetector((hasDarkTheme) => {
if (hasDarkTheme) {
removeStyle();
removeSVGFilter();
onDarkThemeDetected();
}
}, detectorHints);
}
break;
}
case MessageTypeBGtoCS.ADD_DYNAMIC_THEME: {
const {theme, fixes, isIFrame, detectDarkTheme, detectorHints} = message.data;
removeStyle();
createOrUpdateDynamicTheme(theme, fixes, isIFrame);
if (detectDarkTheme) {
runDarkThemeDetector((hasDarkTheme) => {
if (hasDarkTheme) {
removeDynamicTheme();
onDarkThemeDetected();
}
}, detectorHints);
}
if (__TEST__) {
darkReaderDynamicThemeStateForTesting = 'ready';
sendMessageForTesting('darkreader-dynamic-theme-ready');
sendMessageForTesting(`darkreader-dynamic-theme-ready-${document.location.pathname}`);
}
break;
}
case MessageTypeUItoCS.EXPORT_CSS:
collectCSS().then((collectedCSS) => sendMessage({type: MessageTypeCStoUI.EXPORT_CSS_RESPONSE, data: collectedCSS}));
break;
case MessageTypeBGtoCS.UNSUPPORTED_SENDER:
case MessageTypeBGtoCS.CLEAN_UP:
removeStyle();
removeSVGFilter();
removeDynamicTheme();
stopDarkThemeDetector();
break;
default:
break;
}
}
function sendConnectionOrResumeMessage(type: MessageTypeCStoBG.DOCUMENT_CONNECT | MessageTypeCStoBG.DOCUMENT_RESUME) {
sendMessage(
{
type,
scriptId,
data: (__CHROMIUM_MV2__ || __CHROMIUM_MV3__) ? {
isDark: isSystemDarkModeEnabled(),
isTopFrame: window === window.top,
} : {
isDark: isSystemDarkModeEnabled(),
},
});
}
runColorSchemeChangeDetector((isDark) =>
sendMessage({type: MessageTypeCStoBG.COLOR_SCHEME_CHANGE, data: {isDark}})
);
chrome.runtime.onMessage.addListener(onMessage);
sendConnectionOrResumeMessage(MessageTypeCStoBG.DOCUMENT_CONNECT);
function onPageHide(e: PageTransitionEvent) {
if (e.persisted === false) {
sendMessage({type: MessageTypeCStoBG.DOCUMENT_FORGET, scriptId});
}
}
function onFreeze() {
sendMessage({type: MessageTypeCStoBG.DOCUMENT_FREEZE});
}
function onResume() {
sendConnectionOrResumeMessage(MessageTypeCStoBG.DOCUMENT_RESUME);
}
function onDarkThemeDetected() {
sendMessage({type: MessageTypeCStoBG.DARK_THEME_DETECTED});
}
// Thunderbird does not have "tabs", and emails aren't 'frozen' or 'cached'.
// And will currently error: `Promise rejected after context unloaded: Actor 'Conduits' destroyed before query 'RuntimeMessage' was resolved`
if (!__THUNDERBIRD__) {
addEventListener('pagehide', onPageHide, {passive: true});
addEventListener('freeze', onFreeze, {passive: true});
addEventListener('resume', onResume, {passive: true});
}
if (__TEST__) {
async function awaitDOMContentLoaded() {
if (document.readyState === 'loading') {
return new Promise<void>((resolve) => {
addEventListener('DOMContentLoaded', () => resolve(), {passive: true});
});
}
}
async function awaitDarkReaderReady() {
if (darkReaderDynamicThemeStateForTesting !== 'ready') {
return new Promise<void>((resolve) => {
document.addEventListener('test-message', (event: CustomEvent) => {
const message = event.detail;
if (message === 'darkreader-dynamic-theme-ready' && darkReaderDynamicThemeStateForTesting === 'ready') {
resolve();
}
}, {passive: true});
});
}
}
const socket = new WebSocket(`ws://localhost:8894`);
socket.onopen = async () => {
document.addEventListener('test-message', (e: CustomEvent) => {
socket.send(JSON.stringify({
data: {
type: 'page',
uuid: e.detail,
},
id: null,
}));
}, {passive: true});
// Wait for DOM to be complete
// Note that here we wait only for DOM parsing and not for sub-resource load
await awaitDOMContentLoaded();
await awaitDarkReaderReady();
socket.send(JSON.stringify({
data: {
type: 'page',
message: 'page-ready',
uuid: `ready-${document.location.pathname}`,
},
id: null,
}));
};
// TODO(anton): remove this once Firefox supports tab.eval() via WebDriver BiDi
if (__FIREFOX_MV2__) {
function expectPageStyles(data: any) {
const checkOne = (expectation: any) => {
const [selector, cssAttributeName, expectedValue] = expectation;
const selector_ = Array.isArray(selector) ? selector : [selector];
let element = document as any;
for (const part of selector_) {
if (element instanceof HTMLIFrameElement) {
element = element.contentDocument;
}
if (element.shadowRoot instanceof ShadowRoot) {
element = element.shadowRoot;
}
if (part === 'document') {
element = element.documentElement;
} else {
element = element.querySelector(part);
}
if (!element) {
return `Could not find element ${part}`;
}
}
const style = getComputedStyle(element);
if (style[cssAttributeName] !== expectedValue) {
return `Got ${style[cssAttributeName]}`;
}
};
const errors: Array<[number, string]> = [];
const expectations = Array.isArray(data[0]) ? data : [data];
for (let i = 0; i < expectations.length; i++) {
const error = checkOne(expectations[i]);
if (error) {
errors.push([i, error]);
}
}
return errors;
}
socket.onmessage = (e) => {
function respond(data: any) {
socket.send(JSON.stringify({id, data}));
}
const {id, data, type} = JSON.parse(e.data);
switch (type) {
case 'firefox-eval': {
const result = eval(data);
if (result instanceof Promise) {
result.then(respond);
} else {
respond(result);
}
break;
}
case 'firefox-expectPageStyles': {
// Styles may not have been applied to the document yet,
// so we check once immediately and then on an interval.
function checkPageStylesNow() {
const errors = expectPageStyles(data);
if (errors.length === 0) {
respond([]);
interval && clearInterval(interval);
}
}
const interval: number = setInterval(checkPageStylesNow, 200);
checkPageStylesNow();
break;
}
case 'firefox-getColorScheme': {
respond(isSystemDarkModeEnabled() ? 'dark' : 'light');
break;
}
case 'firefox-emulateColorScheme': {
emulateColorScheme(data);
respond(undefined);
break;
}
}
};
}
}