mirror of
https://github.com/jackyzha0/quartz.git
synced 2025-12-27 23:04:05 -06:00
Render images by theme
This commit is contained in:
parent
c7aa0e49c1
commit
5a72e0a54a
@ -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)
|
||||
}
|
||||
|
||||
|
||||
@ -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)
|
||||
|
||||
Loading…
Reference in New Issue
Block a user