Enhance theme switching to handle missing context

Replit-Commit-Author: Agent
Replit-Commit-Session-Id: 705f2157-ef97-4fbd-89e4-8c7f2ecaea90
Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/7ed01c5f-a82d-405a-b728-b2e3d127c60c/70b9c0b1-a5f0-4a27-9a6a-5bb48b9d90b1.jpg
This commit is contained in:
alphaeusmote
2025-04-09 00:47:22 +00:00
parent b466886372
commit 597f859e08
3 changed files with 137 additions and 16 deletions
+59 -2
View File
@@ -59,8 +59,65 @@ export function ThemeProvider({
export const useTheme = (): ThemeContextType => {
const context = useContext(ThemeContext);
if (context === undefined)
throw new Error('useTheme must be used within a ThemeProvider');
if (context === undefined) {
// Fallback implementation that doesn't rely on context
// This prevents crashes but won't sync across components
const storageKey = 'ad-management-theme';
const defaultTheme = 'system';
// Create a fallback state using localStorage
const getThemeFromStorage = (): Theme => {
try {
const storedTheme = localStorage.getItem(storageKey);
return (storedTheme as Theme) || defaultTheme;
} catch (e) {
return defaultTheme;
}
};
const currentTheme = getThemeFromStorage();
const applyThemeToDOM = (newTheme: Theme) => {
try {
const root = window.document.documentElement;
root.classList.remove('light', 'dark');
if (newTheme === 'system') {
const systemTheme = window.matchMedia('(prefers-color-scheme: dark)').matches
? 'dark'
: 'light';
root.classList.add(systemTheme);
} else {
root.classList.add(newTheme);
}
} catch (e) {
console.error('Error applying theme to DOM:', e);
}
};
// Apply the theme immediately for this component
applyThemeToDOM(currentTheme);
// Return a fallback implementation
return {
theme: currentTheme,
setTheme: (newTheme: Theme) => {
try {
localStorage.setItem(storageKey, newTheme);
applyThemeToDOM(newTheme);
// We can't update state here because we're not in a React component
// but we can apply the theme directly to the DOM
console.warn(
'Theme changed outside of ThemeProvider context. ' +
'This change won\'t be synced between components.'
);
} catch (e) {
console.error('Error setting theme:', e);
}
}
};
}
return context;
};