All files / Bandstand/src/components ThemeWatcher.tsx

89.47% Statements 17/19
80% Branches 4/5
66.66% Functions 2/3
89.47% Lines 17/19

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    1x 1x   4x 4x 4x 4x     4x     4x 4x 4x 4x 4x 4x 4x 4x 4x 4x  
'use client'
 
import {useEffect} from 'react'
import {THEME_KEY, applyTheme, parseThemePref} from '@/lib/theme'
 
function storedPref() {
  try {
    return parseThemePref(window.localStorage.getItem(THEME_KEY))
  } catch {
    return parseThemePref(null)
  }
}
 
/** Follows the device's light/dark setting live while the choice is "system". */
export default function ThemeWatcher() {
  useEffect(() => {
    applyTheme(storedPref())
    const mq = window.matchMedia('(prefers-color-scheme: dark)')
    const onChange = () => applyTheme(storedPref())
    mq.addEventListener('change', onChange)
    return () => mq.removeEventListener('change', onChange)
  }, [])
  return null
}