fix: guard frontend theme storage access

This commit is contained in:
Graham McIntire 2026-03-23 13:42:36 -05:00
parent d2fd0d181f
commit c9e5ece185
No known key found for this signature in database
2 changed files with 21 additions and 3 deletions

View file

@ -214,8 +214,24 @@ const applyTheme = (theme: string | null) => {
} }
}; };
const getStoredTheme = (): string => {
try {
return localStorage.getItem("theme") || "auto";
} catch (_error) {
return "auto";
}
};
const setStoredTheme = (theme: string) => {
try {
localStorage.setItem("theme", theme);
} catch (_error) {
// Ignore storage failures in restricted/private browsing contexts.
}
};
// Apply initial theme from localStorage // Apply initial theme from localStorage
applyTheme(localStorage.getItem("theme") || "auto"); applyTheme(getStoredTheme());
const colorSchemeQuery = window.matchMedia const colorSchemeQuery = window.matchMedia
? window.matchMedia("(prefers-color-scheme: dark)") ? window.matchMedia("(prefers-color-scheme: dark)")
@ -225,13 +241,13 @@ const colorSchemeQuery = window.matchMedia
window.addEventListener("phx:set-theme", ((e: CustomEvent<{ theme: string }>) => { window.addEventListener("phx:set-theme", ((e: CustomEvent<{ theme: string }>) => {
const theme = e.detail.theme; const theme = e.detail.theme;
applyTheme(theme); applyTheme(theme);
localStorage.setItem("theme", theme); setStoredTheme(theme);
window.dispatchEvent(new CustomEvent("themeChanged")); window.dispatchEvent(new CustomEvent("themeChanged"));
}) as EventListener); }) as EventListener);
// Listen for system theme changes when auto is selected // Listen for system theme changes when auto is selected
const handleSystemThemeChange = () => { const handleSystemThemeChange = () => {
if (localStorage.getItem("theme") === "auto") { if (getStoredTheme() === "auto") {
applyTheme("auto"); applyTheme("auto");
window.dispatchEvent(new CustomEvent("themeChanged")); window.dispatchEvent(new CustomEvent("themeChanged"));
} }

View file

@ -39,6 +39,8 @@ export function parseTimestamp(timestamp: string | number | Date | undefined): n
return timestamp; return timestamp;
} else if (typeof timestamp === "string") { } else if (typeof timestamp === "string") {
return new Date(timestamp).getTime(); return new Date(timestamp).getTime();
} else if (timestamp instanceof Date) {
return timestamp.getTime();
} }
return Date.now(); return Date.now();
} }