/* * ATTENTION: The "eval" devtool has been used (maybe by default in mode: "development"). * This devtool is neither made for production nor for readable output files. * It uses "eval()" calls to create a separate source file in the browser devtools. * If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/) * or disable the default devtool with "devtool: false". * If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/). */ /******/ (() => { // webpackBootstrap /******/ "use strict"; /******/ var __webpack_modules__ = ({ /***/ "./index.js": /*!******************!*\ !*** ./index.js ***! \******************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _src_main__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/main */ \"./src/main.js\");\n\nwindow.AdminifyDarkMode = {\n enable: config => (0,_src_main__WEBPACK_IMPORTED_MODULE_0__.run)(config),\n disable: () => (0,_src_main__WEBPACK_IMPORTED_MODULE_0__.remove)()\n};\n\n//# sourceURL=webpack://dark-mode/./index.js?"); /***/ }), /***/ "./src/default.js": /*!************************!*\ !*** ./src/default.js ***! \************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ DEFAULT_COLORS: () => (/* binding */ DEFAULT_COLORS),\n/* harmony export */ DEFAULT_COLORSCHEME: () => (/* binding */ DEFAULT_COLORSCHEME),\n/* harmony export */ DEFAULT_SETTINGS: () => (/* binding */ DEFAULT_SETTINGS),\n/* harmony export */ DEFAULT_THEME: () => (/* binding */ DEFAULT_THEME)\n/* harmony export */ });\n// import { ThemeEngine } from \"./generators/theme-engines\";\n// import { isMacOS, isWindows, isCSSColorSchemePropSupported } from \"./utils/platform\";\n// import { AutomationMode } from \"./utils/automation\";\n\nconst DEFAULT_COLORS = {\n darkScheme: {\n // background: \"#181a1b\",\n // text: \"#e8e6e3\",\n\n background: \"#131516\",\n text: \"#d8d4cf\"\n\n // background: \"black\",\n // text: \"white\",\n },\n lightScheme: {\n // background: \"#dcdad7\",\n // text: \"#181a1b\",\n\n background: \"#004daa\",\n text: \"#e8e6e3\"\n }\n};\nconst DEFAULT_THEME = {\n mode: 1,\n brightness: 100,\n contrast: 100,\n grayscale: 0,\n sepia: 0,\n imgGrayscale: false,\n // boolean true | flase\n imgGrayscalePercent: \"100%\",\n // (min:0% | max:100% )\n videoGrayscale: false,\n videoGrayscalePercent: \"100%\",\n useFont: false,\n // fontFamily: isMacOS ? \"Helvetica Neue\" : isWindows ? \"Segoe UI\" : \"Open Sans\",\n fontFamily: \"Open Sans\",\n textStroke: 0,\n engine: \"\",\n //ThemeEngine.dynamicTheme,\n stylesheet: \"\",\n darkSchemeBackgroundColor: DEFAULT_COLORS.darkScheme.background,\n darkSchemeTextColor: DEFAULT_COLORS.darkScheme.text,\n lightSchemeBackgroundColor: DEFAULT_COLORS.lightScheme.background,\n lightSchemeTextColor: DEFAULT_COLORS.lightScheme.text,\n // scrollbarColor: isMacOS ? \"\" : \"auto\",\n scrollbarColor: \"auto\",\n selectionColor: \"auto\",\n styleSystemControls: false,\n lightColorScheme: \"Default\",\n darkColorScheme: \"Default\",\n immediateModify: false\n};\nconst DEFAULT_COLORSCHEME = {\n light: {\n Default: {\n backgroundColor: DEFAULT_COLORS.lightScheme.background,\n textColor: DEFAULT_COLORS.lightScheme.text\n }\n },\n dark: {\n Default: {\n backgroundColor: DEFAULT_COLORS.darkScheme.background,\n textColor: DEFAULT_COLORS.darkScheme.text\n }\n }\n};\nconst DEFAULT_SETTINGS = {\n enabled: true,\n fetchNews: true,\n theme: DEFAULT_THEME,\n presets: [],\n customThemes: [],\n siteList: [],\n siteListEnabled: [],\n applyToListedOnly: false,\n changeBrowserTheme: false,\n syncSettings: true,\n syncSitesFixes: false,\n automation: {\n enabled: false,\n mode: \"\",\n //AutomationMode.NONE,\n behavior: \"OnOff\"\n },\n time: {\n activation: \"18:00\",\n deactivation: \"9:00\"\n },\n location: {\n latitude: null,\n longitude: null\n },\n previewNewDesign: false,\n enableForPDF: true,\n enableForProtectedPages: false,\n enableContextMenus: false,\n detectDarkTheme: false\n};\n\n//# sourceURL=webpack://dark-mode/./src/default.js?"); /***/ }), /***/ "./src/generators/css-filter.js": /*!**************************************!*\ !*** ./src/generators/css-filter.js ***! \**************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ FilterMode: () => (/* binding */ FilterMode),\n/* harmony export */ cssFilterStyleSheetTemplate: () => (/* binding */ cssFilterStyleSheetTemplate),\n/* harmony export */ getCSSFilterValue: () => (/* binding */ getCSSFilterValue),\n/* harmony export */ getInversionFixesFor: () => (/* binding */ getInversionFixesFor),\n/* harmony export */ hasFirefoxNewRootBehavior: () => (/* binding */ hasFirefoxNewRootBehavior),\n/* harmony export */ hasPatchForChromiumIssue501582: () => (/* binding */ hasPatchForChromiumIssue501582)\n/* harmony export */ });\n/* harmony import */ var _utils_matrix__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils/matrix */ \"./src/generators/utils/matrix.js\");\n/* harmony import */ var _utils_parse__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils/parse */ \"./src/generators/utils/parse.js\");\n/* harmony import */ var _utils_text__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/text */ \"./src/utils/text.js\");\n/* harmony import */ var _utils_url__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/url */ \"./src/utils/url.js\");\n/* harmony import */ var _text_style__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./text-style */ \"./src/generators/text-style.js\");\n/* harmony import */ var _utils_platform__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/platform */ \"./src/utils/platform.js\");\n\n\n\n\n\n\nlet FilterMode;\n(function (FilterMode) {\n FilterMode[FilterMode[\"light\"] = 0] = \"light\";\n FilterMode[FilterMode[\"dark\"] = 1] = \"dark\";\n})(FilterMode || (FilterMode = {}));\n\n/**\n * This checks if the current chromium version has the patch in it.\n * As of Chromium v81.0.4035.0 this has been the situation\n *\n * Bug report: https://bugs.chromium.org/p/chromium/issues/detail?id=501582\n * Patch: https://chromium-review.googlesource.com/c/chromium/src/+/1979258\n */\nfunction hasPatchForChromiumIssue501582() {\n return __CHROMIUM_MV3__ || Boolean(__CHROMIUM_MV2__ && (0,_utils_platform__WEBPACK_IMPORTED_MODULE_5__.compareChromeVersions)(_utils_platform__WEBPACK_IMPORTED_MODULE_5__.chromiumVersion, \"81.0.4035.0\") >= 0);\n}\n\n/**\n * Since Firefox v102.0, they have changed to the new root behavior.\n * This was already the case for Chromium v81.0.4035.0 and Firefox now\n * switched over as well.\n */\nfunction hasFirefoxNewRootBehavior() {\n return Boolean(_utils_platform__WEBPACK_IMPORTED_MODULE_5__.isFirefox && (0,_utils_platform__WEBPACK_IMPORTED_MODULE_5__.compareChromeVersions)(_utils_platform__WEBPACK_IMPORTED_MODULE_5__.firefoxVersion, \"102.0\") >= 0);\n}\n\n// export default function createCSSFilterStyleSheet(config, url, isTopFrame, fixes, index) {\n// const filterValue = getCSSFilterValue(config);\n// const reverseFilterValue = \"invert(100%) hue-rotate(180deg)\";\n// return cssFilterStyleSheetTemplate(\n// filterValue,\n// reverseFilterValue,\n// config,\n// url,\n// isTopFrame,\n// fixes,\n// index\n// );\n// }\n\nfunction cssFilterStyleSheetTemplate(filterValue, reverseFilterValue, config, url, isTopFrame, fixes, index) {\n const fix = getInversionFixesFor(url, fixes, index);\n const lines = [];\n lines.push(\"@media screen {\");\n\n // Add leading rule\n if (filterValue && isTopFrame) {\n lines.push(\"\");\n lines.push(\"/* Leading rule */\");\n lines.push(createLeadingRule(filterValue));\n }\n if (config.mode === FilterMode.dark) {\n // Add reverse rule\n lines.push(\"\");\n lines.push(\"/* Reverse rule */\");\n lines.push(createReverseRule(reverseFilterValue, fix));\n }\n if (config.useFont || config.textStroke > 0) {\n // Add text rule\n lines.push(\"\");\n lines.push(\"/* Font */\");\n lines.push((0,_text_style__WEBPACK_IMPORTED_MODULE_4__.createTextStyle)(config));\n }\n\n // Fix bad font hinting after inversion\n lines.push(\"\");\n lines.push(\"/* Text contrast */\");\n lines.push(\"html {\");\n lines.push(\" text-shadow: 0 0 0 !important;\");\n lines.push(\"}\");\n\n // Full screen fix\n lines.push(\"\");\n lines.push(\"/* Full screen */\");\n [\":-webkit-full-screen\", \":-moz-full-screen\", \":fullscreen\"].forEach(fullScreen => {\n lines.push(`${fullScreen}, ${fullScreen} * {`);\n lines.push(\" -webkit-filter: none !important;\");\n lines.push(\" filter: none !important;\");\n lines.push(\"}\");\n });\n if (isTopFrame) {\n const light = [255, 255, 255];\n // If browser affected by Chromium Issue 501582, set dark background on html\n // Or if browser is Firefox v102+\n const bgColor = !hasPatchForChromiumIssue501582() && !hasFirefoxNewRootBehavior() && config.mode === FilterMode.dark ? (0,_utils_matrix__WEBPACK_IMPORTED_MODULE_0__.applyColorMatrix)(light, (0,_utils_matrix__WEBPACK_IMPORTED_MODULE_0__.createFilterMatrix)(config)).map(Math.round) : light;\n lines.push(\"\");\n lines.push(\"/* Page background */\");\n lines.push(\"html {\");\n lines.push(` background: rgb(${bgColor.join(\",\")}) !important;`);\n lines.push(\"}\");\n }\n if (fix.css && fix.css.length > 0 && config.mode === FilterMode.dark) {\n lines.push(\"\");\n lines.push(\"/* Custom rules */\");\n lines.push(fix.css);\n }\n lines.push(\"\");\n lines.push(\"}\");\n return lines.join(\"\\n\");\n}\nfunction getCSSFilterValue(config) {\n const filters = [];\n if (config.mode === FilterMode.dark) {\n filters.push(\"invert(100%) hue-rotate(180deg)\");\n }\n if (config.brightness !== 100) {\n filters.push(`brightness(${config.brightness}%)`);\n }\n if (config.contrast !== 100) {\n filters.push(`contrast(${config.contrast}%)`);\n }\n if (config.grayscale !== 0) {\n filters.push(`grayscale(${config.grayscale}%)`);\n }\n if (config.sepia !== 0) {\n filters.push(`sepia(${config.sepia}%)`);\n }\n if (filters.length === 0) {\n return null;\n }\n return filters.join(\" \");\n}\nfunction createLeadingRule(filterValue) {\n return [\"html {\", ` -webkit-filter: ${filterValue} !important;`, ` filter: ${filterValue} !important;`, \"}\"].join(\"\\n\");\n}\nfunction joinSelectors(selectors) {\n return selectors.map(s => s.replace(/\\,$/, \"\")).join(\",\\n\");\n}\nfunction createReverseRule(reverseFilterValue, fix) {\n const lines = [];\n if (fix.invert.length > 0) {\n lines.push(`${joinSelectors(fix.invert)} {`);\n lines.push(` -webkit-filter: ${reverseFilterValue} !important;`);\n lines.push(` filter: ${reverseFilterValue} !important;`);\n lines.push(\"}\");\n }\n if (fix.noinvert.length > 0) {\n lines.push(`${joinSelectors(fix.noinvert)} {`);\n lines.push(\" -webkit-filter: none !important;\");\n lines.push(\" filter: none !important;\");\n lines.push(\"}\");\n }\n if (fix.removebg.length > 0) {\n lines.push(`${joinSelectors(fix.removebg)} {`);\n lines.push(\" background: white !important;\");\n lines.push(\"}\");\n }\n return lines.join(\"\\n\");\n}\n\n/**\n * Returns fixes for a given URL.\n * If no matches found, common fixes will be returned.\n * @param url Site URL.\n * @param inversionFixes List of inversion fixes.\n */\nfunction getInversionFixesFor(url, fixes, index) {\n const inversionFixes = (0,_utils_parse__WEBPACK_IMPORTED_MODULE_1__.getSitesFixesFor)(url, fixes, index, {\n commands: Object.keys(inversionFixesCommands),\n getCommandPropName: command => inversionFixesCommands[command],\n parseCommandValue: (command, value) => {\n if (command === \"CSS\") {\n return value.trim();\n }\n return (0,_utils_text__WEBPACK_IMPORTED_MODULE_2__.parseArray)(value);\n }\n });\n const common = {\n url: inversionFixes[0].url,\n invert: inversionFixes[0].invert || [],\n noinvert: inversionFixes[0].noinvert || [],\n removebg: inversionFixes[0].removebg || [],\n css: inversionFixes[0].css || \"\"\n };\n if (url) {\n // Search for match with given URL\n const matches = inversionFixes.slice(1).filter(s => (0,_utils_url__WEBPACK_IMPORTED_MODULE_3__.isURLInList)(url, s.url)).sort((a, b) => b.url[0].length - a.url[0].length);\n if (matches.length > 0) {\n const found = matches[0];\n return {\n url: found.url,\n invert: common.invert.concat(found.invert || []),\n noinvert: common.noinvert.concat(found.noinvert || []),\n removebg: common.removebg.concat(found.removebg || []),\n css: [common.css, found.css].filter(s => s).join(\"\\n\")\n };\n }\n }\n return common;\n}\nconst inversionFixesCommands = {\n INVERT: \"invert\",\n \"NO INVERT\": \"noinvert\",\n \"REMOVE BG\": \"removebg\",\n CSS: \"css\"\n};\n\n// export function parseInversionFixes(text) {\n// return parseSitesFixesConfig(text, {\n// commands: Object.keys(inversionFixesCommands),\n// getCommandPropName: (command) => inversionFixesCommands[command],\n// parseCommandValue: (command, value) => {\n// if (command === \"CSS\") {\n// return value.trim();\n// }\n// return parseArray(value);\n// },\n// });\n// }\n\n// export function formatInversionFixes(inversionFixes) {\n// const fixes = inversionFixes.slice().sort((a, b) => compareURLPatterns(a.url[0], b.url[0]));\n\n// return formatSitesFixesConfig(fixes, {\n// props: Object.values(inversionFixesCommands),\n// getPropCommandName: (prop) =>\n// Object.entries(inversionFixesCommands).find(([, p]) => p === prop)[0],\n// formatPropValue: (prop, value) => {\n// if (prop === \"css\") {\n// return value.trim().replace(/\\n+/g, \"\\n\");\n// }\n// return formatArray(value).trim();\n// },\n// shouldIgnoreProp: (prop, value) => {\n// if (prop === \"css\") {\n// return !value;\n// }\n// return !(Array.isArray(value) && value.length > 0);\n// },\n// });\n// }\n\n//# sourceURL=webpack://dark-mode/./src/generators/css-filter.js?"); /***/ }), /***/ "./src/generators/modify-colors.js": /*!*****************************************!*\ !*** ./src/generators/modify-colors.js ***! \*****************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ clearColorModificationCache: () => (/* binding */ clearColorModificationCache),\n/* harmony export */ modifyBackgroundColor: () => (/* binding */ modifyBackgroundColor),\n/* harmony export */ modifyBorderColor: () => (/* binding */ modifyBorderColor),\n/* harmony export */ modifyColor: () => (/* binding */ modifyColor),\n/* harmony export */ modifyForegroundColor: () => (/* binding */ modifyForegroundColor),\n/* harmony export */ modifyGradientColor: () => (/* binding */ modifyGradientColor),\n/* harmony export */ modifyShadowColor: () => (/* binding */ modifyShadowColor)\n/* harmony export */ });\n/* harmony import */ var _utils_color__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/color */ \"./src/utils/color.js\");\n/* harmony import */ var _utils_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/math */ \"./src/utils/math.js\");\n/* harmony import */ var _utils_matrix__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils/matrix */ \"./src/generators/utils/matrix.js\");\n\n\n\nfunction getBgPole(theme) {\n const isDarkScheme = theme.mode === 1;\n const prop = isDarkScheme ? \"darkSchemeBackgroundColor\" : \"lightSchemeBackgroundColor\";\n return theme[prop];\n}\nfunction getFgPole(theme) {\n const isDarkScheme = theme.mode === 1;\n const prop = isDarkScheme ? \"darkSchemeTextColor\" : \"lightSchemeTextColor\";\n return theme[prop];\n}\nconst colorModificationCache = new Map();\nfunction clearColorModificationCache() {\n colorModificationCache.clear();\n}\nconst rgbCacheKeys = [\"r\", \"g\", \"b\", \"a\"];\nconst themeCacheKeys = [\"mode\", \"brightness\", \"contrast\", \"grayscale\", \"sepia\", \"darkSchemeBackgroundColor\", \"darkSchemeTextColor\", \"lightSchemeBackgroundColor\", \"lightSchemeTextColor\"];\nfunction getCacheId(rgb, theme) {\n let resultId = \"\";\n rgbCacheKeys.forEach(key => {\n resultId += `${rgb[key]};`;\n });\n themeCacheKeys.forEach(key => {\n resultId += `${theme[key]};`;\n });\n return resultId;\n}\nfunction modifyColorWithCache(rgb, theme, modifyHSL, poleColor, anotherPoleColor) {\n let fnCache;\n if (colorModificationCache.has(modifyHSL)) {\n fnCache = colorModificationCache.get(modifyHSL);\n } else {\n fnCache = new Map();\n colorModificationCache.set(modifyHSL, fnCache);\n }\n const id = getCacheId(rgb, theme);\n if (fnCache.has(id)) {\n return fnCache.get(id);\n }\n const hsl = (0,_utils_color__WEBPACK_IMPORTED_MODULE_0__.rgbToHSL)(rgb);\n const pole = poleColor == null ? null : (0,_utils_color__WEBPACK_IMPORTED_MODULE_0__.parseToHSLWithCache)(poleColor);\n const anotherPole = anotherPoleColor == null ? null : (0,_utils_color__WEBPACK_IMPORTED_MODULE_0__.parseToHSLWithCache)(anotherPoleColor);\n const modified = modifyHSL(hsl, pole, anotherPole);\n const {\n r,\n g,\n b,\n a\n } = (0,_utils_color__WEBPACK_IMPORTED_MODULE_0__.hslToRGB)(modified);\n const matrix = (0,_utils_matrix__WEBPACK_IMPORTED_MODULE_2__.createFilterMatrix)(theme);\n const [rf, gf, bf] = (0,_utils_matrix__WEBPACK_IMPORTED_MODULE_2__.applyColorMatrix)([r, g, b], matrix);\n const color = a === 1 ? (0,_utils_color__WEBPACK_IMPORTED_MODULE_0__.rgbToHexString)({\n r: rf,\n g: gf,\n b: bf\n }) : (0,_utils_color__WEBPACK_IMPORTED_MODULE_0__.rgbToString)({\n r: rf,\n g: gf,\n b: bf,\n a\n });\n fnCache.set(id, color);\n return color;\n}\nfunction noopHSL(hsl) {\n return hsl;\n}\nfunction modifyColor(rgb, theme) {\n return modifyColorWithCache(rgb, theme, noopHSL);\n}\nfunction modifyLightSchemeColor(rgb, theme) {\n const poleBg = getBgPole(theme);\n const poleFg = getFgPole(theme);\n return modifyColorWithCache(rgb, theme, modifyLightModeHSL, poleFg, poleBg);\n}\nfunction modifyLightModeHSL({\n h,\n s,\n l,\n a\n}, poleFg, poleBg) {\n const isDark = l < 0.5;\n let isNeutral;\n if (isDark) {\n isNeutral = l < 0.2 || s < 0.12;\n } else {\n const isBlue = h > 200 && h < 280;\n isNeutral = s < 0.24 || l > 0.8 && isBlue;\n }\n let hx = h;\n let sx = l;\n if (isNeutral) {\n if (isDark) {\n hx = poleFg.h;\n sx = poleFg.s;\n } else {\n hx = poleBg.h;\n sx = poleBg.s;\n }\n }\n const lx = (0,_utils_math__WEBPACK_IMPORTED_MODULE_1__.scale)(l, 0, 1, poleFg.l, poleBg.l);\n return {\n h: hx,\n s: sx,\n l: lx,\n a\n };\n}\nconst MAX_BG_LIGHTNESS = 0.4;\nfunction modifyBgHSL({\n h,\n s,\n l,\n a\n}, pole) {\n const isDark = l < 0.5;\n const isBlue = h > 200 && h < 280;\n const isNeutral = s < 0.12 || l > 0.8 && isBlue;\n if (isDark) {\n const lx = (0,_utils_math__WEBPACK_IMPORTED_MODULE_1__.scale)(l, 0, 0.5, 0, MAX_BG_LIGHTNESS);\n if (isNeutral) {\n const hx = pole.h;\n const sx = pole.s;\n return {\n h: hx,\n s: sx,\n l: lx,\n a\n };\n }\n return {\n h,\n s,\n l: lx,\n a\n };\n }\n let lx = (0,_utils_math__WEBPACK_IMPORTED_MODULE_1__.scale)(l, 0.5, 1, MAX_BG_LIGHTNESS, pole.l);\n if (isNeutral) {\n const hx = pole.h;\n const sx = pole.s;\n return {\n h: hx,\n s: sx,\n l: lx,\n a\n };\n }\n let hx = h;\n const isYellow = h > 60 && h < 180;\n if (isYellow) {\n const isCloserToGreen = h > 120;\n if (isCloserToGreen) {\n hx = (0,_utils_math__WEBPACK_IMPORTED_MODULE_1__.scale)(h, 120, 180, 135, 180);\n } else {\n hx = (0,_utils_math__WEBPACK_IMPORTED_MODULE_1__.scale)(h, 60, 120, 60, 105);\n }\n }\n\n // Lower the lightness, if the resulting\n // hue is in lower yellow spectrum.\n if (hx > 40 && hx < 80) {\n lx *= 0.75;\n }\n return {\n h: hx,\n s,\n l: lx,\n a\n };\n}\nfunction modifyBackgroundColor(rgb, theme) {\n if (theme.mode === 0) {\n return modifyLightSchemeColor(rgb, theme);\n }\n const pole = getBgPole(theme);\n return modifyColorWithCache(rgb, {\n ...theme,\n mode: 0\n }, modifyBgHSL, pole);\n}\nconst MIN_FG_LIGHTNESS = 0.55;\nfunction modifyBlueFgHue(hue) {\n return (0,_utils_math__WEBPACK_IMPORTED_MODULE_1__.scale)(hue, 205, 245, 205, 220);\n}\nfunction modifyFgHSL({\n h,\n s,\n l,\n a\n}, pole) {\n const isLight = l > 0.5;\n const isNeutral = l < 0.2 || s < 0.24;\n const isBlue = !isNeutral && h > 205 && h < 245;\n if (isLight) {\n const lx = (0,_utils_math__WEBPACK_IMPORTED_MODULE_1__.scale)(l, 0.5, 1, MIN_FG_LIGHTNESS, pole.l);\n if (isNeutral) {\n const hx = pole.h;\n const sx = pole.s;\n return {\n h: hx,\n s: sx,\n l: lx,\n a\n };\n }\n let hx = h;\n if (isBlue) {\n hx = modifyBlueFgHue(h);\n }\n return {\n h: hx,\n s,\n l: lx,\n a\n };\n }\n if (isNeutral) {\n const hx = pole.h;\n const sx = pole.s;\n const lx = (0,_utils_math__WEBPACK_IMPORTED_MODULE_1__.scale)(l, 0, 0.5, pole.l, MIN_FG_LIGHTNESS);\n return {\n h: hx,\n s: sx,\n l: lx,\n a\n };\n }\n let hx = h;\n let lx;\n if (isBlue) {\n hx = modifyBlueFgHue(h);\n lx = (0,_utils_math__WEBPACK_IMPORTED_MODULE_1__.scale)(l, 0, 0.5, pole.l, Math.min(1, MIN_FG_LIGHTNESS + 0.05));\n } else {\n lx = (0,_utils_math__WEBPACK_IMPORTED_MODULE_1__.scale)(l, 0, 0.5, pole.l, MIN_FG_LIGHTNESS);\n }\n return {\n h: hx,\n s,\n l: lx,\n a\n };\n}\nfunction modifyForegroundColor(rgb, theme) {\n if (theme.mode === 0) {\n return modifyLightSchemeColor(rgb, theme);\n }\n const pole = getFgPole(theme);\n return modifyColorWithCache(rgb, {\n ...theme,\n mode: 0\n }, modifyFgHSL, pole);\n}\nfunction modifyBorderHSL({\n h,\n s,\n l,\n a\n}, poleFg, poleBg) {\n const isDark = l < 0.5;\n const isNeutral = l < 0.2 || s < 0.24;\n let hx = h;\n let sx = s;\n if (isNeutral) {\n if (isDark) {\n hx = poleFg.h;\n sx = poleFg.s;\n } else {\n hx = poleBg.h;\n sx = poleBg.s;\n }\n }\n const lx = (0,_utils_math__WEBPACK_IMPORTED_MODULE_1__.scale)(l, 0, 1, 0.5, 0.2);\n return {\n h: hx,\n s: sx,\n l: lx,\n a\n };\n}\nfunction modifyBorderColor(rgb, theme) {\n if (theme.mode === 0) {\n return modifyLightSchemeColor(rgb, theme);\n }\n const poleFg = getFgPole(theme);\n const poleBg = getBgPole(theme);\n return modifyColorWithCache(rgb, {\n ...theme,\n mode: 0\n }, modifyBorderHSL, poleFg, poleBg);\n}\nfunction modifyShadowColor(rgb, filter) {\n return modifyBackgroundColor(rgb, filter);\n}\nfunction modifyGradientColor(rgb, filter) {\n return modifyBackgroundColor(rgb, filter);\n}\n\n//# sourceURL=webpack://dark-mode/./src/generators/modify-colors.js?"); /***/ }), /***/ "./src/generators/svg-filter.js": /*!**************************************!*\ !*** ./src/generators/svg-filter.js ***! \**************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ createSVGFilterStylesheet: () => (/* binding */ createSVGFilterStylesheet),\n/* harmony export */ getSVGFilterMatrixValue: () => (/* binding */ getSVGFilterMatrixValue),\n/* harmony export */ getSVGReverseFilterMatrixValue: () => (/* binding */ getSVGReverseFilterMatrixValue)\n/* harmony export */ });\n/* harmony import */ var _utils_matrix__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils/matrix */ \"./src/generators/utils/matrix.js\");\n/* harmony import */ var _css_filter__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./css-filter */ \"./src/generators/css-filter.js\");\n/* harmony import */ var _utils_platform__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/platform */ \"./src/utils/platform.js\");\n\n\n\nfunction createSVGFilterStylesheet(config, url, isTopFrame, fixes, index) {\n let filterValue;\n let reverseFilterValue;\n if (_utils_platform__WEBPACK_IMPORTED_MODULE_2__.isFirefox) {\n filterValue = getEmbeddedSVGFilterValue(getSVGFilterMatrixValue(config));\n reverseFilterValue = getEmbeddedSVGFilterValue(getSVGReverseFilterMatrixValue());\n } else {\n // Chrome fails with \"Unsafe attempt to load URL ... Domains, protocols and ports must match.\n filterValue = \"url(#dark-reader-filter)\";\n reverseFilterValue = \"url(#dark-reader-reverse-filter)\";\n }\n return (0,_css_filter__WEBPACK_IMPORTED_MODULE_1__.cssFilterStyleSheetTemplate)(filterValue, reverseFilterValue, config, url, isTopFrame, fixes, index);\n}\nfunction getEmbeddedSVGFilterValue(matrixValue) {\n const id = \"adminify-filter\";\n const svg = ['', ``, ``, \"\", \"\"].join(\"\");\n return `url(data:image/svg+xml;base64,${btoa(svg)}#${id})`;\n}\nfunction toSVGMatrix(matrix) {\n return matrix.slice(0, 4).map(m => m.map(m => m.toFixed(3)).join(\" \")).join(\" \");\n}\nfunction getSVGFilterMatrixValue(config) {\n return toSVGMatrix((0,_utils_matrix__WEBPACK_IMPORTED_MODULE_0__.createFilterMatrix)(config));\n}\nfunction getSVGReverseFilterMatrixValue() {\n return toSVGMatrix(_utils_matrix__WEBPACK_IMPORTED_MODULE_0__.Matrix.invertNHue());\n}\n\n//# sourceURL=webpack://dark-mode/./src/generators/svg-filter.js?"); /***/ }), /***/ "./src/generators/text-style.js": /*!**************************************!*\ !*** ./src/generators/text-style.js ***! \**************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ createTextStyle: () => (/* binding */ createTextStyle)\n/* harmony export */ });\nfunction createTextStyle(config) {\n const lines = [];\n // Don't target pre elements as they are preformatted element's e.g. code blocks\n // Exclude font libraries to preserve icons\n lines.push('*:not(pre, pre *, code, .far, .fa, .glyphicon, [class*=\"vjs-\"], .fab, .fa-github, .fas, .material-icons, .icofont, .typcn, mu, [class*=\"mu-\"], .glyphicon, .icon) {');\n if (config.useFont && config.fontFamily) {\n // TODO: Validate...\n lines.push(` font-family: ${config.fontFamily} !important;`);\n }\n if (config.textStroke > 0) {\n lines.push(` -webkit-text-stroke: ${config.textStroke}px !important;`);\n lines.push(` text-stroke: ${config.textStroke}px !important;`);\n }\n lines.push(\"}\");\n return lines.join(\"\\n\");\n}\n\n//# sourceURL=webpack://dark-mode/./src/generators/text-style.js?"); /***/ }), /***/ "./src/generators/utils/matrix.js": /*!****************************************!*\ !*** ./src/generators/utils/matrix.js ***! \****************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Matrix: () => (/* binding */ Matrix),\n/* harmony export */ applyColorMatrix: () => (/* binding */ applyColorMatrix),\n/* harmony export */ createFilterMatrix: () => (/* binding */ createFilterMatrix)\n/* harmony export */ });\n/* harmony import */ var _utils_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../utils/math */ \"./src/utils/math.js\");\n\nfunction createFilterMatrix(config) {\n let m = Matrix.identity();\n if (config.sepia !== 0) {\n m = (0,_utils_math__WEBPACK_IMPORTED_MODULE_0__.multiplyMatrices)(m, Matrix.sepia(config.sepia / 100));\n }\n if (config.grayscale !== 0) {\n m = (0,_utils_math__WEBPACK_IMPORTED_MODULE_0__.multiplyMatrices)(m, Matrix.grayscale(config.grayscale / 100));\n }\n if (config.contrast !== 100) {\n m = (0,_utils_math__WEBPACK_IMPORTED_MODULE_0__.multiplyMatrices)(m, Matrix.contrast(config.contrast / 100));\n }\n if (config.brightness !== 100) {\n m = (0,_utils_math__WEBPACK_IMPORTED_MODULE_0__.multiplyMatrices)(m, Matrix.brightness(config.brightness / 100));\n }\n if (config.mode === 1) {\n m = (0,_utils_math__WEBPACK_IMPORTED_MODULE_0__.multiplyMatrices)(m, Matrix.invertNHue());\n }\n return m;\n}\nfunction applyColorMatrix([r, g, b], matrix) {\n const rgb = [[r / 255], [g / 255], [b / 255], [1], [1]];\n const result = (0,_utils_math__WEBPACK_IMPORTED_MODULE_0__.multiplyMatrices)(matrix, rgb);\n return [0, 1, 2].map(i => (0,_utils_math__WEBPACK_IMPORTED_MODULE_0__.clamp)(Math.round(result[i][0] * 255), 0, 255));\n}\nconst Matrix = {\n identity() {\n return [[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]];\n },\n invertNHue() {\n return [[0.333, -0.667, -0.667, 0, 1], [-0.667, 0.333, -0.667, 0, 1], [-0.667, -0.667, 0.333, 0, 1], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]];\n },\n brightness(v) {\n return [[v, 0, 0, 0, 0], [0, v, 0, 0, 0], [0, 0, v, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]];\n },\n contrast(v) {\n const t = (1 - v) / 2;\n return [[v, 0, 0, 0, t], [0, v, 0, 0, t], [0, 0, v, 0, t], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]];\n },\n sepia(v) {\n return [[0.393 + 0.607 * (1 - v), 0.769 - 0.769 * (1 - v), 0.189 - 0.189 * (1 - v), 0, 0], [0.349 - 0.349 * (1 - v), 0.686 + 0.314 * (1 - v), 0.168 - 0.168 * (1 - v), 0, 0], [0.272 - 0.272 * (1 - v), 0.534 - 0.534 * (1 - v), 0.131 + 0.869 * (1 - v), 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]];\n },\n grayscale(v) {\n return [[0.2126 + 0.7874 * (1 - v), 0.7152 - 0.7152 * (1 - v), 0.0722 - 0.0722 * (1 - v), 0, 0], [0.2126 - 0.2126 * (1 - v), 0.7152 + 0.2848 * (1 - v), 0.0722 - 0.0722 * (1 - v), 0, 0], [0.2126 - 0.2126 * (1 - v), 0.7152 - 0.7152 * (1 - v), 0.0722 + 0.9278 * (1 - v), 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]];\n }\n};\n\n//# sourceURL=webpack://dark-mode/./src/generators/utils/matrix.js?"); /***/ }), /***/ "./src/generators/utils/parse.js": /*!***************************************!*\ !*** ./src/generators/utils/parse.js ***! \***************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ getDomain: () => (/* binding */ getDomain),\n/* harmony export */ getSitesFixesFor: () => (/* binding */ getSitesFixesFor),\n/* harmony export */ parseSitesFixesConfig: () => (/* binding */ parseSitesFixesConfig)\n/* harmony export */ });\n/* harmony import */ var _utils_url__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../utils/url */ \"./src/utils/url.js\");\n/* harmony import */ var _utils_text__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../utils/text */ \"./src/utils/text.js\");\n\n\nconst INDEX_CACHE_CLEANUP_INTERVAL_IN_MS = 60000;\nfunction parseSitesFixesConfig(text, options) {\n const sites = [];\n const blocks = text.replace(/\\r/g, \"\").split(/^\\s*={2,}\\s*$/gm);\n blocks.forEach(block => {\n const lines = block.split(\"\\n\");\n const commandIndices = [];\n lines.forEach((ln, i) => {\n if (ln.match(/^[A-Z]+(\\s[A-Z]+){0,2}$/)) {\n commandIndices.push(i);\n }\n });\n if (commandIndices.length === 0) {\n return;\n }\n const siteFix = {\n url: (0,_utils_text__WEBPACK_IMPORTED_MODULE_1__.parseArray)(lines.slice(0, commandIndices[0]).join(\"\\n\"))\n };\n commandIndices.forEach((commandIndex, i) => {\n const command = lines[commandIndex].trim();\n const valueText = lines.slice(commandIndex + 1, i === commandIndices.length - 1 ? lines.length : commandIndices[i + 1]).join(\"\\n\");\n const prop = options.getCommandPropName(command);\n if (!prop) {\n return;\n }\n const value = options.parseCommandValue(command, valueText);\n siteFix[prop] = value;\n });\n sites.push(siteFix);\n });\n return sites;\n}\n// URL patterns are guaranteed to not have protocol and leading '/'\nfunction getDomain(url) {\n try {\n return new URL(url).hostname.toLowerCase();\n } catch (error) {\n return url.split(\"/\")[0].toLowerCase();\n }\n}\n/*\n * Encode all offsets into a string, where each record is 7 bytes long:\n * - 4 bytes for start offset\n * - 3 bytes for record length (end offset - start offset)\n * Both values are stored in base 36 (radix 36) notation.\n * Maximum supported numbers:\n * - start offset must be no more than parseInt('zzzz', 36) = 1679615\n * - length must be no more than parseInt('zzz', 36) = 46655\n *\n * We have to encode offsets into a string to be able to save them in\n * chrome.storage.local for use in non-persistent background contexts.\n */\n// function encodeOffsets(offsets) {\n// return offsets\n// .map(([offset, length]) => {\n// const stringOffset = offset.toString(36);\n// const stringLength = length.toString(36);\n// return (\n// \"0\".repeat(4 - stringOffset.length) +\n// stringOffset +\n// \"0\".repeat(3 - stringLength.length) +\n// stringLength\n// );\n// })\n// .join(\"\");\n// }\n\nfunction decodeOffset(offsets, index) {\n const base = (4 + 3) * index;\n const offset = parseInt(offsets.substring(base + 0, base + 4), 36);\n const length = parseInt(offsets.substring(base + 4, base + 4 + 3), 36);\n return [offset, offset + length];\n}\n\n// function addLabel(set, label, index) {\n// if (!set[label]) {\n// set[label] = [index];\n// } else if (!set[label].includes(index)) {\n// set[label].push(index);\n// }\n// }\n\n// function extractDomainLabelsFromFullyQualifiedDomainWildcard(fullyQualifiedDomainWildcard) {\n// const postfixStart = fullyQualifiedDomainWildcard.lastIndexOf(\"*\");\n// const postfix = fullyQualifiedDomainWildcard.substring(postfixStart + 2);\n// if (postfixStart < 0 || postfix.length === 0) {\n// return fullyQualifiedDomainWildcard.split(\".\");\n// }\n// const labels = [postfix];\n// const prefix = fullyQualifiedDomainWildcard.substring(0, postfixStart);\n// prefix\n// .split(\".\")\n// .filter(Boolean)\n// .forEach((l) => labels.concat(l));\n// return labels;\n// }\n\n// function indexConfigURLs(urls) {\n// const domains = {};\n// const domainLabels = {};\n// const nonstandard = [];\n// const domainLabelFrequencies = {};\n// const domainLabelMembers = [];\n// for (let index = 0; index < urls.length; index++) {\n// const block = urls[index];\n// const blockDomainLabels = new Set();\n// for (const url of block) {\n// const domain = getDomain(url);\n// if (isFullyQualifiedDomain(domain)) {\n// addLabel(domains, domain, index);\n// } else if (isFullyQualifiedDomainWildcard(domain)) {\n// const labels = extractDomainLabelsFromFullyQualifiedDomainWildcard(domain);\n// domainLabelMembers.push({ labels, index });\n// labels.forEach((l) => blockDomainLabels.add(l));\n// } else {\n// // Sitefix parser encountered non-standard URL\n// nonstandard.push(index);\n// break;\n// }\n// }\n// // Compute domain label frequencies, counting each label within each fix only once\n// for (const label of blockDomainLabels) {\n// if (domainLabelFrequencies[label]) {\n// domainLabelFrequencies[label]++;\n// } else {\n// domainLabelFrequencies[label] = 1;\n// }\n// }\n// }\n// // For each domain name, find the most specific label\n// for (const { labels, index } of domainLabelMembers) {\n// let label = labels[0];\n// for (const currLabel of labels) {\n// if (domainLabelFrequencies[currLabel] < domainLabelFrequencies[label]) {\n// label = currLabel;\n// }\n// }\n// addLabel(domainLabels, label, index);\n// }\n// return { domains, domainLabels, nonstandard };\n// }\n\n// function processSiteFixesConfigBlock(text, offsets, recordStart, recordEnd, urls) {\n// // TODO: more formal definition of URLs and delimiters\n// const block = text.substring(recordStart, recordEnd);\n// const lines = block.split(\"\\n\");\n// const commandIndices = [];\n// lines.forEach((ln, i) => {\n// if (ln.match(/^[A-Z]+(\\s[A-Z]+){0,2}$/)) {\n// commandIndices.push(i);\n// }\n// });\n// if (commandIndices.length === 0) {\n// return;\n// }\n// offsets.push([recordStart, recordEnd - recordStart]);\n// const urls_ = parseArray(lines.slice(0, commandIndices[0]).join(\"\\n\"));\n// urls.push(urls_);\n// }\n\n// function extractURLsFromSiteFixesConfig(text) {\n// const urls = [];\n// // Array of tuples, where first number is an offset of record start and second number is record length.\n// const offsets = [];\n// let recordStart = 0;\n// // Delimiter between two blocks\n// const delimiterRegex = /^\\s*={2,}\\s*$/gm;\n// let delimiter;\n// while ((delimiter = delimiterRegex.exec(text))) {\n// const nextDelimiterStart = delimiter.index;\n// const nextDelimiterEnd = delimiter.index + delimiter[0].length;\n// processSiteFixesConfigBlock(text, offsets, recordStart, nextDelimiterStart, urls);\n// recordStart = nextDelimiterEnd;\n// }\n// processSiteFixesConfigBlock(text, offsets, recordStart, text.length, urls);\n// return { urls, offsets };\n// }\n\n// export function indexSitesFixesConfig(text) {\n// const { urls, offsets } = extractURLsFromSiteFixesConfig(text);\n// const { domains, domainLabels, nonstandard } = indexConfigURLs(urls);\n// return {\n// offsets: encodeOffsets(offsets),\n// domains,\n// domainLabels,\n// nonstandard,\n// cacheDomainIndex: {},\n// cacheSiteFix: {},\n// cacheCleanupTimer: null,\n// };\n// }\n\nfunction lookupConfigURLsInDomainLabels(domain, recordIds, currRecordIds, getAllRecordURLs) {\n for (const recordId of currRecordIds) {\n const recordURLs = getAllRecordURLs(recordId);\n for (const ruleUrl of recordURLs) {\n const wildcard = getDomain(ruleUrl);\n if ((0,_utils_url__WEBPACK_IMPORTED_MODULE_0__.isFullyQualifiedDomainWildcard)(wildcard) && (0,_utils_url__WEBPACK_IMPORTED_MODULE_0__.fullyQualifiedDomainMatchesWildcard)(wildcard, domain)) {\n recordIds.push(recordId);\n } else {\n // Skip this rule, since the label match must have come from a different URL\n }\n }\n }\n}\nfunction lookupConfigURLs(domain, index, getAllRecordURLs) {\n const labels = domain.split(\".\");\n let recordIds = [];\n // Common fix\n if (\"*\" in index.domainLabels) {\n recordIds = recordIds.concat(index.domainLabels[\"*\"]);\n }\n // Wildcard fixes\n for (const label of labels) {\n // We need to use in operator because ids are 0-based and 0 is falsy\n if (label in index.domainLabels) {\n const currRecordIds = index.domainLabels[label];\n lookupConfigURLsInDomainLabels(domain, recordIds, currRecordIds, getAllRecordURLs);\n }\n }\n for (let i = 0; i < labels.length; i++) {\n const substring = labels.slice(i).join(\".\");\n if (substring in index.domains) {\n recordIds = recordIds.concat(index.domains[substring]);\n }\n if (substring in index.domainLabels) {\n const currRecordIds = index.domainLabels[substring];\n lookupConfigURLsInDomainLabels(domain, recordIds, currRecordIds, getAllRecordURLs);\n }\n }\n // Backwards compatibility: check for nonssend over nonstandard patterns, which will be filtered out\n // via regex in content script\n if (index.nonstandard) {\n for (const currRecordId of index.nonstandard) {\n const urls = getAllRecordURLs(currRecordId);\n if (urls.some(url => (0,_utils_url__WEBPACK_IMPORTED_MODULE_0__.isURLMatched)(domain, getDomain(url)))) {\n recordIds.push(currRecordId);\n continue;\n }\n }\n }\n // Deduplicate array elements\n recordIds = Array.from(new Set(recordIds));\n return recordIds;\n}\n/**\n * Extracts a single site fix and parses it (cached)\n * @param text the fix file\n * @param index site fix index\n * @param options fix parsing options\n * @param id numeric index of the fix\n * @returns a single fix\n */\nfunction getSiteFix(text, index, options, id) {\n if (id in index.cacheSiteFix) {\n return index.cacheSiteFix[id];\n }\n const [blockStart, blockEnd] = decodeOffset(index.offsets, id);\n const block = text.substring(blockStart, blockEnd);\n const fix = parseSitesFixesConfig(block, options)[0];\n index.cacheSiteFix[id] = fix;\n return fix;\n}\n/**\n * This function uses setTimeout instead of Alarms API so that background context can\n * go incative (resulting in cleanup of all context variables) and then not be awoken\n * by the alarm.\n * @param index\n */\nfunction scheduleCacheCleanup(index) {\n // if (__TEST__) {\n // return;\n // }\n clearTimeout(index.cacheCleanupTimer);\n index.cacheCleanupTimer = setTimeout(() => {\n index.cacheCleanupTimer = null;\n index.cacheDomainIndex = {};\n index.cacheSiteFix = {};\n }, INDEX_CACHE_CLEANUP_INTERVAL_IN_MS);\n}\n/**\n * Given a URL, raw fixes, and an index, finds the applicable fixes.\n * Note that dependents assume that the first returned fix is a generic fix (has URL pattern '*').\n *\n * This method uses two levels of caching:\n * - caching the site fixes keyed by a numeric id (to avoid re-parsing the site fixes)\n * - caching the numeric ids keyed by domain (to avoid re-computing lists of site fixes for the same site,\n * which is useful if user has multiple tabs of the same site and toggles Dark Reader on)\n */\nfunction getSitesFixesFor(url, text, index, options) {\n const records = [];\n const domain = getDomain(url);\n if (!index.cacheDomainIndex[domain]) {\n index.cacheDomainIndex[domain] = lookupConfigURLs(domain, index, recordId => getSiteFix(text, index, options, recordId).url);\n }\n const recordIds = index.cacheDomainIndex[domain];\n for (const recordId of recordIds) {\n const fix = getSiteFix(text, index, options, recordId);\n records.push(fix);\n }\n scheduleCacheCleanup(index);\n return records;\n}\n\n// export function indexSiteListConfig(text) {\n// const urls = parseArray(text);\n// const urls2D = urls.map((u) => [u]);\n// const { domains, domainLabels, nonstandard } = indexConfigURLs(urls2D);\n// return { domains, domainLabels, nonstandard, urls };\n// }\n\n// function getSiteListFor(url, index) {\n// const domain = getDomain(url);\n// const recordIds = lookupConfigURLs(domain, index, (recordId) => [index.urls[recordId]]);\n// const result = [];\n// for (const recordId of recordIds) {\n// result.push(index.urls[recordId]);\n// }\n// return result;\n// }\n\n// export function isURLInSiteList(url, index) {\n// if (index === null) {\n// return false;\n// }\n// const urls = getSiteListFor(url, index);\n// return isURLInList(url, urls);\n// }\n\n//# sourceURL=webpack://dark-mode/./src/generators/utils/parse.js?"); /***/ }), /***/ "./src/inject/dynamic-theme/css-rules.js": /*!***********************************************!*\ !*** ./src/inject/dynamic-theme/css-rules.js ***! \***********************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ cssImportRegex: () => (/* binding */ cssImportRegex),\n/* harmony export */ cssURLRegex: () => (/* binding */ cssURLRegex),\n/* harmony export */ getCSSBaseBath: () => (/* binding */ getCSSBaseBath),\n/* harmony export */ getCSSURLValue: () => (/* binding */ getCSSURLValue),\n/* harmony export */ iterateCSSDeclarations: () => (/* binding */ iterateCSSDeclarations),\n/* harmony export */ iterateCSSRules: () => (/* binding */ iterateCSSRules),\n/* harmony export */ removeCSSComments: () => (/* binding */ removeCSSComments),\n/* harmony export */ replaceCSSFontFace: () => (/* binding */ replaceCSSFontFace),\n/* harmony export */ replaceCSSRelativeURLsWithAbsolute: () => (/* binding */ replaceCSSRelativeURLsWithAbsolute)\n/* harmony export */ });\n/* harmony import */ var _utils_array__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../utils/array */ \"./src/utils/array.js\");\n/* harmony import */ var _utils_platform__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../utils/platform */ \"./src/utils/platform.js\");\n/* harmony import */ var _utils_url__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../utils/url */ \"./src/utils/url.js\");\n\n\n\n// import { logInfo, logWarn } from \"../utils/log\";\n\nfunction iterateCSSRules(rules, iterate, onMediaRuleError) {\n (0,_utils_array__WEBPACK_IMPORTED_MODULE_0__.forEach)(rules, rule => {\n // Don't rely on prototype or instanceof, they are slow implementations within the browsers.\n // However we can rely on certain properties to indentify which CSSRule we are dealing with.\n // And it's 2x so fast, https://jsben.ch/B0eLa\n if (rule.selectorText) {\n iterate(rule);\n } else if (rule.href) {\n try {\n iterateCSSRules(rule.styleSheet.cssRules, iterate, onMediaRuleError);\n } catch (err) {\n // logInfo(`Found a non-loaded link.`);\n onMediaRuleError && onMediaRuleError();\n }\n } else if (rule.media) {\n const media = Array.from(rule.media);\n const isScreenOrAllOrQuery = media.some(m => m.startsWith(\"screen\") || m.startsWith(\"all\") || m.startsWith(\"(\"));\n const isPrintOrSpeech = media.some(m => m.startsWith(\"print\") || m.startsWith(\"speech\"));\n if (isScreenOrAllOrQuery || !isPrintOrSpeech) {\n iterateCSSRules(rule.cssRules, iterate, onMediaRuleError);\n }\n } else if (rule.conditionText) {\n if (CSS.supports(rule.conditionText)) {\n iterateCSSRules(rule.cssRules, iterate, onMediaRuleError);\n }\n } else {\n // logWarn(`CSSRule type not supported`, rule);\n }\n });\n}\n\n// These properties are not iterable\n// when they depend on variables\nconst shorthandVarDependantProperties = [\"background\", \"border\", \"border-color\", \"border-bottom\", \"border-left\", \"border-right\", \"border-top\", \"outline\", \"outline-color\"];\nconst shorthandVarDepPropRegexps = _utils_platform__WEBPACK_IMPORTED_MODULE_1__.isSafari ? shorthandVarDependantProperties.map(prop => {\n const regexp = new RegExp(`${prop}:\\\\s*(.*?)\\\\s*;`);\n return [prop, regexp];\n}) : null;\nfunction iterateCSSDeclarations(style, iterate) {\n (0,_utils_array__WEBPACK_IMPORTED_MODULE_0__.forEach)(style, property => {\n const value = style.getPropertyValue(property).trim();\n if (!value) {\n return;\n }\n iterate(property, value);\n });\n\n // Bigger sites like gmail.com and google.com will love this optimization.\n // As a side-effect, styles with a lot of `var(` will notice a maximum slowdown of ~50ms.\n // Against the bigger sites that saves around ~150ms+ it's a good win.\n const cssText = style.cssText;\n if (cssText.includes(\"var(\")) {\n if (_utils_platform__WEBPACK_IMPORTED_MODULE_1__.isSafari) {\n // Safari doesn't show shorthand properties' values\n shorthandVarDepPropRegexps.forEach(([prop, regexp]) => {\n const match = cssText.match(regexp);\n if (match && match[1]) {\n const val = match[1].trim();\n iterate(prop, val);\n }\n });\n } else {\n shorthandVarDependantProperties.forEach(prop => {\n const val = style.getPropertyValue(prop);\n if (val && val.includes(\"var(\")) {\n iterate(prop, val);\n }\n });\n }\n }\n}\nconst cssURLRegex = /url\\((('.*?')|(\".*?\")|([^\\)]*?))\\)/g;\nconst cssImportRegex = /@import\\s*(url\\()?(('.+?')|(\".+?\")|([^\\)]*?))\\)? ?(screen)?;?/gi;\n\n// First try to extract the CSS URL value. Then do some post fixes, like unescaping\n// backslashes in the URL. (Chromium don't handle this natively). Remove all newlines\n// beforehand, otherwise `.` will fail matching the content within the url, as it\n// doesn't match any linebreaks.\nfunction getCSSURLValue(cssURL) {\n return cssURL.trim().replace(/[\\n\\r\\\\]+/g, \"\").replace(/^url\\((.*)\\)$/, \"$1\").trim().replace(/^\"(.*)\"$/, \"$1\").replace(/^'(.*)'$/, \"$1\").replace(/(?:\\\\(.))/g, \"$1\");\n}\nfunction getCSSBaseBath(url) {\n const cssURL = (0,_utils_url__WEBPACK_IMPORTED_MODULE_2__.parseURL)(url);\n return `${cssURL.origin}${cssURL.pathname.replace(/\\?.*$/, \"\").replace(/(\\/)([^\\/]+)$/i, \"$1\")}`;\n}\nfunction replaceCSSRelativeURLsWithAbsolute($css, cssBasePath) {\n return $css.replace(cssURLRegex, match => {\n const pathValue = getCSSURLValue(match);\n // Sites can have any kind of specified URL, thus also invalid ones.\n // To prevent the whole operation from failing, let's just skip those\n // invalid URL's and let them be invalid.\n try {\n return `url('${(0,_utils_url__WEBPACK_IMPORTED_MODULE_2__.getAbsoluteURL)(cssBasePath, pathValue)}')`;\n } catch (err) {\n // logWarn(\"Not able to replace relative URL with Absolute URL, skipping\");\n return match;\n }\n });\n}\nconst cssCommentsRegex = /\\/\\*[\\s\\S]*?\\*\\//g;\nfunction removeCSSComments($css) {\n return $css.replace(cssCommentsRegex, \"\");\n}\nconst fontFaceRegex = /@font-face\\s*{[^}]*}/g;\nfunction replaceCSSFontFace($css) {\n return $css.replace(fontFaceRegex, \"\");\n}\n\n//# sourceURL=webpack://dark-mode/./src/inject/dynamic-theme/css-rules.js?"); /***/ }), /***/ "./src/inject/dynamic-theme/image.js": /*!*******************************************!*\ !*** ./src/inject/dynamic-theme/image.js ***! \*******************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ cleanImageProcessingCache: () => (/* binding */ cleanImageProcessingCache),\n/* harmony export */ getFilteredImageDataURL: () => (/* binding */ getFilteredImageDataURL),\n/* harmony export */ getImageDetails: () => (/* binding */ getImageDetails)\n/* harmony export */ });\n/* harmony import */ var _generators_svg_filter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../generators/svg-filter */ \"./src/generators/svg-filter.js\");\n/* harmony import */ var _utils_color__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../utils/color */ \"./src/utils/color.js\");\n/* harmony import */ var _utils_network__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../utils/network */ \"./src/utils/network.js\");\n/* harmony import */ var _utils_async_queue__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../utils/async-queue */ \"./src/utils/async-queue.js\");\n\n// import { bgFetch } from \"./network\";\n\n\n// import { logInfo, logWarn } from \"../utils/log\";\n\nconst imageManager = new _utils_async_queue__WEBPACK_IMPORTED_MODULE_3__[\"default\"]();\nasync function getImageDetails(url) {\n return new Promise(async (resolve, reject) => {\n let dataURL;\n if (url.startsWith(\"data:\")) {\n dataURL = url;\n } else {\n try {\n dataURL = await getImageDataURL(url);\n } catch (error) {\n reject(error);\n return;\n }\n }\n try {\n const image = await urlToImage(dataURL);\n imageManager.addToQueue(() => {\n resolve({\n src: url,\n dataURL,\n width: image.naturalWidth,\n height: image.naturalHeight,\n ...analyzeImage(image)\n });\n });\n } catch (error) {\n reject(error);\n }\n });\n}\nasync function getImageDataURL(url) {\n const parsedURL = new URL(url);\n if (parsedURL.origin === location.origin) {\n return await (0,_utils_network__WEBPACK_IMPORTED_MODULE_2__.loadAsDataURL)(url);\n }\n // return await bgFetch({ url, responseType: \"data-url\" });\n}\nasync function urlToImage(url) {\n return new Promise((resolve, reject) => {\n const image = new Image();\n image.onload = () => resolve(image);\n image.onerror = () => reject(`Unable to load image ${url}`);\n image.src = url;\n });\n}\nconst MAX_ANALIZE_PIXELS_COUNT = 32 * 32;\nlet canvas;\nlet context;\nfunction createCanvas() {\n const maxWidth = MAX_ANALIZE_PIXELS_COUNT;\n const maxHeight = MAX_ANALIZE_PIXELS_COUNT;\n canvas = document.createElement(\"canvas\");\n canvas.width = maxWidth;\n canvas.height = maxHeight;\n context = canvas.getContext(\"2d\", {\n willReadFrequently: true\n });\n context.imageSmoothingEnabled = false;\n}\nfunction removeCanvas() {\n canvas = null;\n context = null;\n}\n\n// 5MB\nconst MAX_IMAGE_SIZE = 5 * 1024 * 1024;\nfunction analyzeImage(image) {\n if (!canvas) {\n createCanvas();\n }\n const {\n naturalWidth,\n naturalHeight\n } = image;\n if (naturalHeight === 0 || naturalWidth === 0) {\n // logWarn(`logWarn(Image is empty ${image.currentSrc})`);\n return {\n isDark: false,\n isLight: false,\n isTransparent: false,\n isLarge: false,\n isTooLarge: false\n };\n }\n\n // Get good appromized image size in memory terms.\n // Width * Height * 4(R, G, B, A) and 500B(metadata) because rgba can contain up to 3 digits.\n const size = naturalWidth * naturalHeight * 4;\n // Is it over ~5MB? Let's not decode the image, it's something that's useless to analyze.\n // And very performance senstive for the browser to decode this image(~50ms) and take into account\n // It's being async `drawImage` calls.\n if (size > MAX_IMAGE_SIZE) {\n // logInfo(\"Skipped large image analyzing(Larger than 5mb in memory)\");\n return {\n isDark: false,\n isLight: false,\n isTransparent: false,\n isLarge: false,\n isTooLarge: true\n };\n }\n const naturalPixelsCount = naturalWidth * naturalHeight;\n const k = Math.min(1, Math.sqrt(MAX_ANALIZE_PIXELS_COUNT / naturalPixelsCount));\n const width = Math.ceil(naturalWidth * k);\n const height = Math.ceil(naturalHeight * k);\n context.clearRect(0, 0, width, height);\n context.drawImage(image, 0, 0, naturalWidth, naturalHeight, 0, 0, width, height);\n const imageData = context.getImageData(0, 0, width, height);\n const d = imageData.data;\n const TRANSPARENT_ALPHA_THRESHOLD = 0.05;\n const DARK_LIGHTNESS_THRESHOLD = 0.4;\n const LIGHT_LIGHTNESS_THRESHOLD = 0.7;\n let transparentPixelsCount = 0;\n let darkPixelsCount = 0;\n let lightPixelsCount = 0;\n let i, x, y;\n let r, g, b, a;\n let l;\n for (y = 0; y < height; y++) {\n for (x = 0; x < width; x++) {\n i = 4 * (y * width + x);\n r = d[i + 0];\n g = d[i + 1];\n b = d[i + 2];\n a = d[i + 3];\n if (a / 255 < TRANSPARENT_ALPHA_THRESHOLD) {\n transparentPixelsCount++;\n } else {\n l = (0,_utils_color__WEBPACK_IMPORTED_MODULE_1__.getSRGBLightness)(r, g, b);\n if (l < DARK_LIGHTNESS_THRESHOLD) {\n darkPixelsCount++;\n }\n if (l > LIGHT_LIGHTNESS_THRESHOLD) {\n lightPixelsCount++;\n }\n }\n }\n }\n const totalPixelsCount = width * height;\n const opaquePixelsCount = totalPixelsCount - transparentPixelsCount;\n const DARK_IMAGE_THRESHOLD = 0.7;\n const LIGHT_IMAGE_THRESHOLD = 0.7;\n const TRANSPARENT_IMAGE_THRESHOLD = 0.1;\n const LARGE_IMAGE_PIXELS_COUNT = 800 * 600;\n return {\n isDark: darkPixelsCount / opaquePixelsCount >= DARK_IMAGE_THRESHOLD,\n isLight: lightPixelsCount / opaquePixelsCount >= LIGHT_IMAGE_THRESHOLD,\n isTransparent: transparentPixelsCount / totalPixelsCount >= TRANSPARENT_IMAGE_THRESHOLD,\n isLarge: naturalPixelsCount >= LARGE_IMAGE_PIXELS_COUNT,\n isTooLarge: false\n };\n}\nfunction getFilteredImageDataURL({\n dataURL,\n width,\n height\n}, theme) {\n const matrix = (0,_generators_svg_filter__WEBPACK_IMPORTED_MODULE_0__.getSVGFilterMatrixValue)(theme);\n const svg = [``, \"\", '', ``, \"\", \"\", ``, \"\"].join(\"\");\n return `data:image/svg+xml;base64,${btoa(svg)}`;\n}\nfunction cleanImageProcessingCache() {\n imageManager && imageManager.stopQueue();\n removeCanvas();\n}\n\n//# sourceURL=webpack://dark-mode/./src/inject/dynamic-theme/image.js?"); /***/ }), /***/ "./src/inject/dynamic-theme/index.js": /*!*******************************************!*\ !*** ./src/inject/dynamic-theme/index.js ***! \*******************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ cleanDynamicThemeCache: () => (/* binding */ cleanDynamicThemeCache),\n/* harmony export */ removeDynamicTheme: () => (/* binding */ removeDynamicTheme),\n/* harmony export */ run_createThemeAndWatchForUpdates: () => (/* binding */ run_createThemeAndWatchForUpdates)\n/* harmony export */ });\n/* harmony import */ var _default__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../default */ \"./src/default.js\");\n/* harmony import */ var _generators_css_filter__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../generators/css-filter */ \"./src/generators/css-filter.js\");\n/* harmony import */ var _generators_modify_colors__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../generators/modify-colors */ \"./src/generators/modify-colors.js\");\n/* harmony import */ var _utils_array__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../utils/array */ \"./src/utils/array.js\");\n/* harmony import */ var _utils_color__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../utils/color */ \"./src/utils/color.js\");\n/* harmony import */ var _utils_throttle__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../utils/throttle */ \"./src/utils/throttle.js\");\n/* harmony import */ var _utils_url__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../utils/url */ \"./src/utils/url.js\");\n/* harmony import */ var _utils_visibility__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../utils/visibility */ \"./src/utils/visibility.js\");\n/* harmony import */ var _utils_dom__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/dom */ \"./src/inject/utils/dom.js\");\n/* harmony import */ var _inline_style__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./inline-style */ \"./src/inject/dynamic-theme/inline-style.js\");\n/* harmony import */ var _modify_css__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./modify-css */ \"./src/inject/dynamic-theme/modify-css.js\");\n/* harmony import */ var _style_manager__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./style-manager */ \"./src/inject/dynamic-theme/style-manager.js\");\n/* harmony import */ var _variables__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./variables */ \"./src/inject/dynamic-theme/variables.js\");\n/* harmony import */ var _watch__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./watch */ \"./src/inject/dynamic-theme/watch.js\");\n\n\n\n\n\n\n\n\n\n// import { logInfo } from \"../utils/log\";\n\n\n\n\n\nlet filter = _default__WEBPACK_IMPORTED_MODULE_0__.DEFAULT_THEME;\nlet fixes = null;\nlet isIFrame = null;\nconst styleManagers = new Map();\nlet ignoredImageAnalysisSelectors = [];\nlet ignoredInlineSelectors = [];\nconst adoptedStyleManagers = [];\nfunction createOrUpdateStyle(className, root = document.head || document) {\n let element = root.querySelector(`.${className}`);\n if (!element) {\n element = document.createElement(\"style\");\n element.classList.add(\"adminify\");\n element.classList.add(className);\n element.media = \"screen\";\n element.textContent = \"\";\n }\n return element;\n}\nconst nodePositionWatchers = new Map();\n\n// **important**\nfunction setupNodePositionWatcher(node, alias) {\n nodePositionWatchers.has(alias) && nodePositionWatchers.get(alias).stop();\n nodePositionWatchers.set(alias, (0,_utils_dom__WEBPACK_IMPORTED_MODULE_8__.watchForNodePosition)(node, \"head\"));\n}\nfunction createStaticStyleOverrides() {\n const fallbackStyle = createOrUpdateStyle(\"adminify--fallback\", document);\n fallbackStyle.textContent = (0,_modify_css__WEBPACK_IMPORTED_MODULE_10__.getModifiedFallbackStyle)(filter, {\n strict: true\n });\n document.head.insertBefore(fallbackStyle, document.head.firstChild);\n setupNodePositionWatcher(fallbackStyle, \"fallback\");\n const userAgentStyle = createOrUpdateStyle(\"adminify--user-agent\");\n userAgentStyle.textContent = (0,_modify_css__WEBPACK_IMPORTED_MODULE_10__.getModifiedUserAgentStyle)(filter, isIFrame, filter.styleSystemControls);\n document.head.insertBefore(userAgentStyle, fallbackStyle.nextSibling);\n setupNodePositionWatcher(userAgentStyle, \"user-agent\");\n const textStyle = createOrUpdateStyle(\"adminify--text\");\n if (filter.useFont || filter.textStroke > 0) {\n textStyle.textContent = createTextStyle(filter);\n } else {\n textStyle.textContent = \"\";\n }\n document.head.insertBefore(textStyle, fallbackStyle.nextSibling);\n setupNodePositionWatcher(textStyle, \"text\");\n const invertStyle = createOrUpdateStyle(\"adminify--invert\");\n if (fixes && Array.isArray(fixes.invert) && fixes.invert.length > 0) {\n invertStyle.textContent = [`${fixes.invert.join(\", \")} {`, ` filter: ${(0,_generators_css_filter__WEBPACK_IMPORTED_MODULE_1__.getCSSFilterValue)({\n ...filter,\n contrast: filter.mode === 0 ? filter.contrast : clamp(filter.contrast - 10, 0, 100)\n })} !important;`, \"}\"].join(\"\\n\");\n } else {\n invertStyle.textContent = \"\";\n }\n document.head.insertBefore(invertStyle, textStyle.nextSibling);\n setupNodePositionWatcher(invertStyle, \"invert\");\n const inlineStyle = createOrUpdateStyle(\"adminify--inline\");\n inlineStyle.textContent = (0,_inline_style__WEBPACK_IMPORTED_MODULE_9__.getInlineOverrideStyle)();\n document.head.insertBefore(inlineStyle, invertStyle.nextSibling);\n setupNodePositionWatcher(inlineStyle, \"inline\");\n const overrideStyle = createOrUpdateStyle(\"adminify--override\");\n overrideStyle.textContent = fixes && fixes.css ? replaceCSSTemplates(fixes.css) : \"\";\n document.head.appendChild(overrideStyle);\n setupNodePositionWatcher(overrideStyle, \"override\");\n const variableStyle = createOrUpdateStyle(\"adminify--variables\");\n const selectionColors = (0,_modify_css__WEBPACK_IMPORTED_MODULE_10__.getSelectionColor)(filter);\n const {\n darkSchemeBackgroundColor,\n darkSchemeTextColor,\n lightSchemeBackgroundColor,\n lightSchemeTextColor,\n mode\n } = filter;\n let schemeBackgroundColor = mode === 0 ? lightSchemeBackgroundColor : darkSchemeBackgroundColor;\n let schemeTextColor = mode === 0 ? lightSchemeTextColor : darkSchemeTextColor;\n schemeBackgroundColor = (0,_generators_modify_colors__WEBPACK_IMPORTED_MODULE_2__.modifyBackgroundColor)((0,_utils_color__WEBPACK_IMPORTED_MODULE_4__.parseColorWithCache)(schemeBackgroundColor), filter);\n schemeTextColor = (0,_generators_modify_colors__WEBPACK_IMPORTED_MODULE_2__.modifyForegroundColor)((0,_utils_color__WEBPACK_IMPORTED_MODULE_4__.parseColorWithCache)(schemeTextColor), filter);\n variableStyle.textContent = [`:root {`, ` --adminify-neutral-background: ${schemeBackgroundColor};`, ` --adminify-neutral-text: ${schemeTextColor};`, ` --adminify-selection-background: ${selectionColors.backgroundColorSelection};`, ` --adminify-selection-text: ${selectionColors.foregroundColorSelection};`, `}`].join(\"\\n\");\n document.head.insertBefore(variableStyle, inlineStyle.nextSibling);\n setupNodePositionWatcher(variableStyle, \"variables\");\n const rootVarsStyle = createOrUpdateStyle(\"adminify--root-vars\");\n document.head.insertBefore(rootVarsStyle, variableStyle.nextSibling);\n\n //Media Grayscale\n if (filter.imgGrayscale || filter.videoGrayscale) {\n const adminifyMediaCSS = createOrUpdateStyle(\"adminify--media\", document);\n adminifyMediaCSS.textContent = `${filter.imgGrayscale ? `img{filter: grayscale(${filter.imgGrayscalePercent})}` : \"\"}${filter.videoGrayscale ? `video, .wp-block-embed-youtube, .wp-block-embed[data-title=\"YouTube\"]{filter: grayscale(${filter.videoGrayscalePercent})}` : \"\"}`;\n document.head.insertBefore(adminifyMediaCSS, rootVarsStyle.nextSibling);\n setupNodePositionWatcher(adminifyMediaCSS, \"media\");\n }\n}\nfunction runDynamicStyle() {\n createDynamicStyleOverrides();\n // watchForUpdates();\n}\nfunction createThemeAndWatchForUpdates() {\n createStaticStyleOverrides();\n if (!(0,_utils_visibility__WEBPACK_IMPORTED_MODULE_7__.documentIsVisible)() && !filter.immediateModify) {\n (0,_utils_visibility__WEBPACK_IMPORTED_MODULE_7__.setDocumentVisibilityListener)(runDynamicStyle);\n } else {\n runDynamicStyle();\n }\n // changeMetaThemeColorWhenAvailable(filter);\n}\n\n//Main Func\nfunction run_createThemeAndWatchForUpdates(config) {\n filter = {\n ...filter,\n ...config\n };\n createThemeAndWatchForUpdates();\n}\nlet loadingStylesCounter = 0;\nconst loadingStyles = new Set();\nfunction createManager(element) {\n const loadingStyleId = ++loadingStylesCounter;\n // logInfo(`New manager for element, with loadingStyleID ${loadingStyleId}`, element);\n\n function loadingStart() {\n if (!(0,_utils_dom__WEBPACK_IMPORTED_MODULE_8__.isDOMReady)() || !(0,_utils_visibility__WEBPACK_IMPORTED_MODULE_7__.documentIsVisible)()) {\n loadingStyles.add(loadingStyleId);\n // logInfo(`Current amount of styles loading: ${loadingStyles.size}`);\n\n const fallbackStyle = document.querySelector(\".adminify--fallback\");\n if (!fallbackStyle.textContent) {\n fallbackStyle.textContent = (0,_modify_css__WEBPACK_IMPORTED_MODULE_10__.getModifiedFallbackStyle)(filter, {\n strict: false\n });\n }\n }\n }\n function loadingEnd() {\n loadingStyles.delete(loadingStyleId);\n // logInfo(`Removed loadingStyle ${loadingStyleId}, now awaiting: ${loadingStyles.size}`);\n // logInfo(`To-do to be loaded`, loadingStyles);\n\n // if (loadingStyles.size === 0 && isDOMReady()) {\n if (loadingStyles.size === 0) {\n cleanFallbackStyle();\n }\n }\n function update() {\n const details = manager.details({\n secondRound: true\n });\n if (!details) {\n return;\n }\n _variables__WEBPACK_IMPORTED_MODULE_12__.variablesStore.addRulesForMatching(details.rules);\n _variables__WEBPACK_IMPORTED_MODULE_12__.variablesStore.matchVariablesAndDependants();\n manager.render(filter, ignoredImageAnalysisSelectors);\n }\n const manager = (0,_style_manager__WEBPACK_IMPORTED_MODULE_11__.manageStyle)(element, {\n update,\n loadingStart,\n loadingEnd\n });\n styleManagers.set(element, manager);\n return manager;\n}\nfunction createDynamicStyleOverrides() {\n const allStyles = (0,_style_manager__WEBPACK_IMPORTED_MODULE_11__.getManageableStyles)(document);\n const newManagers = allStyles.filter(style => !styleManagers.has(style)).map(style => createManager(style));\n newManagers.map(manager => manager.details({\n secondRound: false\n })).filter(detail => detail && detail.rules.length > 0).forEach(detail => {\n _variables__WEBPACK_IMPORTED_MODULE_12__.variablesStore.addRulesForMatching(detail.rules);\n });\n _variables__WEBPACK_IMPORTED_MODULE_12__.variablesStore.matchVariablesAndDependants();\n _variables__WEBPACK_IMPORTED_MODULE_12__.variablesStore.setOnRootVariableChange(() => {\n const rootVarsStyle = createOrUpdateStyle(\"adminify--root-vars\");\n _variables__WEBPACK_IMPORTED_MODULE_12__.variablesStore.putRootVars(rootVarsStyle, filter);\n });\n const rootVarsStyle = createOrUpdateStyle(\"adminify--root-vars\");\n _variables__WEBPACK_IMPORTED_MODULE_12__.variablesStore.putRootVars(rootVarsStyle, filter);\n styleManagers.forEach(manager => manager.render(filter, ignoredImageAnalysisSelectors));\n if (loadingStyles.size === 0) {\n cleanFallbackStyle();\n }\n newManagers.forEach(manager => manager.watch());\n const inlineStyleElements = (0,_utils_array__WEBPACK_IMPORTED_MODULE_3__.toArray)(document.querySelectorAll(_inline_style__WEBPACK_IMPORTED_MODULE_9__.INLINE_STYLE_SELECTOR));\n (0,_utils_dom__WEBPACK_IMPORTED_MODULE_8__.iterateShadowHosts)(document.documentElement, host => {\n createShadowStaticStyleOverrides(host.shadowRoot);\n const elements = host.shadowRoot.querySelectorAll(_inline_style__WEBPACK_IMPORTED_MODULE_9__.INLINE_STYLE_SELECTOR);\n if (elements.length > 0) {\n push(inlineStyleElements, elements);\n }\n });\n inlineStyleElements.forEach(el => (0,_inline_style__WEBPACK_IMPORTED_MODULE_9__.overrideInlineStyle)(el, filter, ignoredInlineSelectors, ignoredImageAnalysisSelectors));\n // handleAdoptedStyleSheets(document);\n}\nfunction cleanFallbackStyle() {\n const fallback = document.querySelector(\".adminify--fallback\");\n if (fallback) {\n fallback.textContent = \"\";\n }\n}\nfunction replaceCSSTemplates($cssText) {\n return $cssText.replace(/\\${(.+?)}/g, (_, $color) => {\n const color = (0,_utils_color__WEBPACK_IMPORTED_MODULE_4__.parseColorWithCache)($color);\n if (color) {\n return (0,_generators_modify_colors__WEBPACK_IMPORTED_MODULE_2__.modifyColor)(color, filter);\n }\n // logWarn(\"Couldn't parse CSSTemplate's color.\");\n return $color;\n });\n}\nfunction createShadowStaticStyleOverrides(root) {\n // The shadow DOM may not be populated yet and the custom element implementation\n // may assume that unpopulated shadow root is empty and inadvertently remove\n // Dark Reader's overrides\n const uninit = root.firstChild === null;\n createShadowStaticStyleOverridesInner(root);\n if (uninit) {\n delayedCreateShadowStaticStyleOverrides(root);\n }\n}\nconst shadowRootsWithOverrides = new Set();\nfunction createShadowStaticStyleOverridesInner(root) {\n const inlineStyle = createOrUpdateStyle(\"adminify--inline\", root);\n inlineStyle.textContent = (0,_inline_style__WEBPACK_IMPORTED_MODULE_9__.getInlineOverrideStyle)();\n root.insertBefore(inlineStyle, root.firstChild);\n const overrideStyle = createOrUpdateStyle(\"adminify--override\", root);\n overrideStyle.textContent = fixes && fixes.css ? replaceCSSTemplates(fixes.css) : \"\";\n root.insertBefore(overrideStyle, inlineStyle.nextSibling);\n const invertStyle = createOrUpdateStyle(\"adminify--invert\", root);\n if (fixes && Array.isArray(fixes.invert) && fixes.invert.length > 0) {\n invertStyle.textContent = [`${fixes.invert.join(\", \")} {`, ` filter: ${(0,_generators_css_filter__WEBPACK_IMPORTED_MODULE_1__.getCSSFilterValue)({\n ...filter,\n contrast: filter.mode === 0 ? filter.contrast : clamp(filter.contrast - 10, 0, 100)\n })} !important;`, \"}\"].join(\"\\n\");\n } else {\n invertStyle.textContent = \"\";\n }\n root.insertBefore(invertStyle, overrideStyle.nextSibling);\n shadowRootsWithOverrides.add(root);\n}\nfunction delayedCreateShadowStaticStyleOverrides(root) {\n const observer = new MutationObserver((mutations, observer) => {\n // Disconnect observer immediatelly before making any other changes\n observer.disconnect();\n\n // Do not make any changes unless Dark Reader's fixes have been removed\n for (const {\n type,\n removedNodes\n } of mutations) {\n if (type === \"childList\") {\n for (const {\n nodeName,\n className\n } of removedNodes) {\n if (nodeName === \"STYLE\" && [\"adminify adminify--inline\", \"adminify adminify--override\", \"adminify adminify--invert\"].includes(className)) {\n createShadowStaticStyleOverridesInner(root);\n return;\n }\n }\n }\n }\n });\n observer.observe(root, {\n childList: true\n });\n}\n\n//remove styles\n\nfunction removeManager(element) {\n const manager = styleManagers.get(element);\n if (manager) {\n manager.destroy();\n styleManagers.delete(element);\n }\n}\nconst throttledRenderAllStyles = (0,_utils_throttle__WEBPACK_IMPORTED_MODULE_5__.throttle)(callback => {\n styleManagers.forEach(manager => manager.render(filter, ignoredImageAnalysisSelectors));\n adoptedStyleManagers.forEach(manager => manager.render(filter, ignoredImageAnalysisSelectors));\n callback && callback();\n});\nconst cancelRendering = function () {\n throttledRenderAllStyles.cancel();\n};\nlet metaObserver;\nfunction removeDynamicTheme() {\n document.documentElement.removeAttribute(`data-adminify-mode`);\n document.documentElement.removeAttribute(`data-adminify-scheme`);\n cleanDynamicThemeCache();\n (0,_utils_dom__WEBPACK_IMPORTED_MODULE_8__.removeNode)(document.querySelector(\".adminify--fallback\"));\n if (document.head) {\n // restoreMetaThemeColor();\n (0,_utils_dom__WEBPACK_IMPORTED_MODULE_8__.removeNode)(document.head.querySelector(\".adminify--user-agent\"));\n (0,_utils_dom__WEBPACK_IMPORTED_MODULE_8__.removeNode)(document.head.querySelector(\".adminify--text\"));\n (0,_utils_dom__WEBPACK_IMPORTED_MODULE_8__.removeNode)(document.head.querySelector(\".adminify--invert\"));\n (0,_utils_dom__WEBPACK_IMPORTED_MODULE_8__.removeNode)(document.head.querySelector(\".adminify--inline\"));\n (0,_utils_dom__WEBPACK_IMPORTED_MODULE_8__.removeNode)(document.head.querySelector(\".adminify--override\"));\n (0,_utils_dom__WEBPACK_IMPORTED_MODULE_8__.removeNode)(document.head.querySelector(\".adminify--variables\"));\n (0,_utils_dom__WEBPACK_IMPORTED_MODULE_8__.removeNode)(document.head.querySelector(\".adminify--root-vars\"));\n (0,_utils_dom__WEBPACK_IMPORTED_MODULE_8__.removeNode)(document.head.querySelector('meta[name=\"adminify\"]'));\n // removeProxy();\n }\n shadowRootsWithOverrides.forEach(root => {\n (0,_utils_dom__WEBPACK_IMPORTED_MODULE_8__.removeNode)(root.querySelector(\".adminify--inline\"));\n (0,_utils_dom__WEBPACK_IMPORTED_MODULE_8__.removeNode)(root.querySelector(\".adminify--override\"));\n });\n shadowRootsWithOverrides.clear();\n (0,_utils_array__WEBPACK_IMPORTED_MODULE_3__.forEach)(styleManagers.keys(), el => removeManager(el));\n loadingStyles.clear();\n\n // cleanLoadingLinks();\n // forEach(document.querySelectorAll(\".adminify\"), removeNode);\n // adoptedStyleManagers.forEach((manager) => {\n // manager.destroy();\n // });\n // adoptedStyleManagers.splice(0);\n // metaObserver && metaObserver.disconnect();\n}\nfunction cleanDynamicThemeCache() {\n _variables__WEBPACK_IMPORTED_MODULE_12__.variablesStore.clear();\n _utils_url__WEBPACK_IMPORTED_MODULE_6__.parsedURLCache.clear();\n (0,_utils_visibility__WEBPACK_IMPORTED_MODULE_7__.removeDocumentVisibilityListener)();\n cancelRendering();\n stopWatchingForUpdates();\n (0,_modify_css__WEBPACK_IMPORTED_MODULE_10__.cleanModificationCache)();\n (0,_utils_color__WEBPACK_IMPORTED_MODULE_4__.clearColorCache)();\n}\nfunction stopWatchingForUpdates() {\n styleManagers.forEach(manager => manager.pause());\n stopStylePositionWatchers();\n (0,_watch__WEBPACK_IMPORTED_MODULE_13__.stopWatchingForStyleChanges)();\n (0,_inline_style__WEBPACK_IMPORTED_MODULE_9__.stopWatchingForInlineStyles)();\n (0,_utils_dom__WEBPACK_IMPORTED_MODULE_8__.removeDOMReadyListener)(onDOMReady);\n (0,_utils_dom__WEBPACK_IMPORTED_MODULE_8__.cleanReadyStateCompleteListeners)();\n}\nfunction stopStylePositionWatchers() {\n (0,_utils_array__WEBPACK_IMPORTED_MODULE_3__.forEach)(nodePositionWatchers.values(), watcher => watcher.stop());\n nodePositionWatchers.clear();\n}\nfunction onDOMReady() {\n if (loadingStyles.size === 0) {\n cleanFallbackStyle();\n return;\n }\n // logWarn(`DOM is ready, but still have styles being loaded.`, loadingStyles);\n}\n\n//# sourceURL=webpack://dark-mode/./src/inject/dynamic-theme/index.js?"); /***/ }), /***/ "./src/inject/dynamic-theme/inline-style.js": /*!**************************************************!*\ !*** ./src/inject/dynamic-theme/inline-style.js ***! \**************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ INLINE_STYLE_SELECTOR: () => (/* binding */ INLINE_STYLE_SELECTOR),\n/* harmony export */ getInlineOverrideStyle: () => (/* binding */ getInlineOverrideStyle),\n/* harmony export */ overrideInlineStyle: () => (/* binding */ overrideInlineStyle),\n/* harmony export */ stopWatchingForInlineStyles: () => (/* binding */ stopWatchingForInlineStyles)\n/* harmony export */ });\n/* harmony import */ var _utils_array__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../utils/array */ \"./src/utils/array.js\");\n/* harmony import */ var _utils_dom__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/dom */ \"./src/inject/utils/dom.js\");\n/* harmony import */ var _css_rules__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./css-rules */ \"./src/inject/dynamic-theme/css-rules.js\");\n/* harmony import */ var _modify_css__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./modify-css */ \"./src/inject/dynamic-theme/modify-css.js\");\n/* harmony import */ var _variables__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./variables */ \"./src/inject/dynamic-theme/variables.js\");\n\n\n\n\n\nconst overrides = {\n \"background-color\": {\n customProp: \"--adminify-inline-bgcolor\",\n cssProp: \"background-color\",\n dataAttr: \"data-adminify-inline-bgcolor\"\n },\n \"background-image\": {\n customProp: \"--adminify-inline-bgimage\",\n cssProp: \"background-image\",\n dataAttr: \"data-adminify-inline-bgimage\"\n },\n \"border-color\": {\n customProp: \"--adminify-inline-border\",\n cssProp: \"border-color\",\n dataAttr: \"data-adminify-inline-border\"\n },\n \"border-bottom-color\": {\n customProp: \"--adminify-inline-border-bottom\",\n cssProp: \"border-bottom-color\",\n dataAttr: \"data-adminify-inline-border-bottom\"\n },\n \"border-left-color\": {\n customProp: \"--adminify-inline-border-left\",\n cssProp: \"border-left-color\",\n dataAttr: \"data-adminify-inline-border-left\"\n },\n \"border-right-color\": {\n customProp: \"--adminify-inline-border-right\",\n cssProp: \"border-right-color\",\n dataAttr: \"data-adminify-inline-border-right\"\n },\n \"border-top-color\": {\n customProp: \"--adminify-inline-border-top\",\n cssProp: \"border-top-color\",\n dataAttr: \"data-adminify-inline-border-top\"\n },\n \"box-shadow\": {\n customProp: \"--adminify-inline-boxshadow\",\n cssProp: \"box-shadow\",\n dataAttr: \"data-adminify-inline-boxshadow\"\n },\n color: {\n customProp: \"--adminify-inline-color\",\n cssProp: \"color\",\n dataAttr: \"data-adminify-inline-color\"\n },\n fill: {\n customProp: \"--adminify-inline-fill\",\n cssProp: \"fill\",\n dataAttr: \"data-adminify-inline-fill\"\n },\n stroke: {\n customProp: \"--adminify-inline-stroke\",\n cssProp: \"stroke\",\n dataAttr: \"data-adminify-inline-stroke\"\n },\n \"outline-color\": {\n customProp: \"--adminify-inline-outline\",\n cssProp: \"outline-color\",\n dataAttr: \"data-adminify-inline-outline\"\n },\n \"stop-color\": {\n customProp: \"--adminify-inline-stopcolor\",\n cssProp: \"stop-color\",\n dataAttr: \"data-adminify-inline-stopcolor\"\n }\n};\nconst overridesList = Object.values(overrides);\nconst normalizedPropList = {};\noverridesList.forEach(({\n cssProp,\n customProp\n}) => normalizedPropList[customProp] = cssProp);\nconst INLINE_STYLE_ATTRS = [\"style\", \"fill\", \"stop-color\", \"stroke\", \"bgcolor\", \"color\"];\nconst INLINE_STYLE_SELECTOR = INLINE_STYLE_ATTRS.map(attr => `[${attr}]`).join(\", \");\nfunction getInlineOverrideStyle() {\n return overridesList.map(({\n dataAttr,\n customProp,\n cssProp\n }) => {\n return [`[${dataAttr}] {`, ` ${cssProp}: var(${customProp}) !important;`, \"}\"].join(\"\\n\");\n }).join(\"\\n\");\n}\nconst inlineStyleCache = new WeakMap();\nconst filterProps = [\"brightness\", \"contrast\", \"grayscale\", \"sepia\", \"mode\"];\nfunction getInlineStyleCacheKey(el, theme) {\n return INLINE_STYLE_ATTRS.map(attr => `${attr}=\"${el.getAttribute(attr)}\"`).concat(filterProps.map(prop => `${prop}=\"${theme[prop]}\"`)).join(\" \");\n}\nfunction overrideInlineStyle(element, theme, ignoreInlineSelectors, ignoreImageSelectors) {\n const cacheKey = getInlineStyleCacheKey(element, theme);\n if (cacheKey === inlineStyleCache.get(element)) {\n return;\n }\n const unsetProps = new Set(Object.keys(overrides));\n function setCustomProp(targetCSSProp, modifierCSSProp, cssVal) {\n const isPropertyVariable = targetCSSProp.startsWith(\"--\");\n const {\n customProp,\n dataAttr\n } = isPropertyVariable ? {} : overrides[targetCSSProp];\n const mod = (0,_modify_css__WEBPACK_IMPORTED_MODULE_3__.getModifiableCSSDeclaration)(modifierCSSProp, cssVal, {\n style: element.style\n }, _variables__WEBPACK_IMPORTED_MODULE_4__.variablesStore, ignoreImageSelectors, null);\n if (!mod) {\n return;\n }\n let value = mod.value;\n if (typeof value === \"function\") {\n value = value(theme);\n }\n\n // typeof value === 'object' always evaluate to true when\n // `isPropertyVariable` is true, but it serves as a type hint for typescript.\n // Such that `as ReturnType` won't error about the possible\n // string type.\n if (isPropertyVariable && typeof value === \"object\") {\n const typedValue = value;\n typedValue.declarations.forEach(({\n property,\n value\n }) => {\n !(value instanceof Promise) && element.style.setProperty(property, value);\n });\n\n // TODO: add listener for `onTypeChange`.\n } else {\n element.style.setProperty(customProp, value);\n if (!element.hasAttribute(dataAttr)) {\n element.setAttribute(dataAttr, \"\");\n }\n unsetProps.delete(targetCSSProp);\n }\n }\n if (ignoreInlineSelectors.length > 0) {\n if (shouldIgnoreInlineStyle(element, ignoreInlineSelectors)) {\n unsetProps.forEach(cssProp => {\n element.removeAttribute(overrides[cssProp].dataAttr);\n });\n return;\n }\n }\n if (element.hasAttribute(\"bgcolor\")) {\n let value = element.getAttribute(\"bgcolor\");\n if (value.match(/^[0-9a-f]{3}$/i) || value.match(/^[0-9a-f]{6}$/i)) {\n value = `#${value}`;\n }\n setCustomProp(\"background-color\", \"background-color\", value);\n }\n\n // We can catch some link elements here, that are from ``.\n // It's valid HTML code according to the specs, https://html.spec.whatwg.org/#attr-link-color\n // We don't want to touch such links, as it cause weird browser behavior (silent DOMException).\n if (element.hasAttribute(\"color\") && element.rel !== \"mask-icon\") {\n let value = element.getAttribute(\"color\");\n if (value.match(/^[0-9a-f]{3}$/i) || value.match(/^[0-9a-f]{6}$/i)) {\n value = `#${value}`;\n }\n setCustomProp(\"color\", \"color\", value);\n }\n if (element instanceof SVGElement) {\n if (element.hasAttribute(\"fill\")) {\n const SMALL_SVG_LIMIT = 32;\n const value = element.getAttribute(\"fill\");\n if (value !== \"none\") {\n if (!(element instanceof SVGTextElement)) {\n // getBoundingClientRect forces a layout change. And when it happens and\n // the DOM is not in the `complete` readystate, it will cause the layout to be drawn\n // and it will cause a layout of unstyled content which results in white flashes.\n // Therefore, check if the DOM is at the `complete` readystate.\n const handleSVGElement = () => {\n const {\n width,\n height\n } = element.getBoundingClientRect();\n const isBg = width > SMALL_SVG_LIMIT || height > SMALL_SVG_LIMIT;\n setCustomProp(\"fill\", isBg ? \"background-color\" : \"color\", value);\n };\n if ((0,_utils_dom__WEBPACK_IMPORTED_MODULE_1__.isReadyStateComplete)()) {\n handleSVGElement();\n } else {\n (0,_utils_dom__WEBPACK_IMPORTED_MODULE_1__.addReadyStateCompleteListener)(handleSVGElement);\n }\n } else {\n setCustomProp(\"fill\", \"color\", value);\n }\n }\n }\n if (element.hasAttribute(\"stop-color\")) {\n setCustomProp(\"stop-color\", \"background-color\", element.getAttribute(\"stop-color\"));\n }\n }\n if (element.hasAttribute(\"stroke\")) {\n const value = element.getAttribute(\"stroke\");\n setCustomProp(\"stroke\", element instanceof SVGLineElement || element instanceof SVGTextElement ? \"border-color\" : \"color\", value);\n }\n element.style && (0,_css_rules__WEBPACK_IMPORTED_MODULE_2__.iterateCSSDeclarations)(element.style, (property, value) => {\n // Temporarily ignore background images due to the possible performance\n // issues and complexity of handling async requests.\n if (property === \"background-image\" && value.includes(\"url\")) {\n return;\n }\n if (overrides.hasOwnProperty(property) || property.startsWith(\"--\") && !normalizedPropList[property]) {\n setCustomProp(property, property, value);\n } else {\n const overridenProp = normalizedPropList[property];\n if (overridenProp && !element.style.getPropertyValue(overridenProp) && !element.hasAttribute(overridenProp)) {\n if (overridenProp === \"background-color\" && element.hasAttribute(\"bgcolor\")) {\n return;\n }\n element.style.setProperty(property, \"\");\n }\n }\n });\n if (element.style && element instanceof SVGTextElement && element.style.fill) {\n setCustomProp(\"fill\", \"color\", element.style.getPropertyValue(\"fill\"));\n }\n (0,_utils_array__WEBPACK_IMPORTED_MODULE_0__.forEach)(unsetProps, cssProp => {\n element.removeAttribute(overrides[cssProp].dataAttr);\n });\n inlineStyleCache.set(element, getInlineStyleCacheKey(element, theme));\n}\nconst treeObservers = new Map();\nconst attrObservers = new Map();\nfunction stopWatchingForInlineStyles() {\n treeObservers.forEach(o => o.disconnect());\n attrObservers.forEach(o => o.disconnect());\n treeObservers.clear();\n attrObservers.clear();\n}\n\n//# sourceURL=webpack://dark-mode/./src/inject/dynamic-theme/inline-style.js?"); /***/ }), /***/ "./src/inject/dynamic-theme/modify-css.js": /*!************************************************!*\ !*** ./src/inject/dynamic-theme/modify-css.js ***! \************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ cleanModificationCache: () => (/* binding */ cleanModificationCache),\n/* harmony export */ getBgImageModifier: () => (/* binding */ getBgImageModifier),\n/* harmony export */ getModifiableCSSDeclaration: () => (/* binding */ getModifiableCSSDeclaration),\n/* harmony export */ getModifiedFallbackStyle: () => (/* binding */ getModifiedFallbackStyle),\n/* harmony export */ getModifiedUserAgentStyle: () => (/* binding */ getModifiedUserAgentStyle),\n/* harmony export */ getSelectionColor: () => (/* binding */ getSelectionColor),\n/* harmony export */ getShadowModifier: () => (/* binding */ getShadowModifier),\n/* harmony export */ getShadowModifierWithInfo: () => (/* binding */ getShadowModifierWithInfo)\n/* harmony export */ });\n/* harmony import */ var _generators_modify_colors__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../generators/modify-colors */ \"./src/generators/modify-colors.js\");\n/* harmony import */ var _utils_color__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../utils/color */ \"./src/utils/color.js\");\n/* harmony import */ var _utils_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../utils/math */ \"./src/utils/math.js\");\n/* harmony import */ var _utils_parsing__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../utils/parsing */ \"./src/utils/parsing.js\");\n/* harmony import */ var _utils_platform__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../utils/platform */ \"./src/utils/platform.js\");\n/* harmony import */ var _utils_text__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../utils/text */ \"./src/utils/text.js\");\n/* harmony import */ var _utils_url__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../utils/url */ \"./src/utils/url.js\");\n/* harmony import */ var _css_rules__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./css-rules */ \"./src/inject/dynamic-theme/css-rules.js\");\n/* harmony import */ var _image__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./image */ \"./src/inject/dynamic-theme/image.js\");\n\n\n\n\n\n\n\n// import { logInfo, logWarn } from \"../utils/log\";\n\n\nlet fallbackFactory = null;\nfunction getPriority(ruleStyle, property) {\n return Boolean(ruleStyle && ruleStyle.getPropertyPriority(property));\n}\nconst unparsableColors = new Set([\"inherit\", \"transparent\", \"initial\", \"currentcolor\", \"none\", \"unset\"]);\nfunction getColorModifier(prop, value, rule) {\n if (unparsableColors.has(value.toLowerCase())) {\n return value;\n }\n const rgb = (0,_utils_color__WEBPACK_IMPORTED_MODULE_1__.parseColorWithCache)(value);\n if (!rgb) {\n // logWarn(\"Couldn't parse color\", value);\n return null;\n }\n if (prop.includes(\"background\")) {\n if (rule.style.webkitMaskImage && rule.style.webkitMaskImage !== \"none\" || rule.style.webkitMask && !rule.style.webkitMask.startsWith(\"none\") || rule.style.mask && rule.style.mask !== \"none\" || rule.style.getPropertyValue(\"mask-image\") && rule.style.getPropertyValue(\"mask-image\") !== \"none\") {\n return filter => (0,_generators_modify_colors__WEBPACK_IMPORTED_MODULE_0__.modifyForegroundColor)(rgb, filter);\n }\n return filter => (0,_generators_modify_colors__WEBPACK_IMPORTED_MODULE_0__.modifyBackgroundColor)(rgb, filter);\n }\n if (prop.includes(\"border\") || prop.includes(\"outline\")) {\n return filter => (0,_generators_modify_colors__WEBPACK_IMPORTED_MODULE_0__.modifyBorderColor)(rgb, filter);\n }\n return filter => (0,_generators_modify_colors__WEBPACK_IMPORTED_MODULE_0__.modifyForegroundColor)(rgb, filter);\n}\nfunction getVariableModifier(variablesStore, prop, value, rule, ignoredImgSelectors, isCancelled) {\n return variablesStore.getModifierForVariable({\n varName: prop,\n sourceValue: value,\n rule,\n ignoredImgSelectors,\n isCancelled\n });\n}\nfunction getVariableDependantModifier(variablesStore, prop, value) {\n return variablesStore.getModifierForVarDependant(prop, value);\n}\nfunction getShadowModifier(value) {\n const shadowModifier = getShadowModifierWithInfo(value);\n if (!shadowModifier) {\n return null;\n }\n return theme => shadowModifier(theme).result;\n}\nfunction getModifiableCSSDeclaration(property, value, rule, variablesStore, ignoreImageSelectors, isCancelled) {\n if (property.startsWith(\"--\")) {\n const modifier = getVariableModifier(variablesStore, property, value, rule, ignoreImageSelectors, isCancelled);\n if (modifier) {\n return {\n property,\n value: modifier,\n important: getPriority(rule.style, property),\n sourceValue: value\n };\n }\n } else if (value.includes(\"var(\")) {\n const modifier = getVariableDependantModifier(variablesStore, property, value);\n if (modifier) {\n return {\n property,\n value: modifier,\n important: getPriority(rule.style, property),\n sourceValue: value\n };\n }\n } else if (property === \"color-scheme\") {\n // Note: this if statement needs to be above the next one\n // logWarn(\"CSS property color-scheme is not supported\");\n return null;\n } else if (property.includes(\"color\") && property !== \"-webkit-print-color-adjust\" || property === \"fill\" || property === \"stroke\" || property === \"stop-color\") {\n const modifier = getColorModifier(property, value, rule);\n if (modifier) {\n return {\n property,\n value: modifier,\n important: getPriority(rule.style, property),\n sourceValue: value\n };\n }\n } else if (property === \"background-image\" || property === \"list-style-image\") {\n const modifier = getBgImageModifier(value, rule, ignoreImageSelectors, isCancelled);\n if (modifier) {\n return {\n property,\n value: modifier,\n important: getPriority(rule.style, property),\n sourceValue: value\n };\n }\n } else if (property.includes(\"shadow\")) {\n const modifier = getShadowModifier(value);\n if (modifier) {\n return {\n property,\n value: modifier,\n important: getPriority(rule.style, property),\n sourceValue: value\n };\n }\n }\n return null;\n}\n\n// **important**\nfunction getModifiedFallbackStyle(filter, {\n strict\n}) {\n const factory = fallbackFactory || defaultFallbackFactory;\n return factory(filter, {\n strict\n });\n}\nfunction joinSelectors(...selectors) {\n return selectors.filter(Boolean).join(\", \");\n}\n\n// **important**\nfunction defaultFallbackFactory(filter, {\n strict\n}) {\n const lines = [];\n // https://github.com/darkreader/darkreader/issues/3618#issuecomment-895477598\n const isMicrosoft = [\"microsoft.com\", \"docs.microsoft.com\"].includes(location.hostname);\n lines.push(`html, body, ${strict ? `body :not(iframe)${isMicrosoft ? ':not(div[style^=\"position:absolute;top:0;left:-\"]' : \"\"}` : \"body > :not(iframe)\"} {`);\n lines.push(` background-color: ${(0,_generators_modify_colors__WEBPACK_IMPORTED_MODULE_0__.modifyBackgroundColor)({\n r: 255,\n g: 255,\n b: 255\n }, filter)} !important;`);\n lines.push(` border-color: ${(0,_generators_modify_colors__WEBPACK_IMPORTED_MODULE_0__.modifyBorderColor)({\n r: 64,\n g: 64,\n b: 64\n }, filter)} !important;`);\n lines.push(` color: ${(0,_generators_modify_colors__WEBPACK_IMPORTED_MODULE_0__.modifyForegroundColor)({\n r: 0,\n g: 0,\n b: 0\n }, filter)} !important;`);\n lines.push(\"}\");\n return lines.join(\"\\n\");\n}\nfunction getSelectionColor(theme) {\n let backgroundColorSelection;\n let foregroundColorSelection;\n if (theme.selectionColor === \"auto\") {\n backgroundColorSelection = (0,_generators_modify_colors__WEBPACK_IMPORTED_MODULE_0__.modifyBackgroundColor)({\n r: 0,\n g: 96,\n b: 212\n }, {\n ...theme,\n grayscale: 0\n });\n foregroundColorSelection = (0,_generators_modify_colors__WEBPACK_IMPORTED_MODULE_0__.modifyForegroundColor)({\n r: 255,\n g: 255,\n b: 255\n }, {\n ...theme,\n grayscale: 0\n });\n } else {\n const rgb = (0,_utils_color__WEBPACK_IMPORTED_MODULE_1__.parseColorWithCache)(theme.selectionColor);\n const hsl = rgbToHSL(rgb);\n backgroundColorSelection = theme.selectionColor;\n if (hsl.l < 0.5) {\n foregroundColorSelection = \"#FFF\";\n } else {\n foregroundColorSelection = \"#000\";\n }\n }\n return {\n backgroundColorSelection,\n foregroundColorSelection\n };\n}\nfunction getModifiedSelectionStyle(theme) {\n const lines = [];\n const modifiedSelectionColor = getSelectionColor(theme);\n const backgroundColorSelection = modifiedSelectionColor.backgroundColorSelection;\n const foregroundColorSelection = modifiedSelectionColor.foregroundColorSelection;\n [\"::selection\", \"::-moz-selection\"].forEach(selection => {\n lines.push(`${selection} {`);\n lines.push(` background-color: ${backgroundColorSelection} !important;`);\n lines.push(` color: ${foregroundColorSelection} !important;`);\n lines.push(\"}\");\n });\n return lines.join(\"\\n\");\n}\nfunction getModifiedUserAgentStyle(theme, isIFrame, styleSystemControls) {\n const lines = [];\n if (!isIFrame) {\n lines.push(\"html {\");\n lines.push(` background-color: ${(0,_generators_modify_colors__WEBPACK_IMPORTED_MODULE_0__.modifyBackgroundColor)({\n r: 255,\n g: 255,\n b: 255\n }, theme)} !important;`);\n lines.push(\"}\");\n }\n if (_utils_platform__WEBPACK_IMPORTED_MODULE_4__.isCSSColorSchemePropSupported) {\n lines.push(\"html {\");\n lines.push(` color-scheme: ${theme.mode === 1 ? \"dark\" : \"dark light\"} !important;`);\n lines.push(\"}\");\n }\n const bgSelectors = joinSelectors(isIFrame ? \"\" : \"html, body\", styleSystemControls ? \"input, textarea, select, button, dialog\" : \"\");\n if (bgSelectors) {\n lines.push(`${bgSelectors} {`);\n lines.push(` background-color: ${(0,_generators_modify_colors__WEBPACK_IMPORTED_MODULE_0__.modifyBackgroundColor)({\n r: 255,\n g: 255,\n b: 255\n }, theme)};`);\n lines.push(\"}\");\n }\n lines.push(`${joinSelectors(\"html, body\", styleSystemControls ? \"input, textarea, select, button\" : \"\")} {`);\n lines.push(` border-color: ${(0,_generators_modify_colors__WEBPACK_IMPORTED_MODULE_0__.modifyBorderColor)({\n r: 76,\n g: 76,\n b: 76\n }, theme)};`);\n lines.push(` color: ${(0,_generators_modify_colors__WEBPACK_IMPORTED_MODULE_0__.modifyForegroundColor)({\n r: 0,\n g: 0,\n b: 0\n }, theme)};`);\n lines.push(\"}\");\n lines.push(\"a {\");\n lines.push(` color: ${(0,_generators_modify_colors__WEBPACK_IMPORTED_MODULE_0__.modifyForegroundColor)({\n r: 0,\n g: 64,\n b: 255\n }, theme)};`);\n lines.push(\"}\");\n lines.push(\"table {\");\n lines.push(` border-color: ${(0,_generators_modify_colors__WEBPACK_IMPORTED_MODULE_0__.modifyBorderColor)({\n r: 128,\n g: 128,\n b: 128\n }, theme)};`);\n lines.push(\"}\");\n lines.push(\"::placeholder {\");\n lines.push(` color: ${(0,_generators_modify_colors__WEBPACK_IMPORTED_MODULE_0__.modifyForegroundColor)({\n r: 169,\n g: 169,\n b: 169\n }, theme)};`);\n lines.push(\"}\");\n lines.push(\"input:-webkit-autofill,\");\n lines.push(\"textarea:-webkit-autofill,\");\n lines.push(\"select:-webkit-autofill {\");\n lines.push(` background-color: ${(0,_generators_modify_colors__WEBPACK_IMPORTED_MODULE_0__.modifyBackgroundColor)({\n r: 250,\n g: 255,\n b: 189\n }, theme)} !important;`);\n lines.push(` color: ${(0,_generators_modify_colors__WEBPACK_IMPORTED_MODULE_0__.modifyForegroundColor)({\n r: 0,\n g: 0,\n b: 0\n }, theme)} !important;`);\n lines.push(\"}\");\n if (theme.scrollbarColor) {\n lines.push(getModifiedScrollbarStyle(theme));\n }\n if (theme.selectionColor) {\n lines.push(getModifiedSelectionStyle(theme));\n }\n return lines.join(\"\\n\");\n}\nfunction getModifiedScrollbarStyle(theme) {\n const lines = [];\n let colorTrack;\n let colorIcons;\n let colorThumb;\n let colorThumbHover;\n let colorThumbActive;\n let colorCorner;\n if (theme.scrollbarColor === \"auto\") {\n colorTrack = (0,_generators_modify_colors__WEBPACK_IMPORTED_MODULE_0__.modifyBackgroundColor)({\n r: 241,\n g: 241,\n b: 241\n }, theme);\n colorIcons = (0,_generators_modify_colors__WEBPACK_IMPORTED_MODULE_0__.modifyForegroundColor)({\n r: 96,\n g: 96,\n b: 96\n }, theme);\n colorThumb = (0,_generators_modify_colors__WEBPACK_IMPORTED_MODULE_0__.modifyBackgroundColor)({\n r: 176,\n g: 176,\n b: 176\n }, theme);\n colorThumbHover = (0,_generators_modify_colors__WEBPACK_IMPORTED_MODULE_0__.modifyBackgroundColor)({\n r: 144,\n g: 144,\n b: 144\n }, theme);\n colorThumbActive = (0,_generators_modify_colors__WEBPACK_IMPORTED_MODULE_0__.modifyBackgroundColor)({\n r: 96,\n g: 96,\n b: 96\n }, theme);\n colorCorner = (0,_generators_modify_colors__WEBPACK_IMPORTED_MODULE_0__.modifyBackgroundColor)({\n r: 255,\n g: 255,\n b: 255\n }, theme);\n } else {\n const rgb = (0,_utils_color__WEBPACK_IMPORTED_MODULE_1__.parseColorWithCache)(theme.scrollbarColor);\n const hsl = rgbToHSL(rgb);\n const isLight = hsl.l > 0.5;\n const lighten = lighter => ({\n ...hsl,\n l: (0,_utils_math__WEBPACK_IMPORTED_MODULE_2__.clamp)(hsl.l + lighter, 0, 1)\n });\n const darken = darker => ({\n ...hsl,\n l: (0,_utils_math__WEBPACK_IMPORTED_MODULE_2__.clamp)(hsl.l - darker, 0, 1)\n });\n colorTrack = hslToString(darken(0.4));\n colorIcons = hslToString(isLight ? darken(0.4) : lighten(0.4));\n colorThumb = hslToString(hsl);\n colorThumbHover = hslToString(lighten(0.1));\n colorThumbActive = hslToString(lighten(0.2));\n colorCorner = hslToString(darken(0.5));\n }\n lines.push(\"::-webkit-scrollbar {\");\n lines.push(` background-color: ${colorTrack};`);\n lines.push(` color: ${colorIcons};`);\n lines.push(\"}\");\n lines.push(\"::-webkit-scrollbar-thumb {\");\n lines.push(` background-color: ${colorThumb};`);\n lines.push(\"}\");\n lines.push(\"::-webkit-scrollbar-thumb:hover {\");\n lines.push(` background-color: ${colorThumbHover};`);\n lines.push(\"}\");\n lines.push(\"::-webkit-scrollbar-thumb:active {\");\n lines.push(` background-color: ${colorThumbActive};`);\n lines.push(\"}\");\n lines.push(\"::-webkit-scrollbar-corner {\");\n lines.push(` background-color: ${colorCorner};`);\n lines.push(\"}\");\n if (_utils_platform__WEBPACK_IMPORTED_MODULE_4__.isFirefox) {\n lines.push(\"* {\");\n lines.push(` scrollbar-color: ${colorThumb} ${colorTrack};`);\n lines.push(\"}\");\n }\n return lines.join(\"\\n\");\n}\nfunction shouldIgnoreImage(selectorText, selectors) {\n if (!selectorText || selectors.length === 0) {\n return false;\n }\n if (selectors.some(s => s === \"*\")) {\n return true;\n }\n const ruleSelectors = selectorText.split(/,\\s*/g);\n for (let i = 0; i < selectors.length; i++) {\n const ignoredSelector = selectors[i];\n if (ruleSelectors.some(s => s === ignoredSelector)) {\n return true;\n }\n }\n return false;\n}\nconst imageDetailsCache = new Map();\nconst awaitingForImageLoading = new Map();\nfunction getBgImageModifier(value, rule, ignoreImageSelectors, isCancelled) {\n try {\n const gradients = (0,_utils_parsing__WEBPACK_IMPORTED_MODULE_3__.parseGradient)(value);\n const urls = (0,_utils_text__WEBPACK_IMPORTED_MODULE_5__.getMatches)(_css_rules__WEBPACK_IMPORTED_MODULE_7__.cssURLRegex, value);\n if (urls.length === 0 && gradients.length === 0) {\n return value;\n }\n const getIndices = matches => {\n let index = 0;\n return matches.map(match => {\n const valueIndex = value.indexOf(match, index);\n index = valueIndex + match.length;\n return {\n match,\n index: valueIndex\n };\n });\n };\n const matches = gradients.map(i => ({\n type: \"gradient\",\n ...i\n })).concat(getIndices(urls).map(i => ({\n type: \"url\",\n offset: 0,\n ...i\n }))).sort((a, b) => a.index > b.index ? 1 : -1);\n const getGradientModifier = gradient => {\n const {\n typeGradient,\n match,\n hasComma\n } = gradient;\n const partsRegex = /([^\\(\\),]+(\\([^\\(\\)]*(\\([^\\(\\)]*\\)*[^\\(\\)]*)?\\))?([^\\(\\), ]|( (?!calc)))*),?/g;\n const colorStopRegex = /^(from|color-stop|to)\\(([^\\(\\)]*?,\\s*)?(.*?)\\)$/;\n const parts = (0,_utils_text__WEBPACK_IMPORTED_MODULE_5__.getMatches)(partsRegex, match, 1).map(part => {\n part = part.trim();\n let rgb = (0,_utils_color__WEBPACK_IMPORTED_MODULE_1__.parseColorWithCache)(part);\n if (rgb) {\n return filter => (0,_generators_modify_colors__WEBPACK_IMPORTED_MODULE_0__.modifyGradientColor)(rgb, filter);\n }\n const space = part.lastIndexOf(\" \");\n rgb = (0,_utils_color__WEBPACK_IMPORTED_MODULE_1__.parseColorWithCache)(part.substring(0, space));\n if (rgb) {\n return filter => `${(0,_generators_modify_colors__WEBPACK_IMPORTED_MODULE_0__.modifyGradientColor)(rgb, filter)} ${part.substring(space + 1)}`;\n }\n const colorStopMatch = part.match(colorStopRegex);\n if (colorStopMatch) {\n rgb = (0,_utils_color__WEBPACK_IMPORTED_MODULE_1__.parseColorWithCache)(colorStopMatch[3]);\n if (rgb) {\n return filter => `${colorStopMatch[1]}(${colorStopMatch[2] ? `${colorStopMatch[2]}, ` : \"\"}${(0,_generators_modify_colors__WEBPACK_IMPORTED_MODULE_0__.modifyGradientColor)(rgb, filter)})`;\n }\n }\n return () => part;\n });\n return filter => {\n return `${typeGradient}(${parts.map(modify => modify(filter)).join(\", \")})${hasComma ? \", \" : \"\"}`;\n };\n };\n const getURLModifier = urlValue => {\n if (shouldIgnoreImage(rule.selectorText, ignoreImageSelectors)) {\n return null;\n }\n let url = (0,_css_rules__WEBPACK_IMPORTED_MODULE_7__.getCSSURLValue)(urlValue);\n const isURLEmpty = url.length === 0;\n const {\n parentStyleSheet\n } = rule;\n const baseURL = parentStyleSheet && parentStyleSheet.href ? (0,_css_rules__WEBPACK_IMPORTED_MODULE_7__.getCSSBaseBath)(parentStyleSheet.href) : parentStyleSheet.ownerNode?.baseURI || location.origin;\n url = (0,_utils_url__WEBPACK_IMPORTED_MODULE_6__.getAbsoluteURL)(baseURL, url);\n const absoluteValue = `url(\"${url}\")`;\n return async filter => {\n if (isURLEmpty) {\n return \"url('')\";\n }\n let imageDetails;\n if (imageDetailsCache.has(url)) {\n imageDetails = imageDetailsCache.get(url);\n } else {\n try {\n if (awaitingForImageLoading.has(url)) {\n const awaiters = awaitingForImageLoading.get(url);\n imageDetails = await new Promise(resolve => awaiters.push(resolve));\n if (!imageDetails) {\n return null;\n }\n } else {\n awaitingForImageLoading.set(url, []);\n imageDetails = await (0,_image__WEBPACK_IMPORTED_MODULE_8__.getImageDetails)(url);\n imageDetailsCache.set(url, imageDetails);\n awaitingForImageLoading.get(url).forEach(resolve => resolve(imageDetails));\n awaitingForImageLoading.delete(url);\n }\n if (isCancelled()) {\n return null;\n }\n } catch (err) {\n // logWarn(err);\n if (awaitingForImageLoading.has(url)) {\n awaitingForImageLoading.get(url).forEach(resolve => resolve(null));\n awaitingForImageLoading.delete(url);\n }\n return absoluteValue;\n }\n }\n const bgImageValue = getBgImageValue(imageDetails, filter) || absoluteValue;\n return bgImageValue;\n };\n };\n const getBgImageValue = (imageDetails, filter) => {\n const {\n isDark,\n isLight,\n isTransparent,\n isLarge,\n isTooLarge,\n width\n } = imageDetails;\n let result;\n if (isTooLarge) {\n // logInfo(`Not modifying too large image ${imageDetails.src}`);\n result = `url(\"${imageDetails.src}\")`;\n } else if (isDark && isTransparent && filter.mode === 1 && !isLarge && width > 2) {\n // logInfo(`Inverting dark image ${imageDetails.src}`);\n const inverted = (0,_image__WEBPACK_IMPORTED_MODULE_8__.getFilteredImageDataURL)(imageDetails, {\n ...filter,\n sepia: (0,_utils_math__WEBPACK_IMPORTED_MODULE_2__.clamp)(filter.sepia + 10, 0, 100)\n });\n result = `url(\"${inverted}\")`;\n } else if (isLight && !isTransparent && filter.mode === 1) {\n if (isLarge) {\n // logInfo(`Not modifying light non-transparent large image ${imageDetails.src}`);\n result = \"none\";\n } else {\n // logInfo(`Dimming light image ${imageDetails.src}`);\n const dimmed = (0,_image__WEBPACK_IMPORTED_MODULE_8__.getFilteredImageDataURL)(imageDetails, filter);\n result = `url(\"${dimmed}\")`;\n }\n } else if (filter.mode === 0 && isLight && !isLarge) {\n // logInfo(`Applying filter to image ${imageDetails.src}`);\n const filtered = (0,_image__WEBPACK_IMPORTED_MODULE_8__.getFilteredImageDataURL)(imageDetails, {\n ...filter,\n brightness: (0,_utils_math__WEBPACK_IMPORTED_MODULE_2__.clamp)(filter.brightness - 10, 5, 200),\n sepia: (0,_utils_math__WEBPACK_IMPORTED_MODULE_2__.clamp)(filter.sepia + 10, 0, 100)\n });\n result = `url(\"${filtered}\")`;\n } else {\n // logInfo(`Not modifying too large image ${imageDetails.src}`);\n result = null;\n }\n return result;\n };\n const modifiers = [];\n let matchIndex = 0;\n let prevHasComma = false;\n matches.forEach(({\n type,\n match,\n index,\n typeGradient,\n hasComma,\n offset\n }, i) => {\n const matchStart = index;\n const prefixStart = matchIndex;\n const matchEnd = matchStart + match.length + offset;\n matchIndex = matchEnd;\n\n // Make sure we still push all the unrelated content between gradients and URLs.\n if (prefixStart !== matchStart) {\n if (prevHasComma) {\n modifiers.push(() => {\n let betweenValue = value.substring(prefixStart, matchStart);\n if (betweenValue[0] === \",\") {\n betweenValue = betweenValue.substring(1);\n }\n return betweenValue;\n });\n } else {\n modifiers.push(() => value.substring(prefixStart, matchStart));\n }\n }\n prevHasComma = hasComma || false;\n if (type === \"url\") {\n modifiers.push(getURLModifier(match));\n } else if (type === \"gradient\") {\n modifiers.push(getGradientModifier({\n match,\n index,\n typeGradient: typeGradient,\n hasComma: hasComma || false,\n offset\n }));\n }\n if (i === matches.length - 1) {\n modifiers.push(() => value.substring(matchEnd));\n }\n });\n return filter => {\n const results = modifiers.filter(Boolean).map(modify => modify(filter));\n if (results.some(r => r instanceof Promise)) {\n return Promise.all(results).then(asyncResults => {\n return asyncResults.filter(Boolean).join(\"\");\n });\n }\n // Strip `, initial` suffix. This is some weird computed value by the browser\n const combinedResult = results.join(\"\");\n if (combinedResult.endsWith(\", initial\")) {\n return combinedResult.slice(0, -9);\n }\n return combinedResult;\n };\n } catch (err) {\n // logWarn(`Unable to parse gradient ${value}`, err);\n return null;\n }\n}\nfunction getShadowModifierWithInfo(value) {\n try {\n let index = 0;\n const colorMatches = (0,_utils_text__WEBPACK_IMPORTED_MODULE_5__.getMatches)(/(^|\\s)(?!calc)([a-z]+\\(.+?\\)|#[0-9a-f]+|[a-z]+)(.*?(inset|outset)?($|,))/gi, value, 2);\n let notParsed = 0;\n const modifiers = colorMatches.map((match, i) => {\n const prefixIndex = index;\n const matchIndex = value.indexOf(match, index);\n const matchEnd = matchIndex + match.length;\n index = matchEnd;\n const rgb = (0,_utils_color__WEBPACK_IMPORTED_MODULE_1__.parseColorWithCache)(match);\n if (!rgb) {\n notParsed++;\n return () => value.substring(prefixIndex, matchEnd);\n }\n return filter => `${value.substring(prefixIndex, matchIndex)}${(0,_generators_modify_colors__WEBPACK_IMPORTED_MODULE_0__.modifyShadowColor)(rgb, filter)}${i === colorMatches.length - 1 ? value.substring(matchEnd) : \"\"}`;\n });\n return filter => {\n const modified = modifiers.map(modify => modify(filter)).join(\"\");\n return {\n matchesLength: colorMatches.length,\n unparseableMatchesLength: notParsed,\n result: modified\n };\n };\n } catch (err) {\n // logWarn(`Unable to parse shadow ${value}`, err);\n return null;\n }\n}\nfunction cleanModificationCache() {\n (0,_generators_modify_colors__WEBPACK_IMPORTED_MODULE_0__.clearColorModificationCache)();\n imageDetailsCache.clear();\n (0,_image__WEBPACK_IMPORTED_MODULE_8__.cleanImageProcessingCache)();\n awaitingForImageLoading.clear();\n}\n\n//# sourceURL=webpack://dark-mode/./src/inject/dynamic-theme/modify-css.js?"); /***/ }), /***/ "./src/inject/dynamic-theme/style-manager.js": /*!***************************************************!*\ !*** ./src/inject/dynamic-theme/style-manager.js ***! \***************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ STYLE_SELECTOR: () => (/* binding */ STYLE_SELECTOR),\n/* harmony export */ cleanLoadingLinks: () => (/* binding */ cleanLoadingLinks),\n/* harmony export */ getManageableStyles: () => (/* binding */ getManageableStyles),\n/* harmony export */ manageStyle: () => (/* binding */ manageStyle),\n/* harmony export */ shouldManageStyle: () => (/* binding */ shouldManageStyle)\n/* harmony export */ });\n/* harmony import */ var _utils_array__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../utils/array */ \"./src/utils/array.js\");\n/* harmony import */ var _utils_platform__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../utils/platform */ \"./src/utils/platform.js\");\n/* harmony import */ var _utils_url__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../utils/url */ \"./src/utils/url.js\");\n/* harmony import */ var _utils_dom__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/dom */ \"./src/inject/utils/dom.js\");\n/* harmony import */ var _css_rules__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./css-rules */ \"./src/inject/dynamic-theme/css-rules.js\");\n/* harmony import */ var _stylesheet_modifier__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./stylesheet-modifier */ \"./src/inject/dynamic-theme/stylesheet-modifier.js\");\n\n\n\n\n// import { logInfo, logWarn } from \"../utils/log\";\n\n\nconst rejectorsForLoadingLinks = new Map();\nconst STYLE_SELECTOR = 'style, link[rel*=\"stylesheet\" i]:not([disabled])';\nlet loadingLinkCounter = 0;\n\n// isFontsGoogleApiStyle returns is the given link element is a style from\n// google fonts.\nfunction isFontsGoogleApiStyle(element) {\n if (!element.href) {\n return false;\n }\n try {\n const elementURL = new URL(element.href);\n return elementURL.hostname === \"fonts.googleapis.com\";\n } catch (err) {\n // logInfo(`Couldn't construct ${element.href} as URL`);\n return false;\n }\n}\nfunction shouldManageStyle(element) {\n return (element instanceof HTMLStyleElement || element instanceof SVGStyleElement || element instanceof HTMLLinkElement && Boolean(element.rel) && element.rel.toLowerCase().includes(\"stylesheet\") && Boolean(element.href) && !element.disabled && (_utils_platform__WEBPACK_IMPORTED_MODULE_1__.isFirefox ? !element.href.startsWith(\"moz-extension://\") : true) && !isFontsGoogleApiStyle(element)) && !element.classList.contains(\"adminify\") && element.media.toLowerCase() !== \"print\" && !element.classList.contains(\"stylus\");\n}\nfunction getManageableStyles(node, results = [], deep = true) {\n if (shouldManageStyle(node)) {\n results.push(node);\n } else if (node instanceof Element || _utils_platform__WEBPACK_IMPORTED_MODULE_1__.isShadowDomSupported && node instanceof ShadowRoot || node === document) {\n (0,_utils_array__WEBPACK_IMPORTED_MODULE_0__.forEach)(node.querySelectorAll(STYLE_SELECTOR), style => getManageableStyles(style, results, false));\n if (deep) {\n (0,_utils_dom__WEBPACK_IMPORTED_MODULE_3__.iterateShadowHosts)(node, host => getManageableStyles(host.shadowRoot, results, false));\n }\n }\n return results;\n}\nconst syncStyleSet = new WeakSet();\nconst corsStyleSet = new WeakSet();\nfunction manageStyle(element, {\n update,\n loadingStart,\n loadingEnd\n}) {\n const prevStyles = [];\n let next = element;\n while ((next = next.nextElementSibling) && next.matches(\".adminify\")) {\n prevStyles.push(next);\n }\n let corsCopy = prevStyles.find(el => el.matches(\".adminify--cors\") && !corsStyleSet.has(el)) || null;\n let syncStyle = prevStyles.find(el => el.matches(\".adminify--sync\") && !syncStyleSet.has(el)) || null;\n let corsCopyPositionWatcher = null;\n let syncStylePositionWatcher = null;\n let cancelAsyncOperations = false;\n let isOverrideEmpty = true;\n const sheetModifier = (0,_stylesheet_modifier__WEBPACK_IMPORTED_MODULE_5__.createStyleSheetModifier)();\n const observer = new MutationObserver(() => {\n update();\n });\n const observerOptions = {\n attributes: true,\n childList: true,\n subtree: true,\n characterData: true\n };\n function containsCSSImport() {\n return element instanceof HTMLStyleElement && element.textContent.trim().match(_css_rules__WEBPACK_IMPORTED_MODULE_4__.cssImportRegex);\n }\n\n // It loops trough the cssRules and check for CSSImportRule and their `href`.\n // If the `href` isn't local and doesn't start with the same-origin.\n // We can be ensure that's a cross-origin import\n // And should add a cors-sheet to this element.\n function hasImports(cssRules, checkCrossOrigin) {\n let result = false;\n if (cssRules) {\n let rule;\n cssRulesLoop: for (let i = 0, len = cssRules.length; i < len; i++) {\n rule = cssRules[i];\n if (rule.href) {\n if (checkCrossOrigin) {\n if (!rule.href.startsWith(\"https://fonts.googleapis.com/\") && rule.href.startsWith(\"http\") && !rule.href.startsWith(location.origin)) {\n result = true;\n break cssRulesLoop;\n }\n } else {\n result = true;\n break cssRulesLoop;\n }\n }\n }\n }\n return result;\n }\n function getRulesSync() {\n if (corsCopy) {\n // logInfo(\"[getRulesSync] Using cors-copy.\");\n return corsCopy.sheet.cssRules;\n }\n if (containsCSSImport()) {\n // logInfo(\"[getRulesSync] CSSImport detected.\");\n return null;\n }\n const cssRules = safeGetSheetRules();\n if (element instanceof HTMLLinkElement && !(0,_utils_url__WEBPACK_IMPORTED_MODULE_2__.isRelativeHrefOnAbsolutePath)(element.href) && hasImports(cssRules, false)) {\n // logInfo(\"[getRulesSync] CSSImportRule detected on non-local href.\");\n return null;\n }\n if (hasImports(cssRules, true)) {\n // logInfo(\"[getRulesSync] Cross-Origin CSSImportRule detected.\");\n return null;\n }\n\n // logInfo(\"[getRulesSync] Using cssRules.\");\n // !cssRules && logWarn(\"[getRulesSync] cssRules is null, trying again.\");\n return cssRules;\n }\n function insertStyle() {\n if (corsCopy) {\n if (element.nextSibling !== corsCopy) {\n element.parentNode.insertBefore(corsCopy, element.nextSibling);\n }\n if (corsCopy.nextSibling !== syncStyle) {\n element.parentNode.insertBefore(syncStyle, corsCopy.nextSibling);\n }\n } else if (element.nextSibling !== syncStyle) {\n element.parentNode.insertBefore(syncStyle, element.nextSibling);\n }\n }\n function createSyncStyle() {\n syncStyle = element instanceof SVGStyleElement ? document.createElementNS(\"http://www.w3.org/2000/svg\", \"style\") : document.createElement(\"style\");\n syncStyle.classList.add(\"adminify\");\n syncStyle.classList.add(\"adminify--sync\");\n syncStyle.media = \"screen\";\n if (element.title) {\n syncStyle.title = element.title;\n }\n syncStyleSet.add(syncStyle);\n }\n let isLoadingRules = false;\n let wasLoadingError = false;\n const loadingLinkId = ++loadingLinkCounter;\n async function getRulesAsync() {\n let cssText;\n let cssBasePath;\n if (element instanceof HTMLLinkElement) {\n let [cssRules, accessError] = getRulesOrError();\n if (accessError) {\n // logWarn(accessError);\n }\n if (_utils_platform__WEBPACK_IMPORTED_MODULE_1__.isSafari && !element.sheet || !_utils_platform__WEBPACK_IMPORTED_MODULE_1__.isSafari && !cssRules && !accessError || isStillLoadingError(accessError)) {\n try {\n // logInfo(\n // `Linkelement ${loadingLinkId} is not loaded yet and thus will be await for`,\n // element\n // );\n await linkLoading(element, loadingLinkId);\n } catch (err) {\n // NOTE: Some @import resources can fail,\n // but the style sheet can still be valid.\n // There's no way to get the actual error.\n // logWarn(err);\n wasLoadingError = true;\n }\n if (cancelAsyncOperations) {\n return null;\n }\n [cssRules, accessError] = getRulesOrError();\n if (accessError) {\n // CORS error, cssRules are not accessible\n // for cross-origin resources\n // logWarn(accessError);\n }\n }\n if (cssRules) {\n if (!hasImports(cssRules, false)) {\n return cssRules;\n }\n }\n\n // cssText = await loadText(element.href);\n // cssBasePath = getCSSBaseBath(element.href);\n // if (cancelAsyncOperations) {\n // return null;\n // }\n } else if (containsCSSImport()) {\n cssText = element.textContent.trim();\n cssBasePath = getCSSBaseBath(location.href);\n } else {\n return null;\n }\n if (cssText) {\n // Sometimes cross-origin stylesheets are protected from direct access\n // so need to load CSS text and insert it into style element\n try {\n const fullCSSText = await replaceCSSImports(cssText, cssBasePath);\n corsCopy = createCORSCopy(element, fullCSSText);\n } catch (err) {\n // logWarn(err);\n }\n if (corsCopy) {\n corsCopyPositionWatcher = (0,_utils_dom__WEBPACK_IMPORTED_MODULE_3__.watchForNodePosition)(corsCopy, \"prev-sibling\");\n return corsCopy.sheet.cssRules;\n }\n }\n return null;\n }\n function details(options) {\n const rules = getRulesSync();\n if (!rules) {\n // secondRound is only true after it's\n // has gone trough `details()` & `getRulesAsync` already\n // So that means that `getRulesSync` shouldn't fail.\n // However as a fail-safe to prevent loops, we should\n // return null here and not continue to `getRulesAsync`\n if (options.secondRound) {\n // logWarn(\"Detected dead-lock at details(), returning early to prevent it.\");\n return null;\n }\n if (isLoadingRules || wasLoadingError) {\n return null;\n }\n isLoadingRules = true;\n loadingStart();\n getRulesAsync().then(results => {\n isLoadingRules = false;\n loadingEnd();\n if (results) {\n update();\n }\n }).catch(err => {\n // logWarn(err);\n isLoadingRules = false;\n loadingEnd();\n });\n return null;\n }\n return {\n rules\n };\n }\n let forceRenderStyle = false;\n function render(theme, ignoreImageAnalysis) {\n const rules = getRulesSync();\n if (!rules) {\n return;\n }\n cancelAsyncOperations = false;\n function removeCSSRulesFromSheet(sheet) {\n if (!sheet) {\n return;\n }\n for (let i = sheet.cssRules.length - 1; i >= 0; i--) {\n sheet.deleteRule(i);\n }\n }\n function prepareOverridesSheet() {\n if (!syncStyle) {\n createSyncStyle();\n }\n syncStylePositionWatcher && syncStylePositionWatcher.stop();\n insertStyle();\n\n // Firefox issue: Some websites get CSP warning,\n // when `textContent` is not set (e.g. pypi.org).\n // But for other websites (e.g. facebook.com)\n // some images disappear when `textContent`\n // is initially set to an empty string.\n if (syncStyle.sheet == null) {\n syncStyle.textContent = \"\";\n }\n const sheet = syncStyle.sheet;\n removeCSSRulesFromSheet(sheet);\n if (syncStylePositionWatcher) {\n syncStylePositionWatcher.run();\n } else {\n syncStylePositionWatcher = (0,_utils_dom__WEBPACK_IMPORTED_MODULE_3__.watchForNodePosition)(syncStyle, \"prev-sibling\", () => {\n forceRenderStyle = true;\n buildOverrides();\n });\n }\n return syncStyle.sheet;\n }\n function buildOverrides() {\n const force = forceRenderStyle;\n forceRenderStyle = false;\n sheetModifier.modifySheet({\n prepareSheet: prepareOverridesSheet,\n sourceCSSRules: rules,\n theme,\n ignoreImageAnalysis,\n force,\n isAsyncCancelled: () => cancelAsyncOperations\n });\n isOverrideEmpty = syncStyle.sheet.cssRules.length === 0;\n if (sheetModifier.shouldRebuildStyle()) {\n // \"update\" function schedules rebuilding the style\n // ideally to wait for link loading, because some sites put links any time,\n // but it can be complicated, so waiting for document completion can do the trick\n addReadyStateCompleteListener(() => update());\n }\n }\n buildOverrides();\n }\n function getRulesOrError() {\n try {\n if (element.sheet == null) {\n return [null, null];\n }\n return [element.sheet.cssRules, null];\n } catch (err) {\n return [null, err];\n }\n }\n\n // NOTE: In Firefox, when link is loading,\n // `sheet` property is not null,\n // but `cssRules` access error is thrown\n function isStillLoadingError(error) {\n return error && error.message && error.message.includes(\"loading\");\n }\n\n // Seems like Firefox bug: silent exception is produced\n // without any notice, when accessing