refactor(web): improve theme style element management in useHighlightTheme hook

This commit is contained in:
lc6464
2026-04-15 18:30:43 +08:00
parent acbe654674
commit 5a2e7795cd
+31 -6
View File
@@ -4,14 +4,39 @@ import githubDarkCss from "highlight.js/styles/github-dark.css?inline"
import githubLightCss from "highlight.js/styles/github.css?inline"
const THEME_STYLE_ID = "hljs-theme-style"
const THEME_STYLE_OWNER_ATTR = "data-picoclaw-highlight-theme"
const THEME_STYLE_OWNER_VALUE = "true"
const MANAGED_THEME_STYLE_SELECTOR = `style[${THEME_STYLE_OWNER_ATTR}="${THEME_STYLE_OWNER_VALUE}"]`
const ID_THEME_STYLE_SELECTOR = `style#${THEME_STYLE_ID}`
function getOrCreateThemeStyleElement() {
let styleElement = document.getElementById(THEME_STYLE_ID)
if (!styleElement) {
styleElement = document.createElement("style")
styleElement.id = THEME_STYLE_ID
document.head.appendChild(styleElement)
function getOrCreateThemeStyleElement(): HTMLStyleElement {
const managedStyleElement = document.head.querySelector<HTMLStyleElement>(
MANAGED_THEME_STYLE_SELECTOR,
)
if (managedStyleElement) {
return managedStyleElement
}
const existingStyleElement =
document.querySelector<HTMLStyleElement>(ID_THEME_STYLE_SELECTOR)
if (existingStyleElement) {
existingStyleElement.setAttribute(
THEME_STYLE_OWNER_ATTR,
THEME_STYLE_OWNER_VALUE,
)
return existingStyleElement
}
const conflictingElement = document.getElementById(THEME_STYLE_ID)
const styleElement = document.createElement("style")
if (!conflictingElement) {
styleElement.id = THEME_STYLE_ID
}
// Leave conflicting non-style nodes untouched and track the injected style explicitly.
styleElement.setAttribute(THEME_STYLE_OWNER_ATTR, THEME_STYLE_OWNER_VALUE)
document.head.appendChild(styleElement)
return styleElement
}