All files / lib/theme theme-store.tsx

75.4% Statements 46/61
56% Branches 14/25
83.33% Functions 15/18
75% Lines 45/60

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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 1701x                           1x 1x 1x                                     1x     13x       16x 16x   16x             3x   3x       3x       5x 5x       1x       13x       13x               3x   3x 3x                 3x                   3x 3x   3x 3x 3x 3x               4x           4x 4x     4x 1x 1x   1x 1x 1x         1x     4x 1x     4x 4x                 4x       4x   4x       4x    
"use client";
 
import {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useSyncExternalStore,
  type ReactNode,
} from "react";
 
export type ThemeMode = "dark" | "light";
 
const storageKey = "headless-commerce-theme";
const listeners = new Set<() => void>();
let fallbackTheme: ThemeMode | null = null;
 
/**
 * Public theme context used by interactive controls.
 */
export interface ThemeContextValue {
  readonly isDark: boolean;
  readonly setTheme: (theme: ThemeMode) => void;
  readonly theme: ThemeMode;
  readonly toggleTheme: () => void;
}
 
/**
 * Theme provider options for the production shell.
 */
export interface ThemeProviderProps {
  readonly children: ReactNode;
}
 
const ThemeContext = createContext<ThemeContextValue | null>(null);
 
function canUseDom(): boolean {
  return typeof window !== "undefined" && typeof document !== "undefined";
}
 
function getStoredTheme(): ThemeMode | null {
  try {
    const value = window.localStorage.getItem(storageKey);
 
    return value === "dark" || value === "light" ? value : null;
  } catch {
    return null;
  }
}
 
function getPreferredTheme(): ThemeMode {
  const storedTheme = getStoredTheme();
 
  Iif (storedTheme) {
    return storedTheme;
  }
 
  return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
}
 
function applyTheme(theme: ThemeMode): void {
  document.documentElement.classList.toggle("dark", theme === "dark");
  document.documentElement.style.colorScheme = theme;
}
 
function emitThemeChange(): void {
  listeners.forEach((listener) => listener());
}
 
function getClientThemeSnapshot(): ThemeMode {
  Iif (!canUseDom()) {
    return "light";
  }
 
  return getStoredTheme() ?? fallbackTheme ?? getPreferredTheme();
}
 
function getServerThemeSnapshot(): ThemeMode {
  return "light";
}
 
function subscribeToTheme(listener: () => void): () => void {
  listeners.add(listener);
 
  const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
  const handleSystemThemeChange = (event: MediaQueryListEvent): void => {
    if (getStoredTheme()) {
      return;
    }
 
    const nextTheme: ThemeMode = event.matches ? "dark" : "light";
    applyTheme(nextTheme);
    emitThemeChange();
  };
  const handleStorageChange = (event: StorageEvent): void => {
    if (event.key !== storageKey) {
      return;
    }
 
    fallbackTheme = null;
    applyTheme(getPreferredTheme());
    emitThemeChange();
  };
 
  mediaQuery.addEventListener("change", handleSystemThemeChange);
  window.addEventListener("storage", handleStorageChange);
 
  return () => {
    listeners.delete(listener);
    mediaQuery.removeEventListener("change", handleSystemThemeChange);
    window.removeEventListener("storage", handleStorageChange);
  };
}
 
/**
 * Client-only theme provider with localStorage persistence and system preference fallback.
 */
export function ThemeProvider({ children }: ThemeProviderProps): ReactNode {
  const theme = useSyncExternalStore(
    subscribeToTheme,
    getClientThemeSnapshot,
    getServerThemeSnapshot,
  );
 
  useEffect(() => {
    applyTheme(theme);
  }, [theme]);
 
  const setTheme = useCallback((nextTheme: ThemeMode) => {
    fallbackTheme = nextTheme;
    applyTheme(nextTheme);
 
    try {
      window.localStorage.setItem(storageKey, nextTheme);
      fallbackTheme = null;
    } catch {
      // Ignore storage failures; the visual theme still updates for the current session.
    }
 
    emitThemeChange();
  }, []);
 
  const toggleTheme = useCallback(() => {
    setTheme(theme === "dark" ? "light" : "dark");
  }, [setTheme, theme]);
 
  const value = useMemo<ThemeContextValue>(
    () => ({
      isDark: theme === "dark",
      setTheme,
      theme,
      toggleTheme,
    }),
    [setTheme, theme, toggleTheme],
  );
 
  return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
}
 
export function useTheme(): ThemeContextValue {
  const context = useContext(ThemeContext);
 
  Iif (!context) {
    throw new Error("useTheme must be used inside ThemeProvider.");
  }
 
  return context;
}