From 5a72e0a54ad3edda5d66db3faaaa7fe9f7964833 Mon Sep 17 00:00:00 2001 From: Emile Bangma Date: Mon, 23 Sep 2024 17:53:14 +0000 Subject: [PATCH] Render images by theme --- quartz/components/scripts/darkmode.inline.ts | 6 ++-- quartz/components/scripts/util.ts | 29 ++++++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/quartz/components/scripts/darkmode.inline.ts b/quartz/components/scripts/darkmode.inline.ts index 038ae0fe5..3494f57dd 100644 --- a/quartz/components/scripts/darkmode.inline.ts +++ b/quartz/components/scripts/darkmode.inline.ts @@ -1,11 +1,13 @@ -const userPref = window.matchMedia("(prefers-color-scheme: light)").matches ? "light" : "dark" -const currentTheme = localStorage.getItem("theme") ?? userPref +import { getUserPreferredColorScheme, renderThemedLinks } from "./util" + +const currentTheme = localStorage.getItem("theme") ?? getUserPreferredColorScheme() document.documentElement.setAttribute("saved-theme", currentTheme) const emitThemeChangeEvent = (theme: "light" | "dark") => { const event: CustomEventMap["themechange"] = new CustomEvent("themechange", { detail: { theme }, }) + renderThemedLinks(theme) document.dispatchEvent(event) } diff --git a/quartz/components/scripts/util.ts b/quartz/components/scripts/util.ts index d0a16c651..4538baace 100644 --- a/quartz/components/scripts/util.ts +++ b/quartz/components/scripts/util.ts @@ -19,6 +19,35 @@ export function registerEscapeHandler(outsideContainer: HTMLElement | null, cb: window.addCleanup(() => document.removeEventListener("keydown", esc)) } +export function renderThemedLinks(theme: "dark" | "light") { + const imageExtensions = new RegExp(".(dark|light).(png|jpg|jpeg|gif|bmp|svg|webp)$") + const imageGroups = { theme: 1, extension: 2 } + Object.values(document.getElementsByTagName("img")).forEach((img) => { + if (img.src.match(imageExtensions)) { + const newImg = imageExtensions.exec(img.src) + img.src.replace(imageExtensions, `.${theme}.${newImg![imageGroups.extension]}`) + } + }) +} + +export function getUserPreferredColorScheme() { + return window.matchMedia("(prefers-color-scheme: light)").matches ? "light" : "dark" +} + +// Have SVG images in the article adhere to the correct color scheme. +document.addEventListener("nav", (e) => { + let theme = localStorage.getItem("theme") ?? getUserPreferredColorScheme() + Object.values(document.getElementsByTagName("article")[0].getElementsByTagName("a")).forEach( + (a) => { + if (a.href.endsWith(".excalidraw")) { + let img = document.createElement("img") + img.src = `${a.href}.${theme}.svg` + a.replaceWith(img) + } + }, + ) +}) + export function removeAllChildren(node: HTMLElement) { while (node.firstChild) { node.removeChild(node.firstChild)