refactor(web): improve theme style element management in useHighlightTheme hook
This commit is contained in:
parent
acbe654674
commit
5a2e7795cd
1 changed files with 31 additions and 6 deletions
|
|
@ -4,14 +4,39 @@ import githubDarkCss from "highlight.js/styles/github-dark.css?inline"
|
||||||
import githubLightCss from "highlight.js/styles/github.css?inline"
|
import githubLightCss from "highlight.js/styles/github.css?inline"
|
||||||
|
|
||||||
const THEME_STYLE_ID = "hljs-theme-style"
|
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() {
|
function getOrCreateThemeStyleElement(): HTMLStyleElement {
|
||||||
let styleElement = document.getElementById(THEME_STYLE_ID)
|
const managedStyleElement = document.head.querySelector<HTMLStyleElement>(
|
||||||
if (!styleElement) {
|
MANAGED_THEME_STYLE_SELECTOR,
|
||||||
styleElement = document.createElement("style")
|
)
|
||||||
styleElement.id = THEME_STYLE_ID
|
if (managedStyleElement) {
|
||||||
document.head.appendChild(styleElement)
|
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
|
return styleElement
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue