chore: remove theme documentation files

This commit is contained in:
Tushar Khatri
2026-01-06 00:58:51 +05:30
parent 09fb559093
commit 2b177e5be0
3 changed files with 0 additions and 418 deletions

View File

@@ -1,163 +0,0 @@
# Theme Persistence - Migration & Developer Guide
## For Other Developers
### New Theme Pattern
Instead of manually manipulating the DOM for theme changes, always use the theme utilities:
❌ **Old Way (Don't do this)**
```typescript
// Bad - Direct DOM manipulation, no persistence
document.documentElement.classList.add('dark');
document.documentElement.classList.remove('dark');
```
✅ **New Way (Do this)**
```typescript
// Good - Uses centralized utilities with persistence
import { setTheme } from '@/lib/theme';
setTheme('dark');
```
### Accessing Current Theme
❌ **Old Way**
```typescript
const isDark = document.documentElement.classList.contains('dark');
```
✅ **New Way**
```typescript
import { useTheme } from '@/hooks/useTheme';
function MyComponent() {
const { isDark, theme } = useTheme();
// ...
}
```
### Listening to Theme Changes
✅ **New Capability**
```typescript
import { onThemeChange } from '@/lib/theme-utils';
// Listen to theme changes across browser tabs
const unsubscribe = onThemeChange((theme) => {
console.log('Theme switched to:', theme);
// Perform any theme-dependent updates
});
// Clean up on unmount
useEffect(() => {
return unsubscribe;
}, []);
```
## Components That Use Theme
### Settings Page
- File: `web/app/settings/page.tsx`
- Lines: Theme toggle UI and applyTheme() function
- Now uses `setTheme()` from `@/lib/theme`
### Global Provider
- File: `web/context/GlobalContext.tsx`
- Theme initialized on app startup
- Syncs with backend on refresh
### Layout
- File: `web/app/layout.tsx`
- ThemeScript in head prevents flash
- Loads theme before React hydration
## API Endpoints Used
### Get Settings
```
GET /api/v1/settings
```
Response includes `ui.theme: "light" | "dark"`
### Update Settings
```
PUT /api/v1/settings/ui
Body: { theme: "light" | "dark", language: "en" | "zh", ... }
```
### Update Theme Only
```
PUT /api/v1/settings/theme
Body: { theme: "light" | "dark" }
```
## localStorage Key
- **Key**: `deeptutor-theme`
- **Values**: `"light"` or `"dark"`
- **Scope**: Browser/Device local storage
## Troubleshooting
### Theme keeps reverting to light
**Solution**: Ensure `setTheme()` is being called instead of direct DOM manipulation
### Flash of wrong theme on load
**Check**:
1. Is `ThemeScript` component in `layout.tsx` head?
2. Is it before other scripts?
**Solution**: Make sure `<ThemeScript />` is inside `<head>` in `layout.tsx`
### Theme not syncing to backend
**Check**:
1. Is `PUT /api/v1/settings/ui` endpoint responding?
2. Is `handleSave()` being called in settings page?
**Solution**: Verify backend settings endpoint is working properly
### localStorage not available (SSR environment)
**All functions check** for window availability:
```typescript
if (typeof window === "undefined") return null;
```
This makes all utilities safe to use in SSR/Next.js
## Best Practices
1. **Always use `setTheme()`** for theme changes - it handles all edge cases
2. **Use `useTheme()` hook** in components - provides clean, reactive API
3. **Don't manually toggle classes** - defeats the purpose of centralized management
4. **Listen for changes** with `onThemeChange()` - for cross-tab sync
5. **Test theme persistence** - refresh page after changing theme
## Future Enhancements
Possible improvements:
- [ ] Add theme transition animations
- [ ] Support custom theme colors
- [ ] Add theme preview before saving
- [ ] Theme auto-switch based on time of day
- [ ] Per-page theme settings
- [ ] Theme inheritance from workspace/team settings
## File Structure
```
web/
├── lib/
│ ├── theme.ts ← Core utilities
│ └── theme-utils.ts ← Helper functions
├── hooks/
│ └── useTheme.ts ← React hook
├── components/
│ └── ThemeScript.tsx ← Flash prevention
└── app/
└── layout.tsx ← Uses ThemeScript
```
## Key Files to Review
1. **Start here**: `web/lib/theme.ts` - Core implementation
2. **Then**: `web/hooks/useTheme.ts` - React integration
3. **Then**: `web/components/ThemeScript.tsx` - Flash prevention
4. **Reference**: `THEME_PERSISTENCE.md` - Full documentation

View File

@@ -1,131 +0,0 @@
# Theme Persistence Implementation
## Overview
Implemented persistent light/dark theme support using localStorage with fallback to system preferences. The theme preference is now:
1. **Persisted locally** - Theme preference saved to localStorage
2. **Synced to backend** - Theme synced with backend settings.json
3. **Flash-free** - Theme applied before React hydration to prevent flash
4. **System preference aware** - Falls back to system theme if not set
## Changes Made
### 1. New Files Created
#### `/web/lib/theme.ts`
Core theme utilities providing:
- `getStoredTheme()` - Get theme from localStorage
- `saveThemeToStorage()` - Save theme to localStorage
- `getSystemTheme()` - Detect system color scheme preference
- `applyThemeToDocument()` - Apply theme class to HTML element
- `initializeTheme()` - Initialize theme on startup (prioritizes localStorage → system → default)
- `setTheme()` - Set and persist theme (applies to DOM + localStorage)
#### `/web/components/ThemeScript.tsx`
Inline script that runs before React hydration to:
- Read localStorage theme preference
- Apply theme class to DOM immediately
- Prevent flash of wrong theme on page load
#### `/web/hooks/useTheme.ts`
Custom React hook for using theme anywhere in the app:
```typescript
const { theme, isDark, isLight, setTheme, isLoaded } = useTheme();
```
### 2. Modified Files
#### `/web/app/layout.tsx`
- Added `ThemeScript` component in `<head>` to initialize theme before hydration
- Prevents theme flash on page load
#### `/web/context/GlobalContext.tsx`
- Imported theme utilities
- Updated `refreshSettings()` to persist theme to localStorage when fetched from backend
- Updated `useEffect` to initialize theme immediately using `initializeTheme()`
- Falls back to localStorage if backend fetch fails
#### `/web/app/settings/page.tsx`
- Imported `setTheme` utility
- Updated `applyTheme()` to use `setTheme()` which persists to localStorage
- Updated `handleSave()` to sync theme immediately when settings are saved
- Theme changes now persist both locally and to backend
## How It Works
### On Page Load
1. **ThemeScript** (in head) runs immediately:
- Reads `deeptutor-theme` from localStorage
- Applies `dark` class to `<html>` if needed
- No flash because this runs before React
2. **GlobalProvider** (React):
- Calls `initializeTheme()` to get current theme
- Fetches theme from backend `/api/v1/settings`
- If backend differs, updates state and localStorage
### On Theme Change
1. User toggles theme in Settings page
2. `handleUIChange()` calls `applyTheme()`
3. `applyTheme()` calls `setTheme()` which:
- Applies theme class to DOM immediately
- Saves to localStorage
4. On save, theme is also synced to backend via `/api/v1/settings/ui`
### Priority Order
When determining theme, the app uses:
1. **localStorage** (`deeptutor-theme`) - User's last selection
2. **System preference** - `prefers-color-scheme: dark` media query
3. **Default** - Light mode
## Usage Examples
### In Components
```typescript
import { useTheme } from '@/hooks/useTheme';
function MyComponent() {
const { theme, isDark, setTheme } = useTheme();
return (
<button onClick={() => setTheme(isDark ? 'light' : 'dark')}>
Toggle Theme
</button>
);
}
```
### In Global Context
```typescript
import { setTheme } from '@/lib/theme';
// Apply theme immediately
setTheme('dark');
```
### Direct Theme Control
```typescript
import { setTheme, initializeTheme, getStoredTheme } from '@/lib/theme';
// Get stored preference
const theme = getStoredTheme(); // 'light' | 'dark' | null
// Initialize theme
const currentTheme = initializeTheme(); // 'light' | 'dark'
// Set and persist theme
setTheme('dark');
```
## Benefits
✅ **No Flash** - Theme applied before hydration
✅ **Persistent** - Saved to localStorage and backend
✅ **Responsive** - System preference detection
✅ **Resilient** - Falls back to localStorage if API fails
✅ **Accessible** - Uses standard `prefers-color-scheme` media query
✅ **Flexible** - Can be used anywhere in the app via hook or utilities
## Testing
1. **Verify no flash** - Open app and check theme loads immediately
2. **Toggle theme** - Change theme in settings and refresh page
3. **Offline mode** - Disconnect from backend, theme should persist
4. **System preference** - Change system theme, verify fallback works on first visit

View File

@@ -1,124 +0,0 @@
# Theme Persistence - Implementation Summary
## ✅ What Was Implemented
Your dark/light theme now **persists** properly using the best practices pattern:
```
User Changes Theme in Settings
↓
applyTheme() → setTheme()
↓
┌─────────────────────────────────────────┐
├─ Saves to localStorage │
├─ Applies to Document DOM immediately │
├─ Syncs to Backend on Save │
└─────────────────────────────────────────┘
↓
Page Refresh/Navigation
↓
ThemeScript (in <head>)
↓
Reads localStorage before React loads
↓
Theme applied instantly (no flash!)
```
## 📁 Files Created
| File | Purpose |
|------|---------|
| `web/lib/theme.ts` | Core theme utilities (get, save, apply, initialize) |
| `web/lib/theme-utils.ts` | Helper functions (toggle, setLight, setDark, etc.) |
| `web/hooks/useTheme.ts` | React hook for theme (`const { isDark, setTheme } = useTheme()`) |
| `web/components/ThemeScript.tsx` | Inline script to prevent theme flash on load |
| `THEME_PERSISTENCE.md` | Complete documentation |
## 🔧 Files Modified
| File | Changes |
|------|---------|
| `web/app/layout.tsx` | Added ThemeScript in `<head>` |
| `web/context/GlobalContext.tsx` | Initialize theme immediately + localStorage sync |
| `web/app/settings/page.tsx` | Use `setTheme()` for persistence |
## 🎯 How It Works
### 1. **Immediate Theme on Load** (No Flash ⚡)
- ThemeScript runs before React hydration
- Reads localStorage and applies theme instantly
- Results in zero flash, smooth experience
### 2. **Smart Theme Selection**
Priority order when theme is not explicitly set:
1. **localStorage** - User's previous selection
2. **System preference** - `prefers-color-scheme: dark`
3. **Default** - Light mode
### 3. **Backend Sync**
- Theme persisted to backend at `/api/v1/settings/ui`
- Allows syncing across devices
- Works offline with localStorage fallback
## 🚀 Usage
### In Any Component
```typescript
import { useTheme } from '@/hooks/useTheme';
export function MyComponent() {
const { isDark, theme, setTheme } = useTheme();
return (
<button onClick={() => setTheme(isDark ? 'light' : 'dark')}>
Toggle {isDark ? '☀️ Light' : '🌙 Dark'}
</button>
);
}
```
### Direct Utilities
```typescript
import { setTheme, toggleTheme, setDarkTheme } from '@/lib/theme';
// Set specific theme
setDarkTheme();
// Toggle between light/dark
const newTheme = toggleTheme(currentTheme);
```
### Watch Theme Changes
```typescript
import { onThemeChange } from '@/lib/theme-utils';
// Listen to theme changes across tabs
const unsubscribe = onThemeChange((theme) => {
console.log('Theme changed to:', theme);
});
// Clean up when done
unsubscribe();
```
## ✨ Key Features
✅ **No Flash** - Theme applied before React renders
✅ **Persistent** - Saved to localStorage + backend
✅ **Offline** - Works even when backend is unavailable
✅ **Smart** - Respects system color scheme preferences
✅ **Type-Safe** - Full TypeScript support
✅ **Accessible** - Uses standard web APIs
✅ **Performant** - Minimal re-renders
## 🧪 Test It
1. **Switch to dark mode** in settings and click save
2. **Refresh the page** - Theme should remain dark
3. **Close and reopen browser** - Theme persists
4. **Change system theme** - App respects on first visit
5. **Open in new tab** - Both tabs sync theme
---
**Everything is now working! Your theme preference will persist across page refreshes, browser sessions, and device sync.** 🎉