DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
refactor: clean up theme system per code review
Tushar Khatri2218a743ed6f
diff --git a/IMPLEMENTATION_COMPLETE.md b/IMPLEMENTATION_COMPLETE.mddeleted file mode 100644index 5d23fe603..000000000--- a/IMPLEMENTATION_COMPLETE.md+++ /dev/null@@ -1,200 +0,0 @@-# Theme Persistence Implementation - Complete--## Problem Solved ✅-**Issue**: When toggling between dark/light theme in settings, the theme would revert to light mode on page refresh.--**Root Cause**: Theme preference was not persisted - it was only stored in React state without localStorage or proper backend sync.--## Solution Implemented--### Architecture-```-┌──────────────────────────────────────────────────────────┐-│ Browser Page Load │-├──────────────────────────────────────────────────────────┤-│ │-│ 1. ThemeScript (in <head>) │-│ └─ Reads localStorage before React │-│ └─ Applies theme class instantly (NO FLASH!) │-│ │-│ 2. React Hydration │-│ └─ GlobalProvider initializes theme │-│ └─ Fetches from backend API │-│ └─ Updates if different │-│ │-│ 3. User Changes Theme │-│ └─ Settings UI → applyTheme() │-│ └─ → setTheme() utility │-│ └─ Persists to localStorage + DOM │-│ └─ Syncs to backend on save │-│ │-│ 4. Page Refresh │-│ └─ Cycle starts again → Theme loads instantly │-│ │-└──────────────────────────────────────────────────────────┘-```--## Files Created (5 new files)--### 1. `web/lib/theme.ts`-Core theme management utilities:-- `getStoredTheme()` - Read from localStorage-- `saveThemeToStorage()` - Write to localStorage-- `getSystemTheme()` - Detect system preference-- `applyThemeToDocument()` - Update DOM-- `initializeTheme()` - Initialize on startup-- `setTheme()` - Main function (apply + persist)--### 2. `web/lib/theme-utils.ts`-Helper functions for common scenarios:-- `toggleTheme()` - Toggle between light/dark-- `setLightTheme()` - Set light mode-- `setDarkTheme()` - Set dark mode-- `getThemeClass()` - Get CSS classes-- `onThemeChange()` - Listen to changes--### 3. `web/hooks/useTheme.ts`-React hook for component usage:-```typescript-const { theme, isDark, isLight, setTheme, isLoaded } = useTheme();-```--### 4. `web/components/ThemeScript.tsx`-Inline script to prevent theme flash:-- Runs before React hydration-- Reads localStorage immediately-- Applies theme to DOM-- No JavaScript flashing!--### 5. Documentation (3 files)-- `THEME_PERSISTENCE.md` - Complete technical documentation-- `THEME_SETUP_GUIDE.md` - Quick setup and usage guide-- `THEME_DEVELOPER_GUIDE.md` - Developer best practices--## Files Modified (3 files)--### 1. `web/app/layout.tsx`-**Changes**:-- Added `ThemeScript` import-- Added `<ThemeScript />` in `<head>`-- Prevents theme flash on load--### 2. `web/context/GlobalContext.tsx`-**Changes**:-- Imported theme utilities-- Updated theme initialization to call `initializeTheme()`-- Updated `refreshSettings()` to sync to localStorage-- Added fallback if API fails--### 3. `web/app/settings/page.tsx`-**Changes**:-- Imported `setTheme` utility-- Updated `applyTheme()` to use `setTheme()`-- Updated `handleSave()` to sync theme immediately-- Theme now persists on every save--## How It Works--### Priority Order-When determining which theme to use:-1. **localStorage** - User's saved preference (highest priority)-2. **System preference** - `prefers-color-scheme: dark` media query-3. **Default** - Light mode--### Theme Persistence Flow-```-localStorage ← → Backend (settings.json)- ↓ ↓- saved on synced on- change save- ↓ ↓- Available Available- offline cross-device-```--### No Flash Magic 🪄-```html-<!-- In <head> of layout.tsx -->-<script>- // This runs BEFORE React loads- // Reads localStorage and applies theme immediately- (function() {- const theme = localStorage.getItem('deeptutor-theme');- if (theme === 'dark') {- document.documentElement.classList.add('dark');- }- })();-</script>-```--## Testing Checklist--- [x] Theme saves to localStorage-- [x] Theme persists on page refresh-- [x] No flash of wrong theme on load-- [x] Theme syncs to backend-- [x] Works offline with localStorage-- [x] System preference detection works-- [x] Multiple browser tabs sync-- [x] Theme applies to all components--## Usage Examples--### Toggle Theme Button-```typescript-import { useTheme } from '@/hooks/useTheme';--function ThemeToggle() {- const { isDark, setTheme } = useTheme();-- return (- <button onClick={() => setTheme(isDark ? 'light' : 'dark')}>- {isDark ? '☀️ Light' : '🌙 Dark'}- </button>- );-}-```--### Watch Theme Changes-```typescript-import { onThemeChange } from '@/lib/theme-utils';--useEffect(() => {- const unsubscribe = onThemeChange((theme) => {- console.log('Theme changed to:', theme);- });- return unsubscribe;-}, []);-```--### Direct Theme Change-```typescript-import { setDarkTheme, setLightTheme } from '@/lib/theme-utils';--// Set dark mode-setDarkTheme();--// Set light mode-setLightTheme();-```--## Benefits--✅ **No Flash** - Theme loads before React renders-✅ **Persistent** - Saved locally and on backend-✅ **Resilient** - Works offline with localStorage-✅ **Smart** - Respects system preferences-✅ **Type-Safe** - Full TypeScript support-✅ **Accessible** - Follows web standards-✅ **Easy to Use** - Simple API for developers--## Next Steps--1. Test the theme persistence in your app-2. Share the `THEME_DEVELOPER_GUIDE.md` with your team-3. Update any other theme-related code to use the utilities-4. Consider the "Future Enhancements" in the developer guide-------**Implementation complete! Your app now has bulletproof theme persistence.** 🎉diff --git a/web/app/settings/page.tsx b/web/app/settings/page.tsxindex 3be54381a..c555d9fd2 100644--- a/web/app/settings/page.tsx+++ b/web/app/settings/page.tsx@@ -1,6 +1,6 @@"use client";-import { useState, useEffect } from "react";+import { useState, useEffect, useRef } from "react";import {Settings as SettingsIcon,Sun,@@ -30,6 +30,7 @@ import {import { apiUrl } from "@/lib/api";import { getTranslation } from "@/lib/i18n";import { setTheme } from "@/lib/theme";+import { debounce } from "@/lib/debounce";import { useGlobal } from "@/context/GlobalContext";@@ -225,6 +226,21 @@ export default function SettingsPage() {string | null>(null);+ // Create debounced theme save function+ const debouncedSaveTheme = useRef(+ debounce(async (themeValue: "light" | "dark", uiSettings: UISettings) => {+ try {+ await fetch(apiUrl("/api/v1/settings/ui"), {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ ...uiSettings, theme: themeValue }),+ });+ } catch (err) {+ // Silently fail - theme is still saved to localStorage+ }+ }, 500)+ ).current;+useEffect(() => {fetchSettings();fetchSettings();@@ -444,22 +460,18 @@ export default function SettingsPage() {const res = await fetch(apiUrl("/api/v1/settings"));if (res.ok) {const responseData = await res.json();- console.log("[settings] fetchSettings - backend ui:", responseData.ui);setData(responseData);setEditedConfig(JSON.parse(JSON.stringify(responseData.config)));if (!editedUI) {const uiData = JSON.parse(JSON.stringify(responseData.ui));- // If there's a stored theme in localStorage, use it instead of backend default+ // localStorage takes priority over backendconst storedTheme = localStorage.getItem('deeptutor-theme');- console.log("[settings] fetchSettings - storedTheme from localStorage:", storedTheme);if (storedTheme === 'light' || storedTheme === 'dark') {- console.log("[settings] Using localStorage theme:", storedTheme, "instead of backend:", uiData.theme);uiData.theme = storedTheme;}setEditedUI(uiData);- // Apply the theme (either from localStorage or backend)+ // Apply theme if presentif (uiData.theme) {- console.log("[settings] Applying theme:", uiData.theme);applyTheme(uiData.theme);}}@@ -595,8 +607,6 @@ export default function SettingsPage() {const applyTheme = (theme: "light" | "dark") => {// Persist theme to localStorage and document immediatelysetTheme(theme);- // Console log for debugging- console.log("Theme changed to:", theme, "and saved to localStorage");};const handleSave = async () => {@@ -674,12 +684,8 @@ export default function SettingsPage() {const newUI = { ...prev, [key]: value };if (key === "theme") {applyTheme(value);- // Auto-save theme to backend immediately- fetch(apiUrl("/api/v1/settings/ui"), {- method: "PUT",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ ...newUI, [key]: value }),- }).catch((err) => console.error("Failed to save theme:", err));+ // Debounced auto-save to backend+ debouncedSaveTheme(value, newUI);}return newUI;});diff --git a/web/components/ThemeScript.tsx b/web/components/ThemeScript.tsxindex b10ca0968..b7e0dff3f 100644--- a/web/components/ThemeScript.tsx+++ b/web/components/ThemeScript.tsx@@ -9,28 +9,22 @@ export default function ThemeScript() {(function() {try {const stored = localStorage.getItem('deeptutor-theme');- console.log('[ThemeScript] localStorage theme:', stored);if (stored === 'dark') {- console.log('[ThemeScript] Applying dark theme from localStorage');document.documentElement.classList.add('dark');} else if (stored === 'light') {- console.log('[ThemeScript] Applying light theme from localStorage');document.documentElement.classList.remove('dark');} else {- console.log('[ThemeScript] No theme in localStorage, checking system preference');// Use system preference if not setif (window.matchMedia('(prefers-color-scheme: dark)').matches) {- console.log('[ThemeScript] System prefers dark, applying dark theme');document.documentElement.classList.add('dark');localStorage.setItem('deeptutor-theme', 'dark');} else {- console.log('[ThemeScript] System prefers light, applying light theme');localStorage.setItem('deeptutor-theme', 'light');}}} catch (e) {- console.error('[ThemeScript] Error:', e);+ // Silently fail - localStorage may be disabled}})();`;diff --git a/web/context/GlobalContext.tsx b/web/context/GlobalContext.tsxindex 13cb28cc9..58f5505f0 100644--- a/web/context/GlobalContext.tsx+++ b/web/context/GlobalContext.tsx@@ -270,26 +270,22 @@ export function GlobalProvider({ children }: { children: React.ReactNode }) {if (res.ok) {const data = await res.json();if (data.ui) {- // Check if localStorage has a saved theme preference+ // localStorage takes priority over backendconst storedTheme = getStoredTheme();const themeToUse = storedTheme || data.ui.theme;- console.log("[GlobalContext] refreshSettings - storedTheme:", storedTheme, "backendTheme:", data.ui.theme, "final:", themeToUse);-setUiSettings({theme: themeToUse,language: data.ui.language,});- // Persist theme to localStorage (will sync with backend on save)+ // Apply and persist themesetTheme(themeToUse);}}} catch (e) {- console.error("Failed to load settings from backend", e);- // Fall back to localStorage theme+ // Fall back to localStorage theme on errorconst stored = getStoredTheme();if (stored) {- console.log("[GlobalContext] Using fallback localStorage theme:", stored);setUiSettings((prev) => ({ ...prev, theme: stored }));}}@@ -299,7 +295,6 @@ export function GlobalProvider({ children }: { children: React.ReactNode }) {// Initialize theme immediately on first renderif (!isInitialized) {const initialTheme = initializeTheme();- console.log("[GlobalContext] useEffect - initialized theme:", initialTheme);setUiSettings((prev) => ({ ...prev, theme: initialTheme }));setIsInitialized(true);diff --git a/web/lib/debounce.ts b/web/lib/debounce.tsnew file mode 100644index 000000000..54a3368fe--- /dev/null+++ b/web/lib/debounce.ts@@ -0,0 +1,22 @@+/**+ * Debounce utility+ * Delays function execution until after wait milliseconds have elapsed since the last call+ */+export function debounce<T extends (...args: any[]) => any>(+ func: T,+ wait: number+): (...args: Parameters<T>) => void {+ let timeout: NodeJS.Timeout | null = null;++ return function executedFunction(...args: Parameters<T>) {+ const later = () => {+ timeout = null;+ func(...args);+ };++ if (timeout) {+ clearTimeout(timeout);+ }+ timeout = setTimeout(later, wait);+ };+}diff --git a/web/lib/theme.ts b/web/lib/theme.tsindex 4e56a27d1..a3160c26e 100644--- a/web/lib/theme.ts+++ b/web/lib/theme.ts@@ -5,7 +5,25 @@export type Theme = "light" | "dark";-const THEME_STORAGE_KEY = "deeptutor-theme";+export const THEME_STORAGE_KEY = "deeptutor-theme";++type ThemeChangeListener = (theme: Theme) => void;+const themeListeners = new Set<ThemeChangeListener>();++/**+ * Subscribe to theme changes+ */+export function subscribeToThemeChanges(listener: ThemeChangeListener): () => void {+ themeListeners.add(listener);+ return () => themeListeners.delete(listener);+}++/**+ * Notify all listeners of theme change+ */+function notifyThemeChange(theme: Theme): void {+ themeListeners.forEach(listener => listener(theme));+}/*** Get the stored theme from localStorage@@ -19,7 +37,7 @@ export function getStoredTheme(): Theme | null {return stored;}} catch (e) {- console.error("Failed to read theme from localStorage", e);+ // Silently fail - localStorage may be disabled}return null;@@ -28,14 +46,15 @@ export function getStoredTheme(): Theme | null {/*** Save theme to localStorage*/-export function saveThemeToStorage(theme: Theme): void {- if (typeof window === "undefined") return;+export function saveThemeToStorage(theme: Theme): boolean {+ if (typeof window === "undefined") return false;try {localStorage.setItem(THEME_STORAGE_KEY, theme);- console.log("[theme.ts] Saved theme to localStorage:", theme);+ return true;} catch (e) {- console.error("Failed to save theme to localStorage", e);+ // Silently fail - localStorage may be disabled or full+ return false;}}@@ -59,10 +78,8 @@ export function applyThemeToDocument(theme: Theme): void {const html = document.documentElement;if (theme === "dark") {html.classList.add("dark");- console.log("[theme.ts] Applied dark theme to document");} else {html.classList.remove("dark");- console.log("[theme.ts] Applied light theme to document");}}@@ -81,6 +98,7 @@ export function initializeTheme(): Theme {// Fall back to system preferenceconst systemTheme = getSystemTheme();applyThemeToDocument(systemTheme);+ saveThemeToStorage(systemTheme);return systemTheme;}@@ -88,7 +106,7 @@ export function initializeTheme(): Theme {* Set theme and persist it*/export function setTheme(theme: Theme): void {- console.log("[theme.ts] setTheme called with:", theme);applyThemeToDocument(theme);saveThemeToStorage(theme);+ notifyThemeChange(theme);}