mirror of
https://github.com/handsomezhuzhu/2fa-tool.git
synced 2026-04-18 14:22:54 +00:00
Create React Context-based theme provider with localStorage support. Co-authored-by: Simon <85533298+handsomezhuzhu@users.noreply.github.com>
102 lines
2.5 KiB
TypeScript
102 lines
2.5 KiB
TypeScript
"use client"
|
|
|
|
import * as React from "react"
|
|
import { createContext, useContext, useEffect, useState } from "react"
|
|
|
|
type Theme = "dark" | "light" | "system"
|
|
|
|
type ThemeProviderProps = {
|
|
children: React.ReactNode
|
|
defaultTheme?: Theme
|
|
storageKey?: string
|
|
attribute?: string
|
|
enableSystem?: boolean
|
|
disableTransitionOnChange?: boolean
|
|
}
|
|
|
|
type ThemeProviderState = {
|
|
theme: Theme
|
|
setTheme: (theme: Theme) => void
|
|
resolvedTheme?: string
|
|
}
|
|
|
|
const ThemeProviderContext = createContext<ThemeProviderState | undefined>(undefined)
|
|
|
|
export function ThemeProvider({
|
|
children,
|
|
defaultTheme = "system",
|
|
storageKey = "theme",
|
|
...props
|
|
}: ThemeProviderProps) {
|
|
const [theme, setTheme] = useState<Theme>(defaultTheme)
|
|
const [resolvedTheme, setResolvedTheme] = useState<string | undefined>(undefined)
|
|
const [mounted, setMounted] = useState(false)
|
|
|
|
useEffect(() => {
|
|
setMounted(true)
|
|
const stored = localStorage.getItem(storageKey) as Theme | null
|
|
if (stored) {
|
|
setTheme(stored)
|
|
}
|
|
}, [storageKey])
|
|
|
|
useEffect(() => {
|
|
if (!mounted) return
|
|
|
|
const root = window.document.documentElement
|
|
|
|
root.classList.remove("light", "dark")
|
|
|
|
let resolved: string
|
|
if (theme === "system") {
|
|
resolved = window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"
|
|
} else {
|
|
resolved = theme
|
|
}
|
|
|
|
root.classList.add(resolved)
|
|
setResolvedTheme(resolved)
|
|
}, [theme, mounted])
|
|
|
|
useEffect(() => {
|
|
if (!mounted || theme !== "system") return
|
|
|
|
const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)")
|
|
const handleChange = () => {
|
|
const resolved = mediaQuery.matches ? "dark" : "light"
|
|
const root = window.document.documentElement
|
|
root.classList.remove("light", "dark")
|
|
root.classList.add(resolved)
|
|
setResolvedTheme(resolved)
|
|
}
|
|
|
|
mediaQuery.addEventListener("change", handleChange)
|
|
return () => mediaQuery.removeEventListener("change", handleChange)
|
|
}, [theme, mounted])
|
|
|
|
const value = {
|
|
theme,
|
|
setTheme: (newTheme: Theme) => {
|
|
localStorage.setItem(storageKey, newTheme)
|
|
setTheme(newTheme)
|
|
},
|
|
resolvedTheme,
|
|
}
|
|
|
|
return (
|
|
<ThemeProviderContext.Provider value={value}>
|
|
{children}
|
|
</ThemeProviderContext.Provider>
|
|
)
|
|
}
|
|
|
|
export function useTheme() {
|
|
const context = useContext(ThemeProviderContext)
|
|
|
|
if (context === undefined) {
|
|
throw new Error("useTheme must be used within a ThemeProvider")
|
|
}
|
|
|
|
return context
|
|
}
|