-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
adopted-style-manger.ts
332 lines (279 loc) · 10.2 KB
/
adopted-style-manger.ts
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
import type {Theme} from '../../definitions';
import {iterateCSSRules} from './css-rules';
import type {CSSBuilder} from './stylesheet-modifier';
import {createStyleSheetModifier} from './stylesheet-modifier';
let canUseSheetProxy = false;
document.addEventListener('__darkreader__inlineScriptsAllowed', () => canUseSheetProxy = true, {once: true});
const overrides = new WeakSet<CSSStyleSheet>();
const overridesBySource = new WeakMap<CSSStyleSheet, CSSStyleSheet>();
export interface AdoptedStyleSheetManager {
render(theme: Theme, ignoreImageAnalysis: string[]): void;
destroy(): void;
watch(callback: (sheets: CSSStyleSheet[]) => void): void;
}
export function canHaveAdoptedStyleSheets(node: Document | ShadowRoot): boolean {
return Array.isArray(node.adoptedStyleSheets);
}
export function createAdoptedStyleSheetOverride(node: Document | ShadowRoot): AdoptedStyleSheetManager {
let cancelAsyncOperations = false;
function iterateSourceSheets(iterator: (sheet: CSSStyleSheet) => void) {
node.adoptedStyleSheets.forEach((sheet) => {
if (!overrides.has(sheet)) {
iterator(sheet);
}
});
}
function injectSheet(sheet: CSSStyleSheet, override: CSSStyleSheet) {
const newSheets = [...node.adoptedStyleSheets];
const sheetIndex = newSheets.indexOf(sheet);
const overrideIndex = newSheets.indexOf(override);
if (overrideIndex >= 0) {
newSheets.splice(overrideIndex, 1);
}
newSheets.splice(sheetIndex + 1, 0, override);
node.adoptedStyleSheets = newSheets;
}
function clear() {
const newSheets = [...node.adoptedStyleSheets];
for (let i = newSheets.length - 1; i >= 0; i--) {
const sheet = newSheets[i];
if (overrides.has(sheet)) {
newSheets.splice(i, 1);
overrides.delete(sheet);
}
}
if (node.adoptedStyleSheets.length !== newSheets.length) {
node.adoptedStyleSheets = newSheets;
}
sourceSheets = new WeakSet();
sourceDeclarations = new WeakSet();
}
const cleaners: Array<() => void> = [];
function destroy() {
cleaners.forEach((c) => c());
cleaners.splice(0);
cancelAsyncOperations = true;
clear();
if (frameId) {
cancelAnimationFrame(frameId);
frameId = null;
}
}
let rulesChangeKey = 0;
function getRulesChangeKey() {
let count = 0;
iterateSourceSheets((sheet) => {
count += sheet.cssRules.length;
});
if (count === 1) {
// MS Copilot issue, where there is an empty `:root {}` style at the beginning.
// Counting all the rules for all the shadow DOM elements can be expensive.
const rule = node.adoptedStyleSheets[0].cssRules[0];
return rule instanceof CSSStyleRule ? rule.style.length : count;
}
return count;
}
let sourceSheets = new WeakSet<CSSStyleSheet>();
let sourceDeclarations = new WeakSet<CSSStyleDeclaration>();
function render(theme: Theme, ignoreImageAnalysis: string[]) {
clear();
for (let i = node.adoptedStyleSheets.length - 1; i >= 0; i--) {
const sheet = node.adoptedStyleSheets[i];
if (overrides.has(sheet)) {
continue;
}
sourceSheets.add(sheet);
const readyOverride = overridesBySource.get(sheet);
if (readyOverride) {
rulesChangeKey = getRulesChangeKey();
injectSheet(sheet, readyOverride);
continue;
}
const rules = sheet.cssRules;
const override = new CSSStyleSheet();
overridesBySource.set(sheet, override);
iterateCSSRules(rules, (rule) => sourceDeclarations.add(rule.style));
const prepareSheet = () => {
for (let i = override.cssRules.length - 1; i >= 0; i--) {
override.deleteRule(i);
}
override.insertRule('#__darkreader__adoptedOverride {}');
injectSheet(sheet, override);
overrides.add(override);
return override;
};
const sheetModifier = createStyleSheetModifier();
sheetModifier.modifySheet({
prepareSheet,
sourceCSSRules: rules,
theme,
ignoreImageAnalysis,
force: false,
isAsyncCancelled: () => cancelAsyncOperations,
});
}
rulesChangeKey = getRulesChangeKey();
}
let callbackRequested = false;
function handleArrayChange(callback: (sheets: CSSStyleSheet[]) => void) {
if (callbackRequested) {
return;
}
callbackRequested = true;
queueMicrotask(() => {
callbackRequested = false;
const sheets = node.adoptedStyleSheets.filter((s) => !overrides.has(s));
sheets.forEach((sheet) => overridesBySource.delete(sheet));
callback(sheets);
});
}
function checkForUpdates() {
return getRulesChangeKey() !== rulesChangeKey;
}
let frameId: number | null = null;
function watchUsingRAF(callback: (sheets: CSSStyleSheet[]) => void) {
frameId = requestAnimationFrame(() => {
if (canUseSheetProxy) {
return;
}
if (checkForUpdates()) {
handleArrayChange(callback);
}
watchUsingRAF(callback);
});
}
function addSheetChangeEventListener(type: string, listener: (e: CustomEvent) => void) {
node.addEventListener(type, listener);
cleaners.push(() => node.removeEventListener(type, listener));
}
function watch(callback: (sheets: CSSStyleSheet[]) => void) {
const onAdoptedSheetsChange = () => {
canUseSheetProxy = true;
handleArrayChange(callback);
};
addSheetChangeEventListener('__darkreader__adoptedStyleSheetsChange', onAdoptedSheetsChange);
addSheetChangeEventListener('__darkreader__adoptedStyleSheetChange', onAdoptedSheetsChange);
addSheetChangeEventListener('__darkreader__adoptedStyleDeclarationChange', onAdoptedSheetsChange);
if (canUseSheetProxy) {
return;
}
watchUsingRAF(callback);
}
return {
render,
destroy,
watch,
};
}
export interface AdoptedStyleSheetFallback {
render(theme: Theme, ignoreImageAnalysis: string[]): void;
updateCSS(cssRules: CSSRule[]): void;
commands(): DeepStyleSheetCommand[];
destroy(): void;
}
interface StyleSheetInsertCommand {
type: 'insert';
index: number;
cssText: string;
}
interface StyleSheetDeleteCommand {
type: 'delete';
index: number;
}
interface StyleSheetReplaceCommand {
type: 'replace';
cssText: string;
}
type StyleSheetCommand = StyleSheetInsertCommand | StyleSheetDeleteCommand | StyleSheetReplaceCommand;
interface DeepStyleSheetCommand {
type: 'insert' | 'delete' | 'replace';
path: number[];
cssText?: string;
}
class StyleSheetCommandBuilder implements CSSBuilder {
cssRules: StyleSheetCommandBuilder[] = [];
private commands: StyleSheetCommand[] = [];
private onChange: () => void;
constructor(onChange: () => void) {
this.onChange = onChange;
}
insertRule(cssText: string, index = 0): number {
this.commands.push({type: 'insert', index, cssText});
this.cssRules.splice(index, 0, new StyleSheetCommandBuilder(this.onChange));
this.onChange();
return index;
}
deleteRule(index: number): void {
this.commands.push({type: 'delete', index});
this.cssRules.splice(index, 1);
this.onChange();
}
replaceSync(cssText: string) {
this.commands.splice(0);
this.commands.push({type: 'replace', cssText});
if (cssText === '') {
this.cssRules.splice(0);
} else {
throw new Error('StyleSheetCommandBuilder.replaceSync() is not fully supported');
}
this.onChange();
}
getDeepCSSCommands() {
const deep: DeepStyleSheetCommand[] = [];
this.commands.forEach((command) => {
deep.push({
type: command.type,
cssText: command.type !== 'delete' ? command.cssText : '',
path: command.type === 'replace' ? [] : [command.index],
});
});
this.cssRules.forEach((rule, i) => {
const childCommands = rule.getDeepCSSCommands();
childCommands.forEach((c) => c.path.unshift(i));
});
return deep;
}
clearDeepCSSCommands() {
this.commands.splice(0);
this.cssRules.forEach((rule) => rule.clearDeepCSSCommands());
}
}
export function createAdoptedStyleSheetFallback(onChange: () => void): AdoptedStyleSheetFallback {
let cancelAsyncOperations = false;
let sourceCSSRules: CSSRule[] = [];
let lastTheme: Theme;
let lastIgnoreImageAnalysis: string[];
function updateCSS(cssRules: CSSRule[]) {
sourceCSSRules = cssRules;
if (lastTheme && lastIgnoreImageAnalysis) {
render(lastTheme, lastIgnoreImageAnalysis);
}
}
const builder = new StyleSheetCommandBuilder(onChange);
function render(theme: Theme, ignoreImageAnalysis: string[]) {
lastTheme = theme;
lastIgnoreImageAnalysis = ignoreImageAnalysis;
const prepareSheet = () => {
builder.replaceSync('');
return builder;
};
const sheetModifier = createStyleSheetModifier();
sheetModifier.modifySheet({
prepareSheet,
sourceCSSRules,
theme,
ignoreImageAnalysis,
force: false,
isAsyncCancelled: () => cancelAsyncOperations,
});
}
function commands() {
const commands = builder.getDeepCSSCommands();
builder.clearDeepCSSCommands();
return commands;
}
function destroy() {
cancelAsyncOperations = true;
}
return {render, destroy, updateCSS, commands};
}