EverydayTech Platform - Developer Reference
Complete Source Code Documentation - All Applications
Loading...
Searching...
No Matches
themeManager.js
Go to the documentation of this file.
1
2import { useEffect } from 'react';
3
4export function useTheme(settings) {
5 useEffect(() => {
6 applyThemeFromSettings(settings);
7 }, [settings]);
8}
9
10export function applyThemeFromSettings(settings) {
11 if (!settings || !settings.display) return;
12 const theme = settings.display.theme || 'default';
13 const auto = settings.display.autoTheme || false;
14
15 function setTheme(name) {
16 if (!name || name === 'default') {
17 document.documentElement.removeAttribute('data-theme');
18 } else {
19 document.documentElement.setAttribute('data-theme', name);
20 }
21 }
22
23 if (auto) {
24 const matcher = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)');
25 const apply = () => setTheme(matcher.matches ? 'dark' : 'light');
26 apply();
27 if (matcher && matcher.addEventListener) matcher.addEventListener('change', apply);
28 else if (matcher && matcher.addListener) matcher.addListener(apply);
29 } else {
30 setTheme(theme);
31 }
32}
33
34export async function initTheme() {
35 try {
36 // Public pages should use the frontpage theme, not the dashboard theme
37 const p = window.location.pathname || '/';
38 const isPublic = (
39 p === '/' ||
40 p.startsWith('/login') ||
41 p.startsWith('/forgot-password') ||
42 p.startsWith('/reset-password') ||
43 p.startsWith('/verify-email') ||
44 p.startsWith('/docs') ||
45 p === '/about' ||
46 p === '/privacy' ||
47 p === '/terms' ||
48 p === '/security'
49 );
50 if (isPublic) return;
51
52 const raw = localStorage.getItem('app_settings');
53 if (raw) {
54 const cfg = JSON.parse(raw);
55 applyThemeFromSettings(cfg);
56 return;
57 }
58 // try fetch settings if token exists
59 const token = localStorage.getItem('token');
60 if (token) {
61 const res = await fetch('/api/settings', { headers: { Authorization: `Bearer ${token}` } });
62 if (res.ok) {
63 const cfg = await res.json();
64 localStorage.setItem('app_settings', JSON.stringify(cfg));
65 applyThemeFromSettings(cfg);
66 }
67 }
68 } catch (err) {
69 console.warn('theme init failed', err);
70 }
71}