Skip to content
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 41 additions & 4 deletions packages/harmony/src/foundations/theme/ThemeProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, type ReactNode } from 'react'
import { useEffect, useRef, type ReactNode } from 'react'

import { ThemeProvider as EmotionThemeProvider } from '@emotion/react'

Expand All @@ -13,14 +13,51 @@ type ThemeProviderProps = {
children: ReactNode
}

type ThemeProviderInstance = {
id: number
theme: Theme
}

let instanceId = 0
let providerStack: ThemeProviderInstance[] = []

const syncDocumentTheme = () => {
if (typeof document === 'undefined') return

const activeProvider = providerStack[providerStack.length - 1]
if (activeProvider) {
document.documentElement.setAttribute('data-theme', activeProvider.theme)
} else {
document.documentElement.removeAttribute('data-theme')
}
}

export const ThemeProvider = (props: ThemeProviderProps) => {
const { children, theme } = props
const providerIdRef = useRef<number | null>(null)
if (providerIdRef.current == null) {
providerIdRef.current = ++instanceId
}
const providerId = providerIdRef.current

useEffect(() => {
if (typeof document !== 'undefined') {
document.documentElement.setAttribute('data-theme', theme)
providerStack = [...providerStack, { id: providerId, theme }]
syncDocumentTheme()

return () => {
providerStack = providerStack.filter(
(provider) => provider.id !== providerId
)
syncDocumentTheme()
}
}, [theme])
}, [providerId])

useEffect(() => {
providerStack = providerStack.map((provider) =>
provider.id === providerId ? { ...provider, theme } : provider
)
syncDocumentTheme()
}, [providerId, theme])

return (
<EmotionThemeProvider theme={themes[theme]}>
Expand Down
Loading