svg theme changer

This commit is contained in:
Mylloon 2024-11-06 18:17:29 +01:00
parent 0f6f2f1fc4
commit a3161d822d
Signed by: Anri
GPG key ID: A82D63DFF8D1317F

View file

@ -80,11 +80,16 @@ const deepestNodeOpened = (path, options) => {
} }
}; };
const svgDarkTheme = () => { const Mode = {
Light: 1,
Dark: 2,
};
const svgChangeTheme = (mode) => {
for (const item of document.getElementsByTagName("img")) { for (const item of document.getElementsByTagName("img")) {
if (!item.src.startsWith("data:image/svg+xml;base64,")) { if (!item.src.startsWith("data:image/svg+xml;base64,")) {
// Exclude image who aren't SVG and base64 encoded // Exclude image who aren't SVG and base64 encoded
break; continue;
} }
/** Convert to grayscale */ /** Convert to grayscale */
@ -129,9 +134,19 @@ const svgDarkTheme = () => {
const totalGrayscale = grayscaleValues.reduce((acc, val) => acc + val, 0); const totalGrayscale = grayscaleValues.reduce((acc, val) => acc + val, 0);
const averageGrayscale = totalGrayscale / grayscaleValues.length; const averageGrayscale = totalGrayscale / grayscaleValues.length;
if (averageGrayscale < 128) { const treshold = 128;
if (averageGrayscale < treshold && mode === Mode.Dark) {
item.style = "filter: invert(1);"; item.style = "filter: invert(1);";
continue;
} }
if (averageGrayscale > treshold && mode === Mode.Light) {
item.style = "filter: invert(1);";
continue;
}
item.style = "";
} }
}; };
@ -160,13 +175,16 @@ window.addEventListener("load", () => {
uncollapse(last_openeded); uncollapse(last_openeded);
} }
// Fix SVG images in dark mode // Fix SVG images
if (window.matchMedia("(prefers-color-scheme: dark)").matches) { svgChangeTheme(
svgDarkTheme(); window.matchMedia("(prefers-color-scheme: dark)").matches
} ? Mode.Dark
: Mode.Light
);
}); });
// Is this working?
window window
.matchMedia("(prefers-color-scheme: dark)") .matchMedia("(prefers-color-scheme: dark)")
.addEventListener("change", svgDarkTheme); .addEventListener("change", (event) =>
svgChangeTheme(event.matches ? Mode.Dark : Mode.Light)
);