All files / src/common/theme theme.ts

89.47% Statements 34/38
71.42% Branches 10/14
100% Functions 5/5
89.47% Lines 34/38

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    1x   1x 6x 6x 6x 6x 6x     6x   1x 4x 4x 2x 2x 2x 2x 4x 4x 4x     4x   1x 2x 2x 2x     2x   1x 16x 16x 16x   1x 2x 2x 2x 2x 2x  
export type ThemeMode = 'light' | 'dark';
 
const STORAGE_KEY = 'theme';
 
export function getStoredTheme(): ThemeMode | null {
  try {
    const v = localStorage.getItem(STORAGE_KEY);
    if (v === 'light' || v === 'dark') return v;
    return null;
  } catch {
    return null;
  }
}
 
export function applyTheme(mode: ThemeMode) {
  const root = document.documentElement;
  if (mode === 'dark') {
    root.classList.add('dark');
  } else {
    root.classList.remove('dark');
  }
  try {
    window.dispatchEvent(new CustomEvent('nh-theme-change', { detail: { mode } }));
  } catch {
    // no-op
  }
}
 
export function setStoredTheme(mode: ThemeMode) {
  try {
    localStorage.setItem(STORAGE_KEY, mode);
  } catch {
    // no-op
  }
}
 
export function getCurrentTheme(): ThemeMode {
  const root = document.documentElement;
  return root.classList.contains('dark') ? 'dark' : 'light';
}
 
export function toggleTheme(): ThemeMode {
  const next: ThemeMode = getCurrentTheme() === 'dark' ? 'light' : 'dark';
  applyTheme(next);
  setStoredTheme(next);
  return next;
}