Files
supervisor-ui/components/providers/ThemeProvider.tsx
Sebastian Krüger 3d5e9e36d6
All checks were successful
Build and Push Docker Image to Gitea / build-and-push (push) Successful in 1m6s
fix: resolve ThemeProvider SSR issue causing 500 error
The app was crashing with "useTheme must be used within ThemeProvider"
error during server-side rendering.

Changes:
- Created AppLayout client component to wrap Navbar
- Modified useTheme hook to return default values during SSR
  instead of throwing an error
- Updated Navbar to safely handle theme context
- Moved Navbar rendering into client-side only AppLayout

This fixes the SSR hydration mismatch and allows the app
to render correctly on both server and client.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-23 20:27:44 +01:00

83 lines
2.0 KiB
TypeScript

'use client';
import { createContext, useContext, useEffect, useState, ReactNode } from 'react';
type Theme = 'light' | 'dark' | 'system';
interface ThemeContextType {
theme: Theme;
setTheme: (theme: Theme) => void;
resolvedTheme: 'light' | 'dark';
}
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);
export function ThemeProvider({ children }: { children: ReactNode }) {
const [theme, setThemeState] = useState<Theme>('system');
const [resolvedTheme, setResolvedTheme] = useState<'light' | 'dark'>('light');
const [mounted, setMounted] = useState(false);
useEffect(() => {
setMounted(true);
const stored = localStorage.getItem('theme') as Theme | null;
if (stored) {
setThemeState(stored);
}
}, []);
useEffect(() => {
if (!mounted) return;
const root = document.documentElement;
const systemTheme = window.matchMedia('(prefers-color-scheme: dark)').matches
? 'dark'
: 'light';
const effectiveTheme = theme === 'system' ? systemTheme : theme;
// Add transition disable class
root.classList.add('disable-transitions');
// Update theme
if (effectiveTheme === 'dark') {
root.classList.add('dark');
} else {
root.classList.remove('dark');
}
setResolvedTheme(effectiveTheme);
// Re-enable transitions after a frame
requestAnimationFrame(() => {
root.classList.remove('disable-transitions');
});
}, [theme, mounted]);
const setTheme = (newTheme: Theme) => {
setThemeState(newTheme);
localStorage.setItem('theme', newTheme);
};
if (!mounted) {
return <>{children}</>;
}
return (
<ThemeContext.Provider value={{ theme, setTheme, resolvedTheme }}>
{children}
</ThemeContext.Provider>
);
}
export function useTheme() {
const context = useContext(ThemeContext);
if (!context) {
// Return a default context for SSR or when outside provider
return {
theme: 'system' as Theme,
setTheme: () => {},
resolvedTheme: 'light' as 'light' | 'dark',
};
}
return context;
}