ThemeContext.tsx 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. import { createContext, useContext, useEffect, useState, type ReactNode } from 'react';
  2. import { api } from '../api/client';
  3. import { useAuth } from './AuthContext';
  4. type ThemeMode = 'light' | 'dark' | 'system';
  5. type ThemeStyle = 'classic' | 'glow' | 'vibrant';
  6. type DarkBackground = 'neutral' | 'warm' | 'cool' | 'oled' | 'slate' | 'forest';
  7. type LightBackground = 'neutral' | 'warm' | 'cool';
  8. type ThemeAccent = 'green' | 'teal' | 'blue' | 'orange' | 'purple' | 'red';
  9. interface ThemeContextType {
  10. mode: ThemeMode;
  11. resolvedMode: 'light' | 'dark';
  12. // Dark mode settings
  13. darkStyle: ThemeStyle;
  14. darkBackground: DarkBackground;
  15. darkAccent: ThemeAccent;
  16. // Light mode settings
  17. lightStyle: ThemeStyle;
  18. lightBackground: LightBackground;
  19. lightAccent: ThemeAccent;
  20. // Actions
  21. toggleMode: () => void;
  22. setMode: (mode: ThemeMode) => void;
  23. setDarkStyle: (style: ThemeStyle) => void;
  24. setDarkBackground: (background: DarkBackground) => void;
  25. setDarkAccent: (accent: ThemeAccent) => void;
  26. setLightStyle: (style: ThemeStyle) => void;
  27. setLightBackground: (background: LightBackground) => void;
  28. setLightAccent: (accent: ThemeAccent) => void;
  29. }
  30. const ThemeContext = createContext<ThemeContextType | undefined>(undefined);
  31. export function ThemeProvider({ children }: { children: ReactNode }) {
  32. // Auth-aware: read state from AuthContext so the initial getSettings()
  33. // sync waits until we know whether (a) auth is enabled and (b) there
  34. // is a logged-in user. Without this the fetch fires on the login page
  35. // and returns 401 — harmless (the catch swallows it) but noisy in the
  36. // network panel and wasteful. ThemeProvider is mounted inside
  37. // AuthProvider in App.tsx specifically so this hook is callable.
  38. const { authEnabled, user, loading: authLoading } = useAuth();
  39. // Mode
  40. const [mode, setModeState] = useState<ThemeMode>(() => {
  41. const stored = localStorage.getItem('theme-mode') as ThemeMode | null;
  42. const legacy = localStorage.getItem('theme') as ThemeMode | null;
  43. return stored || legacy || 'dark';
  44. });
  45. // System preference detection
  46. const [systemPreference, setSystemPreference] = useState<'light' | 'dark'>(() => {
  47. return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
  48. });
  49. useEffect(() => {
  50. const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
  51. const handler = (e: MediaQueryListEvent) => {
  52. setSystemPreference(e.matches ? 'dark' : 'light');
  53. };
  54. mediaQuery.addEventListener('change', handler);
  55. return () => mediaQuery.removeEventListener('change', handler);
  56. }, []);
  57. // Resolved mode: what's actually applied (always 'light' or 'dark')
  58. const resolvedMode: 'light' | 'dark' = mode === 'system' ? systemPreference : mode;
  59. // Dark mode settings
  60. const [darkStyle, setDarkStyleState] = useState<ThemeStyle>(() => {
  61. return (localStorage.getItem('dark-style') as ThemeStyle) || 'vibrant';
  62. });
  63. const [darkBackground, setDarkBackgroundState] = useState<DarkBackground>(() => {
  64. return (localStorage.getItem('dark-background') as DarkBackground) || 'cool';
  65. });
  66. const [darkAccent, setDarkAccentState] = useState<ThemeAccent>(() => {
  67. return (localStorage.getItem('dark-accent') as ThemeAccent) || 'green';
  68. });
  69. // Light mode settings
  70. const [lightStyle, setLightStyleState] = useState<ThemeStyle>(() => {
  71. return (localStorage.getItem('light-style') as ThemeStyle) || 'classic';
  72. });
  73. const [lightBackground, setLightBackgroundState] = useState<LightBackground>(() => {
  74. return (localStorage.getItem('light-background') as LightBackground) || 'neutral';
  75. });
  76. const [lightAccent, setLightAccentState] = useState<ThemeAccent>(() => {
  77. return (localStorage.getItem('light-accent') as ThemeAccent) || 'green';
  78. });
  79. // Sync from API once auth state is known. Same gate shape as
  80. // useStreamTokenSync / ColorCatalogProvider: wait for AuthContext to
  81. // settle, then only fetch when we can actually expect a 200 (auth
  82. // disabled, or auth enabled with a logged-in user).
  83. useEffect(() => {
  84. if (authLoading) return;
  85. if (authEnabled && user === null) return;
  86. api.getSettings().then((settings) => {
  87. // Dark settings
  88. if (settings.dark_style) {
  89. setDarkStyleState(settings.dark_style as ThemeStyle);
  90. localStorage.setItem('dark-style', settings.dark_style);
  91. }
  92. if (settings.dark_background) {
  93. setDarkBackgroundState(settings.dark_background as DarkBackground);
  94. localStorage.setItem('dark-background', settings.dark_background);
  95. }
  96. if (settings.dark_accent) {
  97. setDarkAccentState(settings.dark_accent as ThemeAccent);
  98. localStorage.setItem('dark-accent', settings.dark_accent);
  99. }
  100. // Light settings
  101. if (settings.light_style) {
  102. setLightStyleState(settings.light_style as ThemeStyle);
  103. localStorage.setItem('light-style', settings.light_style);
  104. }
  105. if (settings.light_background) {
  106. setLightBackgroundState(settings.light_background as LightBackground);
  107. localStorage.setItem('light-background', settings.light_background);
  108. }
  109. if (settings.light_accent) {
  110. setLightAccentState(settings.light_accent as ThemeAccent);
  111. localStorage.setItem('light-accent', settings.light_accent);
  112. }
  113. }).catch(() => {});
  114. // Re-fetch when auth state transitions (e.g. login completes); the
  115. // gate above short-circuits subsequent calls once we already have a
  116. // valid sync.
  117. }, [authLoading, authEnabled, user]);
  118. // Apply theme classes based on current mode
  119. useEffect(() => {
  120. const root = document.documentElement;
  121. // Remove all theme classes
  122. root.classList.remove(
  123. 'dark',
  124. 'style-classic', 'style-glow', 'style-vibrant',
  125. 'bg-neutral', 'bg-warm', 'bg-cool', 'bg-oled', 'bg-slate', 'bg-forest',
  126. 'accent-green', 'accent-teal', 'accent-blue', 'accent-orange', 'accent-purple', 'accent-red'
  127. );
  128. // Apply based on resolved mode
  129. if (resolvedMode === 'dark') {
  130. root.classList.add('dark');
  131. root.classList.add(`style-${darkStyle}`);
  132. root.classList.add(`bg-${darkBackground}`);
  133. root.classList.add(`accent-${darkAccent}`);
  134. } else {
  135. root.classList.add(`style-${lightStyle}`);
  136. root.classList.add(`bg-${lightBackground}`);
  137. root.classList.add(`accent-${lightAccent}`);
  138. }
  139. localStorage.setItem('theme-mode', mode);
  140. localStorage.removeItem('theme');
  141. }, [mode, resolvedMode, darkStyle, darkBackground, darkAccent, lightStyle, lightBackground, lightAccent]);
  142. const toggleMode = () => setModeState(prev => {
  143. if (prev === 'dark') return 'light';
  144. if (prev === 'light') return 'system';
  145. return 'dark';
  146. });
  147. const setMode = (m: ThemeMode) => setModeState(m);
  148. // Dark setters
  149. const setDarkStyle = (v: ThemeStyle) => {
  150. setDarkStyleState(v);
  151. localStorage.setItem('dark-style', v);
  152. api.updateSettings({ dark_style: v }).catch(() => {});
  153. };
  154. const setDarkBackground = (v: DarkBackground) => {
  155. setDarkBackgroundState(v);
  156. localStorage.setItem('dark-background', v);
  157. api.updateSettings({ dark_background: v }).catch(() => {});
  158. };
  159. const setDarkAccent = (v: ThemeAccent) => {
  160. setDarkAccentState(v);
  161. localStorage.setItem('dark-accent', v);
  162. api.updateSettings({ dark_accent: v }).catch(() => {});
  163. };
  164. // Light setters
  165. const setLightStyle = (v: ThemeStyle) => {
  166. setLightStyleState(v);
  167. localStorage.setItem('light-style', v);
  168. api.updateSettings({ light_style: v }).catch(() => {});
  169. };
  170. const setLightBackground = (v: LightBackground) => {
  171. setLightBackgroundState(v);
  172. localStorage.setItem('light-background', v);
  173. api.updateSettings({ light_background: v }).catch(() => {});
  174. };
  175. const setLightAccent = (v: ThemeAccent) => {
  176. setLightAccentState(v);
  177. localStorage.setItem('light-accent', v);
  178. api.updateSettings({ light_accent: v }).catch(() => {});
  179. };
  180. return (
  181. <ThemeContext.Provider value={{
  182. mode,
  183. resolvedMode,
  184. darkStyle, darkBackground, darkAccent,
  185. lightStyle, lightBackground, lightAccent,
  186. toggleMode, setMode,
  187. setDarkStyle, setDarkBackground, setDarkAccent,
  188. setLightStyle, setLightBackground, setLightAccent,
  189. }}>
  190. {children}
  191. </ThemeContext.Provider>
  192. );
  193. }
  194. export function useTheme() {
  195. const context = useContext(ThemeContext);
  196. if (!context) throw new Error('useTheme must be used within ThemeProvider');
  197. return context;
  198. }
  199. export type { ThemeMode, ThemeStyle, DarkBackground, LightBackground, ThemeAccent };