Align admin, community, search, library, learning and course management with the mockup. Add saved courses, download history, public community feed, instructor directory, backend search, course views, admin content tools and community moderation. Harden API and Nginx for production.
40 lines
1.3 KiB
TypeScript
40 lines
1.3 KiB
TypeScript
import React, { createContext, useCallback, useContext, useEffect, useState } from 'react';
|
|
import { readPreference, writePreference } from '../lib/storage';
|
|
|
|
type Theme = 'light' | 'dark';
|
|
|
|
interface ThemeContextType {
|
|
theme: Theme;
|
|
toggleTheme: () => void;
|
|
}
|
|
|
|
const THEME_KEY = 'ca-theme';
|
|
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);
|
|
|
|
// Light by default; the choice is saved and the system preference is not followed.
|
|
const initialTheme = (): Theme => (readPreference(THEME_KEY) === 'dark' ? 'dark' : 'light');
|
|
|
|
export const ThemeProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
|
const [theme, setTheme] = useState<Theme>(initialTheme);
|
|
|
|
useEffect(() => {
|
|
document.documentElement.classList.toggle('dark', theme === 'dark');
|
|
}, [theme]);
|
|
|
|
const toggleTheme = useCallback(() => {
|
|
setTheme((current) => {
|
|
const next = current === 'dark' ? 'light' : 'dark';
|
|
writePreference(THEME_KEY, next);
|
|
return next;
|
|
});
|
|
}, []);
|
|
|
|
return <ThemeContext.Provider value={{ theme, toggleTheme }}>{children}</ThemeContext.Provider>;
|
|
};
|
|
|
|
export const useTheme = () => {
|
|
const context = useContext(ThemeContext);
|
|
if (!context) throw new Error('useTheme must be used within ThemeProvider');
|
|
return context;
|
|
};
|