1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | (function (global, factory) {
|
7 | typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
|
8 | typeof define === 'function' && define.amd ? define(['exports'], factory) :
|
9 | (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.DarkReader = {}));
|
10 | }(this, (function (exports) { 'use strict';
|
11 |
|
12 | |
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 | var __assign = function() {
|
28 | __assign = Object.assign || function __assign(t) {
|
29 | for (var s, i = 1, n = arguments.length; i < n; i++) {
|
30 | s = arguments[i];
|
31 | for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
|
32 | }
|
33 | return t;
|
34 | };
|
35 | return __assign.apply(this, arguments);
|
36 | };
|
37 |
|
38 | function __awaiter(thisArg, _arguments, P, generator) {
|
39 | function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
40 | return new (P || (P = Promise))(function (resolve, reject) {
|
41 | function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
42 | function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
43 | function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
44 | step((generator = generator.apply(thisArg, _arguments || [])).next());
|
45 | });
|
46 | }
|
47 |
|
48 | function __generator(thisArg, body) {
|
49 | var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
|
50 | return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
|
51 | function verb(n) { return function (v) { return step([n, v]); }; }
|
52 | function step(op) {
|
53 | if (f) throw new TypeError("Generator is already executing.");
|
54 | while (_) try {
|
55 | if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
|
56 | if (y = 0, t) op = [op[0] & 2, t.value];
|
57 | switch (op[0]) {
|
58 | case 0: case 1: t = op; break;
|
59 | case 4: _.label++; return { value: op[1], done: false };
|
60 | case 5: _.label++; y = op[1]; op = [0]; continue;
|
61 | case 7: op = _.ops.pop(); _.trys.pop(); continue;
|
62 | default:
|
63 | if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
|
64 | if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
|
65 | if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
|
66 | if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
|
67 | if (t[2]) _.ops.pop();
|
68 | _.trys.pop(); continue;
|
69 | }
|
70 | op = body.call(thisArg, _);
|
71 | } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
|
72 | if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
|
73 | }
|
74 | }
|
75 |
|
76 | function __values(o) {
|
77 | var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
|
78 | if (m) return m.call(o);
|
79 | if (o && typeof o.length === "number") return {
|
80 | next: function () {
|
81 | if (o && i >= o.length) o = void 0;
|
82 | return { value: o && o[i++], done: !o };
|
83 | }
|
84 | };
|
85 | throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
|
86 | }
|
87 |
|
88 | function __read(o, n) {
|
89 | var m = typeof Symbol === "function" && o[Symbol.iterator];
|
90 | if (!m) return o;
|
91 | var i = m.call(o), r, ar = [], e;
|
92 | try {
|
93 | while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
|
94 | }
|
95 | catch (error) { e = { error: error }; }
|
96 | finally {
|
97 | try {
|
98 | if (r && !r.done && (m = i["return"])) m.call(i);
|
99 | }
|
100 | finally { if (e) throw e.error; }
|
101 | }
|
102 | return ar;
|
103 | }
|
104 |
|
105 | function __spread() {
|
106 | for (var ar = [], i = 0; i < arguments.length; i++)
|
107 | ar = ar.concat(__read(arguments[i]));
|
108 | return ar;
|
109 | }
|
110 |
|
111 | var userAgent = typeof navigator === 'undefined' ? 'some useragent' : navigator.userAgent.toLowerCase();
|
112 | var platform = typeof navigator === 'undefined' ? 'some platform' : navigator.platform.toLowerCase();
|
113 | var isChromium = userAgent.includes('chrome') || userAgent.includes('chromium');
|
114 | var isThunderbird = userAgent.includes('thunderbird');
|
115 | var isFirefox = userAgent.includes('firefox') || isThunderbird;
|
116 | var isVivaldi = userAgent.includes('vivaldi');
|
117 | var isYaBrowser = userAgent.includes('yabrowser');
|
118 | var isOpera = userAgent.includes('opr') || userAgent.includes('opera');
|
119 | var isEdge = userAgent.includes('edg');
|
120 | var isSafari = userAgent.includes('safari') && !isChromium;
|
121 | var isWindows = platform.startsWith('win');
|
122 | var isMacOS = platform.startsWith('mac');
|
123 | var isMobile = userAgent.includes('mobile');
|
124 | var isShadowDomSupported = typeof ShadowRoot === 'function';
|
125 | var isMatchMediaChangeEventListenerSupported = (typeof MediaQueryList === 'function' &&
|
126 | typeof MediaQueryList.prototype.addEventListener === 'function');
|
127 | var chromiumVersion = (function () {
|
128 | var m = userAgent.match(/chrom[e|ium]\/([^ ]+)/);
|
129 | if (m && m[1]) {
|
130 | return m[1];
|
131 | }
|
132 | else {
|
133 | return '';
|
134 | }
|
135 | })();
|
136 | var isDefinedSelectorSupported = (function () {
|
137 | try {
|
138 | document.querySelector(':defined');
|
139 | return true;
|
140 | }
|
141 | catch (err) {
|
142 | return false;
|
143 | }
|
144 | })();
|
145 | var isCSSStyleSheetConstructorSupported = (function () {
|
146 | try {
|
147 | new CSSStyleSheet();
|
148 | return true;
|
149 | }
|
150 | catch (err) {
|
151 | return false;
|
152 | }
|
153 | })();
|
154 |
|
155 | function getOKResponse(url, mimeType) {
|
156 | return __awaiter(this, void 0, void 0, function () {
|
157 | var response;
|
158 | return __generator(this, function (_a) {
|
159 | switch (_a.label) {
|
160 | case 0: return [4, fetch(url, {
|
161 | cache: 'force-cache',
|
162 | credentials: 'omit',
|
163 | })];
|
164 | case 1:
|
165 | response = _a.sent();
|
166 | if (isFirefox && mimeType === 'text/css' && url.startsWith('moz-extension://') && url.endsWith('.css')) {
|
167 | return [2, response];
|
168 | }
|
169 | if (mimeType && !response.headers.get('Content-Type').startsWith(mimeType)) {
|
170 | throw new Error("Mime type mismatch when loading " + url);
|
171 | }
|
172 | if (!response.ok) {
|
173 | throw new Error("Unable to load " + url + " " + response.status + " " + response.statusText);
|
174 | }
|
175 | return [2, response];
|
176 | }
|
177 | });
|
178 | });
|
179 | }
|
180 | function loadAsDataURL(url, mimeType) {
|
181 | return __awaiter(this, void 0, void 0, function () {
|
182 | var response;
|
183 | return __generator(this, function (_a) {
|
184 | switch (_a.label) {
|
185 | case 0: return [4, getOKResponse(url, mimeType)];
|
186 | case 1:
|
187 | response = _a.sent();
|
188 | return [4, readResponseAsDataURL(response)];
|
189 | case 2: return [2, _a.sent()];
|
190 | }
|
191 | });
|
192 | });
|
193 | }
|
194 | function readResponseAsDataURL(response) {
|
195 | return __awaiter(this, void 0, void 0, function () {
|
196 | var blob, dataURL;
|
197 | return __generator(this, function (_a) {
|
198 | switch (_a.label) {
|
199 | case 0: return [4, response.blob()];
|
200 | case 1:
|
201 | blob = _a.sent();
|
202 | return [4, (new Promise(function (resolve) {
|
203 | var reader = new FileReader();
|
204 | reader.onloadend = function () { return resolve(reader.result); };
|
205 | reader.readAsDataURL(blob);
|
206 | }))];
|
207 | case 2:
|
208 | dataURL = _a.sent();
|
209 | return [2, dataURL];
|
210 | }
|
211 | });
|
212 | });
|
213 | }
|
214 |
|
215 | var throwCORSError = function (url) { return __awaiter(void 0, void 0, void 0, function () {
|
216 | return __generator(this, function (_a) {
|
217 | return [2, Promise.reject(new Error([
|
218 | 'Embedded Dark Reader cannot access a cross-origin resource',
|
219 | url,
|
220 | 'Overview your URLs and CORS policies or use',
|
221 | '`DarkReader.setFetchMethod(fetch: (url) => Promise<Response>))`.',
|
222 | 'See if using `DarkReader.setFetchMethod(window.fetch)`',
|
223 | 'before `DarkReader.enable()` works.'
|
224 | ].join(' ')))];
|
225 | });
|
226 | }); };
|
227 | var fetcher = throwCORSError;
|
228 | function setFetchMethod(fetch) {
|
229 | if (fetch) {
|
230 | fetcher = fetch;
|
231 | }
|
232 | else {
|
233 | fetcher = throwCORSError;
|
234 | }
|
235 | }
|
236 | function callFetchMethod(url) {
|
237 | return __awaiter(this, void 0, void 0, function () {
|
238 | return __generator(this, function (_a) {
|
239 | switch (_a.label) {
|
240 | case 0: return [4, fetcher(url)];
|
241 | case 1: return [2, _a.sent()];
|
242 | }
|
243 | });
|
244 | });
|
245 | }
|
246 |
|
247 | if (!window.chrome) {
|
248 | window.chrome = {};
|
249 | }
|
250 | if (!chrome.runtime) {
|
251 | chrome.runtime = {};
|
252 | }
|
253 | var messageListeners = new Set();
|
254 | function sendMessage() {
|
255 | var args = [];
|
256 | for (var _i = 0; _i < arguments.length; _i++) {
|
257 | args[_i] = arguments[_i];
|
258 | }
|
259 | return __awaiter(this, void 0, void 0, function () {
|
260 | var id_1, _a, url, responseType, response, text_1, err_1;
|
261 | return __generator(this, function (_b) {
|
262 | switch (_b.label) {
|
263 | case 0:
|
264 | if (!(args[0] && args[0].type === 'fetch')) return [3, 8];
|
265 | id_1 = args[0].id;
|
266 | _b.label = 1;
|
267 | case 1:
|
268 | _b.trys.push([1, 7, , 8]);
|
269 | _a = args[0].data, url = _a.url, responseType = _a.responseType;
|
270 | return [4, callFetchMethod(url)];
|
271 | case 2:
|
272 | response = _b.sent();
|
273 | if (!(responseType === 'data-url')) return [3, 4];
|
274 | return [4, readResponseAsDataURL(response)];
|
275 | case 3:
|
276 | text_1 = _b.sent();
|
277 | return [3, 6];
|
278 | case 4: return [4, response.text()];
|
279 | case 5:
|
280 | text_1 = _b.sent();
|
281 | _b.label = 6;
|
282 | case 6:
|
283 | messageListeners.forEach(function (cb) { return cb({ type: 'fetch-response', data: text_1, error: null, id: id_1 }); });
|
284 | return [3, 8];
|
285 | case 7:
|
286 | err_1 = _b.sent();
|
287 | console.error(err_1);
|
288 | messageListeners.forEach(function (cb) { return cb({ type: 'fetch-response', data: null, err: err_1, id: id_1 }); });
|
289 | return [3, 8];
|
290 | case 8: return [2];
|
291 | }
|
292 | });
|
293 | });
|
294 | }
|
295 | function addMessageListener(callback) {
|
296 | messageListeners.add(callback);
|
297 | }
|
298 | if (typeof chrome.runtime.sendMessage === 'function') {
|
299 | var nativeSendMessage_1 = chrome.runtime.sendMessage;
|
300 | chrome.runtime.sendMessage = function () {
|
301 | var args = [];
|
302 | for (var _i = 0; _i < arguments.length; _i++) {
|
303 | args[_i] = arguments[_i];
|
304 | }
|
305 | sendMessage.apply(void 0, __spread(args));
|
306 | nativeSendMessage_1.apply(chrome.runtime, args);
|
307 | };
|
308 | }
|
309 | else {
|
310 | chrome.runtime.sendMessage = sendMessage;
|
311 | }
|
312 | if (!chrome.runtime.onMessage) {
|
313 | chrome.runtime.onMessage = {};
|
314 | }
|
315 | if (typeof chrome.runtime.onMessage.addListener === 'function') {
|
316 | var nativeAddListener_1 = chrome.runtime.onMessage.addListener;
|
317 | chrome.runtime.onMessage.addListener = function () {
|
318 | var args = [];
|
319 | for (var _i = 0; _i < arguments.length; _i++) {
|
320 | args[_i] = arguments[_i];
|
321 | }
|
322 | addMessageListener.apply(void 0, __spread(args));
|
323 | nativeAddListener_1.apply(chrome.runtime.onMessage, args);
|
324 | };
|
325 | }
|
326 | else {
|
327 | chrome.runtime.onMessage.addListener = addMessageListener;
|
328 | }
|
329 |
|
330 | var ThemeEngines = {
|
331 | cssFilter: 'cssFilter',
|
332 | svgFilter: 'svgFilter',
|
333 | staticTheme: 'staticTheme',
|
334 | dynamicTheme: 'dynamicTheme',
|
335 | };
|
336 |
|
337 | var DEFAULT_COLORS = {
|
338 | darkScheme: {
|
339 | background: '#181a1b',
|
340 | text: '#e8e6e3',
|
341 | },
|
342 | lightScheme: {
|
343 | background: '#dcdad7',
|
344 | text: '#181a1b',
|
345 | },
|
346 | };
|
347 | var DEFAULT_THEME = {
|
348 | mode: 1,
|
349 | brightness: 100,
|
350 | contrast: 100,
|
351 | grayscale: 0,
|
352 | sepia: 0,
|
353 | useFont: false,
|
354 | fontFamily: isMacOS ? 'Helvetica Neue' : isWindows ? 'Segoe UI' : 'Open Sans',
|
355 | textStroke: 0,
|
356 | engine: ThemeEngines.dynamicTheme,
|
357 | stylesheet: '',
|
358 | darkSchemeBackgroundColor: DEFAULT_COLORS.darkScheme.background,
|
359 | darkSchemeTextColor: DEFAULT_COLORS.darkScheme.text,
|
360 | lightSchemeBackgroundColor: DEFAULT_COLORS.lightScheme.background,
|
361 | lightSchemeTextColor: DEFAULT_COLORS.lightScheme.text,
|
362 | scrollbarColor: isMacOS ? '' : 'auto',
|
363 | selectionColor: 'auto',
|
364 | styleSystemControls: true,
|
365 | };
|
366 |
|
367 | function isArrayLike(items) {
|
368 | return items.length != null;
|
369 | }
|
370 | function forEach(items, iterator) {
|
371 | var e_1, _a;
|
372 | if (isArrayLike(items)) {
|
373 | for (var i = 0, len = items.length; i < len; i++) {
|
374 | iterator(items[i]);
|
375 | }
|
376 | }
|
377 | else {
|
378 | try {
|
379 | for (var items_1 = __values(items), items_1_1 = items_1.next(); !items_1_1.done; items_1_1 = items_1.next()) {
|
380 | var item = items_1_1.value;
|
381 | iterator(item);
|
382 | }
|
383 | }
|
384 | catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
385 | finally {
|
386 | try {
|
387 | if (items_1_1 && !items_1_1.done && (_a = items_1.return)) _a.call(items_1);
|
388 | }
|
389 | finally { if (e_1) throw e_1.error; }
|
390 | }
|
391 | }
|
392 | }
|
393 | function push(array, addition) {
|
394 | forEach(addition, function (a) { return array.push(a); });
|
395 | }
|
396 | function toArray(items) {
|
397 | var results = [];
|
398 | for (var i = 0, len = items.length; i < len; i++) {
|
399 | results.push(items[i]);
|
400 | }
|
401 | return results;
|
402 | }
|
403 |
|
404 | var anchor;
|
405 | var parsedURLCache = new Map();
|
406 | function fixBaseURL($url) {
|
407 | if (!anchor) {
|
408 | anchor = document.createElement('a');
|
409 | }
|
410 | anchor.href = $url;
|
411 | return anchor.href;
|
412 | }
|
413 | function parseURL($url, $base) {
|
414 | if ($base === void 0) { $base = null; }
|
415 | var key = "" + $url + ($base ? ';' + $base : '');
|
416 | if (parsedURLCache.has(key)) {
|
417 | return parsedURLCache.get(key);
|
418 | }
|
419 | if ($base) {
|
420 | var parsedURL_1 = new URL($url, fixBaseURL($base));
|
421 | parsedURLCache.set(key, parsedURL_1);
|
422 | return parsedURL_1;
|
423 | }
|
424 | var parsedURL = new URL(fixBaseURL($url));
|
425 | parsedURLCache.set($url, parsedURL);
|
426 | return parsedURL;
|
427 | }
|
428 | function getAbsoluteURL($base, $relative) {
|
429 | if ($relative.match(/^data\:/)) {
|
430 | return $relative;
|
431 | }
|
432 | var b = parseURL($base);
|
433 | var a = parseURL($relative, b.href);
|
434 | return a.href;
|
435 | }
|
436 | function getURLHostOrProtocol($url) {
|
437 | var url = new URL($url);
|
438 | if (url.host) {
|
439 | return url.host;
|
440 | }
|
441 | else {
|
442 | return url.protocol;
|
443 | }
|
444 | }
|
445 |
|
446 | function logInfo() {
|
447 | var args = [];
|
448 | for (var _i = 0; _i < arguments.length; _i++) {
|
449 | args[_i] = arguments[_i];
|
450 | }
|
451 | }
|
452 | function logWarn() {
|
453 | var args = [];
|
454 | for (var _i = 0; _i < arguments.length; _i++) {
|
455 | args[_i] = arguments[_i];
|
456 | }
|
457 | }
|
458 |
|
459 | function iterateCSSRules(rules, iterate) {
|
460 | forEach(rules, function (rule) {
|
461 | if (rule instanceof CSSMediaRule) {
|
462 | var media = Array.from(rule.media);
|
463 | if (media.includes('screen') || media.includes('all') || !(media.includes('print') || media.includes('speech'))) {
|
464 | iterateCSSRules(rule.cssRules, iterate);
|
465 | }
|
466 | }
|
467 | else if (rule instanceof CSSStyleRule) {
|
468 | iterate(rule);
|
469 | }
|
470 | else if (rule instanceof CSSImportRule) {
|
471 | try {
|
472 | iterateCSSRules(rule.styleSheet.cssRules, iterate);
|
473 | }
|
474 | catch (err) {
|
475 | logWarn(err);
|
476 | }
|
477 | }
|
478 | else if (rule instanceof CSSSupportsRule) {
|
479 | if (CSS.supports(rule.conditionText)) {
|
480 | iterateCSSRules(rule.cssRules, iterate);
|
481 | }
|
482 | }
|
483 | else {
|
484 | logWarn("CSSRule type not supported", rule);
|
485 | }
|
486 | });
|
487 | }
|
488 | function iterateCSSDeclarations(style, iterate) {
|
489 | forEach(style, function (property) {
|
490 | var value = style.getPropertyValue(property).trim();
|
491 | if (!value) {
|
492 | return;
|
493 | }
|
494 | iterate(property, value);
|
495 | });
|
496 | }
|
497 | function isCSSVariable(property) {
|
498 | return property.startsWith('--') && !property.startsWith('--darkreader');
|
499 | }
|
500 | function getCSSVariables(rules) {
|
501 | var variables = new Map();
|
502 | rules && iterateCSSRules(rules, function (rule) {
|
503 | rule.style && iterateCSSDeclarations(rule.style, function (property, value) {
|
504 | if (isCSSVariable(property)) {
|
505 | variables.set(property, value);
|
506 | }
|
507 | });
|
508 | });
|
509 | return variables;
|
510 | }
|
511 | function getElementCSSVariables(element) {
|
512 | var variables = new Map();
|
513 | iterateCSSDeclarations(element.style, function (property, value) {
|
514 | if (isCSSVariable(property)) {
|
515 | variables.set(property, value);
|
516 | }
|
517 | });
|
518 | return variables;
|
519 | }
|
520 | var cssURLRegex = /url\((('.+?')|(".+?")|([^\)]*?))\)/g;
|
521 | var cssImportRegex = /@import\s*(url\()?(('.+?')|(".+?")|([^\)]*?))\)?;?/g;
|
522 | function getCSSURLValue(cssURL) {
|
523 | return cssURL.replace(/^url\((.*)\)$/, '$1').replace(/^"(.*)"$/, '$1').replace(/^'(.*)'$/, '$1');
|
524 | }
|
525 | function getCSSBaseBath(url) {
|
526 | var cssURL = parseURL(url);
|
527 | return "" + cssURL.origin + cssURL.pathname.replace(/\?.*$/, '').replace(/(\/)([^\/]+)$/i, '$1');
|
528 | }
|
529 | function replaceCSSRelativeURLsWithAbsolute($css, cssBasePath) {
|
530 | return $css.replace(cssURLRegex, function (match) {
|
531 | var pathValue = getCSSURLValue(match);
|
532 | return "url(\"" + getAbsoluteURL(cssBasePath, pathValue) + "\")";
|
533 | });
|
534 | }
|
535 | var cssCommentsRegex = /\/\*[\s\S]*?\*\//g;
|
536 | function removeCSSComments($css) {
|
537 | return $css.replace(cssCommentsRegex, '');
|
538 | }
|
539 | var fontFaceRegex = /@font-face\s*{[^}]*}/g;
|
540 | function replaceCSSFontFace($css) {
|
541 | return $css.replace(fontFaceRegex, '');
|
542 | }
|
543 | var varRegex = /var\((--[^\s,\(\)]+),?\s*([^\(\)]*(\([^\(\)]*\)[^\(\)]*)*\s*)\)/g;
|
544 | function replaceCSSVariables(value, variables, stack) {
|
545 | if (stack === void 0) { stack = new Set(); }
|
546 | var missing = false;
|
547 | var unresolvable = new Set();
|
548 | var result = value.replace(varRegex, function (match, name, fallback) {
|
549 | if (stack.has(name)) {
|
550 | logWarn("Circular reference to variable " + name);
|
551 | if (fallback) {
|
552 | return fallback;
|
553 | }
|
554 | missing = true;
|
555 | return match;
|
556 | }
|
557 | if (variables.has(name)) {
|
558 | var value_1 = variables.get(name);
|
559 | if (value_1.match(varRegex)) {
|
560 | unresolvable.add(name);
|
561 | }
|
562 | return value_1;
|
563 | }
|
564 | else if (fallback) {
|
565 | return fallback;
|
566 | }
|
567 | else {
|
568 | logWarn("Variable " + name + " not found");
|
569 | missing = true;
|
570 | }
|
571 | return match;
|
572 | });
|
573 | if (missing) {
|
574 | return result;
|
575 | }
|
576 | if (result.match(varRegex)) {
|
577 | unresolvable.forEach(function (v) { return stack.add(v); });
|
578 | return replaceCSSVariables(result, variables, stack);
|
579 | }
|
580 | return result;
|
581 | }
|
582 |
|
583 | function throttle(callback) {
|
584 | var pending = false;
|
585 | var frameId = null;
|
586 | var lastArgs;
|
587 | var throttled = (function () {
|
588 | var args = [];
|
589 | for (var _i = 0; _i < arguments.length; _i++) {
|
590 | args[_i] = arguments[_i];
|
591 | }
|
592 | lastArgs = args;
|
593 | if (frameId) {
|
594 | pending = true;
|
595 | }
|
596 | else {
|
597 | callback.apply(void 0, __spread(lastArgs));
|
598 | frameId = requestAnimationFrame(function () {
|
599 | frameId = null;
|
600 | if (pending) {
|
601 | callback.apply(void 0, __spread(lastArgs));
|
602 | pending = false;
|
603 | }
|
604 | });
|
605 | }
|
606 | });
|
607 | var cancel = function () {
|
608 | cancelAnimationFrame(frameId);
|
609 | pending = false;
|
610 | frameId = null;
|
611 | };
|
612 | return Object.assign(throttled, { cancel: cancel });
|
613 | }
|
614 | function createAsyncTasksQueue() {
|
615 | var tasks = [];
|
616 | var frameId = null;
|
617 | function runTasks() {
|
618 | var task;
|
619 | while ((task = tasks.shift())) {
|
620 | task();
|
621 | }
|
622 | frameId = null;
|
623 | }
|
624 | function add(task) {
|
625 | tasks.push(task);
|
626 | if (!frameId) {
|
627 | frameId = requestAnimationFrame(runTasks);
|
628 | }
|
629 | }
|
630 | function cancel() {
|
631 | tasks.splice(0);
|
632 | cancelAnimationFrame(frameId);
|
633 | frameId = null;
|
634 | }
|
635 | return { add: add, cancel: cancel };
|
636 | }
|
637 |
|
638 | function getDuration(time) {
|
639 | var duration = 0;
|
640 | if (time.seconds) {
|
641 | duration += time.seconds * 1000;
|
642 | }
|
643 | if (time.minutes) {
|
644 | duration += time.minutes * 60 * 1000;
|
645 | }
|
646 | if (time.hours) {
|
647 | duration += time.hours * 60 * 60 * 1000;
|
648 | }
|
649 | if (time.days) {
|
650 | duration += time.days * 24 * 60 * 60 * 1000;
|
651 | }
|
652 | return duration;
|
653 | }
|
654 |
|
655 | function removeNode(node) {
|
656 | node && node.parentNode && node.parentNode.removeChild(node);
|
657 | }
|
658 | function watchForNodePosition(node, mode, onRestore) {
|
659 | if (onRestore === void 0) { onRestore = Function.prototype; }
|
660 | var MAX_ATTEMPTS_COUNT = 10;
|
661 | var RETRY_TIMEOUT = getDuration({ seconds: 2 });
|
662 | var ATTEMPTS_INTERVAL = getDuration({ seconds: 10 });
|
663 | var prevSibling = node.previousSibling;
|
664 | var parent = node.parentNode;
|
665 | if (!parent) {
|
666 | throw new Error('Unable to watch for node position: parent element not found');
|
667 | }
|
668 | if (mode === 'prev-sibling' && !prevSibling) {
|
669 | throw new Error('Unable to watch for node position: there is no previous sibling');
|
670 | }
|
671 | var attempts = 0;
|
672 | var start = null;
|
673 | var timeoutId = null;
|
674 | var restore = throttle(function () {
|
675 | if (timeoutId) {
|
676 | return;
|
677 | }
|
678 | attempts++;
|
679 | var now = Date.now();
|
680 | if (start == null) {
|
681 | start = now;
|
682 | }
|
683 | else if (attempts >= MAX_ATTEMPTS_COUNT) {
|
684 | if (now - start < ATTEMPTS_INTERVAL) {
|
685 | logWarn("Node position watcher paused: retry in " + RETRY_TIMEOUT + "ms", node, prevSibling);
|
686 | timeoutId = setTimeout(function () {
|
687 | start = null;
|
688 | attempts = 0;
|
689 | timeoutId = null;
|
690 | restore();
|
691 | }, RETRY_TIMEOUT);
|
692 | return;
|
693 | }
|
694 | start = now;
|
695 | attempts = 1;
|
696 | }
|
697 | if (mode === 'parent') {
|
698 | if (prevSibling && prevSibling.parentNode !== parent) {
|
699 | logWarn('Unable to restore node position: sibling parent changed', node, prevSibling, parent);
|
700 | stop();
|
701 | return;
|
702 | }
|
703 | }
|
704 | if (mode === 'prev-sibling') {
|
705 | if (prevSibling.parentNode == null) {
|
706 | logWarn('Unable to restore node position: sibling was removed', node, prevSibling, parent);
|
707 | stop();
|
708 | return;
|
709 | }
|
710 | if (prevSibling.parentNode !== parent) {
|
711 | logWarn('Style was moved to another parent', node, prevSibling, parent);
|
712 | updateParent(prevSibling.parentNode);
|
713 | }
|
714 | }
|
715 | logWarn('Restoring node position', node, prevSibling, parent);
|
716 | parent.insertBefore(node, prevSibling ? prevSibling.nextSibling : parent.firstChild);
|
717 | observer.takeRecords();
|
718 | onRestore && onRestore();
|
719 | });
|
720 | var observer = new MutationObserver(function () {
|
721 | if ((mode === 'parent' && node.parentNode !== parent) ||
|
722 | (mode === 'prev-sibling' && node.previousSibling !== prevSibling)) {
|
723 | restore();
|
724 | }
|
725 | });
|
726 | var run = function () {
|
727 | observer.observe(parent, { childList: true });
|
728 | };
|
729 | var stop = function () {
|
730 | clearTimeout(timeoutId);
|
731 | observer.disconnect();
|
732 | restore.cancel();
|
733 | };
|
734 | var skip = function () {
|
735 | observer.takeRecords();
|
736 | };
|
737 | var updateParent = function (parentNode) {
|
738 | parent = parentNode;
|
739 | stop();
|
740 | run();
|
741 | };
|
742 | run();
|
743 | return { run: run, stop: stop, skip: skip };
|
744 | }
|
745 | function iterateShadowHosts(root, iterator) {
|
746 | if (root == null) {
|
747 | return;
|
748 | }
|
749 | var walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT, {
|
750 | acceptNode: function (node) {
|
751 | return node.shadowRoot == null ? NodeFilter.FILTER_SKIP : NodeFilter.FILTER_ACCEPT;
|
752 | }
|
753 | });
|
754 | for (var node = (root.shadowRoot ? walker.currentNode : walker.nextNode()); node != null; node = walker.nextNode()) {
|
755 | iterator(node);
|
756 | iterateShadowHosts(node.shadowRoot, iterator);
|
757 | }
|
758 | }
|
759 | function isDOMReady() {
|
760 | return document.readyState === 'complete' || document.readyState === 'interactive';
|
761 | }
|
762 | var readyStateListeners = new Set();
|
763 | function addDOMReadyListener(listener) {
|
764 | readyStateListeners.add(listener);
|
765 | }
|
766 | function removeDOMReadyListener(listener) {
|
767 | readyStateListeners.delete(listener);
|
768 | }
|
769 | if (!isDOMReady()) {
|
770 | var onReadyStateChange_1 = function () {
|
771 | if (isDOMReady()) {
|
772 | document.removeEventListener('readystatechange', onReadyStateChange_1);
|
773 | readyStateListeners.forEach(function (listener) { return listener(); });
|
774 | readyStateListeners.clear();
|
775 | }
|
776 | };
|
777 | document.addEventListener('readystatechange', onReadyStateChange_1);
|
778 | }
|
779 | var HUGE_MUTATIONS_COUNT = 1000;
|
780 | function isHugeMutation(mutations) {
|
781 | if (mutations.length > HUGE_MUTATIONS_COUNT) {
|
782 | return true;
|
783 | }
|
784 | var addedNodesCount = 0;
|
785 | for (var i = 0; i < mutations.length; i++) {
|
786 | addedNodesCount += mutations[i].addedNodes.length;
|
787 | if (addedNodesCount > HUGE_MUTATIONS_COUNT) {
|
788 | return true;
|
789 | }
|
790 | }
|
791 | return false;
|
792 | }
|
793 | function getElementsTreeOperations(mutations) {
|
794 | var additions = new Set();
|
795 | var deletions = new Set();
|
796 | var moves = new Set();
|
797 | mutations.forEach(function (m) {
|
798 | forEach(m.addedNodes, function (n) {
|
799 | if (n instanceof Element && n.isConnected) {
|
800 | additions.add(n);
|
801 | }
|
802 | });
|
803 | forEach(m.removedNodes, function (n) {
|
804 | if (n instanceof Element) {
|
805 | if (n.isConnected) {
|
806 | moves.add(n);
|
807 | }
|
808 | else {
|
809 | deletions.add(n);
|
810 | }
|
811 | }
|
812 | });
|
813 | });
|
814 | moves.forEach(function (n) { return additions.delete(n); });
|
815 | var duplicateAdditions = [];
|
816 | var duplicateDeletions = [];
|
817 | additions.forEach(function (node) {
|
818 | if (additions.has(node.parentElement)) {
|
819 | duplicateAdditions.push(node);
|
820 | }
|
821 | });
|
822 | deletions.forEach(function (node) {
|
823 | if (deletions.has(node.parentElement)) {
|
824 | duplicateDeletions.push(node);
|
825 | }
|
826 | });
|
827 | duplicateAdditions.forEach(function (node) { return additions.delete(node); });
|
828 | duplicateDeletions.forEach(function (node) { return deletions.delete(node); });
|
829 | return { additions: additions, moves: moves, deletions: deletions };
|
830 | }
|
831 | var optimizedTreeObservers = new Map();
|
832 | var optimizedTreeCallbacks = new WeakMap();
|
833 | function createOptimizedTreeObserver(root, callbacks) {
|
834 | var observer;
|
835 | var observerCallbacks;
|
836 | var domReadyListener;
|
837 | if (optimizedTreeObservers.has(root)) {
|
838 | observer = optimizedTreeObservers.get(root);
|
839 | observerCallbacks = optimizedTreeCallbacks.get(observer);
|
840 | }
|
841 | else {
|
842 | var hadHugeMutationsBefore_1 = false;
|
843 | var subscribedForReadyState_1 = false;
|
844 | observer = new MutationObserver(function (mutations) {
|
845 | if (isHugeMutation(mutations)) {
|
846 | if (!hadHugeMutationsBefore_1 || isDOMReady()) {
|
847 | observerCallbacks.forEach(function (_a) {
|
848 | var onHugeMutations = _a.onHugeMutations;
|
849 | return onHugeMutations(root);
|
850 | });
|
851 | }
|
852 | else {
|
853 | if (!subscribedForReadyState_1) {
|
854 | domReadyListener = function () { return observerCallbacks.forEach(function (_a) {
|
855 | var onHugeMutations = _a.onHugeMutations;
|
856 | return onHugeMutations(root);
|
857 | }); };
|
858 | addDOMReadyListener(domReadyListener);
|
859 | subscribedForReadyState_1 = true;
|
860 | }
|
861 | }
|
862 | hadHugeMutationsBefore_1 = true;
|
863 | }
|
864 | else {
|
865 | var elementsOperations_1 = getElementsTreeOperations(mutations);
|
866 | observerCallbacks.forEach(function (_a) {
|
867 | var onMinorMutations = _a.onMinorMutations;
|
868 | return onMinorMutations(elementsOperations_1);
|
869 | });
|
870 | }
|
871 | });
|
872 | observer.observe(root, { childList: true, subtree: true });
|
873 | optimizedTreeObservers.set(root, observer);
|
874 | observerCallbacks = new Set();
|
875 | optimizedTreeCallbacks.set(observer, observerCallbacks);
|
876 | }
|
877 | observerCallbacks.add(callbacks);
|
878 | return {
|
879 | disconnect: function () {
|
880 | observerCallbacks.delete(callbacks);
|
881 | if (domReadyListener) {
|
882 | removeDOMReadyListener(domReadyListener);
|
883 | }
|
884 | if (observerCallbacks.size === 0) {
|
885 | observer.disconnect();
|
886 | optimizedTreeCallbacks.delete(observer);
|
887 | optimizedTreeObservers.delete(root);
|
888 | }
|
889 | },
|
890 | };
|
891 | }
|
892 | var tempStyle = null;
|
893 | function getTempCSSStyleSheet() {
|
894 | if (tempStyle) {
|
895 | return tempStyle;
|
896 | }
|
897 | if (isCSSStyleSheetConstructorSupported) {
|
898 | tempStyle = new CSSStyleSheet();
|
899 | return tempStyle;
|
900 | }
|
901 | else {
|
902 | var tempStyleElement = document.createElement('style');
|
903 | document.head.append(tempStyleElement);
|
904 | tempStyle = tempStyleElement.sheet;
|
905 | document.head.removeChild(tempStyleElement);
|
906 | return tempStyle;
|
907 | }
|
908 | }
|
909 |
|
910 | function hslToRGB(_a) {
|
911 | var h = _a.h, s = _a.s, l = _a.l, _b = _a.a, a = _b === void 0 ? 1 : _b;
|
912 | if (s === 0) {
|
913 | var _c = __read([l, l, l].map(function (x) { return Math.round(x * 255); }), 3), r_1 = _c[0], b_1 = _c[1], g_1 = _c[2];
|
914 | return { r: r_1, g: g_1, b: b_1, a: a };
|
915 | }
|
916 | var c = (1 - Math.abs(2 * l - 1)) * s;
|
917 | var x = c * (1 - Math.abs((h / 60) % 2 - 1));
|
918 | var m = l - c / 2;
|
919 | var _d = __read((h < 60 ? [c, x, 0] :
|
920 | h < 120 ? [x, c, 0] :
|
921 | h < 180 ? [0, c, x] :
|
922 | h < 240 ? [0, x, c] :
|
923 | h < 300 ? [x, 0, c] :
|
924 | [c, 0, x]).map(function (n) { return Math.round((n + m) * 255); }), 3), r = _d[0], g = _d[1], b = _d[2];
|
925 | return { r: r, g: g, b: b, a: a };
|
926 | }
|
927 | function rgbToHSL(_a) {
|
928 | var r255 = _a.r, g255 = _a.g, b255 = _a.b, _b = _a.a, a = _b === void 0 ? 1 : _b;
|
929 | var r = r255 / 255;
|
930 | var g = g255 / 255;
|
931 | var b = b255 / 255;
|
932 | var max = Math.max(r, g, b);
|
933 | var min = Math.min(r, g, b);
|
934 | var c = max - min;
|
935 | var l = (max + min) / 2;
|
936 | if (c === 0) {
|
937 | return { h: 0, s: 0, l: l, a: a };
|
938 | }
|
939 | var h = (max === r ? (((g - b) / c) % 6) :
|
940 | max === g ? ((b - r) / c + 2) :
|
941 | ((r - g) / c + 4)) * 60;
|
942 | if (h < 0) {
|
943 | h += 360;
|
944 | }
|
945 | var s = c / (1 - Math.abs(2 * l - 1));
|
946 | return { h: h, s: s, l: l, a: a };
|
947 | }
|
948 | function toFixed(n, digits) {
|
949 | if (digits === void 0) { digits = 0; }
|
950 | var fixed = n.toFixed(digits);
|
951 | if (digits === 0) {
|
952 | return fixed;
|
953 | }
|
954 | var dot = fixed.indexOf('.');
|
955 | if (dot >= 0) {
|
956 | var zerosMatch = fixed.match(/0+$/);
|
957 | if (zerosMatch) {
|
958 | if (zerosMatch.index === dot + 1) {
|
959 | return fixed.substring(0, dot);
|
960 | }
|
961 | return fixed.substring(0, zerosMatch.index);
|
962 | }
|
963 | }
|
964 | return fixed;
|
965 | }
|
966 | function rgbToString(rgb) {
|
967 | var r = rgb.r, g = rgb.g, b = rgb.b, a = rgb.a;
|
968 | if (a != null && a < 1) {
|
969 | return "rgba(" + toFixed(r) + ", " + toFixed(g) + ", " + toFixed(b) + ", " + toFixed(a, 2) + ")";
|
970 | }
|
971 | return "rgb(" + toFixed(r) + ", " + toFixed(g) + ", " + toFixed(b) + ")";
|
972 | }
|
973 | function rgbToHexString(_a) {
|
974 | var r = _a.r, g = _a.g, b = _a.b, a = _a.a;
|
975 | return "#" + (a != null && a < 1 ? [r, g, b, Math.round(a * 255)] : [r, g, b]).map(function (x) {
|
976 | return "" + (x < 16 ? '0' : '') + x.toString(16);
|
977 | }).join('');
|
978 | }
|
979 | function hslToString(hsl) {
|
980 | var h = hsl.h, s = hsl.s, l = hsl.l, a = hsl.a;
|
981 | if (a != null && a < 1) {
|
982 | return "hsla(" + toFixed(h) + ", " + toFixed(s * 100) + "%, " + toFixed(l * 100) + "%, " + toFixed(a, 2) + ")";
|
983 | }
|
984 | return "hsl(" + toFixed(h) + ", " + toFixed(s * 100) + "%, " + toFixed(l * 100) + "%)";
|
985 | }
|
986 | var rgbMatch = /^rgba?\([^\(\)]+\)$/;
|
987 | var hslMatch = /^hsla?\([^\(\)]+\)$/;
|
988 | var hexMatch = /^#[0-9a-f]+$/i;
|
989 | function parse($color) {
|
990 | var c = $color.trim().toLowerCase();
|
991 | if (c.match(rgbMatch)) {
|
992 | return parseRGB(c);
|
993 | }
|
994 | if (c.match(hslMatch)) {
|
995 | return parseHSL(c);
|
996 | }
|
997 | if (c.match(hexMatch)) {
|
998 | return parseHex(c);
|
999 | }
|
1000 | if (knownColors.has(c)) {
|
1001 | return getColorByName(c);
|
1002 | }
|
1003 | if (systemColors.has(c)) {
|
1004 | return getSystemColor(c);
|
1005 | }
|
1006 | if ($color === 'transparent') {
|
1007 | return { r: 0, g: 0, b: 0, a: 0 };
|
1008 | }
|
1009 | throw new Error("Unable to parse " + $color);
|
1010 | }
|
1011 | function getNumbersFromString(str, splitter, range, units) {
|
1012 | var raw = str.split(splitter).filter(function (x) { return x; });
|
1013 | var unitsList = Object.entries(units);
|
1014 | var numbers = raw.map(function (r) { return r.trim(); }).map(function (r, i) {
|
1015 | var n;
|
1016 | var unit = unitsList.find(function (_a) {
|
1017 | var _b = __read(_a, 1), u = _b[0];
|
1018 | return r.endsWith(u);
|
1019 | });
|
1020 | if (unit) {
|
1021 | n = parseFloat(r.substring(0, r.length - unit[0].length)) / unit[1] * range[i];
|
1022 | }
|
1023 | else {
|
1024 | n = parseFloat(r);
|
1025 | }
|
1026 | if (range[i] > 1) {
|
1027 | return Math.round(n);
|
1028 | }
|
1029 | return n;
|
1030 | });
|
1031 | return numbers;
|
1032 | }
|
1033 | var rgbSplitter = /rgba?|\(|\)|\/|,|\s/ig;
|
1034 | var rgbRange = [255, 255, 255, 1];
|
1035 | var rgbUnits = { '%': 100 };
|
1036 | function parseRGB($rgb) {
|
1037 | var _a = __read(getNumbersFromString($rgb, rgbSplitter, rgbRange, rgbUnits), 4), r = _a[0], g = _a[1], b = _a[2], _b = _a[3], a = _b === void 0 ? 1 : _b;
|
1038 | return { r: r, g: g, b: b, a: a };
|
1039 | }
|
1040 | var hslSplitter = /hsla?|\(|\)|\/|,|\s/ig;
|
1041 | var hslRange = [360, 1, 1, 1];
|
1042 | var hslUnits = { '%': 100, 'deg': 360, 'rad': 2 * Math.PI, 'turn': 1 };
|
1043 | function parseHSL($hsl) {
|
1044 | var _a = __read(getNumbersFromString($hsl, hslSplitter, hslRange, hslUnits), 4), h = _a[0], s = _a[1], l = _a[2], _b = _a[3], a = _b === void 0 ? 1 : _b;
|
1045 | return hslToRGB({ h: h, s: s, l: l, a: a });
|
1046 | }
|
1047 | function parseHex($hex) {
|
1048 | var h = $hex.substring(1);
|
1049 | switch (h.length) {
|
1050 | case 3:
|
1051 | case 4: {
|
1052 | var _a = __read([0, 1, 2].map(function (i) { return parseInt("" + h[i] + h[i], 16); }), 3), r = _a[0], g = _a[1], b = _a[2];
|
1053 | var a = h.length === 3 ? 1 : (parseInt("" + h[3] + h[3], 16) / 255);
|
1054 | return { r: r, g: g, b: b, a: a };
|
1055 | }
|
1056 | case 6:
|
1057 | case 8: {
|
1058 | var _b = __read([0, 2, 4].map(function (i) { return parseInt(h.substring(i, i + 2), 16); }), 3), r = _b[0], g = _b[1], b = _b[2];
|
1059 | var a = h.length === 6 ? 1 : (parseInt(h.substring(6, 8), 16) / 255);
|
1060 | return { r: r, g: g, b: b, a: a };
|
1061 | }
|
1062 | }
|
1063 | throw new Error("Unable to parse " + $hex);
|
1064 | }
|
1065 | function getColorByName($color) {
|
1066 | var n = knownColors.get($color);
|
1067 | return {
|
1068 | r: (n >> 16) & 255,
|
1069 | g: (n >> 8) & 255,
|
1070 | b: (n >> 0) & 255,
|
1071 | a: 1
|
1072 | };
|
1073 | }
|
1074 | function getSystemColor($color) {
|
1075 | var n = systemColors.get($color);
|
1076 | return {
|
1077 | r: (n >> 16) & 255,
|
1078 | g: (n >> 8) & 255,
|
1079 | b: (n >> 0) & 255,
|
1080 | a: 1
|
1081 | };
|
1082 | }
|
1083 | var knownColors = new Map(Object.entries({
|
1084 | aliceblue: 0xf0f8ff,
|
1085 | antiquewhite: 0xfaebd7,
|
1086 | aqua: 0x00ffff,
|
1087 | aquamarine: 0x7fffd4,
|
1088 | azure: 0xf0ffff,
|
1089 | beige: 0xf5f5dc,
|
1090 | bisque: 0xffe4c4,
|
1091 | black: 0x000000,
|
1092 | blanchedalmond: 0xffebcd,
|
1093 | blue: 0x0000ff,
|
1094 | blueviolet: 0x8a2be2,
|
1095 | brown: 0xa52a2a,
|
1096 | burlywood: 0xdeb887,
|
1097 | cadetblue: 0x5f9ea0,
|
1098 | chartreuse: 0x7fff00,
|
1099 | chocolate: 0xd2691e,
|
1100 | coral: 0xff7f50,
|
1101 | cornflowerblue: 0x6495ed,
|
1102 | cornsilk: 0xfff8dc,
|
1103 | crimson: 0xdc143c,
|
1104 | cyan: 0x00ffff,
|
1105 | darkblue: 0x00008b,
|
1106 | darkcyan: 0x008b8b,
|
1107 | darkgoldenrod: 0xb8860b,
|
1108 | darkgray: 0xa9a9a9,
|
1109 | darkgrey: 0xa9a9a9,
|
1110 | darkgreen: 0x006400,
|
1111 | darkkhaki: 0xbdb76b,
|
1112 | darkmagenta: 0x8b008b,
|
1113 | darkolivegreen: 0x556b2f,
|
1114 | darkorange: 0xff8c00,
|
1115 | darkorchid: 0x9932cc,
|
1116 | darkred: 0x8b0000,
|
1117 | darksalmon: 0xe9967a,
|
1118 | darkseagreen: 0x8fbc8f,
|
1119 | darkslateblue: 0x483d8b,
|
1120 | darkslategray: 0x2f4f4f,
|
1121 | darkslategrey: 0x2f4f4f,
|
1122 | darkturquoise: 0x00ced1,
|
1123 | darkviolet: 0x9400d3,
|
1124 | deeppink: 0xff1493,
|
1125 | deepskyblue: 0x00bfff,
|
1126 | dimgray: 0x696969,
|
1127 | dimgrey: 0x696969,
|
1128 | dodgerblue: 0x1e90ff,
|
1129 | firebrick: 0xb22222,
|
1130 | floralwhite: 0xfffaf0,
|
1131 | forestgreen: 0x228b22,
|
1132 | fuchsia: 0xff00ff,
|
1133 | gainsboro: 0xdcdcdc,
|
1134 | ghostwhite: 0xf8f8ff,
|
1135 | gold: 0xffd700,
|
1136 | goldenrod: 0xdaa520,
|
1137 | gray: 0x808080,
|
1138 | grey: 0x808080,
|
1139 | green: 0x008000,
|
1140 | greenyellow: 0xadff2f,
|
1141 | honeydew: 0xf0fff0,
|
1142 | hotpink: 0xff69b4,
|
1143 | indianred: 0xcd5c5c,
|
1144 | indigo: 0x4b0082,
|
1145 | ivory: 0xfffff0,
|
1146 | khaki: 0xf0e68c,
|
1147 | lavender: 0xe6e6fa,
|
1148 | lavenderblush: 0xfff0f5,
|
1149 | lawngreen: 0x7cfc00,
|
1150 | lemonchiffon: 0xfffacd,
|
1151 | lightblue: 0xadd8e6,
|
1152 | lightcoral: 0xf08080,
|
1153 | lightcyan: 0xe0ffff,
|
1154 | lightgoldenrodyellow: 0xfafad2,
|
1155 | lightgray: 0xd3d3d3,
|
1156 | lightgrey: 0xd3d3d3,
|
1157 | lightgreen: 0x90ee90,
|
1158 | lightpink: 0xffb6c1,
|
1159 | lightsalmon: 0xffa07a,
|
1160 | lightseagreen: 0x20b2aa,
|
1161 | lightskyblue: 0x87cefa,
|
1162 | lightslategray: 0x778899,
|
1163 | lightslategrey: 0x778899,
|
1164 | lightsteelblue: 0xb0c4de,
|
1165 | lightyellow: 0xffffe0,
|
1166 | lime: 0x00ff00,
|
1167 | limegreen: 0x32cd32,
|
1168 | linen: 0xfaf0e6,
|
1169 | magenta: 0xff00ff,
|
1170 | maroon: 0x800000,
|
1171 | mediumaquamarine: 0x66cdaa,
|
1172 | mediumblue: 0x0000cd,
|
1173 | mediumorchid: 0xba55d3,
|
1174 | mediumpurple: 0x9370db,
|
1175 | mediumseagreen: 0x3cb371,
|
1176 | mediumslateblue: 0x7b68ee,
|
1177 | mediumspringgreen: 0x00fa9a,
|
1178 | mediumturquoise: 0x48d1cc,
|
1179 | mediumvioletred: 0xc71585,
|
1180 | midnightblue: 0x191970,
|
1181 | mintcream: 0xf5fffa,
|
1182 | mistyrose: 0xffe4e1,
|
1183 | moccasin: 0xffe4b5,
|
1184 | navajowhite: 0xffdead,
|
1185 | navy: 0x000080,
|
1186 | oldlace: 0xfdf5e6,
|
1187 | olive: 0x808000,
|
1188 | olivedrab: 0x6b8e23,
|
1189 | orange: 0xffa500,
|
1190 | orangered: 0xff4500,
|
1191 | orchid: 0xda70d6,
|
1192 | palegoldenrod: 0xeee8aa,
|
1193 | palegreen: 0x98fb98,
|
1194 | paleturquoise: 0xafeeee,
|
1195 | palevioletred: 0xdb7093,
|
1196 | papayawhip: 0xffefd5,
|
1197 | peachpuff: 0xffdab9,
|
1198 | peru: 0xcd853f,
|
1199 | pink: 0xffc0cb,
|
1200 | plum: 0xdda0dd,
|
1201 | powderblue: 0xb0e0e6,
|
1202 | purple: 0x800080,
|
1203 | rebeccapurple: 0x663399,
|
1204 | red: 0xff0000,
|
1205 | rosybrown: 0xbc8f8f,
|
1206 | royalblue: 0x4169e1,
|
1207 | saddlebrown: 0x8b4513,
|
1208 | salmon: 0xfa8072,
|
1209 | sandybrown: 0xf4a460,
|
1210 | seagreen: 0x2e8b57,
|
1211 | seashell: 0xfff5ee,
|
1212 | sienna: 0xa0522d,
|
1213 | silver: 0xc0c0c0,
|
1214 | skyblue: 0x87ceeb,
|
1215 | slateblue: 0x6a5acd,
|
1216 | slategray: 0x708090,
|
1217 | slategrey: 0x708090,
|
1218 | snow: 0xfffafa,
|
1219 | springgreen: 0x00ff7f,
|
1220 | steelblue: 0x4682b4,
|
1221 | tan: 0xd2b48c,
|
1222 | teal: 0x008080,
|
1223 | thistle: 0xd8bfd8,
|
1224 | tomato: 0xff6347,
|
1225 | turquoise: 0x40e0d0,
|
1226 | violet: 0xee82ee,
|
1227 | wheat: 0xf5deb3,
|
1228 | white: 0xffffff,
|
1229 | whitesmoke: 0xf5f5f5,
|
1230 | yellow: 0xffff00,
|
1231 | yellowgreen: 0x9acd32,
|
1232 | }));
|
1233 | var systemColors = new Map(Object.entries({
|
1234 | ActiveBorder: 0x3b99fc,
|
1235 | ActiveCaption: 0x000000,
|
1236 | AppWorkspace: 0xaaaaaa,
|
1237 | Background: 0x6363ce,
|
1238 | ButtonFace: 0xffffff,
|
1239 | ButtonHighlight: 0xe9e9e9,
|
1240 | ButtonShadow: 0x9fa09f,
|
1241 | ButtonText: 0x000000,
|
1242 | CaptionText: 0x000000,
|
1243 | GrayText: 0x7f7f7f,
|
1244 | Highlight: 0xb2d7ff,
|
1245 | HighlightText: 0x000000,
|
1246 | InactiveBorder: 0xffffff,
|
1247 | InactiveCaption: 0xffffff,
|
1248 | InactiveCaptionText: 0x000000,
|
1249 | InfoBackground: 0xfbfcc5,
|
1250 | InfoText: 0x000000,
|
1251 | Menu: 0xf6f6f6,
|
1252 | MenuText: 0xffffff,
|
1253 | Scrollbar: 0xaaaaaa,
|
1254 | ThreeDDarkShadow: 0x000000,
|
1255 | ThreeDFace: 0xc0c0c0,
|
1256 | ThreeDHighlight: 0xffffff,
|
1257 | ThreeDLightShadow: 0xffffff,
|
1258 | ThreeDShadow: 0x000000,
|
1259 | Window: 0xececec,
|
1260 | WindowFrame: 0xaaaaaa,
|
1261 | WindowText: 0x000000,
|
1262 | '-webkit-focus-ring-color': 0xe59700
|
1263 | }).map(function (_a) {
|
1264 | var _b = __read(_a, 2), key = _b[0], value = _b[1];
|
1265 | return [key.toLowerCase(), value];
|
1266 | }));
|
1267 |
|
1268 | function scale(x, inLow, inHigh, outLow, outHigh) {
|
1269 | return (x - inLow) * (outHigh - outLow) / (inHigh - inLow) + outLow;
|
1270 | }
|
1271 | function clamp(x, min, max) {
|
1272 | return Math.min(max, Math.max(min, x));
|
1273 | }
|
1274 | function multiplyMatrices(m1, m2) {
|
1275 | var result = [];
|
1276 | for (var i = 0, len = m1.length; i < len; i++) {
|
1277 | result[i] = [];
|
1278 | for (var j = 0, len2 = m2[0].length; j < len2; j++) {
|
1279 | var sum = 0;
|
1280 | for (var k = 0, len3 = m1[0].length; k < len3; k++) {
|
1281 | sum += m1[i][k] * m2[k][j];
|
1282 | }
|
1283 | result[i][j] = sum;
|
1284 | }
|
1285 | }
|
1286 | return result;
|
1287 | }
|
1288 |
|
1289 | function getMatches(regex, input, group) {
|
1290 | if (group === void 0) { group = 0; }
|
1291 | var matches = [];
|
1292 | var m;
|
1293 | while ((m = regex.exec(input))) {
|
1294 | matches.push(m[group]);
|
1295 | }
|
1296 | return matches;
|
1297 | }
|
1298 | function formatCSS(text) {
|
1299 | function trimLeft(text) {
|
1300 | return text.replace(/^\s+/, '');
|
1301 | }
|
1302 | function getIndent(depth) {
|
1303 | if (depth === 0) {
|
1304 | return '';
|
1305 | }
|
1306 | return ' '.repeat(4 * depth);
|
1307 | }
|
1308 | var emptyRuleRegexp = /[^{}]+{\s*}/g;
|
1309 | while (emptyRuleRegexp.test(text)) {
|
1310 | text = text.replace(emptyRuleRegexp, '');
|
1311 | }
|
1312 | var css = (text
|
1313 | .replace(/\s{2,}/g, ' ')
|
1314 | .replace(/\{/g, '{\n')
|
1315 | .replace(/\}/g, '\n}\n')
|
1316 | .replace(/\;(?![^\(|\"]*(\)|\"))/g, ';\n')
|
1317 | .replace(/\,(?![^\(|\"]*(\)|\"))/g, ',\n')
|
1318 | .replace(/\n\s*\n/g, '\n')
|
1319 | .split('\n'));
|
1320 | var depth = 0;
|
1321 | var formatted = [];
|
1322 | for (var x = 0, len = css.length; x < len; x++) {
|
1323 | var line = css[x] + '\n';
|
1324 | if (line.match(/\{/)) {
|
1325 | formatted.push(getIndent(depth++) + trimLeft(line));
|
1326 | }
|
1327 | else if (line.match(/\}/)) {
|
1328 | formatted.push(getIndent(--depth) + trimLeft(line));
|
1329 | }
|
1330 | else {
|
1331 | formatted.push(getIndent(depth) + trimLeft(line));
|
1332 | }
|
1333 | }
|
1334 | return formatted.join('').trim();
|
1335 | }
|
1336 |
|
1337 | function createFilterMatrix(config) {
|
1338 | var m = Matrix.identity();
|
1339 | if (config.sepia !== 0) {
|
1340 | m = multiplyMatrices(m, Matrix.sepia(config.sepia / 100));
|
1341 | }
|
1342 | if (config.grayscale !== 0) {
|
1343 | m = multiplyMatrices(m, Matrix.grayscale(config.grayscale / 100));
|
1344 | }
|
1345 | if (config.contrast !== 100) {
|
1346 | m = multiplyMatrices(m, Matrix.contrast(config.contrast / 100));
|
1347 | }
|
1348 | if (config.brightness !== 100) {
|
1349 | m = multiplyMatrices(m, Matrix.brightness(config.brightness / 100));
|
1350 | }
|
1351 | if (config.mode === 1) {
|
1352 | m = multiplyMatrices(m, Matrix.invertNHue());
|
1353 | }
|
1354 | return m;
|
1355 | }
|
1356 | function applyColorMatrix(_a, matrix) {
|
1357 | var _b = __read(_a, 3), r = _b[0], g = _b[1], b = _b[2];
|
1358 | var rgb = [[r / 255], [g / 255], [b / 255], [1], [1]];
|
1359 | var result = multiplyMatrices(matrix, rgb);
|
1360 | return [0, 1, 2].map(function (i) { return clamp(Math.round(result[i][0] * 255), 0, 255); });
|
1361 | }
|
1362 | var Matrix = {
|
1363 | identity: function () {
|
1364 | return [
|
1365 | [1, 0, 0, 0, 0],
|
1366 | [0, 1, 0, 0, 0],
|
1367 | [0, 0, 1, 0, 0],
|
1368 | [0, 0, 0, 1, 0],
|
1369 | [0, 0, 0, 0, 1]
|
1370 | ];
|
1371 | },
|
1372 | invertNHue: function () {
|
1373 | return [
|
1374 | [0.333, -0.667, -0.667, 0, 1],
|
1375 | [-0.667, 0.333, -0.667, 0, 1],
|
1376 | [-0.667, -0.667, 0.333, 0, 1],
|
1377 | [0, 0, 0, 1, 0],
|
1378 | [0, 0, 0, 0, 1]
|
1379 | ];
|
1380 | },
|
1381 | brightness: function (v) {
|
1382 | return [
|
1383 | [v, 0, 0, 0, 0],
|
1384 | [0, v, 0, 0, 0],
|
1385 | [0, 0, v, 0, 0],
|
1386 | [0, 0, 0, 1, 0],
|
1387 | [0, 0, 0, 0, 1]
|
1388 | ];
|
1389 | },
|
1390 | contrast: function (v) {
|
1391 | var t = (1 - v) / 2;
|
1392 | return [
|
1393 | [v, 0, 0, 0, t],
|
1394 | [0, v, 0, 0, t],
|
1395 | [0, 0, v, 0, t],
|
1396 | [0, 0, 0, 1, 0],
|
1397 | [0, 0, 0, 0, 1]
|
1398 | ];
|
1399 | },
|
1400 | sepia: function (v) {
|
1401 | return [
|
1402 | [(0.393 + 0.607 * (1 - v)), (0.769 - 0.769 * (1 - v)), (0.189 - 0.189 * (1 - v)), 0, 0],
|
1403 | [(0.349 - 0.349 * (1 - v)), (0.686 + 0.314 * (1 - v)), (0.168 - 0.168 * (1 - v)), 0, 0],
|
1404 | [(0.272 - 0.272 * (1 - v)), (0.534 - 0.534 * (1 - v)), (0.131 + 0.869 * (1 - v)), 0, 0],
|
1405 | [0, 0, 0, 1, 0],
|
1406 | [0, 0, 0, 0, 1]
|
1407 | ];
|
1408 | },
|
1409 | grayscale: function (v) {
|
1410 | return [
|
1411 | [(0.2126 + 0.7874 * (1 - v)), (0.7152 - 0.7152 * (1 - v)), (0.0722 - 0.0722 * (1 - v)), 0, 0],
|
1412 | [(0.2126 - 0.2126 * (1 - v)), (0.7152 + 0.2848 * (1 - v)), (0.0722 - 0.0722 * (1 - v)), 0, 0],
|
1413 | [(0.2126 - 0.2126 * (1 - v)), (0.7152 - 0.7152 * (1 - v)), (0.0722 + 0.9278 * (1 - v)), 0, 0],
|
1414 | [0, 0, 0, 1, 0],
|
1415 | [0, 0, 0, 0, 1]
|
1416 | ];
|
1417 | },
|
1418 | };
|
1419 |
|
1420 | function getBgPole(theme) {
|
1421 | var isDarkScheme = theme.mode === 1;
|
1422 | var prop = isDarkScheme ? 'darkSchemeBackgroundColor' : 'lightSchemeBackgroundColor';
|
1423 | return theme[prop];
|
1424 | }
|
1425 | function getFgPole(theme) {
|
1426 | var isDarkScheme = theme.mode === 1;
|
1427 | var prop = isDarkScheme ? 'darkSchemeTextColor' : 'lightSchemeTextColor';
|
1428 | return theme[prop];
|
1429 | }
|
1430 | var colorModificationCache = new Map();
|
1431 | var colorParseCache = new Map();
|
1432 | function parseToHSLWithCache(color) {
|
1433 | if (colorParseCache.has(color)) {
|
1434 | return colorParseCache.get(color);
|
1435 | }
|
1436 | var rgb = parse(color);
|
1437 | var hsl = rgbToHSL(rgb);
|
1438 | colorParseCache.set(color, hsl);
|
1439 | return hsl;
|
1440 | }
|
1441 | function clearColorModificationCache() {
|
1442 | colorModificationCache.clear();
|
1443 | colorParseCache.clear();
|
1444 | }
|
1445 | var rgbCacheKeys = ['r', 'g', 'b', 'a'];
|
1446 | var themeCacheKeys = ['mode', 'brightness', 'contrast', 'grayscale', 'sepia', 'darkSchemeBackgroundColor', 'darkSchemeTextColor', 'lightSchemeBackgroundColor', 'lightSchemeTextColor'];
|
1447 | function getCacheId(rgb, theme) {
|
1448 | return rgbCacheKeys.map(function (k) { return rgb[k]; })
|
1449 | .concat(themeCacheKeys.map(function (k) { return theme[k]; }))
|
1450 | .join(';');
|
1451 | }
|
1452 | function modifyColorWithCache(rgb, theme, modifyHSL, poleColor, anotherPoleColor) {
|
1453 | var fnCache;
|
1454 | if (colorModificationCache.has(modifyHSL)) {
|
1455 | fnCache = colorModificationCache.get(modifyHSL);
|
1456 | }
|
1457 | else {
|
1458 | fnCache = new Map();
|
1459 | colorModificationCache.set(modifyHSL, fnCache);
|
1460 | }
|
1461 | var id = getCacheId(rgb, theme);
|
1462 | if (fnCache.has(id)) {
|
1463 | return fnCache.get(id);
|
1464 | }
|
1465 | var hsl = rgbToHSL(rgb);
|
1466 | var pole = poleColor == null ? null : parseToHSLWithCache(poleColor);
|
1467 | var anotherPole = anotherPoleColor == null ? null : parseToHSLWithCache(anotherPoleColor);
|
1468 | var modified = modifyHSL(hsl, pole, anotherPole);
|
1469 | var _a = hslToRGB(modified), r = _a.r, g = _a.g, b = _a.b, a = _a.a;
|
1470 | var matrix = createFilterMatrix(theme);
|
1471 | var _b = __read(applyColorMatrix([r, g, b], matrix), 3), rf = _b[0], gf = _b[1], bf = _b[2];
|
1472 | var color = (a === 1 ?
|
1473 | rgbToHexString({ r: rf, g: gf, b: bf }) :
|
1474 | rgbToString({ r: rf, g: gf, b: bf, a: a }));
|
1475 | fnCache.set(id, color);
|
1476 | return color;
|
1477 | }
|
1478 | function noopHSL(hsl) {
|
1479 | return hsl;
|
1480 | }
|
1481 | function modifyColor(rgb, theme) {
|
1482 | return modifyColorWithCache(rgb, theme, noopHSL);
|
1483 | }
|
1484 | function modifyLightSchemeColor(rgb, theme) {
|
1485 | var poleBg = getBgPole(theme);
|
1486 | var poleFg = getFgPole(theme);
|
1487 | return modifyColorWithCache(rgb, theme, modifyLightModeHSL, poleFg, poleBg);
|
1488 | }
|
1489 | function modifyLightModeHSL(_a, poleFg, poleBg) {
|
1490 | var h = _a.h, s = _a.s, l = _a.l, a = _a.a;
|
1491 | var isDark = l < 0.5;
|
1492 | var isNeutral;
|
1493 | if (isDark) {
|
1494 | isNeutral = l < 0.2 || s < 0.12;
|
1495 | }
|
1496 | else {
|
1497 | var isBlue = h > 200 && h < 280;
|
1498 | isNeutral = s < 0.24 || (l > 0.8 && isBlue);
|
1499 | }
|
1500 | var hx = h;
|
1501 | var sx = l;
|
1502 | if (isNeutral) {
|
1503 | if (isDark) {
|
1504 | hx = poleFg.h;
|
1505 | sx = poleFg.s;
|
1506 | }
|
1507 | else {
|
1508 | hx = poleBg.h;
|
1509 | sx = poleBg.s;
|
1510 | }
|
1511 | }
|
1512 | var lx = scale(l, 0, 1, poleFg.l, poleBg.l);
|
1513 | return { h: hx, s: sx, l: lx, a: a };
|
1514 | }
|
1515 | var MAX_BG_LIGHTNESS = 0.4;
|
1516 | function modifyBgHSL(_a, pole) {
|
1517 | var h = _a.h, s = _a.s, l = _a.l, a = _a.a;
|
1518 | var isDark = l < 0.5;
|
1519 | var isBlue = h > 200 && h < 280;
|
1520 | var isNeutral = s < 0.12 || (l > 0.8 && isBlue);
|
1521 | if (isDark) {
|
1522 | var lx_1 = scale(l, 0, 0.5, 0, MAX_BG_LIGHTNESS);
|
1523 | if (isNeutral) {
|
1524 | var hx_1 = pole.h;
|
1525 | var sx = pole.s;
|
1526 | return { h: hx_1, s: sx, l: lx_1, a: a };
|
1527 | }
|
1528 | return { h: h, s: s, l: lx_1, a: a };
|
1529 | }
|
1530 | var lx = scale(l, 0.5, 1, MAX_BG_LIGHTNESS, pole.l);
|
1531 | if (isNeutral) {
|
1532 | var hx_2 = pole.h;
|
1533 | var sx = pole.s;
|
1534 | return { h: hx_2, s: sx, l: lx, a: a };
|
1535 | }
|
1536 | var hx = h;
|
1537 | var isYellow = h > 60 && h < 180;
|
1538 | if (isYellow) {
|
1539 | var isCloserToGreen = h > 120;
|
1540 | if (isCloserToGreen) {
|
1541 | hx = scale(h, 120, 180, 135, 180);
|
1542 | }
|
1543 | else {
|
1544 | hx = scale(h, 60, 120, 60, 105);
|
1545 | }
|
1546 | }
|
1547 | return { h: hx, s: s, l: lx, a: a };
|
1548 | }
|
1549 | function modifyBackgroundColor(rgb, theme) {
|
1550 | if (theme.mode === 0) {
|
1551 | return modifyLightSchemeColor(rgb, theme);
|
1552 | }
|
1553 | var pole = getBgPole(theme);
|
1554 | return modifyColorWithCache(rgb, __assign(__assign({}, theme), { mode: 0 }), modifyBgHSL, pole);
|
1555 | }
|
1556 | var MIN_FG_LIGHTNESS = 0.55;
|
1557 | function modifyBlueFgHue(hue) {
|
1558 | return scale(hue, 205, 245, 205, 220);
|
1559 | }
|
1560 | function modifyFgHSL(_a, pole) {
|
1561 | var h = _a.h, s = _a.s, l = _a.l, a = _a.a;
|
1562 | var isLight = l > 0.5;
|
1563 | var isNeutral = l < 0.2 || s < 0.24;
|
1564 | var isBlue = !isNeutral && h > 205 && h < 245;
|
1565 | if (isLight) {
|
1566 | var lx_2 = scale(l, 0.5, 1, MIN_FG_LIGHTNESS, pole.l);
|
1567 | if (isNeutral) {
|
1568 | var hx_3 = pole.h;
|
1569 | var sx = pole.s;
|
1570 | return { h: hx_3, s: sx, l: lx_2, a: a };
|
1571 | }
|
1572 | var hx_4 = h;
|
1573 | if (isBlue) {
|
1574 | hx_4 = modifyBlueFgHue(h);
|
1575 | }
|
1576 | return { h: hx_4, s: s, l: lx_2, a: a };
|
1577 | }
|
1578 | if (isNeutral) {
|
1579 | var hx_5 = pole.h;
|
1580 | var sx = pole.s;
|
1581 | var lx_3 = scale(l, 0, 0.5, pole.l, MIN_FG_LIGHTNESS);
|
1582 | return { h: hx_5, s: sx, l: lx_3, a: a };
|
1583 | }
|
1584 | var hx = h;
|
1585 | var lx;
|
1586 | if (isBlue) {
|
1587 | hx = modifyBlueFgHue(h);
|
1588 | lx = scale(l, 0, 0.5, pole.l, Math.min(1, MIN_FG_LIGHTNESS + 0.05));
|
1589 | }
|
1590 | else {
|
1591 | lx = scale(l, 0, 0.5, pole.l, MIN_FG_LIGHTNESS);
|
1592 | }
|
1593 | return { h: hx, s: s, l: lx, a: a };
|
1594 | }
|
1595 | function modifyForegroundColor(rgb, theme) {
|
1596 | if (theme.mode === 0) {
|
1597 | return modifyLightSchemeColor(rgb, theme);
|
1598 | }
|
1599 | var pole = getFgPole(theme);
|
1600 | return modifyColorWithCache(rgb, __assign(__assign({}, theme), { mode: 0 }), modifyFgHSL, pole);
|
1601 | }
|
1602 | function modifyBorderHSL(_a, poleFg, poleBg) {
|
1603 | var h = _a.h, s = _a.s, l = _a.l, a = _a.a;
|
1604 | var isDark = l < 0.5;
|
1605 | var isNeutral = l < 0.2 || s < 0.24;
|
1606 | var hx = h;
|
1607 | var sx = s;
|
1608 | if (isNeutral) {
|
1609 | if (isDark) {
|
1610 | hx = poleFg.h;
|
1611 | sx = poleFg.s;
|
1612 | }
|
1613 | else {
|
1614 | hx = poleBg.h;
|
1615 | sx = poleBg.s;
|
1616 | }
|
1617 | }
|
1618 | var lx = scale(l, 0, 1, 0.5, 0.2);
|
1619 | return { h: hx, s: sx, l: lx, a: a };
|
1620 | }
|
1621 | function modifyBorderColor(rgb, theme) {
|
1622 | if (theme.mode === 0) {
|
1623 | return modifyLightSchemeColor(rgb, theme);
|
1624 | }
|
1625 | var poleFg = getFgPole(theme);
|
1626 | var poleBg = getBgPole(theme);
|
1627 | return modifyColorWithCache(rgb, __assign(__assign({}, theme), { mode: 0 }), modifyBorderHSL, poleFg, poleBg);
|
1628 | }
|
1629 | function modifyShadowColor(rgb, filter) {
|
1630 | return modifyBackgroundColor(rgb, filter);
|
1631 | }
|
1632 | function modifyGradientColor(rgb, filter) {
|
1633 | return modifyBackgroundColor(rgb, filter);
|
1634 | }
|
1635 |
|
1636 | function createTextStyle(config) {
|
1637 | var lines = [];
|
1638 | lines.push('*:not(pre) {');
|
1639 | if (config.useFont && config.fontFamily) {
|
1640 | lines.push(" font-family: " + config.fontFamily + " !important;");
|
1641 | }
|
1642 | if (config.textStroke > 0) {
|
1643 | lines.push(" -webkit-text-stroke: " + config.textStroke + "px !important;");
|
1644 | lines.push(" text-stroke: " + config.textStroke + "px !important;");
|
1645 | }
|
1646 | lines.push('}');
|
1647 | return lines.join('\n');
|
1648 | }
|
1649 |
|
1650 | var FilterMode;
|
1651 | (function (FilterMode) {
|
1652 | FilterMode[FilterMode["light"] = 0] = "light";
|
1653 | FilterMode[FilterMode["dark"] = 1] = "dark";
|
1654 | })(FilterMode || (FilterMode = {}));
|
1655 | function getCSSFilterValue(config) {
|
1656 | var filters = [];
|
1657 | if (config.mode === FilterMode.dark) {
|
1658 | filters.push('invert(100%) hue-rotate(180deg)');
|
1659 | }
|
1660 | if (config.brightness !== 100) {
|
1661 | filters.push("brightness(" + config.brightness + "%)");
|
1662 | }
|
1663 | if (config.contrast !== 100) {
|
1664 | filters.push("contrast(" + config.contrast + "%)");
|
1665 | }
|
1666 | if (config.grayscale !== 0) {
|
1667 | filters.push("grayscale(" + config.grayscale + "%)");
|
1668 | }
|
1669 | if (config.sepia !== 0) {
|
1670 | filters.push("sepia(" + config.sepia + "%)");
|
1671 | }
|
1672 | if (filters.length === 0) {
|
1673 | return null;
|
1674 | }
|
1675 | return filters.join(' ');
|
1676 | }
|
1677 |
|
1678 | function toSVGMatrix(matrix) {
|
1679 | return matrix.slice(0, 4).map(function (m) { return m.map(function (m) { return m.toFixed(3); }).join(' '); }).join(' ');
|
1680 | }
|
1681 | function getSVGFilterMatrixValue(config) {
|
1682 | return toSVGMatrix(createFilterMatrix(config));
|
1683 | }
|
1684 |
|
1685 | var counter = 0;
|
1686 | var resolvers = new Map();
|
1687 | var rejectors = new Map();
|
1688 | function bgFetch(request) {
|
1689 | return __awaiter(this, void 0, void 0, function () {
|
1690 | return __generator(this, function (_a) {
|
1691 | return [2, new Promise(function (resolve, reject) {
|
1692 | var id = ++counter;
|
1693 | resolvers.set(id, resolve);
|
1694 | rejectors.set(id, reject);
|
1695 | chrome.runtime.sendMessage({ type: 'fetch', data: request, id: id });
|
1696 | })];
|
1697 | });
|
1698 | });
|
1699 | }
|
1700 | chrome.runtime.onMessage.addListener(function (_a) {
|
1701 | var type = _a.type, data = _a.data, error = _a.error, id = _a.id;
|
1702 | if (type === 'fetch-response') {
|
1703 | var resolve = resolvers.get(id);
|
1704 | var reject = rejectors.get(id);
|
1705 | resolvers.delete(id);
|
1706 | rejectors.delete(id);
|
1707 | if (error) {
|
1708 | reject && reject(error);
|
1709 | }
|
1710 | else {
|
1711 | resolve && resolve(data);
|
1712 | }
|
1713 | }
|
1714 | });
|
1715 |
|
1716 | function getImageDetails(url) {
|
1717 | return __awaiter(this, void 0, void 0, function () {
|
1718 | var dataURL, image, info;
|
1719 | return __generator(this, function (_a) {
|
1720 | switch (_a.label) {
|
1721 | case 0:
|
1722 | if (!url.startsWith('data:')) return [3, 1];
|
1723 | dataURL = url;
|
1724 | return [3, 3];
|
1725 | case 1: return [4, getImageDataURL(url)];
|
1726 | case 2:
|
1727 | dataURL = _a.sent();
|
1728 | _a.label = 3;
|
1729 | case 3: return [4, urlToImage(dataURL)];
|
1730 | case 4:
|
1731 | image = _a.sent();
|
1732 | info = analyzeImage(image);
|
1733 | return [2, __assign({ src: url, dataURL: dataURL, width: image.naturalWidth, height: image.naturalHeight }, info)];
|
1734 | }
|
1735 | });
|
1736 | });
|
1737 | }
|
1738 | function getImageDataURL(url) {
|
1739 | return __awaiter(this, void 0, void 0, function () {
|
1740 | return __generator(this, function (_a) {
|
1741 | switch (_a.label) {
|
1742 | case 0:
|
1743 | if (!(getURLHostOrProtocol(url) === (location.host || location.protocol))) return [3, 2];
|
1744 | return [4, loadAsDataURL(url)];
|
1745 | case 1: return [2, _a.sent()];
|
1746 | case 2: return [4, bgFetch({ url: url, responseType: 'data-url' })];
|
1747 | case 3: return [2, _a.sent()];
|
1748 | }
|
1749 | });
|
1750 | });
|
1751 | }
|
1752 | function urlToImage(url) {
|
1753 | return __awaiter(this, void 0, void 0, function () {
|
1754 | return __generator(this, function (_a) {
|
1755 | return [2, new Promise(function (resolve, reject) {
|
1756 | var image = new Image();
|
1757 | image.onload = function () { return resolve(image); };
|
1758 | image.onerror = function () { return reject("Unable to load image " + url); };
|
1759 | image.src = url;
|
1760 | })];
|
1761 | });
|
1762 | });
|
1763 | }
|
1764 | var MAX_ANALIZE_PIXELS_COUNT = 32 * 32;
|
1765 | var canvas;
|
1766 | var context;
|
1767 | function createCanvas() {
|
1768 | var maxWidth = MAX_ANALIZE_PIXELS_COUNT;
|
1769 | var maxHeight = MAX_ANALIZE_PIXELS_COUNT;
|
1770 | canvas = document.createElement('canvas');
|
1771 | canvas.width = maxWidth;
|
1772 | canvas.height = maxHeight;
|
1773 | context = canvas.getContext('2d');
|
1774 | context.imageSmoothingEnabled = false;
|
1775 | }
|
1776 | function removeCanvas() {
|
1777 | canvas = null;
|
1778 | context = null;
|
1779 | }
|
1780 | function analyzeImage(image) {
|
1781 | if (!canvas) {
|
1782 | createCanvas();
|
1783 | }
|
1784 | var naturalWidth = image.naturalWidth, naturalHeight = image.naturalHeight;
|
1785 | if (naturalHeight === 0 || naturalWidth === 0) {
|
1786 | logWarn("logWarn(Image is empty " + image.currentSrc + ")");
|
1787 | return null;
|
1788 | }
|
1789 | var naturalPixelsCount = naturalWidth * naturalHeight;
|
1790 | var k = Math.min(1, Math.sqrt(MAX_ANALIZE_PIXELS_COUNT / naturalPixelsCount));
|
1791 | var width = Math.ceil(naturalWidth * k);
|
1792 | var height = Math.ceil(naturalHeight * k);
|
1793 | context.clearRect(0, 0, width, height);
|
1794 | context.drawImage(image, 0, 0, naturalWidth, naturalHeight, 0, 0, width, height);
|
1795 | var imageData = context.getImageData(0, 0, width, height);
|
1796 | var d = imageData.data;
|
1797 | var TRANSPARENT_ALPHA_THRESHOLD = 0.05;
|
1798 | var DARK_LIGHTNESS_THRESHOLD = 0.4;
|
1799 | var LIGHT_LIGHTNESS_THRESHOLD = 0.7;
|
1800 | var transparentPixelsCount = 0;
|
1801 | var darkPixelsCount = 0;
|
1802 | var lightPixelsCount = 0;
|
1803 | var i, x, y;
|
1804 | var r, g, b, a;
|
1805 | var l;
|
1806 | for (y = 0; y < height; y++) {
|
1807 | for (x = 0; x < width; x++) {
|
1808 | i = 4 * (y * width + x);
|
1809 | r = d[i + 0] / 255;
|
1810 | g = d[i + 1] / 255;
|
1811 | b = d[i + 2] / 255;
|
1812 | a = d[i + 3] / 255;
|
1813 | if (a < TRANSPARENT_ALPHA_THRESHOLD) {
|
1814 | transparentPixelsCount++;
|
1815 | }
|
1816 | else {
|
1817 | l = 0.2126 * r + 0.7152 * g + 0.0722 * b;
|
1818 | if (l < DARK_LIGHTNESS_THRESHOLD) {
|
1819 | darkPixelsCount++;
|
1820 | }
|
1821 | if (l > LIGHT_LIGHTNESS_THRESHOLD) {
|
1822 | lightPixelsCount++;
|
1823 | }
|
1824 | }
|
1825 | }
|
1826 | }
|
1827 | var totalPixelsCount = width * height;
|
1828 | var opaquePixelsCount = totalPixelsCount - transparentPixelsCount;
|
1829 | var DARK_IMAGE_THRESHOLD = 0.7;
|
1830 | var LIGHT_IMAGE_THRESHOLD = 0.7;
|
1831 | var TRANSPARENT_IMAGE_THRESHOLD = 0.1;
|
1832 | var LARGE_IMAGE_PIXELS_COUNT = 800 * 600;
|
1833 | return {
|
1834 | isDark: ((darkPixelsCount / opaquePixelsCount) >= DARK_IMAGE_THRESHOLD),
|
1835 | isLight: ((lightPixelsCount / opaquePixelsCount) >= LIGHT_IMAGE_THRESHOLD),
|
1836 | isTransparent: ((transparentPixelsCount / totalPixelsCount) >= TRANSPARENT_IMAGE_THRESHOLD),
|
1837 | isLarge: (naturalPixelsCount >= LARGE_IMAGE_PIXELS_COUNT),
|
1838 | };
|
1839 | }
|
1840 | var objectURLs = new Set();
|
1841 | function getFilteredImageDataURL(_a, filter) {
|
1842 | var dataURL = _a.dataURL, width = _a.width, height = _a.height;
|
1843 | var matrix = getSVGFilterMatrixValue(filter);
|
1844 | var svg = [
|
1845 | "<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"" + width + "\" height=\"" + height + "\">",
|
1846 | '<defs>',
|
1847 | '<filter id="darkreader-image-filter">',
|
1848 | "<feColorMatrix type=\"matrix\" values=\"" + matrix + "\" />",
|
1849 | '</filter>',
|
1850 | '</defs>',
|
1851 | "<image width=\"" + width + "\" height=\"" + height + "\" filter=\"url(#darkreader-image-filter)\" xlink:href=\"" + dataURL + "\" />",
|
1852 | '</svg>',
|
1853 | ].join('');
|
1854 | var bytes = new Uint8Array(svg.length);
|
1855 | for (var i = 0; i < svg.length; i++) {
|
1856 | bytes[i] = svg.charCodeAt(i);
|
1857 | }
|
1858 | var blob = new Blob([bytes], { type: 'image/svg+xml' });
|
1859 | var objectURL = URL.createObjectURL(blob);
|
1860 | objectURLs.add(objectURL);
|
1861 | return objectURL;
|
1862 | }
|
1863 | function cleanImageProcessingCache() {
|
1864 | removeCanvas();
|
1865 | objectURLs.forEach(function (u) { return URL.revokeObjectURL(u); });
|
1866 | objectURLs.clear();
|
1867 | }
|
1868 |
|
1869 | function getModifiableCSSDeclaration(property, value, rule, ignoreImageSelectors, isCancelled) {
|
1870 | var important = Boolean(rule && rule.style && rule.style.getPropertyPriority(property));
|
1871 | var sourceValue = value;
|
1872 | if (property.startsWith('--')) {
|
1873 | return null;
|
1874 | }
|
1875 | else if ((property.indexOf('color') >= 0 && property !== '-webkit-print-color-adjust') ||
|
1876 | property === 'fill' ||
|
1877 | property === 'stroke' ||
|
1878 | property === 'stop-color') {
|
1879 | var modifier = getColorModifier(property, value);
|
1880 | if (modifier) {
|
1881 | return { property: property, value: modifier, important: important, sourceValue: sourceValue };
|
1882 | }
|
1883 | }
|
1884 | else if (property === 'background-image' || property === 'list-style-image') {
|
1885 | var modifier = getBgImageModifier(value, rule, ignoreImageSelectors, isCancelled);
|
1886 | if (modifier) {
|
1887 | return { property: property, value: modifier, important: important, sourceValue: sourceValue };
|
1888 | }
|
1889 | }
|
1890 | else if (property.indexOf('shadow') >= 0) {
|
1891 | var modifier = getShadowModifier(value);
|
1892 | if (modifier) {
|
1893 | return { property: property, value: modifier, important: important, sourceValue: sourceValue };
|
1894 | }
|
1895 | }
|
1896 | return null;
|
1897 | }
|
1898 | function getModifiedUserAgentStyle(theme, isIFrame, styleSystemControls) {
|
1899 | var lines = [];
|
1900 | if (!isIFrame) {
|
1901 | lines.push('html {');
|
1902 | lines.push(" background-color: " + modifyBackgroundColor({ r: 255, g: 255, b: 255 }, theme) + " !important;");
|
1903 | lines.push('}');
|
1904 | }
|
1905 | lines.push("" + (isIFrame ? '' : 'html, body, ') + (styleSystemControls ? 'input, textarea, select, button' : '') + " {");
|
1906 | lines.push(" background-color: " + modifyBackgroundColor({ r: 255, g: 255, b: 255 }, theme) + ";");
|
1907 | lines.push('}');
|
1908 | lines.push("html, body, " + (styleSystemControls ? 'input, textarea, select, button' : '') + " {");
|
1909 | lines.push(" border-color: " + modifyBorderColor({ r: 76, g: 76, b: 76 }, theme) + ";");
|
1910 | lines.push(" color: " + modifyForegroundColor({ r: 0, g: 0, b: 0 }, theme) + ";");
|
1911 | lines.push('}');
|
1912 | lines.push('a {');
|
1913 | lines.push(" color: " + modifyForegroundColor({ r: 0, g: 64, b: 255 }, theme) + ";");
|
1914 | lines.push('}');
|
1915 | lines.push('table {');
|
1916 | lines.push(" border-color: " + modifyBorderColor({ r: 128, g: 128, b: 128 }, theme) + ";");
|
1917 | lines.push('}');
|
1918 | lines.push('::placeholder {');
|
1919 | lines.push(" color: " + modifyForegroundColor({ r: 169, g: 169, b: 169 }, theme) + ";");
|
1920 | lines.push('}');
|
1921 | lines.push('input:-webkit-autofill,');
|
1922 | lines.push('textarea:-webkit-autofill,');
|
1923 | lines.push('select:-webkit-autofill {');
|
1924 | lines.push(" background-color: " + modifyBackgroundColor({ r: 250, g: 255, b: 189 }, theme) + " !important;");
|
1925 | lines.push(" color: " + modifyForegroundColor({ r: 0, g: 0, b: 0 }, theme) + " !important;");
|
1926 | lines.push('}');
|
1927 | if (theme.scrollbarColor) {
|
1928 | lines.push(getModifiedScrollbarStyle(theme));
|
1929 | }
|
1930 | if (theme.selectionColor) {
|
1931 | lines.push(getModifiedSelectionStyle(theme));
|
1932 | }
|
1933 | return lines.join('\n');
|
1934 | }
|
1935 | function getSelectionColor(theme) {
|
1936 | var backgroundColorSelection;
|
1937 | var foregroundColorSelection;
|
1938 | if (theme.selectionColor === 'auto') {
|
1939 | backgroundColorSelection = modifyBackgroundColor({ r: 0, g: 96, b: 212 }, __assign(__assign({}, theme), { grayscale: 0 }));
|
1940 | foregroundColorSelection = modifyForegroundColor({ r: 255, g: 255, b: 255 }, __assign(__assign({}, theme), { grayscale: 0 }));
|
1941 | }
|
1942 | else {
|
1943 | var rgb = parse(theme.selectionColor);
|
1944 | var hsl = rgbToHSL(rgb);
|
1945 | backgroundColorSelection = theme.selectionColor;
|
1946 | if (hsl.l < 0.5) {
|
1947 | foregroundColorSelection = '#FFF';
|
1948 | }
|
1949 | else {
|
1950 | foregroundColorSelection = '#000';
|
1951 | }
|
1952 | }
|
1953 | return { backgroundColorSelection: backgroundColorSelection, foregroundColorSelection: foregroundColorSelection };
|
1954 | }
|
1955 | function getModifiedSelectionStyle(theme) {
|
1956 | var lines = [];
|
1957 | var modifiedSelectionColor = getSelectionColor(theme);
|
1958 | var backgroundColorSelection = modifiedSelectionColor.backgroundColorSelection;
|
1959 | var foregroundColorSelection = modifiedSelectionColor.foregroundColorSelection;
|
1960 | ['::selection', '::-moz-selection'].forEach(function (selection) {
|
1961 | lines.push(selection + " {");
|
1962 | lines.push(" background-color: " + backgroundColorSelection + " !important;");
|
1963 | lines.push(" color: " + foregroundColorSelection + " !important;");
|
1964 | lines.push('}');
|
1965 | });
|
1966 | return lines.join('\n');
|
1967 | }
|
1968 | function getModifiedScrollbarStyle(theme) {
|
1969 | var lines = [];
|
1970 | var colorTrack;
|
1971 | var colorIcons;
|
1972 | var colorThumb;
|
1973 | var colorThumbHover;
|
1974 | var colorThumbActive;
|
1975 | var colorCorner;
|
1976 | if (theme.scrollbarColor === 'auto') {
|
1977 | colorTrack = modifyBackgroundColor({ r: 241, g: 241, b: 241 }, theme);
|
1978 | colorIcons = modifyForegroundColor({ r: 96, g: 96, b: 96 }, theme);
|
1979 | colorThumb = modifyBackgroundColor({ r: 176, g: 176, b: 176 }, theme);
|
1980 | colorThumbHover = modifyBackgroundColor({ r: 144, g: 144, b: 144 }, theme);
|
1981 | colorThumbActive = modifyBackgroundColor({ r: 96, g: 96, b: 96 }, theme);
|
1982 | colorCorner = modifyBackgroundColor({ r: 255, g: 255, b: 255 }, theme);
|
1983 | }
|
1984 | else {
|
1985 | var rgb = parse(theme.scrollbarColor);
|
1986 | var hsl_1 = rgbToHSL(rgb);
|
1987 | var isLight = hsl_1.l > 0.5;
|
1988 | var lighten = function (lighter) { return (__assign(__assign({}, hsl_1), { l: clamp(hsl_1.l + lighter, 0, 1) })); };
|
1989 | var darken = function (darker) { return (__assign(__assign({}, hsl_1), { l: clamp(hsl_1.l - darker, 0, 1) })); };
|
1990 | colorTrack = hslToString(darken(0.4));
|
1991 | colorIcons = hslToString(isLight ? darken(0.4) : lighten(0.4));
|
1992 | colorThumb = hslToString(hsl_1);
|
1993 | colorThumbHover = hslToString(lighten(0.1));
|
1994 | colorThumbActive = hslToString(lighten(0.2));
|
1995 | }
|
1996 | lines.push('::-webkit-scrollbar {');
|
1997 | lines.push(" background-color: " + colorTrack + ";");
|
1998 | lines.push(" color: " + colorIcons + ";");
|
1999 | lines.push('}');
|
2000 | lines.push('::-webkit-scrollbar-thumb {');
|
2001 | lines.push(" background-color: " + colorThumb + ";");
|
2002 | lines.push('}');
|
2003 | lines.push('::-webkit-scrollbar-thumb:hover {');
|
2004 | lines.push(" background-color: " + colorThumbHover + ";");
|
2005 | lines.push('}');
|
2006 | lines.push('::-webkit-scrollbar-thumb:active {');
|
2007 | lines.push(" background-color: " + colorThumbActive + ";");
|
2008 | lines.push('}');
|
2009 | lines.push('::-webkit-scrollbar-corner {');
|
2010 | lines.push(" background-color: " + colorCorner + ";");
|
2011 | lines.push('}');
|
2012 | if (isFirefox) {
|
2013 | lines.push('* {');
|
2014 | lines.push(" scrollbar-color: " + colorThumb + " " + colorTrack + ";");
|
2015 | lines.push('}');
|
2016 | }
|
2017 | return lines.join('\n');
|
2018 | }
|
2019 | function getModifiedFallbackStyle(filter, _a) {
|
2020 | var strict = _a.strict;
|
2021 | var lines = [];
|
2022 | lines.push("html, body, " + (strict ? 'body :not(iframe)' : 'body > :not(iframe)') + " {");
|
2023 | lines.push(" background-color: " + modifyBackgroundColor({ r: 255, g: 255, b: 255 }, filter) + " !important;");
|
2024 | lines.push(" border-color: " + modifyBorderColor({ r: 64, g: 64, b: 64 }, filter) + " !important;");
|
2025 | lines.push(" color: " + modifyForegroundColor({ r: 0, g: 0, b: 0 }, filter) + " !important;");
|
2026 | lines.push('}');
|
2027 | return lines.join('\n');
|
2028 | }
|
2029 | var unparsableColors = new Set([
|
2030 | 'inherit',
|
2031 | 'transparent',
|
2032 | 'initial',
|
2033 | 'currentcolor',
|
2034 | 'none',
|
2035 | 'unset',
|
2036 | ]);
|
2037 | var colorParseCache$1 = new Map();
|
2038 | function parseColorWithCache($color) {
|
2039 | $color = $color.trim();
|
2040 | if (colorParseCache$1.has($color)) {
|
2041 | return colorParseCache$1.get($color);
|
2042 | }
|
2043 | var color = parse($color);
|
2044 | colorParseCache$1.set($color, color);
|
2045 | return color;
|
2046 | }
|
2047 | function tryParseColor($color) {
|
2048 | try {
|
2049 | return parseColorWithCache($color);
|
2050 | }
|
2051 | catch (err) {
|
2052 | return null;
|
2053 | }
|
2054 | }
|
2055 | function getColorModifier(prop, value) {
|
2056 | if (unparsableColors.has(value.toLowerCase())) {
|
2057 | return value;
|
2058 | }
|
2059 | try {
|
2060 | var rgb_1 = parseColorWithCache(value);
|
2061 | if (prop.indexOf('background') >= 0) {
|
2062 | return function (filter) { return modifyBackgroundColor(rgb_1, filter); };
|
2063 | }
|
2064 | if (prop.indexOf('border') >= 0 || prop.indexOf('outline') >= 0) {
|
2065 | return function (filter) { return modifyBorderColor(rgb_1, filter); };
|
2066 | }
|
2067 | return function (filter) { return modifyForegroundColor(rgb_1, filter); };
|
2068 | }
|
2069 | catch (err) {
|
2070 | logWarn('Color parse error', err);
|
2071 | return null;
|
2072 | }
|
2073 | }
|
2074 | var gradientRegex = /[\-a-z]+gradient\(([^\(\)]*(\(([^\(\)]*(\(.*?\)))*[^\(\)]*\))){0,15}[^\(\)]*\)/g;
|
2075 | var imageDetailsCache = new Map();
|
2076 | var awaitingForImageLoading = new Map();
|
2077 | function shouldIgnoreImage(rule, selectors) {
|
2078 | if (!rule || selectors.length === 0) {
|
2079 | return false;
|
2080 | }
|
2081 | if (selectors.some(function (s) { return s === '*'; })) {
|
2082 | return true;
|
2083 | }
|
2084 | var ruleSelectors = rule.selectorText.split(/,\s*/g);
|
2085 | var _loop_1 = function (i) {
|
2086 | var ignoredSelector = selectors[i];
|
2087 | if (ruleSelectors.some(function (s) { return s === ignoredSelector; })) {
|
2088 | return { value: true };
|
2089 | }
|
2090 | };
|
2091 | for (var i = 0; i < selectors.length; i++) {
|
2092 | var state_1 = _loop_1(i);
|
2093 | if (typeof state_1 === "object")
|
2094 | return state_1.value;
|
2095 | }
|
2096 | return false;
|
2097 | }
|
2098 | function getBgImageModifier(value, rule, ignoreImageSelectors, isCancelled) {
|
2099 | var _this = this;
|
2100 | try {
|
2101 | var gradients = getMatches(gradientRegex, value);
|
2102 | var urls = getMatches(cssURLRegex, value);
|
2103 | if (urls.length === 0 && gradients.length === 0) {
|
2104 | return value;
|
2105 | }
|
2106 | var getIndices = function (matches) {
|
2107 | var index = 0;
|
2108 | return matches.map(function (match) {
|
2109 | var valueIndex = value.indexOf(match, index);
|
2110 | index = valueIndex + match.length;
|
2111 | return { match: match, index: valueIndex };
|
2112 | });
|
2113 | };
|
2114 | var matches_1 = getIndices(urls).map(function (i) { return (__assign({ type: 'url' }, i)); })
|
2115 | .concat(getIndices(gradients).map(function (i) { return (__assign({ type: 'gradient' }, i)); }))
|
2116 | .sort(function (a, b) { return a.index - b.index; });
|
2117 | var getGradientModifier_1 = function (gradient) {
|
2118 | var match = gradient.match(/^(.*-gradient)\((.*)\)$/);
|
2119 | var type = match[1];
|
2120 | var content = match[2];
|
2121 | var partsRegex = /([^\(\),]+(\([^\(\)]*(\([^\(\)]*\)*[^\(\)]*)?\))?[^\(\),]*),?/g;
|
2122 | var colorStopRegex = /^(from|color-stop|to)\(([^\(\)]*?,\s*)?(.*?)\)$/;
|
2123 | var parts = getMatches(partsRegex, content, 1).map(function (part) {
|
2124 | part = part.trim();
|
2125 | var rgb = tryParseColor(part);
|
2126 | if (rgb) {
|
2127 | return function (filter) { return modifyGradientColor(rgb, filter); };
|
2128 | }
|
2129 | var space = part.lastIndexOf(' ');
|
2130 | rgb = tryParseColor(part.substring(0, space));
|
2131 | if (rgb) {
|
2132 | return function (filter) { return modifyGradientColor(rgb, filter) + " " + part.substring(space + 1); };
|
2133 | }
|
2134 | var colorStopMatch = part.match(colorStopRegex);
|
2135 | if (colorStopMatch) {
|
2136 | rgb = tryParseColor(colorStopMatch[3]);
|
2137 | if (rgb) {
|
2138 | return function (filter) { return colorStopMatch[1] + "(" + (colorStopMatch[2] ? colorStopMatch[2] + ", " : '') + modifyGradientColor(rgb, filter) + ")"; };
|
2139 | }
|
2140 | }
|
2141 | return function () { return part; };
|
2142 | });
|
2143 | return function (filter) {
|
2144 | return type + "(" + parts.map(function (modify) { return modify(filter); }).join(', ') + ")";
|
2145 | };
|
2146 | };
|
2147 | var getURLModifier_1 = function (urlValue) {
|
2148 | var url = getCSSURLValue(urlValue);
|
2149 | if (rule.parentStyleSheet.href) {
|
2150 | var basePath = getCSSBaseBath(rule.parentStyleSheet.href);
|
2151 | url = getAbsoluteURL(basePath, url);
|
2152 | }
|
2153 | else if (rule.parentStyleSheet.ownerNode && rule.parentStyleSheet.ownerNode.baseURI) {
|
2154 | url = getAbsoluteURL(rule.parentStyleSheet.ownerNode.baseURI, url);
|
2155 | }
|
2156 | else {
|
2157 | url = getAbsoluteURL(location.origin, url);
|
2158 | }
|
2159 | var absoluteValue = "url(\"" + url + "\")";
|
2160 | return function (filter) { return __awaiter(_this, void 0, void 0, function () {
|
2161 | var imageDetails, awaiters_1, err_1, bgImageValue;
|
2162 | return __generator(this, function (_a) {
|
2163 | switch (_a.label) {
|
2164 | case 0:
|
2165 | if (!imageDetailsCache.has(url)) return [3, 1];
|
2166 | imageDetails = imageDetailsCache.get(url);
|
2167 | return [3, 7];
|
2168 | case 1:
|
2169 | _a.trys.push([1, 6, , 7]);
|
2170 | if (shouldIgnoreImage(rule, ignoreImageSelectors)) {
|
2171 | return [2, null];
|
2172 | }
|
2173 | if (!awaitingForImageLoading.has(url)) return [3, 3];
|
2174 | awaiters_1 = awaitingForImageLoading.get(url);
|
2175 | return [4, new Promise(function (resolve) { return awaiters_1.push(resolve); })];
|
2176 | case 2:
|
2177 | imageDetails = _a.sent();
|
2178 | if (!imageDetails) {
|
2179 | return [2, null];
|
2180 | }
|
2181 | return [3, 5];
|
2182 | case 3:
|
2183 | awaitingForImageLoading.set(url, []);
|
2184 | return [4, getImageDetails(url)];
|
2185 | case 4:
|
2186 | imageDetails = _a.sent();
|
2187 | imageDetailsCache.set(url, imageDetails);
|
2188 | awaitingForImageLoading.get(url).forEach(function (resolve) { return resolve(imageDetails); });
|
2189 | awaitingForImageLoading.delete(url);
|
2190 | _a.label = 5;
|
2191 | case 5:
|
2192 | if (isCancelled()) {
|
2193 | return [2, null];
|
2194 | }
|
2195 | return [3, 7];
|
2196 | case 6:
|
2197 | err_1 = _a.sent();
|
2198 | logWarn(err_1);
|
2199 | if (awaitingForImageLoading.has(url)) {
|
2200 | awaitingForImageLoading.get(url).forEach(function (resolve) { return resolve(null); });
|
2201 | awaitingForImageLoading.delete(url);
|
2202 | }
|
2203 | return [2, absoluteValue];
|
2204 | case 7:
|
2205 | bgImageValue = getBgImageValue_1(imageDetails, filter) || absoluteValue;
|
2206 | return [2, bgImageValue];
|
2207 | }
|
2208 | });
|
2209 | }); };
|
2210 | };
|
2211 | var getBgImageValue_1 = function (imageDetails, filter) {
|
2212 | var isDark = imageDetails.isDark, isLight = imageDetails.isLight, isTransparent = imageDetails.isTransparent, isLarge = imageDetails.isLarge, width = imageDetails.width;
|
2213 | var result;
|
2214 | if (isDark && isTransparent && filter.mode === 1 && !isLarge && width > 2) {
|
2215 | logInfo("Inverting dark image " + imageDetails.src);
|
2216 | var inverted = getFilteredImageDataURL(imageDetails, __assign(__assign({}, filter), { sepia: clamp(filter.sepia + 10, 0, 100) }));
|
2217 | result = "url(\"" + inverted + "\")";
|
2218 | }
|
2219 | else if (isLight && !isTransparent && filter.mode === 1) {
|
2220 | if (isLarge) {
|
2221 | result = 'none';
|
2222 | }
|
2223 | else {
|
2224 | logInfo("Dimming light image " + imageDetails.src);
|
2225 | var dimmed = getFilteredImageDataURL(imageDetails, filter);
|
2226 | result = "url(\"" + dimmed + "\")";
|
2227 | }
|
2228 | }
|
2229 | else if (filter.mode === 0 && isLight && !isLarge) {
|
2230 | logInfo("Applying filter to image " + imageDetails.src);
|
2231 | var filtered = getFilteredImageDataURL(imageDetails, __assign(__assign({}, filter), { brightness: clamp(filter.brightness - 10, 5, 200), sepia: clamp(filter.sepia + 10, 0, 100) }));
|
2232 | result = "url(\"" + filtered + "\")";
|
2233 | }
|
2234 | else {
|
2235 | result = null;
|
2236 | }
|
2237 | return result;
|
2238 | };
|
2239 | var modifiers_1 = [];
|
2240 | var index_1 = 0;
|
2241 | matches_1.forEach(function (_a, i) {
|
2242 | var match = _a.match, type = _a.type, matchStart = _a.index;
|
2243 | var prefixStart = index_1;
|
2244 | var matchEnd = matchStart + match.length;
|
2245 | index_1 = matchEnd;
|
2246 | modifiers_1.push(function () { return value.substring(prefixStart, matchStart); });
|
2247 | modifiers_1.push(type === 'url' ? getURLModifier_1(match) : getGradientModifier_1(match));
|
2248 | if (i === matches_1.length - 1) {
|
2249 | modifiers_1.push(function () { return value.substring(matchEnd); });
|
2250 | }
|
2251 | });
|
2252 | return function (filter) {
|
2253 | var results = modifiers_1.map(function (modify) { return modify(filter); });
|
2254 | if (results.some(function (r) { return r instanceof Promise; })) {
|
2255 | return Promise.all(results)
|
2256 | .then(function (asyncResults) {
|
2257 | return asyncResults.join('');
|
2258 | });
|
2259 | }
|
2260 | return results.join('');
|
2261 | };
|
2262 | }
|
2263 | catch (err) {
|
2264 | logWarn("Unable to parse gradient " + value, err);
|
2265 | return null;
|
2266 | }
|
2267 | }
|
2268 | function getShadowModifier(value) {
|
2269 | try {
|
2270 | var index_2 = 0;
|
2271 | var colorMatches_1 = getMatches(/(^|\s)([a-z]+\(.+?\)|#[0-9a-f]+|[a-z]+)(.*?(inset|outset)?($|,))/ig, value, 2);
|
2272 | var modifiers_2 = colorMatches_1.map(function (match, i) {
|
2273 | var prefixIndex = index_2;
|
2274 | var matchIndex = value.indexOf(match, index_2);
|
2275 | var matchEnd = matchIndex + match.length;
|
2276 | index_2 = matchEnd;
|
2277 | var rgb = tryParseColor(match);
|
2278 | if (!rgb) {
|
2279 | return function () { return value.substring(prefixIndex, matchEnd); };
|
2280 | }
|
2281 | return function (filter) { return "" + value.substring(prefixIndex, matchIndex) + modifyShadowColor(rgb, filter) + (i === colorMatches_1.length - 1 ? value.substring(matchEnd) : ''); };
|
2282 | });
|
2283 | return function (filter) { return modifiers_2.map(function (modify) { return modify(filter); }).join(''); };
|
2284 | }
|
2285 | catch (err) {
|
2286 | logWarn("Unable to parse shadow " + value, err);
|
2287 | return null;
|
2288 | }
|
2289 | }
|
2290 | function cleanModificationCache() {
|
2291 | colorParseCache$1.clear();
|
2292 | clearColorModificationCache();
|
2293 | imageDetailsCache.clear();
|
2294 | cleanImageProcessingCache();
|
2295 | awaitingForImageLoading.clear();
|
2296 | }
|
2297 |
|
2298 | var overrides = {
|
2299 | 'background-color': {
|
2300 | customProp: '--darkreader-inline-bgcolor',
|
2301 | cssProp: 'background-color',
|
2302 | dataAttr: 'data-darkreader-inline-bgcolor',
|
2303 | },
|
2304 | 'background-image': {
|
2305 | customProp: '--darkreader-inline-bgimage',
|
2306 | cssProp: 'background-image',
|
2307 | dataAttr: 'data-darkreader-inline-bgimage',
|
2308 | },
|
2309 | 'border-color': {
|
2310 | customProp: '--darkreader-inline-border',
|
2311 | cssProp: 'border-color',
|
2312 | dataAttr: 'data-darkreader-inline-border',
|
2313 | },
|
2314 | 'border-bottom-color': {
|
2315 | customProp: '--darkreader-inline-border-bottom',
|
2316 | cssProp: 'border-bottom-color',
|
2317 | dataAttr: 'data-darkreader-inline-border-bottom',
|
2318 | },
|
2319 | 'border-left-color': {
|
2320 | customProp: '--darkreader-inline-border-left',
|
2321 | cssProp: 'border-left-color',
|
2322 | dataAttr: 'data-darkreader-inline-border-left',
|
2323 | },
|
2324 | 'border-right-color': {
|
2325 | customProp: '--darkreader-inline-border-right',
|
2326 | cssProp: 'border-right-color',
|
2327 | dataAttr: 'data-darkreader-inline-border-right',
|
2328 | },
|
2329 | 'border-top-color': {
|
2330 | customProp: '--darkreader-inline-border-top',
|
2331 | cssProp: 'border-top-color',
|
2332 | dataAttr: 'data-darkreader-inline-border-top',
|
2333 | },
|
2334 | 'box-shadow': {
|
2335 | customProp: '--darkreader-inline-boxshadow',
|
2336 | cssProp: 'box-shadow',
|
2337 | dataAttr: 'data-darkreader-inline-boxshadow',
|
2338 | },
|
2339 | 'color': {
|
2340 | customProp: '--darkreader-inline-color',
|
2341 | cssProp: 'color',
|
2342 | dataAttr: 'data-darkreader-inline-color',
|
2343 | },
|
2344 | 'fill': {
|
2345 | customProp: '--darkreader-inline-fill',
|
2346 | cssProp: 'fill',
|
2347 | dataAttr: 'data-darkreader-inline-fill',
|
2348 | },
|
2349 | 'stroke': {
|
2350 | customProp: '--darkreader-inline-stroke',
|
2351 | cssProp: 'stroke',
|
2352 | dataAttr: 'data-darkreader-inline-stroke',
|
2353 | },
|
2354 | 'outline-color': {
|
2355 | customProp: '--darkreader-inline-outline',
|
2356 | cssProp: 'outline-color',
|
2357 | dataAttr: 'data-darkreader-inline-outline',
|
2358 | },
|
2359 | 'stop-color': {
|
2360 | customProp: '--darkreader-inline-stopcolor',
|
2361 | cssProp: 'stop-color',
|
2362 | dataAttr: 'data-darkreader-inline-stopcolor',
|
2363 | },
|
2364 | };
|
2365 | var overridesList = Object.values(overrides);
|
2366 | var INLINE_STYLE_ATTRS = ['style', 'fill', 'stop-color', 'stroke', 'bgcolor', 'color'];
|
2367 | var INLINE_STYLE_SELECTOR = INLINE_STYLE_ATTRS.map(function (attr) { return "[" + attr + "]"; }).join(', ');
|
2368 | function getInlineOverrideStyle() {
|
2369 | return overridesList.map(function (_a) {
|
2370 | var dataAttr = _a.dataAttr, customProp = _a.customProp, cssProp = _a.cssProp;
|
2371 | return [
|
2372 | "[" + dataAttr + "] {",
|
2373 | " " + cssProp + ": var(" + customProp + ") !important;",
|
2374 | '}',
|
2375 | ].join('\n');
|
2376 | }).join('\n');
|
2377 | }
|
2378 | function getInlineStyleElements(root) {
|
2379 | var results = [];
|
2380 | if (root instanceof Element && root.matches(INLINE_STYLE_SELECTOR)) {
|
2381 | results.push(root);
|
2382 | }
|
2383 | if (root instanceof Element || (isShadowDomSupported && root instanceof ShadowRoot) || root instanceof Document) {
|
2384 | push(results, root.querySelectorAll(INLINE_STYLE_SELECTOR));
|
2385 | }
|
2386 | return results;
|
2387 | }
|
2388 | var treeObservers = new Map();
|
2389 | var attrObservers = new Map();
|
2390 | function watchForInlineStyles(elementStyleDidChange, shadowRootDiscovered) {
|
2391 | deepWatchForInlineStyles(document, elementStyleDidChange, shadowRootDiscovered);
|
2392 | iterateShadowHosts(document.documentElement, function (host) {
|
2393 | deepWatchForInlineStyles(host.shadowRoot, elementStyleDidChange, shadowRootDiscovered);
|
2394 | });
|
2395 | }
|
2396 | function deepWatchForInlineStyles(root, elementStyleDidChange, shadowRootDiscovered) {
|
2397 | if (treeObservers.has(root)) {
|
2398 | treeObservers.get(root).disconnect();
|
2399 | attrObservers.get(root).disconnect();
|
2400 | }
|
2401 | var discoveredNodes = new WeakSet();
|
2402 | function discoverNodes(node) {
|
2403 | getInlineStyleElements(node).forEach(function (el) {
|
2404 | if (discoveredNodes.has(el)) {
|
2405 | return;
|
2406 | }
|
2407 | discoveredNodes.add(el);
|
2408 | elementStyleDidChange(el);
|
2409 | });
|
2410 | iterateShadowHosts(node, function (n) {
|
2411 | if (discoveredNodes.has(node)) {
|
2412 | return;
|
2413 | }
|
2414 | discoveredNodes.add(node);
|
2415 | shadowRootDiscovered(n.shadowRoot);
|
2416 | deepWatchForInlineStyles(n.shadowRoot, elementStyleDidChange, shadowRootDiscovered);
|
2417 | });
|
2418 | }
|
2419 | var treeObserver = createOptimizedTreeObserver(root, {
|
2420 | onMinorMutations: function (_a) {
|
2421 | var additions = _a.additions;
|
2422 | additions.forEach(function (added) { return discoverNodes(added); });
|
2423 | },
|
2424 | onHugeMutations: function () {
|
2425 | discoverNodes(root);
|
2426 | },
|
2427 | });
|
2428 | treeObservers.set(root, treeObserver);
|
2429 | var attemptCount = 0;
|
2430 | var start = null;
|
2431 | var ATTEMPTS_INTERVAL = getDuration({ seconds: 10 });
|
2432 | var RETRY_TIMEOUT = getDuration({ seconds: 2 });
|
2433 | var MAX_ATTEMPTS_COUNT = 50;
|
2434 | var cache = [];
|
2435 | var timeoutId = null;
|
2436 | var handleAttributeMutations = throttle(function (mutations) {
|
2437 | mutations.forEach(function (m) {
|
2438 | if (INLINE_STYLE_ATTRS.includes(m.attributeName)) {
|
2439 | elementStyleDidChange(m.target);
|
2440 | }
|
2441 | });
|
2442 | });
|
2443 | var attrObserver = new MutationObserver(function (mutations) {
|
2444 | if (timeoutId) {
|
2445 | cache.push.apply(cache, __spread(mutations));
|
2446 | return;
|
2447 | }
|
2448 | attemptCount++;
|
2449 | var now = Date.now();
|
2450 | if (start == null) {
|
2451 | start = now;
|
2452 | }
|
2453 | else if (attemptCount >= MAX_ATTEMPTS_COUNT) {
|
2454 | if (now - start < ATTEMPTS_INTERVAL) {
|
2455 | timeoutId = setTimeout(function () {
|
2456 | start = null;
|
2457 | attemptCount = 0;
|
2458 | timeoutId = null;
|
2459 | var attributeCache = cache;
|
2460 | cache = [];
|
2461 | handleAttributeMutations(attributeCache);
|
2462 | }, RETRY_TIMEOUT);
|
2463 | cache.push.apply(cache, __spread(mutations));
|
2464 | return;
|
2465 | }
|
2466 | start = now;
|
2467 | attemptCount = 1;
|
2468 | }
|
2469 | handleAttributeMutations(mutations);
|
2470 | });
|
2471 | attrObserver.observe(root, {
|
2472 | attributes: true,
|
2473 | attributeFilter: INLINE_STYLE_ATTRS.concat(overridesList.map(function (_a) {
|
2474 | var dataAttr = _a.dataAttr;
|
2475 | return dataAttr;
|
2476 | })),
|
2477 | subtree: true,
|
2478 | });
|
2479 | attrObservers.set(root, attrObserver);
|
2480 | }
|
2481 | function stopWatchingForInlineStyles() {
|
2482 | treeObservers.forEach(function (o) { return o.disconnect(); });
|
2483 | attrObservers.forEach(function (o) { return o.disconnect(); });
|
2484 | treeObservers.clear();
|
2485 | attrObservers.clear();
|
2486 | }
|
2487 | var inlineStyleCache = new WeakMap();
|
2488 | var filterProps = ['brightness', 'contrast', 'grayscale', 'sepia', 'mode'];
|
2489 | function getInlineStyleCacheKey(el, theme) {
|
2490 | return INLINE_STYLE_ATTRS
|
2491 | .map(function (attr) { return attr + "=\"" + el.getAttribute(attr) + "\""; })
|
2492 | .concat(filterProps.map(function (prop) { return prop + "=\"" + theme[prop] + "\""; }))
|
2493 | .join(' ');
|
2494 | }
|
2495 | function shouldIgnoreInlineStyle(element, selectors) {
|
2496 | for (var i = 0, len = selectors.length; i < len; i++) {
|
2497 | var ingnoredSelector = selectors[i];
|
2498 | if (element.matches(ingnoredSelector)) {
|
2499 | return true;
|
2500 | }
|
2501 | }
|
2502 | return false;
|
2503 | }
|
2504 | function overrideInlineStyle(element, theme, ignoreInlineSelectors, ignoreImageSelectors) {
|
2505 | var cacheKey = getInlineStyleCacheKey(element, theme);
|
2506 | if (cacheKey === inlineStyleCache.get(element)) {
|
2507 | return;
|
2508 | }
|
2509 | var unsetProps = new Set(Object.keys(overrides));
|
2510 | function setCustomProp(targetCSSProp, modifierCSSProp, cssVal) {
|
2511 | var _a = overrides[targetCSSProp], customProp = _a.customProp, dataAttr = _a.dataAttr;
|
2512 | var mod = getModifiableCSSDeclaration(modifierCSSProp, cssVal, null, ignoreImageSelectors, null);
|
2513 | if (!mod) {
|
2514 | return;
|
2515 | }
|
2516 | var value = mod.value;
|
2517 | if (typeof value === 'function') {
|
2518 | value = value(theme);
|
2519 | }
|
2520 | element.style.setProperty(customProp, value);
|
2521 | if (!element.hasAttribute(dataAttr)) {
|
2522 | element.setAttribute(dataAttr, '');
|
2523 | }
|
2524 | unsetProps.delete(targetCSSProp);
|
2525 | }
|
2526 | if (ignoreInlineSelectors.length > 0) {
|
2527 | if (shouldIgnoreInlineStyle(element, ignoreInlineSelectors)) {
|
2528 | unsetProps.forEach(function (cssProp) {
|
2529 | element.removeAttribute(overrides[cssProp].dataAttr);
|
2530 | });
|
2531 | return;
|
2532 | }
|
2533 | }
|
2534 | if (element.hasAttribute('bgcolor')) {
|
2535 | var value = element.getAttribute('bgcolor');
|
2536 | if (value.match(/^[0-9a-f]{3}$/i) || value.match(/^[0-9a-f]{6}$/i)) {
|
2537 | value = "#" + value;
|
2538 | }
|
2539 | setCustomProp('background-color', 'background-color', value);
|
2540 | }
|
2541 | if (element.hasAttribute('color')) {
|
2542 | var value = element.getAttribute('color');
|
2543 | if (value.match(/^[0-9a-f]{3}$/i) || value.match(/^[0-9a-f]{6}$/i)) {
|
2544 | value = "#" + value;
|
2545 | }
|
2546 | setCustomProp('color', 'color', value);
|
2547 | }
|
2548 | if (element instanceof SVGElement) {
|
2549 | if (element.hasAttribute('fill')) {
|
2550 | var SMALL_SVG_LIMIT = 32;
|
2551 | var value = element.getAttribute('fill');
|
2552 | var isBg = false;
|
2553 | if (!(element instanceof SVGTextElement)) {
|
2554 | var _a = element.getBoundingClientRect(), width = _a.width, height = _a.height;
|
2555 | isBg = (width > SMALL_SVG_LIMIT || height > SMALL_SVG_LIMIT);
|
2556 | }
|
2557 | setCustomProp('fill', isBg ? 'background-color' : 'color', value);
|
2558 | }
|
2559 | if (element.hasAttribute('stop-color')) {
|
2560 | setCustomProp('stop-color', 'background-color', element.getAttribute('stop-color'));
|
2561 | }
|
2562 | }
|
2563 | if (element.hasAttribute('stroke')) {
|
2564 | var value = element.getAttribute('stroke');
|
2565 | setCustomProp('stroke', element instanceof SVGLineElement || element instanceof SVGTextElement ? 'border-color' : 'color', value);
|
2566 | }
|
2567 | element.style && iterateCSSDeclarations(element.style, function (property, value) {
|
2568 | if (property === 'background-image' && value.indexOf('url') >= 0) {
|
2569 | return;
|
2570 | }
|
2571 | if (overrides.hasOwnProperty(property)) {
|
2572 | setCustomProp(property, property, value);
|
2573 | }
|
2574 | });
|
2575 | if (element.style && element instanceof SVGTextElement && element.style.fill) {
|
2576 | setCustomProp('fill', 'color', element.style.getPropertyValue('fill'));
|
2577 | }
|
2578 | forEach(unsetProps, function (cssProp) {
|
2579 | element.removeAttribute(overrides[cssProp].dataAttr);
|
2580 | });
|
2581 | inlineStyleCache.set(element, getInlineStyleCacheKey(element, theme));
|
2582 | }
|
2583 |
|
2584 | var metaThemeColorName = 'theme-color';
|
2585 | var metaThemeColorSelector = "meta[name=\"" + metaThemeColorName + "\"]";
|
2586 | var srcMetaThemeColor = null;
|
2587 | var observer = null;
|
2588 | function changeMetaThemeColor(meta, theme) {
|
2589 | srcMetaThemeColor = srcMetaThemeColor || meta.content;
|
2590 | try {
|
2591 | var color = parse(srcMetaThemeColor);
|
2592 | meta.content = modifyBackgroundColor(color, theme);
|
2593 | }
|
2594 | catch (err) {
|
2595 | logWarn(err);
|
2596 | }
|
2597 | }
|
2598 | function changeMetaThemeColorWhenAvailable(theme) {
|
2599 | var meta = document.querySelector(metaThemeColorSelector);
|
2600 | if (meta) {
|
2601 | changeMetaThemeColor(meta, theme);
|
2602 | }
|
2603 | else {
|
2604 | if (observer) {
|
2605 | observer.disconnect();
|
2606 | }
|
2607 | observer = new MutationObserver(function (mutations) {
|
2608 | loop: for (var i = 0; i < mutations.length; i++) {
|
2609 | var addedNodes = mutations[i].addedNodes;
|
2610 | for (var j = 0; j < addedNodes.length; j++) {
|
2611 | var node = addedNodes[j];
|
2612 | if (node instanceof HTMLMetaElement && node.name === metaThemeColorName) {
|
2613 | observer.disconnect();
|
2614 | observer = null;
|
2615 | changeMetaThemeColor(node, theme);
|
2616 | break loop;
|
2617 | }
|
2618 | }
|
2619 | }
|
2620 | });
|
2621 | observer.observe(document.head, { childList: true });
|
2622 | }
|
2623 | }
|
2624 | function restoreMetaThemeColor() {
|
2625 | if (observer) {
|
2626 | observer.disconnect();
|
2627 | observer = null;
|
2628 | }
|
2629 | var meta = document.querySelector(metaThemeColorSelector);
|
2630 | if (meta && srcMetaThemeColor) {
|
2631 | meta.content = srcMetaThemeColor;
|
2632 | }
|
2633 | }
|
2634 |
|
2635 | var themeCacheKeys$1 = [
|
2636 | 'mode',
|
2637 | 'brightness',
|
2638 | 'contrast',
|
2639 | 'grayscale',
|
2640 | 'sepia',
|
2641 | 'darkSchemeBackgroundColor',
|
2642 | 'darkSchemeTextColor',
|
2643 | 'lightSchemeBackgroundColor',
|
2644 | 'lightSchemeTextColor',
|
2645 | ];
|
2646 | function getThemeKey(theme) {
|
2647 | return themeCacheKeys$1.map(function (p) { return p + ":" + theme[p]; }).join(';');
|
2648 | }
|
2649 | var asyncQueue = createAsyncTasksQueue();
|
2650 | function createStyleSheetModifier() {
|
2651 | var renderId = 0;
|
2652 | var rulesTextCache = new Map();
|
2653 | var rulesModCache = new Map();
|
2654 | var prevFilterKey = null;
|
2655 | function modifySheet(options) {
|
2656 | var rules = options.sourceCSSRules;
|
2657 | var theme = options.theme, variables = options.variables, ignoreImageAnalysis = options.ignoreImageAnalysis, force = options.force, prepareSheet = options.prepareSheet, isAsyncCancelled = options.isAsyncCancelled;
|
2658 | var rulesChanged = (rulesModCache.size === 0);
|
2659 | var notFoundCacheKeys = new Set(rulesModCache.keys());
|
2660 | var themeKey = getThemeKey(theme);
|
2661 | var themeChanged = (themeKey !== prevFilterKey);
|
2662 | var modRules = [];
|
2663 | iterateCSSRules(rules, function (rule) {
|
2664 | var cssText = rule.cssText;
|
2665 | var textDiffersFromPrev = false;
|
2666 | notFoundCacheKeys.delete(cssText);
|
2667 | if (!rulesTextCache.has(cssText)) {
|
2668 | rulesTextCache.set(cssText, cssText);
|
2669 | textDiffersFromPrev = true;
|
2670 | }
|
2671 | var vars;
|
2672 | var varsRule = null;
|
2673 | if (variables.size > 0 || cssText.includes('var(')) {
|
2674 | var cssTextWithVariables = replaceCSSVariables(cssText, variables);
|
2675 | if (rulesTextCache.get(cssText) !== cssTextWithVariables) {
|
2676 | rulesTextCache.set(cssText, cssTextWithVariables);
|
2677 | textDiffersFromPrev = true;
|
2678 | vars = getTempCSSStyleSheet();
|
2679 | vars.insertRule(cssTextWithVariables);
|
2680 | varsRule = vars.cssRules[0];
|
2681 | }
|
2682 | }
|
2683 | if (textDiffersFromPrev) {
|
2684 | rulesChanged = true;
|
2685 | }
|
2686 | else {
|
2687 | modRules.push(rulesModCache.get(cssText));
|
2688 | return;
|
2689 | }
|
2690 | var modDecs = [];
|
2691 | var targetRule = varsRule || rule;
|
2692 | targetRule && targetRule.style && iterateCSSDeclarations(targetRule.style, function (property, value) {
|
2693 | var mod = getModifiableCSSDeclaration(property, value, rule, ignoreImageAnalysis, isAsyncCancelled);
|
2694 | if (mod) {
|
2695 | modDecs.push(mod);
|
2696 | }
|
2697 | });
|
2698 | var modRule = null;
|
2699 | if (modDecs.length > 0) {
|
2700 | var parentRule = rule.parentRule;
|
2701 | modRule = { selector: rule.selectorText, declarations: modDecs, parentRule: parentRule };
|
2702 | modRules.push(modRule);
|
2703 | }
|
2704 | rulesModCache.set(cssText, modRule);
|
2705 | vars && vars.deleteRule(0);
|
2706 | });
|
2707 | notFoundCacheKeys.forEach(function (key) {
|
2708 | rulesTextCache.delete(key);
|
2709 | rulesModCache.delete(key);
|
2710 | });
|
2711 | prevFilterKey = themeKey;
|
2712 | if (!force && !rulesChanged && !themeChanged) {
|
2713 | return;
|
2714 | }
|
2715 | renderId++;
|
2716 | function setRule(target, index, rule) {
|
2717 | var selector = rule.selector, declarations = rule.declarations;
|
2718 | target.insertRule(selector + " {}", index);
|
2719 | var style = target.cssRules[index].style;
|
2720 | declarations.forEach(function (_a) {
|
2721 | var property = _a.property, value = _a.value, important = _a.important, sourceValue = _a.sourceValue;
|
2722 | style.setProperty(property, value == null ? sourceValue : value, important ? 'important' : '');
|
2723 | });
|
2724 | }
|
2725 | var asyncDeclarations = new Map();
|
2726 | var asyncDeclarationCounter = 0;
|
2727 | var rootReadyGroup = { rule: null, rules: [], isGroup: true };
|
2728 | var groupRefs = new WeakMap();
|
2729 | function getGroup(rule) {
|
2730 | if (rule == null) {
|
2731 | return rootReadyGroup;
|
2732 | }
|
2733 | if (groupRefs.has(rule)) {
|
2734 | return groupRefs.get(rule);
|
2735 | }
|
2736 | var group = { rule: rule, rules: [], isGroup: true };
|
2737 | groupRefs.set(rule, group);
|
2738 | var parentGroup = getGroup(rule.parentRule);
|
2739 | parentGroup.rules.push(group);
|
2740 | return group;
|
2741 | }
|
2742 | modRules.filter(function (r) { return r; }).forEach(function (_a) {
|
2743 | var selector = _a.selector, declarations = _a.declarations, parentRule = _a.parentRule;
|
2744 | var group = getGroup(parentRule);
|
2745 | var readyStyleRule = { selector: selector, declarations: [], isGroup: false };
|
2746 | var readyDeclarations = readyStyleRule.declarations;
|
2747 | group.rules.push(readyStyleRule);
|
2748 | declarations.forEach(function (_a) {
|
2749 | var property = _a.property, value = _a.value, important = _a.important, sourceValue = _a.sourceValue;
|
2750 | if (typeof value === 'function') {
|
2751 | var modified = value(theme);
|
2752 | if (modified instanceof Promise) {
|
2753 | var asyncKey_1 = asyncDeclarationCounter++;
|
2754 | var asyncDeclaration_1 = { property: property, value: null, important: important, asyncKey: asyncKey_1, sourceValue: sourceValue };
|
2755 | readyDeclarations.push(asyncDeclaration_1);
|
2756 | var promise = modified;
|
2757 | var currentRenderId_1 = renderId;
|
2758 | promise.then(function (asyncValue) {
|
2759 | if (!asyncValue || isAsyncCancelled() || currentRenderId_1 !== renderId) {
|
2760 | return;
|
2761 | }
|
2762 | asyncDeclaration_1.value = asyncValue;
|
2763 | asyncQueue.add(function () {
|
2764 | if (isAsyncCancelled() || currentRenderId_1 !== renderId) {
|
2765 | return;
|
2766 | }
|
2767 | rebuildAsyncRule(asyncKey_1);
|
2768 | });
|
2769 | });
|
2770 | }
|
2771 | else {
|
2772 | readyDeclarations.push({ property: property, value: modified, important: important, sourceValue: sourceValue });
|
2773 | }
|
2774 | }
|
2775 | else {
|
2776 | readyDeclarations.push({ property: property, value: value, important: important, sourceValue: sourceValue });
|
2777 | }
|
2778 | });
|
2779 | });
|
2780 | var sheet = prepareSheet();
|
2781 | function buildStyleSheet() {
|
2782 | function createTarget(group, parent) {
|
2783 | var rule = group.rule;
|
2784 | if (rule instanceof CSSMediaRule) {
|
2785 | var media = rule.media;
|
2786 | var index = parent.cssRules.length;
|
2787 | parent.insertRule("@media " + media.mediaText + " {}", index);
|
2788 | return parent.cssRules[index];
|
2789 | }
|
2790 | return parent;
|
2791 | }
|
2792 | function iterateReadyRules(group, target, styleIterator) {
|
2793 | group.rules.forEach(function (r) {
|
2794 | if (r.isGroup) {
|
2795 | var t = createTarget(r, target);
|
2796 | iterateReadyRules(r, t, styleIterator);
|
2797 | }
|
2798 | else {
|
2799 | styleIterator(r, target);
|
2800 | }
|
2801 | });
|
2802 | }
|
2803 | iterateReadyRules(rootReadyGroup, sheet, function (rule, target) {
|
2804 | var index = target.cssRules.length;
|
2805 | rule.declarations
|
2806 | .filter(function (_a) {
|
2807 | var value = _a.value;
|
2808 | return value == null;
|
2809 | })
|
2810 | .forEach(function (_a) {
|
2811 | var asyncKey = _a.asyncKey;
|
2812 | return asyncDeclarations.set(asyncKey, { rule: rule, target: target, index: index });
|
2813 | });
|
2814 | setRule(target, index, rule);
|
2815 | });
|
2816 | }
|
2817 | function rebuildAsyncRule(key) {
|
2818 | var _a = asyncDeclarations.get(key), rule = _a.rule, target = _a.target, index = _a.index;
|
2819 | target.deleteRule(index);
|
2820 | setRule(target, index, rule);
|
2821 | asyncDeclarations.delete(key);
|
2822 | }
|
2823 | buildStyleSheet();
|
2824 | }
|
2825 | return { modifySheet: modifySheet };
|
2826 | }
|
2827 |
|
2828 | var STYLE_SELECTOR = 'style, link[rel*="stylesheet" i]:not([disabled])';
|
2829 | function shouldManageStyle(element) {
|
2830 | return (((element instanceof HTMLStyleElement) ||
|
2831 | (element instanceof SVGStyleElement) ||
|
2832 | (element instanceof HTMLLinkElement &&
|
2833 | element.rel &&
|
2834 | element.rel.toLowerCase().includes('stylesheet') &&
|
2835 | !element.disabled)) &&
|
2836 | !element.classList.contains('darkreader') &&
|
2837 | element.media !== 'print' &&
|
2838 | !element.classList.contains('stylus'));
|
2839 | }
|
2840 | function getManageableStyles(node, results, deep) {
|
2841 | if (results === void 0) { results = []; }
|
2842 | if (deep === void 0) { deep = true; }
|
2843 | if (shouldManageStyle(node)) {
|
2844 | results.push(node);
|
2845 | }
|
2846 | else if (node instanceof Element || (isShadowDomSupported && node instanceof ShadowRoot) || node === document) {
|
2847 | forEach(node.querySelectorAll(STYLE_SELECTOR), function (style) { return getManageableStyles(style, results, false); });
|
2848 | if (deep) {
|
2849 | iterateShadowHosts(node, function (host) { return getManageableStyles(host.shadowRoot, results, false); });
|
2850 | }
|
2851 | }
|
2852 | return results;
|
2853 | }
|
2854 | var syncStyleSet = new WeakSet();
|
2855 | var corsStyleSet = new WeakSet();
|
2856 | var canOptimizeUsingProxy = false;
|
2857 | document.addEventListener('__darkreader__inlineScriptsAllowed', function () {
|
2858 | canOptimizeUsingProxy = true;
|
2859 | });
|
2860 | function manageStyle(element, _a) {
|
2861 | var update = _a.update, loadingStart = _a.loadingStart, loadingEnd = _a.loadingEnd;
|
2862 | var prevStyles = [];
|
2863 | var next = element;
|
2864 | while ((next = next.nextElementSibling) && next.matches('.darkreader')) {
|
2865 | prevStyles.push(next);
|
2866 | }
|
2867 | var corsCopy = prevStyles.find(function (el) { return el.matches('.darkreader--cors') && !corsStyleSet.has(el); }) || null;
|
2868 | var syncStyle = prevStyles.find(function (el) { return el.matches('.darkreader--sync') && !syncStyleSet.has(el); }) || null;
|
2869 | var corsCopyPositionWatcher = null;
|
2870 | var syncStylePositionWatcher = null;
|
2871 | var cancelAsyncOperations = false;
|
2872 | var sheetModifier = createStyleSheetModifier();
|
2873 | var observer = new MutationObserver(function () {
|
2874 | update();
|
2875 | });
|
2876 | var observerOptions = { attributes: true, childList: true, subtree: true, characterData: true };
|
2877 | function containsCSSImport() {
|
2878 | return element instanceof HTMLStyleElement && element.textContent.trim().match(cssImportRegex);
|
2879 | }
|
2880 | function getRulesSync() {
|
2881 | if (corsCopy) {
|
2882 | return corsCopy.sheet.cssRules;
|
2883 | }
|
2884 | if (containsCSSImport()) {
|
2885 | return null;
|
2886 | }
|
2887 | return safeGetSheetRules();
|
2888 | }
|
2889 | function insertStyle() {
|
2890 | if (corsCopy) {
|
2891 | if (element.nextSibling !== corsCopy) {
|
2892 | element.parentNode.insertBefore(corsCopy, element.nextSibling);
|
2893 | }
|
2894 | if (corsCopy.nextSibling !== syncStyle) {
|
2895 | element.parentNode.insertBefore(syncStyle, corsCopy.nextSibling);
|
2896 | }
|
2897 | }
|
2898 | else if (element.nextSibling !== syncStyle) {
|
2899 | element.parentNode.insertBefore(syncStyle, element.nextSibling);
|
2900 | }
|
2901 | }
|
2902 | function createSyncStyle() {
|
2903 | syncStyle = element instanceof SVGStyleElement ?
|
2904 | document.createElementNS('http://www.w3.org/2000/svg', 'style') :
|
2905 | document.createElement('style');
|
2906 | syncStyle.classList.add('darkreader');
|
2907 | syncStyle.classList.add('darkreader--sync');
|
2908 | syncStyle.media = 'screen';
|
2909 | syncStyleSet.add(syncStyle);
|
2910 | }
|
2911 | var isLoadingRules = false;
|
2912 | var wasLoadingError = false;
|
2913 | function getRulesAsync() {
|
2914 | return __awaiter(this, void 0, void 0, function () {
|
2915 | var cssText, cssBasePath, _a, cssRules, accessError, err_1, fullCSSText, err_2;
|
2916 | var _b;
|
2917 | return __generator(this, function (_c) {
|
2918 | switch (_c.label) {
|
2919 | case 0:
|
2920 | if (!(element instanceof HTMLLinkElement)) return [3, 7];
|
2921 | _a = __read(getRulesOrError(), 2), cssRules = _a[0], accessError = _a[1];
|
2922 | if (accessError) {
|
2923 | logWarn(accessError);
|
2924 | }
|
2925 | if (!((!cssRules && !accessError && !isSafari) ||
|
2926 | (isSafari && !element.sheet) ||
|
2927 | isStillLoadingError(accessError))) return [3, 5];
|
2928 | _c.label = 1;
|
2929 | case 1:
|
2930 | _c.trys.push([1, 3, , 4]);
|
2931 | return [4, linkLoading(element)];
|
2932 | case 2:
|
2933 | _c.sent();
|
2934 | return [3, 4];
|
2935 | case 3:
|
2936 | err_1 = _c.sent();
|
2937 | logWarn(err_1);
|
2938 | wasLoadingError = true;
|
2939 | return [3, 4];
|
2940 | case 4:
|
2941 | if (cancelAsyncOperations) {
|
2942 | return [2, null];
|
2943 | }
|
2944 | _b = __read(getRulesOrError(), 2), cssRules = _b[0], accessError = _b[1];
|
2945 | if (accessError) {
|
2946 | logWarn(accessError);
|
2947 | }
|
2948 | _c.label = 5;
|
2949 | case 5:
|
2950 | if (cssRules != null) {
|
2951 | return [2, cssRules];
|
2952 | }
|
2953 | return [4, loadText(element.href)];
|
2954 | case 6:
|
2955 | cssText = _c.sent();
|
2956 | cssBasePath = getCSSBaseBath(element.href);
|
2957 | if (cancelAsyncOperations) {
|
2958 | return [2, null];
|
2959 | }
|
2960 | return [3, 8];
|
2961 | case 7:
|
2962 | if (containsCSSImport()) {
|
2963 | cssText = element.textContent.trim();
|
2964 | cssBasePath = getCSSBaseBath(location.href);
|
2965 | }
|
2966 | else {
|
2967 | return [2, null];
|
2968 | }
|
2969 | _c.label = 8;
|
2970 | case 8:
|
2971 | if (!cssText) return [3, 13];
|
2972 | _c.label = 9;
|
2973 | case 9:
|
2974 | _c.trys.push([9, 11, , 12]);
|
2975 | return [4, replaceCSSImports(cssText, cssBasePath)];
|
2976 | case 10:
|
2977 | fullCSSText = _c.sent();
|
2978 | corsCopy = createCORSCopy(element, fullCSSText);
|
2979 | return [3, 12];
|
2980 | case 11:
|
2981 | err_2 = _c.sent();
|
2982 | logWarn(err_2);
|
2983 | return [3, 12];
|
2984 | case 12:
|
2985 | if (corsCopy) {
|
2986 | corsCopyPositionWatcher = watchForNodePosition(corsCopy, 'prev-sibling');
|
2987 | return [2, corsCopy.sheet.cssRules];
|
2988 | }
|
2989 | _c.label = 13;
|
2990 | case 13: return [2, null];
|
2991 | }
|
2992 | });
|
2993 | });
|
2994 | }
|
2995 | function details() {
|
2996 | var rules = getRulesSync();
|
2997 | if (!rules) {
|
2998 | if (isLoadingRules || wasLoadingError) {
|
2999 | return null;
|
3000 | }
|
3001 | isLoadingRules = true;
|
3002 | loadingStart();
|
3003 | getRulesAsync().then(function (results) {
|
3004 | isLoadingRules = false;
|
3005 | loadingEnd();
|
3006 | if (results) {
|
3007 | update();
|
3008 | }
|
3009 | }).catch(function (err) {
|
3010 | logWarn(err);
|
3011 | isLoadingRules = false;
|
3012 | loadingEnd();
|
3013 | });
|
3014 | return null;
|
3015 | }
|
3016 | var variables = getCSSVariables(rules);
|
3017 | return { variables: variables };
|
3018 | }
|
3019 | var forceRenderStyle = false;
|
3020 | function render(theme, variables, ignoreImageAnalysis) {
|
3021 | var rules = getRulesSync();
|
3022 | if (!rules) {
|
3023 | return;
|
3024 | }
|
3025 | cancelAsyncOperations = false;
|
3026 | function prepareOverridesSheet() {
|
3027 | if (!syncStyle) {
|
3028 | createSyncStyle();
|
3029 | }
|
3030 | syncStylePositionWatcher && syncStylePositionWatcher.stop();
|
3031 | insertStyle();
|
3032 | if (syncStyle.sheet == null) {
|
3033 | syncStyle.textContent = '';
|
3034 | }
|
3035 | var sheet = syncStyle.sheet;
|
3036 | for (var i = sheet.cssRules.length - 1; i >= 0; i--) {
|
3037 | sheet.deleteRule(i);
|
3038 | }
|
3039 | if (syncStylePositionWatcher) {
|
3040 | syncStylePositionWatcher.run();
|
3041 | }
|
3042 | else {
|
3043 | syncStylePositionWatcher = watchForNodePosition(syncStyle, 'prev-sibling', function () {
|
3044 | forceRenderStyle = true;
|
3045 | buildOverrides();
|
3046 | });
|
3047 | }
|
3048 | return syncStyle.sheet;
|
3049 | }
|
3050 | function buildOverrides() {
|
3051 | var force = forceRenderStyle;
|
3052 | forceRenderStyle = false;
|
3053 | sheetModifier.modifySheet({
|
3054 | prepareSheet: prepareOverridesSheet,
|
3055 | sourceCSSRules: rules,
|
3056 | theme: theme,
|
3057 | variables: variables,
|
3058 | ignoreImageAnalysis: ignoreImageAnalysis,
|
3059 | force: force,
|
3060 | isAsyncCancelled: function () { return cancelAsyncOperations; },
|
3061 | });
|
3062 | }
|
3063 | buildOverrides();
|
3064 | }
|
3065 | function getRulesOrError() {
|
3066 | try {
|
3067 | if (element.sheet == null) {
|
3068 | return [null, null];
|
3069 | }
|
3070 | return [element.sheet.cssRules, null];
|
3071 | }
|
3072 | catch (err) {
|
3073 | return [null, err];
|
3074 | }
|
3075 | }
|
3076 | function isStillLoadingError(error) {
|
3077 | return error && error.message && error.message.includes('loading');
|
3078 | }
|
3079 | function safeGetSheetRules() {
|
3080 | var _a = __read(getRulesOrError(), 2), cssRules = _a[0], err = _a[1];
|
3081 | if (err) {
|
3082 | logWarn(err);
|
3083 | return null;
|
3084 | }
|
3085 | return cssRules;
|
3086 | }
|
3087 | function watchForSheetChanges() {
|
3088 | watchForSheetChangesUsingProxy();
|
3089 | if (!isThunderbird && !(canOptimizeUsingProxy && element.sheet)) {
|
3090 | watchForSheetChangesUsingRAF();
|
3091 | }
|
3092 | }
|
3093 | var rulesChangeKey = null;
|
3094 | var rulesCheckFrameId = null;
|
3095 | function getRulesChangeKey() {
|
3096 | var rules = safeGetSheetRules();
|
3097 | return rules ? rules.length : null;
|
3098 | }
|
3099 | function didRulesKeyChange() {
|
3100 | return getRulesChangeKey() !== rulesChangeKey;
|
3101 | }
|
3102 | function watchForSheetChangesUsingRAF() {
|
3103 | rulesChangeKey = getRulesChangeKey();
|
3104 | stopWatchingForSheetChangesUsingRAF();
|
3105 | var checkForUpdate = function () {
|
3106 | if (didRulesKeyChange()) {
|
3107 | rulesChangeKey = getRulesChangeKey();
|
3108 | update();
|
3109 | }
|
3110 | if (canOptimizeUsingProxy && element.sheet) {
|
3111 | stopWatchingForSheetChangesUsingRAF();
|
3112 | return;
|
3113 | }
|
3114 | rulesCheckFrameId = requestAnimationFrame(checkForUpdate);
|
3115 | };
|
3116 | checkForUpdate();
|
3117 | }
|
3118 | function stopWatchingForSheetChangesUsingRAF() {
|
3119 | cancelAnimationFrame(rulesCheckFrameId);
|
3120 | }
|
3121 | var areSheetChangesPending = false;
|
3122 | function onSheetChange() {
|
3123 | canOptimizeUsingProxy = true;
|
3124 | stopWatchingForSheetChangesUsingRAF();
|
3125 | if (areSheetChangesPending) {
|
3126 | return;
|
3127 | }
|
3128 | function handleSheetChanges() {
|
3129 | areSheetChangesPending = false;
|
3130 | if (cancelAsyncOperations) {
|
3131 | return;
|
3132 | }
|
3133 | update();
|
3134 | }
|
3135 | areSheetChangesPending = true;
|
3136 | if (typeof queueMicrotask === 'function') {
|
3137 | queueMicrotask(handleSheetChanges);
|
3138 | }
|
3139 | else {
|
3140 | requestAnimationFrame(handleSheetChanges);
|
3141 | }
|
3142 | }
|
3143 | function watchForSheetChangesUsingProxy() {
|
3144 | element.addEventListener('__darkreader__updateSheet', onSheetChange);
|
3145 | }
|
3146 | function stopWatchingForSheetChangesUsingProxy() {
|
3147 | element.removeEventListener('__darkreader__updateSheet', onSheetChange);
|
3148 | }
|
3149 | function stopWatchingForSheetChanges() {
|
3150 | stopWatchingForSheetChangesUsingProxy();
|
3151 | stopWatchingForSheetChangesUsingRAF();
|
3152 | }
|
3153 | function pause() {
|
3154 | observer.disconnect();
|
3155 | cancelAsyncOperations = true;
|
3156 | corsCopyPositionWatcher && corsCopyPositionWatcher.stop();
|
3157 | syncStylePositionWatcher && syncStylePositionWatcher.stop();
|
3158 | stopWatchingForSheetChanges();
|
3159 | }
|
3160 | function destroy() {
|
3161 | pause();
|
3162 | removeNode(corsCopy);
|
3163 | removeNode(syncStyle);
|
3164 | }
|
3165 | function watch() {
|
3166 | observer.observe(element, observerOptions);
|
3167 | if (element instanceof HTMLStyleElement) {
|
3168 | watchForSheetChanges();
|
3169 | }
|
3170 | }
|
3171 | var maxMoveCount = 10;
|
3172 | var moveCount = 0;
|
3173 | function restore() {
|
3174 | if (!syncStyle) {
|
3175 | return;
|
3176 | }
|
3177 | moveCount++;
|
3178 | if (moveCount > maxMoveCount) {
|
3179 | logWarn('Style sheet was moved multiple times', element);
|
3180 | return;
|
3181 | }
|
3182 | logWarn('Restore style', syncStyle, element);
|
3183 | var shouldForceRender = syncStyle.sheet == null || syncStyle.sheet.cssRules.length > 0;
|
3184 | insertStyle();
|
3185 | corsCopyPositionWatcher && corsCopyPositionWatcher.skip();
|
3186 | syncStylePositionWatcher && syncStylePositionWatcher.skip();
|
3187 | if (shouldForceRender) {
|
3188 | forceRenderStyle = true;
|
3189 | update();
|
3190 | }
|
3191 | }
|
3192 | return {
|
3193 | details: details,
|
3194 | render: render,
|
3195 | pause: pause,
|
3196 | destroy: destroy,
|
3197 | watch: watch,
|
3198 | restore: restore,
|
3199 | };
|
3200 | }
|
3201 | function linkLoading(link) {
|
3202 | return __awaiter(this, void 0, void 0, function () {
|
3203 | return __generator(this, function (_a) {
|
3204 | return [2, new Promise(function (resolve, reject) {
|
3205 | var cleanUp = function () {
|
3206 | link.removeEventListener('load', onLoad);
|
3207 | link.removeEventListener('error', onError);
|
3208 | };
|
3209 | var onLoad = function () {
|
3210 | cleanUp();
|
3211 | resolve();
|
3212 | };
|
3213 | var onError = function () {
|
3214 | cleanUp();
|
3215 | reject("Link loading failed " + link.href);
|
3216 | };
|
3217 | link.addEventListener('load', onLoad);
|
3218 | link.addEventListener('error', onError);
|
3219 | })];
|
3220 | });
|
3221 | });
|
3222 | }
|
3223 | function getCSSImportURL(importDeclaration) {
|
3224 | return getCSSURLValue(importDeclaration.substring(8).replace(/;$/, ''));
|
3225 | }
|
3226 | function loadText(url) {
|
3227 | return __awaiter(this, void 0, void 0, function () {
|
3228 | return __generator(this, function (_a) {
|
3229 | switch (_a.label) {
|
3230 | case 0:
|
3231 | if (!url.startsWith('data:')) return [3, 3];
|
3232 | return [4, fetch(url)];
|
3233 | case 1: return [4, (_a.sent()).text()];
|
3234 | case 2: return [2, _a.sent()];
|
3235 | case 3: return [4, bgFetch({ url: url, responseType: 'text', mimeType: 'text/css' })];
|
3236 | case 4: return [2, _a.sent()];
|
3237 | }
|
3238 | });
|
3239 | });
|
3240 | }
|
3241 | function replaceCSSImports(cssText, basePath, cache) {
|
3242 | if (cache === void 0) { cache = new Map(); }
|
3243 | return __awaiter(this, void 0, void 0, function () {
|
3244 | var importMatches, importMatches_1, importMatches_1_1, match, importURL, absoluteURL, importedCSS, err_3, e_1_1;
|
3245 | var e_1, _a;
|
3246 | return __generator(this, function (_b) {
|
3247 | switch (_b.label) {
|
3248 | case 0:
|
3249 | cssText = removeCSSComments(cssText);
|
3250 | cssText = replaceCSSFontFace(cssText);
|
3251 | cssText = replaceCSSRelativeURLsWithAbsolute(cssText, basePath);
|
3252 | importMatches = getMatches(cssImportRegex, cssText);
|
3253 | _b.label = 1;
|
3254 | case 1:
|
3255 | _b.trys.push([1, 10, 11, 12]);
|
3256 | importMatches_1 = __values(importMatches), importMatches_1_1 = importMatches_1.next();
|
3257 | _b.label = 2;
|
3258 | case 2:
|
3259 | if (!!importMatches_1_1.done) return [3, 9];
|
3260 | match = importMatches_1_1.value;
|
3261 | importURL = getCSSImportURL(match);
|
3262 | absoluteURL = getAbsoluteURL(basePath, importURL);
|
3263 | importedCSS = void 0;
|
3264 | if (!cache.has(absoluteURL)) return [3, 3];
|
3265 | importedCSS = cache.get(absoluteURL);
|
3266 | return [3, 7];
|
3267 | case 3:
|
3268 | _b.trys.push([3, 6, , 7]);
|
3269 | return [4, loadText(absoluteURL)];
|
3270 | case 4:
|
3271 | importedCSS = _b.sent();
|
3272 | cache.set(absoluteURL, importedCSS);
|
3273 | return [4, replaceCSSImports(importedCSS, getCSSBaseBath(absoluteURL), cache)];
|
3274 | case 5:
|
3275 | importedCSS = _b.sent();
|
3276 | return [3, 7];
|
3277 | case 6:
|
3278 | err_3 = _b.sent();
|
3279 | logWarn(err_3);
|
3280 | importedCSS = '';
|
3281 | return [3, 7];
|
3282 | case 7:
|
3283 | cssText = cssText.split(match).join(importedCSS);
|
3284 | _b.label = 8;
|
3285 | case 8:
|
3286 | importMatches_1_1 = importMatches_1.next();
|
3287 | return [3, 2];
|
3288 | case 9: return [3, 12];
|
3289 | case 10:
|
3290 | e_1_1 = _b.sent();
|
3291 | e_1 = { error: e_1_1 };
|
3292 | return [3, 12];
|
3293 | case 11:
|
3294 | try {
|
3295 | if (importMatches_1_1 && !importMatches_1_1.done && (_a = importMatches_1.return)) _a.call(importMatches_1);
|
3296 | }
|
3297 | finally { if (e_1) throw e_1.error; }
|
3298 | return [7];
|
3299 | case 12:
|
3300 | cssText = cssText.trim();
|
3301 | return [2, cssText];
|
3302 | }
|
3303 | });
|
3304 | });
|
3305 | }
|
3306 | function createCORSCopy(srcElement, cssText) {
|
3307 | if (!cssText) {
|
3308 | return null;
|
3309 | }
|
3310 | var cors = document.createElement('style');
|
3311 | cors.classList.add('darkreader');
|
3312 | cors.classList.add('darkreader--cors');
|
3313 | cors.media = 'screen';
|
3314 | cors.textContent = cssText;
|
3315 | srcElement.parentNode.insertBefore(cors, srcElement.nextSibling);
|
3316 | cors.sheet.disabled = true;
|
3317 | corsStyleSet.add(cors);
|
3318 | return cors;
|
3319 | }
|
3320 |
|
3321 | var observers = [];
|
3322 | var observedRoots;
|
3323 | var undefinedGroups = new Map();
|
3324 | var elementsDefinitionCallback;
|
3325 | function collectUndefinedElements(root) {
|
3326 | if (!isDefinedSelectorSupported) {
|
3327 | return;
|
3328 | }
|
3329 | forEach(root.querySelectorAll(':not(:defined)'), function (el) {
|
3330 | var tag = el.tagName.toLowerCase();
|
3331 | if (!undefinedGroups.has(tag)) {
|
3332 | undefinedGroups.set(tag, new Set());
|
3333 | customElementsWhenDefined(tag).then(function () {
|
3334 | if (elementsDefinitionCallback) {
|
3335 | var elements = undefinedGroups.get(tag);
|
3336 | undefinedGroups.delete(tag);
|
3337 | elementsDefinitionCallback(Array.from(elements));
|
3338 | }
|
3339 | });
|
3340 | }
|
3341 | undefinedGroups.get(tag).add(el);
|
3342 | });
|
3343 | }
|
3344 | var canOptimizeUsingProxy$1 = false;
|
3345 | document.addEventListener('__darkreader__inlineScriptsAllowed', function () {
|
3346 | canOptimizeUsingProxy$1 = true;
|
3347 | });
|
3348 | var resolvers$1 = new Map();
|
3349 | function handleIsDefined(e) {
|
3350 | canOptimizeUsingProxy$1 = true;
|
3351 | if (resolvers$1.has(e.detail.tag)) {
|
3352 | var resolve = resolvers$1.get(e.detail.tag);
|
3353 | resolve();
|
3354 | }
|
3355 | }
|
3356 | function customElementsWhenDefined(tag) {
|
3357 | return __awaiter(this, void 0, void 0, function () {
|
3358 | return __generator(this, function (_a) {
|
3359 | return [2, new Promise(function (resolve) {
|
3360 | if (window.customElements && typeof customElements.whenDefined === 'function') {
|
3361 | customElements.whenDefined(tag).then(resolve);
|
3362 | }
|
3363 | else if (canOptimizeUsingProxy$1) {
|
3364 | resolvers$1.set(tag, resolve);
|
3365 | document.dispatchEvent(new CustomEvent('__darkreader__addUndefinedResolver', { detail: { tag: tag } }));
|
3366 | }
|
3367 | else {
|
3368 | var checkIfDefined_1 = function () {
|
3369 | var elements = undefinedGroups.get(tag);
|
3370 | if (elements && elements.size > 0) {
|
3371 | if (elements.values().next().value.matches(':defined')) {
|
3372 | resolve();
|
3373 | }
|
3374 | else {
|
3375 | requestAnimationFrame(checkIfDefined_1);
|
3376 | }
|
3377 | }
|
3378 | };
|
3379 | requestAnimationFrame(checkIfDefined_1);
|
3380 | }
|
3381 | })];
|
3382 | });
|
3383 | });
|
3384 | }
|
3385 | function watchWhenCustomElementsDefined(callback) {
|
3386 | elementsDefinitionCallback = callback;
|
3387 | }
|
3388 | function unsubscribeFromDefineCustomElements() {
|
3389 | elementsDefinitionCallback = null;
|
3390 | undefinedGroups.clear();
|
3391 | document.removeEventListener('__darkreader__isDefined', handleIsDefined);
|
3392 | }
|
3393 | function watchForStyleChanges(currentStyles, update, shadowRootDiscovered) {
|
3394 | stopWatchingForStyleChanges();
|
3395 | var prevStyles = new Set(currentStyles);
|
3396 | var prevStyleSiblings = new WeakMap();
|
3397 | var nextStyleSiblings = new WeakMap();
|
3398 | function saveStylePosition(style) {
|
3399 | prevStyleSiblings.set(style, style.previousElementSibling);
|
3400 | nextStyleSiblings.set(style, style.nextElementSibling);
|
3401 | }
|
3402 | function forgetStylePosition(style) {
|
3403 | prevStyleSiblings.delete(style);
|
3404 | nextStyleSiblings.delete(style);
|
3405 | }
|
3406 | function didStylePositionChange(style) {
|
3407 | return (style.previousElementSibling !== prevStyleSiblings.get(style) ||
|
3408 | style.nextElementSibling !== nextStyleSiblings.get(style));
|
3409 | }
|
3410 | currentStyles.forEach(saveStylePosition);
|
3411 | function handleStyleOperations(operations) {
|
3412 | var createdStyles = operations.createdStyles, removedStyles = operations.removedStyles, movedStyles = operations.movedStyles;
|
3413 | createdStyles.forEach(function (s) { return saveStylePosition(s); });
|
3414 | movedStyles.forEach(function (s) { return saveStylePosition(s); });
|
3415 | removedStyles.forEach(function (s) { return forgetStylePosition(s); });
|
3416 | createdStyles.forEach(function (s) { return prevStyles.add(s); });
|
3417 | removedStyles.forEach(function (s) { return prevStyles.delete(s); });
|
3418 | if (createdStyles.size + removedStyles.size + movedStyles.size > 0) {
|
3419 | update({
|
3420 | created: Array.from(createdStyles),
|
3421 | removed: Array.from(removedStyles),
|
3422 | moved: Array.from(movedStyles),
|
3423 | updated: [],
|
3424 | });
|
3425 | }
|
3426 | }
|
3427 | function handleMinorTreeMutations(_a) {
|
3428 | var additions = _a.additions, moves = _a.moves, deletions = _a.deletions;
|
3429 | var createdStyles = new Set();
|
3430 | var removedStyles = new Set();
|
3431 | var movedStyles = new Set();
|
3432 | additions.forEach(function (node) { return getManageableStyles(node).forEach(function (style) { return createdStyles.add(style); }); });
|
3433 | deletions.forEach(function (node) { return getManageableStyles(node).forEach(function (style) { return removedStyles.add(style); }); });
|
3434 | moves.forEach(function (node) { return getManageableStyles(node).forEach(function (style) { return movedStyles.add(style); }); });
|
3435 | handleStyleOperations({ createdStyles: createdStyles, removedStyles: removedStyles, movedStyles: movedStyles });
|
3436 | additions.forEach(function (n) {
|
3437 | iterateShadowHosts(n, subscribeForShadowRootChanges);
|
3438 | collectUndefinedElements(n);
|
3439 | });
|
3440 | }
|
3441 | function handleHugeTreeMutations(root) {
|
3442 | var styles = new Set(getManageableStyles(root));
|
3443 | var createdStyles = new Set();
|
3444 | var removedStyles = new Set();
|
3445 | var movedStyles = new Set();
|
3446 | styles.forEach(function (s) {
|
3447 | if (!prevStyles.has(s)) {
|
3448 | createdStyles.add(s);
|
3449 | }
|
3450 | });
|
3451 | prevStyles.forEach(function (s) {
|
3452 | if (!styles.has(s)) {
|
3453 | removedStyles.add(s);
|
3454 | }
|
3455 | });
|
3456 | styles.forEach(function (s) {
|
3457 | if (!createdStyles.has(s) && !removedStyles.has(s) && didStylePositionChange(s)) {
|
3458 | movedStyles.add(s);
|
3459 | }
|
3460 | });
|
3461 | handleStyleOperations({ createdStyles: createdStyles, removedStyles: removedStyles, movedStyles: movedStyles });
|
3462 | iterateShadowHosts(root, subscribeForShadowRootChanges);
|
3463 | collectUndefinedElements(root);
|
3464 | }
|
3465 | function handleAttributeMutations(mutations) {
|
3466 | var updatedStyles = new Set();
|
3467 | var removedStyles = new Set();
|
3468 | mutations.forEach(function (m) {
|
3469 | var target = m.target;
|
3470 | if (target.isConnected) {
|
3471 | if (shouldManageStyle(target)) {
|
3472 | updatedStyles.add(target);
|
3473 | }
|
3474 | else if (target instanceof HTMLLinkElement && target.disabled) {
|
3475 | removedStyles.add(target);
|
3476 | }
|
3477 | }
|
3478 | });
|
3479 | if (updatedStyles.size + removedStyles.size > 0) {
|
3480 | update({
|
3481 | updated: Array.from(updatedStyles),
|
3482 | created: [],
|
3483 | removed: Array.from(removedStyles),
|
3484 | moved: [],
|
3485 | });
|
3486 | }
|
3487 | }
|
3488 | function observe(root) {
|
3489 | var treeObserver = createOptimizedTreeObserver(root, {
|
3490 | onMinorMutations: handleMinorTreeMutations,
|
3491 | onHugeMutations: handleHugeTreeMutations,
|
3492 | });
|
3493 | var attrObserver = new MutationObserver(handleAttributeMutations);
|
3494 | attrObserver.observe(root, { attributes: true, attributeFilter: ['rel', 'disabled', 'media'], subtree: true });
|
3495 | observers.push(treeObserver, attrObserver);
|
3496 | observedRoots.add(root);
|
3497 | }
|
3498 | function subscribeForShadowRootChanges(node) {
|
3499 | var shadowRoot = node.shadowRoot;
|
3500 | if (shadowRoot == null || observedRoots.has(shadowRoot)) {
|
3501 | return;
|
3502 | }
|
3503 | observe(shadowRoot);
|
3504 | shadowRootDiscovered(shadowRoot);
|
3505 | }
|
3506 | observe(document);
|
3507 | iterateShadowHosts(document.documentElement, subscribeForShadowRootChanges);
|
3508 | watchWhenCustomElementsDefined(function (hosts) {
|
3509 | var newStyles = [];
|
3510 | hosts.forEach(function (host) { return push(newStyles, getManageableStyles(host.shadowRoot)); });
|
3511 | update({ created: newStyles, updated: [], removed: [], moved: [] });
|
3512 | hosts.forEach(function (host) {
|
3513 | var shadowRoot = host.shadowRoot;
|
3514 | if (shadowRoot == null) {
|
3515 | return;
|
3516 | }
|
3517 | subscribeForShadowRootChanges(host);
|
3518 | iterateShadowHosts(shadowRoot, subscribeForShadowRootChanges);
|
3519 | collectUndefinedElements(shadowRoot);
|
3520 | });
|
3521 | });
|
3522 | document.addEventListener('__darkreader__isDefined', handleIsDefined);
|
3523 | collectUndefinedElements(document);
|
3524 | }
|
3525 | function resetObservers() {
|
3526 | observers.forEach(function (o) { return o.disconnect(); });
|
3527 | observers.splice(0, observers.length);
|
3528 | observedRoots = new WeakSet();
|
3529 | }
|
3530 | function stopWatchingForStyleChanges() {
|
3531 | resetObservers();
|
3532 | unsubscribeFromDefineCustomElements();
|
3533 | }
|
3534 |
|
3535 | function hexify(number) {
|
3536 | return ((number < 16 ? '0' : '') + number.toString(16));
|
3537 | }
|
3538 | function generateUID() {
|
3539 | return Array.from(crypto.getRandomValues(new Uint8Array(16))).map(function (x) { return hexify(x); }).join('');
|
3540 | }
|
3541 |
|
3542 | var adoptedStyleOverrides = new WeakMap();
|
3543 | var overrideList = new WeakSet();
|
3544 | function createAdoptedStyleSheetOverride(node) {
|
3545 | var cancelAsyncOperations = false;
|
3546 | function injectSheet(sheet, override) {
|
3547 | var newSheets = __spread(node.adoptedStyleSheets);
|
3548 | var sheetIndex = newSheets.indexOf(sheet);
|
3549 | var existingIndex = newSheets.indexOf(override);
|
3550 | if (sheetIndex === existingIndex - 1) {
|
3551 | return;
|
3552 | }
|
3553 | if (existingIndex >= 0) {
|
3554 | newSheets.splice(existingIndex, 1);
|
3555 | }
|
3556 | newSheets.splice(sheetIndex + 1, 0, override);
|
3557 | node.adoptedStyleSheets = newSheets;
|
3558 | }
|
3559 | function destroy() {
|
3560 | cancelAsyncOperations = true;
|
3561 | var newSheets = __spread(node.adoptedStyleSheets);
|
3562 | node.adoptedStyleSheets.forEach(function (adoptedStyleSheet) {
|
3563 | if (overrideList.has(adoptedStyleSheet)) {
|
3564 | var existingIndex = newSheets.indexOf(adoptedStyleSheet);
|
3565 | if (existingIndex >= 0) {
|
3566 | newSheets.splice(existingIndex, 1);
|
3567 | }
|
3568 | adoptedStyleOverrides.delete(adoptedStyleSheet);
|
3569 | overrideList.delete(adoptedStyleSheet);
|
3570 | }
|
3571 | });
|
3572 | node.adoptedStyleSheets = newSheets;
|
3573 | }
|
3574 | function render(theme, globalVariables, ignoreImageAnalysis) {
|
3575 | node.adoptedStyleSheets.forEach(function (sheet) {
|
3576 | if (overrideList.has(sheet)) {
|
3577 | return;
|
3578 | }
|
3579 | var rules = sheet.rules;
|
3580 | var override = new CSSStyleSheet();
|
3581 | function prepareOverridesSheet() {
|
3582 | for (var i = override.cssRules.length - 1; i >= 0; i--) {
|
3583 | override.deleteRule(i);
|
3584 | }
|
3585 | injectSheet(sheet, override);
|
3586 | adoptedStyleOverrides.set(sheet, override);
|
3587 | overrideList.add(override);
|
3588 | return override;
|
3589 | }
|
3590 | var variables = globalVariables;
|
3591 | getCSSVariables(sheet.cssRules).forEach(function (value, key) { return variables.set(key, value); });
|
3592 | var sheetModifier = createStyleSheetModifier();
|
3593 | sheetModifier.modifySheet({
|
3594 | prepareSheet: prepareOverridesSheet,
|
3595 | sourceCSSRules: rules,
|
3596 | theme: theme,
|
3597 | variables: variables,
|
3598 | ignoreImageAnalysis: ignoreImageAnalysis,
|
3599 | force: false,
|
3600 | isAsyncCancelled: function () { return cancelAsyncOperations; },
|
3601 | });
|
3602 | });
|
3603 | }
|
3604 | return {
|
3605 | render: render,
|
3606 | destroy: destroy
|
3607 | };
|
3608 | }
|
3609 |
|
3610 | function injectProxy() {
|
3611 | document.dispatchEvent(new CustomEvent('__darkreader__inlineScriptsAllowed'));
|
3612 | var addRuleDescriptor = Object.getOwnPropertyDescriptor(CSSStyleSheet.prototype, 'addRule');
|
3613 | var insertRuleDescriptor = Object.getOwnPropertyDescriptor(CSSStyleSheet.prototype, 'insertRule');
|
3614 | var deleteRuleDescriptor = Object.getOwnPropertyDescriptor(CSSStyleSheet.prototype, 'deleteRule');
|
3615 | var removeRuleDescriptor = Object.getOwnPropertyDescriptor(CSSStyleSheet.prototype, 'removeRule');
|
3616 | var cleanUp = function () {
|
3617 | Object.defineProperty(CSSStyleSheet.prototype, 'addRule', addRuleDescriptor);
|
3618 | Object.defineProperty(CSSStyleSheet.prototype, 'insertRule', insertRuleDescriptor);
|
3619 | Object.defineProperty(CSSStyleSheet.prototype, 'deleteRule', deleteRuleDescriptor);
|
3620 | Object.defineProperty(CSSStyleSheet.prototype, 'removeRule', removeRuleDescriptor);
|
3621 | document.removeEventListener('__darkreader__cleanUp', cleanUp);
|
3622 | document.removeEventListener('__darkreader__addUndefinedResolver', addUndefinedResolver);
|
3623 | };
|
3624 | var addUndefinedResolver = function (e) {
|
3625 | customElements.whenDefined(e.detail.tag).then(function () {
|
3626 | document.dispatchEvent(new CustomEvent('__darkreader__isDefined', { detail: { tag: e.detail.tag } }));
|
3627 | });
|
3628 | };
|
3629 | document.addEventListener('__darkreader__cleanUp', cleanUp);
|
3630 | document.addEventListener('__darkreader__addUndefinedResolver', addUndefinedResolver);
|
3631 | var updateSheetEvent = new Event('__darkreader__updateSheet');
|
3632 | function proxyAddRule(selector, style, index) {
|
3633 | addRuleDescriptor.value.call(this, selector, style, index);
|
3634 | if (this.ownerNode && !this.ownerNode.classList.contains('darkreader')) {
|
3635 | this.ownerNode.dispatchEvent(updateSheetEvent);
|
3636 | }
|
3637 | return -1;
|
3638 | }
|
3639 | function proxyInsertRule(rule, index) {
|
3640 | var returnValue = insertRuleDescriptor.value.call(this, rule, index);
|
3641 | if (this.ownerNode && !this.ownerNode.classList.contains('darkreader')) {
|
3642 | this.ownerNode.dispatchEvent(updateSheetEvent);
|
3643 | }
|
3644 | return returnValue;
|
3645 | }
|
3646 | function proxyDeleteRule(index) {
|
3647 | deleteRuleDescriptor.value.call(this, index);
|
3648 | if (this.ownerNode && !this.ownerNode.classList.contains('darkreader')) {
|
3649 | this.ownerNode.dispatchEvent(updateSheetEvent);
|
3650 | }
|
3651 | }
|
3652 | function proxyRemoveRule(index) {
|
3653 | removeRuleDescriptor.value.call(this, index);
|
3654 | if (this.ownerNode && !this.ownerNode.classList.contains('darkreader')) {
|
3655 | this.ownerNode.dispatchEvent(updateSheetEvent);
|
3656 | }
|
3657 | }
|
3658 | Object.defineProperty(CSSStyleSheet.prototype, 'addRule', Object.assign({}, addRuleDescriptor, { value: proxyAddRule }));
|
3659 | Object.defineProperty(CSSStyleSheet.prototype, 'insertRule', Object.assign({}, insertRuleDescriptor, { value: proxyInsertRule }));
|
3660 | Object.defineProperty(CSSStyleSheet.prototype, 'deleteRule', Object.assign({}, deleteRuleDescriptor, { value: proxyDeleteRule }));
|
3661 | Object.defineProperty(CSSStyleSheet.prototype, 'removeRule', Object.assign({}, removeRuleDescriptor, { value: proxyRemoveRule }));
|
3662 | }
|
3663 |
|
3664 | var variables = new Map();
|
3665 | var INSTANCE_ID = generateUID();
|
3666 | var styleManagers = new Map();
|
3667 | var adoptedStyleManagers = [];
|
3668 | var filter = null;
|
3669 | var fixes = null;
|
3670 | var isIFrame = null;
|
3671 | var ignoredImageAnalysisSelectors = null;
|
3672 | var ignoredInlineSelectors = null;
|
3673 | function createOrUpdateStyle(className, root) {
|
3674 | if (root === void 0) { root = document.head || document; }
|
3675 | var element = root.querySelector("." + className);
|
3676 | if (!element) {
|
3677 | element = document.createElement('style');
|
3678 | element.classList.add('darkreader');
|
3679 | element.classList.add(className);
|
3680 | element.media = 'screen';
|
3681 | }
|
3682 | return element;
|
3683 | }
|
3684 | function createOrUpdateScript(className, root) {
|
3685 | if (root === void 0) { root = document.head || document; }
|
3686 | var element = root.querySelector("." + className);
|
3687 | if (!element) {
|
3688 | element = document.createElement('script');
|
3689 | element.classList.add('darkreader');
|
3690 | element.classList.add(className);
|
3691 | }
|
3692 | return element;
|
3693 | }
|
3694 | var nodePositionWatchers = new Map();
|
3695 | function setupNodePositionWatcher(node, alias) {
|
3696 | nodePositionWatchers.has(alias) && nodePositionWatchers.get(alias).stop();
|
3697 | nodePositionWatchers.set(alias, watchForNodePosition(node, 'parent'));
|
3698 | }
|
3699 | function stopStylePositionWatchers() {
|
3700 | forEach(nodePositionWatchers.values(), function (watcher) { return watcher.stop(); });
|
3701 | nodePositionWatchers.clear();
|
3702 | }
|
3703 | function createStaticStyleOverrides() {
|
3704 | var fallbackStyle = createOrUpdateStyle('darkreader--fallback', document);
|
3705 | fallbackStyle.textContent = getModifiedFallbackStyle(filter, { strict: true });
|
3706 | document.head.insertBefore(fallbackStyle, document.head.firstChild);
|
3707 | setupNodePositionWatcher(fallbackStyle, 'fallback');
|
3708 | var userAgentStyle = createOrUpdateStyle('darkreader--user-agent');
|
3709 | userAgentStyle.textContent = getModifiedUserAgentStyle(filter, isIFrame, filter.styleSystemControls);
|
3710 | document.head.insertBefore(userAgentStyle, fallbackStyle.nextSibling);
|
3711 | setupNodePositionWatcher(userAgentStyle, 'user-agent');
|
3712 | var textStyle = createOrUpdateStyle('darkreader--text');
|
3713 | if (filter.useFont || filter.textStroke > 0) {
|
3714 | textStyle.textContent = createTextStyle(filter);
|
3715 | }
|
3716 | else {
|
3717 | textStyle.textContent = '';
|
3718 | }
|
3719 | document.head.insertBefore(textStyle, fallbackStyle.nextSibling);
|
3720 | setupNodePositionWatcher(textStyle, 'text');
|
3721 | var invertStyle = createOrUpdateStyle('darkreader--invert');
|
3722 | if (fixes && Array.isArray(fixes.invert) && fixes.invert.length > 0) {
|
3723 | invertStyle.textContent = [
|
3724 | fixes.invert.join(', ') + " {",
|
3725 | " filter: " + getCSSFilterValue(__assign(__assign({}, filter), { contrast: filter.mode === 0 ? filter.contrast : clamp(filter.contrast - 10, 0, 100) })) + " !important;",
|
3726 | '}',
|
3727 | ].join('\n');
|
3728 | }
|
3729 | else {
|
3730 | invertStyle.textContent = '';
|
3731 | }
|
3732 | document.head.insertBefore(invertStyle, textStyle.nextSibling);
|
3733 | setupNodePositionWatcher(invertStyle, 'invert');
|
3734 | var inlineStyle = createOrUpdateStyle('darkreader--inline');
|
3735 | inlineStyle.textContent = getInlineOverrideStyle();
|
3736 | document.head.insertBefore(inlineStyle, invertStyle.nextSibling);
|
3737 | setupNodePositionWatcher(inlineStyle, 'inline');
|
3738 | var overrideStyle = createOrUpdateStyle('darkreader--override');
|
3739 | overrideStyle.textContent = fixes && fixes.css ? replaceCSSTemplates(fixes.css) : '';
|
3740 | document.head.appendChild(overrideStyle);
|
3741 | setupNodePositionWatcher(overrideStyle, 'override');
|
3742 | var variableStyle = createOrUpdateStyle('darkreader--variables');
|
3743 | var selectionColors = getSelectionColor(filter);
|
3744 | var darkSchemeBackgroundColor = filter.darkSchemeBackgroundColor, darkSchemeTextColor = filter.darkSchemeTextColor, lightSchemeBackgroundColor = filter.lightSchemeBackgroundColor, lightSchemeTextColor = filter.lightSchemeTextColor, mode = filter.mode;
|
3745 | var schemeBackgroundColor = mode === 0 ? lightSchemeBackgroundColor : darkSchemeBackgroundColor;
|
3746 | var schemeTextColor = mode === 0 ? lightSchemeTextColor : darkSchemeTextColor;
|
3747 | schemeBackgroundColor = modifyBackgroundColor(parse(schemeBackgroundColor), filter);
|
3748 | schemeTextColor = modifyForegroundColor(parse(schemeTextColor), filter);
|
3749 | variableStyle.textContent = [
|
3750 | ":root {",
|
3751 | " --darkreader-neutral-background: " + schemeBackgroundColor + ";",
|
3752 | " --darkreader-neutral-text: " + schemeTextColor + ";",
|
3753 | " --darkreader-selection-background: " + selectionColors.backgroundColorSelection + ";",
|
3754 | " --darkreader-selection-text: " + selectionColors.foregroundColorSelection + ";",
|
3755 | "}"
|
3756 | ].join('\n');
|
3757 | document.head.insertBefore(variableStyle, inlineStyle.nextSibling);
|
3758 | setupNodePositionWatcher(variableStyle, 'variables');
|
3759 | var proxyScript = createOrUpdateScript('darkreader--proxy');
|
3760 | proxyScript.textContent = "(" + injectProxy + ")()";
|
3761 | document.head.insertBefore(proxyScript, variableStyle.nextSibling);
|
3762 | }
|
3763 | var shadowRootsWithOverrides = new Set();
|
3764 | function createShadowStaticStyleOverrides(root) {
|
3765 | var inlineStyle = createOrUpdateStyle('darkreader--inline', root);
|
3766 | inlineStyle.textContent = getInlineOverrideStyle();
|
3767 | root.insertBefore(inlineStyle, root.firstChild);
|
3768 | var overrideStyle = createOrUpdateStyle('darkreader--override', root);
|
3769 | overrideStyle.textContent = fixes && fixes.css ? replaceCSSTemplates(fixes.css) : '';
|
3770 | root.insertBefore(overrideStyle, inlineStyle.nextSibling);
|
3771 | shadowRootsWithOverrides.add(root);
|
3772 | }
|
3773 | function replaceCSSTemplates($cssText) {
|
3774 | return $cssText.replace(/\${(.+?)}/g, function (m0, $color) {
|
3775 | try {
|
3776 | var color = parseColorWithCache($color);
|
3777 | return modifyColor(color, filter);
|
3778 | }
|
3779 | catch (err) {
|
3780 | logWarn(err);
|
3781 | return $color;
|
3782 | }
|
3783 | });
|
3784 | }
|
3785 | function cleanFallbackStyle() {
|
3786 | var fallback = document.querySelector('.darkreader--fallback');
|
3787 | if (fallback) {
|
3788 | fallback.textContent = '';
|
3789 | }
|
3790 | }
|
3791 | function createDynamicStyleOverrides() {
|
3792 | cancelRendering();
|
3793 | updateVariables(getElementCSSVariables(document.documentElement));
|
3794 | var allStyles = getManageableStyles(document);
|
3795 | var newManagers = allStyles
|
3796 | .filter(function (style) { return !styleManagers.has(style); })
|
3797 | .map(function (style) { return createManager(style); });
|
3798 | var newVariables = newManagers
|
3799 | .map(function (manager) { return manager.details(); })
|
3800 | .filter(function (details) { return details && details.variables.size > 0; })
|
3801 | .map(function (_a) {
|
3802 | var variables = _a.variables;
|
3803 | return variables;
|
3804 | });
|
3805 | if (newVariables.length === 0) {
|
3806 | styleManagers.forEach(function (manager) { return manager.render(filter, variables, ignoredImageAnalysisSelectors); });
|
3807 | if (loadingStyles.size === 0) {
|
3808 | cleanFallbackStyle();
|
3809 | }
|
3810 | }
|
3811 | else {
|
3812 | newVariables.forEach(function (variables) { return updateVariables(variables); });
|
3813 | throttledRenderAllStyles(function () {
|
3814 | if (loadingStyles.size === 0) {
|
3815 | cleanFallbackStyle();
|
3816 | }
|
3817 | });
|
3818 | }
|
3819 | newManagers.forEach(function (manager) { return manager.watch(); });
|
3820 | var inlineStyleElements = toArray(document.querySelectorAll(INLINE_STYLE_SELECTOR));
|
3821 | iterateShadowHosts(document.documentElement, function (host) {
|
3822 | createShadowStaticStyleOverrides(host.shadowRoot);
|
3823 | var elements = host.shadowRoot.querySelectorAll(INLINE_STYLE_SELECTOR);
|
3824 | if (elements.length > 0) {
|
3825 | push(inlineStyleElements, elements);
|
3826 | }
|
3827 | });
|
3828 | inlineStyleElements.forEach(function (el) { return overrideInlineStyle(el, filter, ignoredInlineSelectors, ignoredImageAnalysisSelectors); });
|
3829 | handleAdoptedStyleSheets(document);
|
3830 | }
|
3831 | var loadingStylesCounter = 0;
|
3832 | var loadingStyles = new Set();
|
3833 | function createManager(element) {
|
3834 | var loadingStyleId = ++loadingStylesCounter;
|
3835 | function loadingStart() {
|
3836 | if (!isDOMReady() || !didDocumentShowUp) {
|
3837 | loadingStyles.add(loadingStyleId);
|
3838 | var fallbackStyle = document.querySelector('.darkreader--fallback');
|
3839 | if (!fallbackStyle.textContent) {
|
3840 | fallbackStyle.textContent = getModifiedFallbackStyle(filter, { strict: false });
|
3841 | }
|
3842 | }
|
3843 | }
|
3844 | function loadingEnd() {
|
3845 | loadingStyles.delete(loadingStyleId);
|
3846 | if (loadingStyles.size === 0 && isDOMReady()) {
|
3847 | cleanFallbackStyle();
|
3848 | }
|
3849 | }
|
3850 | function update() {
|
3851 | var details = manager.details();
|
3852 | if (!details) {
|
3853 | return;
|
3854 | }
|
3855 | if (details.variables.size === 0) {
|
3856 | manager.render(filter, variables, ignoredImageAnalysisSelectors);
|
3857 | }
|
3858 | else {
|
3859 | updateVariables(details.variables);
|
3860 | throttledRenderAllStyles();
|
3861 | }
|
3862 | }
|
3863 | var manager = manageStyle(element, { update: update, loadingStart: loadingStart, loadingEnd: loadingEnd });
|
3864 | styleManagers.set(element, manager);
|
3865 | return manager;
|
3866 | }
|
3867 | function updateVariables(newVars) {
|
3868 | if (newVars.size === 0) {
|
3869 | return;
|
3870 | }
|
3871 | newVars.forEach(function (value, key) {
|
3872 | variables.set(key, value);
|
3873 | });
|
3874 | variables.forEach(function (value, key) {
|
3875 | variables.set(key, replaceCSSVariables(value, variables));
|
3876 | });
|
3877 | }
|
3878 | function removeManager(element) {
|
3879 | var manager = styleManagers.get(element);
|
3880 | if (manager) {
|
3881 | manager.destroy();
|
3882 | styleManagers.delete(element);
|
3883 | }
|
3884 | }
|
3885 | var throttledRenderAllStyles = throttle(function (callback) {
|
3886 | styleManagers.forEach(function (manager) { return manager.render(filter, variables, ignoredImageAnalysisSelectors); });
|
3887 | adoptedStyleManagers.forEach(function (manager) { return manager.render(filter, variables, ignoredImageAnalysisSelectors); });
|
3888 | callback && callback();
|
3889 | });
|
3890 | var cancelRendering = function () {
|
3891 | throttledRenderAllStyles.cancel();
|
3892 | };
|
3893 | function onDOMReady() {
|
3894 | if (loadingStyles.size === 0) {
|
3895 | cleanFallbackStyle();
|
3896 | }
|
3897 | }
|
3898 | var documentVisibilityListener = null;
|
3899 | var didDocumentShowUp = !document.hidden;
|
3900 | function watchForDocumentVisibility(callback) {
|
3901 | var alreadyWatching = Boolean(documentVisibilityListener);
|
3902 | documentVisibilityListener = function () {
|
3903 | if (!document.hidden) {
|
3904 | stopWatchingForDocumentVisibility();
|
3905 | callback();
|
3906 | didDocumentShowUp = true;
|
3907 | }
|
3908 | };
|
3909 | if (!alreadyWatching) {
|
3910 | document.addEventListener('visibilitychange', documentVisibilityListener);
|
3911 | }
|
3912 | }
|
3913 | function stopWatchingForDocumentVisibility() {
|
3914 | document.removeEventListener('visibilitychange', documentVisibilityListener);
|
3915 | documentVisibilityListener = null;
|
3916 | }
|
3917 | function createThemeAndWatchForUpdates() {
|
3918 | createStaticStyleOverrides();
|
3919 | function runDynamicStyle() {
|
3920 | createDynamicStyleOverrides();
|
3921 | watchForUpdates();
|
3922 | }
|
3923 | if (document.hidden) {
|
3924 | watchForDocumentVisibility(runDynamicStyle);
|
3925 | }
|
3926 | else {
|
3927 | runDynamicStyle();
|
3928 | }
|
3929 | changeMetaThemeColorWhenAvailable(filter);
|
3930 | }
|
3931 | function handleAdoptedStyleSheets(node) {
|
3932 | if (Array.isArray(node.adoptedStyleSheets)) {
|
3933 | if (node.adoptedStyleSheets.length > 0) {
|
3934 | var newManger = createAdoptedStyleSheetOverride(node);
|
3935 | adoptedStyleManagers.push(newManger);
|
3936 | newManger.render(filter, variables, ignoredImageAnalysisSelectors);
|
3937 | }
|
3938 | }
|
3939 | }
|
3940 | function watchForUpdates() {
|
3941 | var managedStyles = Array.from(styleManagers.keys());
|
3942 | watchForStyleChanges(managedStyles, function (_a) {
|
3943 | var created = _a.created, updated = _a.updated, removed = _a.removed, moved = _a.moved;
|
3944 | var stylesToRemove = removed;
|
3945 | var stylesToManage = created.concat(updated).concat(moved)
|
3946 | .filter(function (style) { return !styleManagers.has(style); });
|
3947 | var stylesToRestore = moved
|
3948 | .filter(function (style) { return styleManagers.has(style); });
|
3949 | stylesToRemove.forEach(function (style) { return removeManager(style); });
|
3950 | var newManagers = stylesToManage
|
3951 | .map(function (style) { return createManager(style); });
|
3952 | var newVariables = newManagers
|
3953 | .map(function (manager) { return manager.details(); })
|
3954 | .filter(function (details) { return details && details.variables.size > 0; })
|
3955 | .map(function (_a) {
|
3956 | var variables = _a.variables;
|
3957 | return variables;
|
3958 | });
|
3959 | if (newVariables.length === 0) {
|
3960 | newManagers.forEach(function (manager) { return manager.render(filter, variables, ignoredImageAnalysisSelectors); });
|
3961 | }
|
3962 | else {
|
3963 | newVariables.forEach(function (variables) { return updateVariables(variables); });
|
3964 | throttledRenderAllStyles();
|
3965 | }
|
3966 | newManagers.forEach(function (manager) { return manager.watch(); });
|
3967 | stylesToRestore.forEach(function (style) { return styleManagers.get(style).restore(); });
|
3968 | }, function (shadowRoot) {
|
3969 | createShadowStaticStyleOverrides(shadowRoot);
|
3970 | handleAdoptedStyleSheets(shadowRoot);
|
3971 | });
|
3972 | watchForInlineStyles(function (element) {
|
3973 | overrideInlineStyle(element, filter, ignoredInlineSelectors, ignoredImageAnalysisSelectors);
|
3974 | if (element === document.documentElement) {
|
3975 | var rootVariables = getElementCSSVariables(document.documentElement);
|
3976 | if (rootVariables.size > 0) {
|
3977 | updateVariables(rootVariables);
|
3978 | throttledRenderAllStyles();
|
3979 | }
|
3980 | }
|
3981 | }, function (root) {
|
3982 | createShadowStaticStyleOverrides(root);
|
3983 | var inlineStyleElements = root.querySelectorAll(INLINE_STYLE_SELECTOR);
|
3984 | if (inlineStyleElements.length > 0) {
|
3985 | forEach(inlineStyleElements, function (el) { return overrideInlineStyle(el, filter, ignoredInlineSelectors, ignoredImageAnalysisSelectors); });
|
3986 | }
|
3987 | });
|
3988 | addDOMReadyListener(onDOMReady);
|
3989 | }
|
3990 | function stopWatchingForUpdates() {
|
3991 | styleManagers.forEach(function (manager) { return manager.pause(); });
|
3992 | stopStylePositionWatchers();
|
3993 | stopWatchingForStyleChanges();
|
3994 | stopWatchingForInlineStyles();
|
3995 | removeDOMReadyListener(onDOMReady);
|
3996 | }
|
3997 | function createDarkReaderInstanceMarker() {
|
3998 | var metaElement = document.createElement('meta');
|
3999 | metaElement.name = 'darkreader';
|
4000 | metaElement.content = INSTANCE_ID;
|
4001 | document.head.appendChild(metaElement);
|
4002 | }
|
4003 | function isAnotherDarkReaderInstanceActive() {
|
4004 | var meta = document.querySelector('meta[name="darkreader"]');
|
4005 | if (meta) {
|
4006 | if (meta.content !== INSTANCE_ID) {
|
4007 | return true;
|
4008 | }
|
4009 | return false;
|
4010 | }
|
4011 | else {
|
4012 | createDarkReaderInstanceMarker();
|
4013 | return false;
|
4014 | }
|
4015 | }
|
4016 | function createOrUpdateDynamicTheme(filterConfig, dynamicThemeFixes, iframe) {
|
4017 | filter = filterConfig;
|
4018 | fixes = dynamicThemeFixes;
|
4019 | if (fixes) {
|
4020 | ignoredImageAnalysisSelectors = Array.isArray(fixes.ignoreImageAnalysis) ? fixes.ignoreImageAnalysis : [];
|
4021 | ignoredInlineSelectors = Array.isArray(fixes.ignoreInlineStyle) ? fixes.ignoreInlineStyle : [];
|
4022 | }
|
4023 | else {
|
4024 | ignoredImageAnalysisSelectors = [];
|
4025 | ignoredInlineSelectors = [];
|
4026 | }
|
4027 | isIFrame = iframe;
|
4028 | if (document.head) {
|
4029 | if (isAnotherDarkReaderInstanceActive()) {
|
4030 | return;
|
4031 | }
|
4032 | createThemeAndWatchForUpdates();
|
4033 | }
|
4034 | else {
|
4035 | if (!isFirefox) {
|
4036 | var fallbackStyle = createOrUpdateStyle('darkreader--fallback');
|
4037 | document.documentElement.appendChild(fallbackStyle);
|
4038 | fallbackStyle.textContent = getModifiedFallbackStyle(filter, { strict: true });
|
4039 | }
|
4040 | var headObserver_1 = new MutationObserver(function () {
|
4041 | if (document.head) {
|
4042 | headObserver_1.disconnect();
|
4043 | if (isAnotherDarkReaderInstanceActive()) {
|
4044 | removeDynamicTheme();
|
4045 | return;
|
4046 | }
|
4047 | createThemeAndWatchForUpdates();
|
4048 | }
|
4049 | });
|
4050 | headObserver_1.observe(document, { childList: true, subtree: true });
|
4051 | }
|
4052 | }
|
4053 | function removeProxy() {
|
4054 | document.dispatchEvent(new CustomEvent('__darkreader__cleanUp'));
|
4055 | removeNode(document.head.querySelector('.darkreader--proxy'));
|
4056 | }
|
4057 | function removeDynamicTheme() {
|
4058 | cleanDynamicThemeCache();
|
4059 | removeNode(document.querySelector('.darkreader--fallback'));
|
4060 | if (document.head) {
|
4061 | restoreMetaThemeColor();
|
4062 | removeNode(document.head.querySelector('.darkreader--user-agent'));
|
4063 | removeNode(document.head.querySelector('.darkreader--text'));
|
4064 | removeNode(document.head.querySelector('.darkreader--invert'));
|
4065 | removeNode(document.head.querySelector('.darkreader--inline'));
|
4066 | removeNode(document.head.querySelector('.darkreader--override'));
|
4067 | removeNode(document.head.querySelector('meta[name="darkreader"]'));
|
4068 | removeProxy();
|
4069 | }
|
4070 | shadowRootsWithOverrides.forEach(function (root) {
|
4071 | removeNode(root.querySelector('.darkreader--inline'));
|
4072 | removeNode(root.querySelector('.darkreader--override'));
|
4073 | });
|
4074 | shadowRootsWithOverrides.clear();
|
4075 | forEach(styleManagers.keys(), function (el) { return removeManager(el); });
|
4076 | forEach(document.querySelectorAll('.darkreader'), removeNode);
|
4077 | adoptedStyleManagers.forEach(function (manager) {
|
4078 | manager.destroy();
|
4079 | });
|
4080 | adoptedStyleManagers.splice(0);
|
4081 | parsedURLCache.clear();
|
4082 | }
|
4083 | function cleanDynamicThemeCache() {
|
4084 | variables.clear();
|
4085 | stopWatchingForDocumentVisibility();
|
4086 | cancelRendering();
|
4087 | stopWatchingForUpdates();
|
4088 | cleanModificationCache();
|
4089 | }
|
4090 |
|
4091 | var blobRegex = /url\(\"(blob\:.*?)\"\)/g;
|
4092 | function replaceBlobs(text) {
|
4093 | return __awaiter(this, void 0, void 0, function () {
|
4094 | var promises, data;
|
4095 | return __generator(this, function (_a) {
|
4096 | switch (_a.label) {
|
4097 | case 0:
|
4098 | promises = [];
|
4099 | getMatches(blobRegex, text, 1).forEach(function (url) {
|
4100 | var promise = loadAsDataURL(url);
|
4101 | promises.push(promise);
|
4102 | });
|
4103 | return [4, Promise.all(promises)];
|
4104 | case 1:
|
4105 | data = _a.sent();
|
4106 | return [2, text.replace(blobRegex, function () { return "url(\"" + data.shift() + "\")"; })];
|
4107 | }
|
4108 | });
|
4109 | });
|
4110 | }
|
4111 | var banner = "/*\n _______\n / \\\n .==. .==.\n (( ))==(( ))\n / \"==\" \"==\"\\\n /____|| || ||___\\\n ________ ____ ________ ___ ___\n | ___ \\ / \\ | ___ \\ | | / /\n | | \\ \\ / /\\ \\ | | \\ \\| |_/ /\n | | ) / /__\\ \\ | |__/ /| ___ \\\n | |__/ / ______ \\| ____ \\| | \\ \\\n_______|_______/__/ ____ \\__\\__|___\\__\\__|___\\__\\____\n| ___ \\ | ____/ / \\ | ___ \\ | ____| ___ \\\n| | \\ \\| |___ / /\\ \\ | | \\ \\| |___| | \\ \\\n| |__/ /| ____/ /__\\ \\ | | ) | ____| |__/ /\n| ____ \\| |__/ ______ \\| |__/ /| |___| ____ \\\n|__| \\__\\____/__/ \\__\\_______/ |______|__| \\__\\\n https://darkreader.org\n*/";
|
4112 | function collectCSS() {
|
4113 | return __awaiter(this, void 0, void 0, function () {
|
4114 | function addStaticCSS(selector, comment) {
|
4115 | var staticStyle = document.querySelector(selector);
|
4116 | if (staticStyle && staticStyle.textContent) {
|
4117 | css.push("/* " + comment + " */");
|
4118 | css.push(staticStyle.textContent);
|
4119 | css.push('');
|
4120 | }
|
4121 | }
|
4122 | var css, modifiedCSS, formattedCSS, _a, _b;
|
4123 | return __generator(this, function (_c) {
|
4124 | switch (_c.label) {
|
4125 | case 0:
|
4126 | css = [banner];
|
4127 | addStaticCSS('.darkreader--fallback', 'Fallback Style');
|
4128 | addStaticCSS('.darkreader--user-agent', 'User-Agent Style');
|
4129 | addStaticCSS('.darkreader--text', 'Text Style');
|
4130 | addStaticCSS('.darkreader--invert', 'Invert Style');
|
4131 | addStaticCSS('.darkreader--variables', 'Variables Style');
|
4132 | modifiedCSS = [];
|
4133 | document.querySelectorAll('.darkreader--sync').forEach(function (element) {
|
4134 | forEach(element.sheet.cssRules, function (rule) {
|
4135 | rule && rule.cssText && modifiedCSS.push(rule.cssText);
|
4136 | });
|
4137 | });
|
4138 | if (!(modifiedCSS.length != 0)) return [3, 2];
|
4139 | formattedCSS = formatCSS(modifiedCSS.join('\n'));
|
4140 | css.push('/* Modified CSS */');
|
4141 | _b = (_a = css).push;
|
4142 | return [4, replaceBlobs(formattedCSS)];
|
4143 | case 1:
|
4144 | _b.apply(_a, [_c.sent()]);
|
4145 | css.push('');
|
4146 | _c.label = 2;
|
4147 | case 2:
|
4148 | addStaticCSS('.darkreader--override', 'Override Style');
|
4149 | return [2, css.join('\n')];
|
4150 | }
|
4151 | });
|
4152 | });
|
4153 | }
|
4154 |
|
4155 | var isDarkReaderEnabled = false;
|
4156 | var isIFrame$1 = (function () {
|
4157 | try {
|
4158 | return window.self !== window.top;
|
4159 | }
|
4160 | catch (err) {
|
4161 | console.warn(err);
|
4162 | return true;
|
4163 | }
|
4164 | })();
|
4165 | function enable(themeOptions, fixes) {
|
4166 | if (themeOptions === void 0) { themeOptions = {}; }
|
4167 | if (fixes === void 0) { fixes = null; }
|
4168 | var theme = __assign(__assign({}, DEFAULT_THEME), themeOptions);
|
4169 | if (theme.engine !== ThemeEngines.dynamicTheme) {
|
4170 | throw new Error('Theme engine is not supported.');
|
4171 | }
|
4172 | createOrUpdateDynamicTheme(theme, fixes, isIFrame$1);
|
4173 | isDarkReaderEnabled = true;
|
4174 | }
|
4175 | function isEnabled() {
|
4176 | return isDarkReaderEnabled;
|
4177 | }
|
4178 | function disable() {
|
4179 | removeDynamicTheme();
|
4180 | isDarkReaderEnabled = false;
|
4181 | }
|
4182 | var darkScheme = matchMedia('(prefers-color-scheme: dark)');
|
4183 | var store = {
|
4184 | themeOptions: null,
|
4185 | fixes: null,
|
4186 | };
|
4187 | function handleColorScheme() {
|
4188 | if (darkScheme.matches) {
|
4189 | enable(store.themeOptions, store.fixes);
|
4190 | }
|
4191 | else {
|
4192 | disable();
|
4193 | }
|
4194 | }
|
4195 | function auto(themeOptions, fixes) {
|
4196 | if (themeOptions === void 0) { themeOptions = {}; }
|
4197 | if (fixes === void 0) { fixes = null; }
|
4198 | if (themeOptions) {
|
4199 | store = { themeOptions: themeOptions, fixes: fixes };
|
4200 | handleColorScheme();
|
4201 | if (isMatchMediaChangeEventListenerSupported) {
|
4202 | darkScheme.addEventListener('change', handleColorScheme);
|
4203 | }
|
4204 | else {
|
4205 | darkScheme.addListener(handleColorScheme);
|
4206 | }
|
4207 | }
|
4208 | else {
|
4209 | if (isMatchMediaChangeEventListenerSupported) {
|
4210 | darkScheme.removeEventListener('change', handleColorScheme);
|
4211 | }
|
4212 | else {
|
4213 | darkScheme.removeListener(handleColorScheme);
|
4214 | }
|
4215 | disable();
|
4216 | }
|
4217 | }
|
4218 | function exportGeneratedCSS() {
|
4219 | return __awaiter(this, void 0, void 0, function () {
|
4220 | return __generator(this, function (_a) {
|
4221 | switch (_a.label) {
|
4222 | case 0: return [4, collectCSS()];
|
4223 | case 1: return [2, _a.sent()];
|
4224 | }
|
4225 | });
|
4226 | });
|
4227 | }
|
4228 | var setFetchMethod$1 = setFetchMethod;
|
4229 |
|
4230 | exports.auto = auto;
|
4231 | exports.disable = disable;
|
4232 | exports.enable = enable;
|
4233 | exports.exportGeneratedCSS = exportGeneratedCSS;
|
4234 | exports.isEnabled = isEnabled;
|
4235 | exports.setFetchMethod = setFetchMethod$1;
|
4236 |
|
4237 | Object.defineProperty(exports, '__esModule', { value: true });
|
4238 |
|
4239 | })));
|