All files / src/app/providers ThemeProvider.tsx

90.32% Statements 28/31
100% Branches 11/11
90% Functions 9/10
89.28% Lines 25/28

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70        3x 3x     10x       12x 12x 12x     1x         25x       13x                       14x 14x   14x 13x 13x 13x   13x   5x 5x         5x 5x     14x 1x 1x 1x           14x    
import { useEffect, useState, type ReactNode } from 'react'
 
import { ThemeContext, type ResolvedTheme, type ThemeMode } from './theme-context'
 
const STORAGE_KEY = 'theme'
const DARK_MEDIA_QUERY = '(prefers-color-scheme: dark)'
 
function getSystemPreference(): ResolvedTheme {
  return window.matchMedia(DARK_MEDIA_QUERY).matches ? 'dark' : 'light'
}
 
function readStoredTheme(): ThemeMode {
  try {
    const stored = window.localStorage.getItem(STORAGE_KEY)
    return stored === 'light' || stored === 'dark' || stored === 'system' ? stored : 'system'
  } catch {
    // Blocking site storage must not prevent the application from mounting.
    return 'system'
  }
}
 
function resolveTheme(theme: ThemeMode): ResolvedTheme {
  return theme === 'system' ? getSystemPreference() : theme
}
 
function applyResolvedTheme(resolved: ResolvedTheme) {
  document.documentElement.classList.toggle('dark', resolved === 'dark')
}
 
interface ThemeProviderProps {
  children: ReactNode
}
 
// Applies/removes Tailwind's `.dark` class on <html> based on a persisted
// 'light' | 'dark' | 'system' preference (localStorage key: 'theme'),
// falling back to the OS-level prefers-color-scheme when set to 'system'
// (and reacting live to OS-level changes while in that mode).
export function ThemeProvider({ children }: ThemeProviderProps) {
  const [theme, setThemeState] = useState<ThemeMode>(readStoredTheme)
  const [resolvedTheme, setResolvedTheme] = useState<ResolvedTheme>(() => resolveTheme(theme))
 
  useEffect(() => {
    const resolved = resolveTheme(theme)
    setResolvedTheme(resolved)
    applyResolvedTheme(resolved)
 
    if (theme !== 'system') return
 
    const mediaQuery = window.matchMedia(DARK_MEDIA_QUERY)
    const handleChange = () => {
      const nextResolved = getSystemPreference()
      setResolvedTheme(nextResolved)
      applyResolvedTheme(nextResolved)
    }
    mediaQuery.addEventListener('change', handleChange)
    return () => mediaQuery.removeEventListener('change', handleChange)
  }, [theme])
 
  const setTheme = (next: ThemeMode) => {
    setThemeState(next)
    try {
      window.localStorage.setItem(STORAGE_KEY, next)
    } catch {
      // The preference still works for this session when persistence is unavailable.
    }
  }
 
  return <ThemeContext.Provider value={{ theme, resolvedTheme, setTheme }}>{children}</ThemeContext.Provider>
}