All files / apps / web/src / lib theme.ts

100% Statements 16/16
100% Branches 12/12
100% Functions 8/8
100% Lines 14/14

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            9x         10x 10x   10x   1x         5x 5x             10x         14x   14x         8x   2x   2x   2x    
import { MEDIA_QUERY } from '@/constants/media'
import { STORAGE_KEY } from '@/constants/storage'
 
export type ThemeChoice = 'light' | 'dark' | 'system'
 
function isThemeChoice(value: unknown): value is ThemeChoice {
  return value === 'light' || value === 'dark' || value === 'system'
}
 
// Storage can throw in a private window; the theme then follows the system.
export function readThemeChoice(): ThemeChoice {
  try {
    const stored = localStorage.getItem(STORAGE_KEY.theme)
 
    return isThemeChoice(stored) ? stored : 'system'
  } catch {
    return 'system'
  }
}
 
export function saveThemeChoice(choice: ThemeChoice): void {
  try {
    localStorage.setItem(STORAGE_KEY.theme, choice)
  } catch {
    // Not saved: the choice still applies until the page reloads.
  }
}
 
export function systemPrefersDark(): boolean {
  return typeof window.matchMedia === 'function' && window.matchMedia(MEDIA_QUERY.dark).matches
}
 
// tokens.css (src/styles/) keys the dark tokens on `.dark` at the root.
export function applyTheme(choice: ThemeChoice): void {
  const isDark = choice === 'dark' || (choice === 'system' && systemPrefersDark())
 
  document.documentElement.classList.toggle('dark', isDark)
}
 
// Calls back when the system switches between light and dark; returns the unsubscribe.
export function onSystemThemeChange(callback: () => void): () => void {
  if (typeof window.matchMedia !== 'function') return () => {}
 
  const query = window.matchMedia(MEDIA_QUERY.dark)
 
  query.addEventListener('change', callback)
 
  return () => query.removeEventListener('change', callback)
}