Skip to content

Commit

Permalink
fix: shadow dom style injected in prod build
Browse files Browse the repository at this point in the history
Signed-off-by: Innei <[email protected]>
  • Loading branch information
Innei committed Aug 30, 2024
1 parent 66035fe commit 3f1c588
Showing 1 changed file with 51 additions and 15 deletions.
66 changes: 51 additions & 15 deletions src/renderer/src/components/common/ShadowDOM.tsx
Original file line number Diff line number Diff line change
@@ -1,29 +1,65 @@
import { useIsDark } from "@renderer/hooks/common"
import type { FC, PropsWithChildren, ReactNode } from "react"
import { createContext, createElement, useContext, useState } from "react"
import {
createContext,
createElement,
useContext,
useLayoutEffect,
useState,
} from "react"
import root from "react-shadow"

const ShadowDOMContext = createContext(false)

const cloneStylesElement = () => {
const $styles = document.head.querySelectorAll("style").values()
const reactNodes = [] as ReactNode[]
let i = 0
for (const style of $styles) {
const key = `style-${i++}`
reactNodes.push(
createElement("style", {
key,
dangerouslySetInnerHTML: { __html: style.innerHTML },
}),
)
}

document.head.querySelectorAll("link[rel=stylesheet]").forEach((link) => {
const key = `link-${i++}`
reactNodes.push(
createElement("link", {
key,
rel: "stylesheet",
href: link.getAttribute("href"),
crossOrigin: link.getAttribute("crossorigin"),
}),
)
})

return reactNodes
}
export const ShadowDOM: FC<PropsWithChildren<React.HTMLProps<HTMLElement>>> & {
useIsShadowDOM: () => boolean
} = (props) => {
const { ...rest } = props

const [stylesElements] = useState<ReactNode[]>(() => {
const $styles = document.head.querySelectorAll("style").values()
const reactNodes = [] as ReactNode[]
let i = 0
for (const style of $styles) {
const key = `style-${i++}`
reactNodes.push(
createElement("style", {
key,
dangerouslySetInnerHTML: { __html: style.innerHTML },
}),
)
const [stylesElements, setStylesElements] =
useState<ReactNode[]>(cloneStylesElement)

useLayoutEffect(() => {
const mutationObserver = new MutationObserver(() => {
setStylesElements(cloneStylesElement())
})
mutationObserver.observe(document.head, {
childList: true,
subtree: true,
})

return () => {
mutationObserver.disconnect()
}
return reactNodes
})
}, [])

const dark = useIsDark()
return (
Expand Down

0 comments on commit 3f1c588

Please sign in to comment.