All files / src/lib theme.ts

100% Statements 13/13
100% Branches 8/8
100% Functions 3/3
100% Lines 13/13

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                    1x 1x       8x 8x 8x 3x         5x               6x 2x   4x         3x 3x 3x    
/**
 * Theme utilities for the marketplace app.
 *
 * Shared localStorage key with portal ensures theme preference
 * carries across apps on the same domain.
 */
 
export type Theme = "light" | "dark" | "system";
export type ResolvedTheme = "light" | "dark";
 
export const STORAGE_KEY = "decor-rocket-theme";
export const VALID_THEMES: Theme[] = ["light", "dark", "system"];
 
/** Read stored theme from localStorage, defaulting to "system". */
export function getStoredTheme(): Theme {
	try {
		const stored = localStorage.getItem(STORAGE_KEY);
		if (stored && VALID_THEMES.includes(stored as Theme)) {
			return stored as Theme;
		}
	} catch {
		// localStorage unavailable (SSR, private browsing, etc.)
	}
	return "light";
}
 
/** Resolve a theme preference to an actual light/dark value. */
export function resolveTheme(
	theme: Theme,
	prefersDark: boolean,
): ResolvedTheme {
	if (theme === "system") {
		return prefersDark ? "dark" : "light";
	}
	return theme;
}
 
/** Cycle to the next theme: system → light → dark → system. */
export function getNextTheme(current: Theme): Theme {
	const cycle: Theme[] = ["system", "light", "dark"];
	const index = cycle.indexOf(current);
	return cycle[(index + 1) % cycle.length];
}