Repository navigation
Expand file tree
/
Copy paththeme.js
More file actions
90 lines (78 loc) · 2.35 KB
/
Copy paththeme.js
File metadata and controls
90 lines (78 loc) · 2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
const STORAGE_KEY = 'marreq-theme';
const root = document.documentElement;
export function applyTheme(theme) {
if (theme === 'dark') {
root.setAttribute('data-theme', 'dark');
} else {
root.removeAttribute('data-theme');
}
}
export function getStoredTheme() {
try {
return localStorage.getItem(STORAGE_KEY);
} catch (error) {
return null;
}
}
export function setStoredTheme(theme) {
try {
localStorage.setItem(STORAGE_KEY, theme);
} catch (error) {
/* ignore quota/permission errors */
}
}
export function resolvePreferredTheme() {
const stored = getStoredTheme();
if (stored === 'dark' || stored === 'light') {
return stored;
}
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
return 'dark';
}
return 'light';
}
export function updateToggleMeta(theme) {
const isDark = theme === 'dark';
const label = isDark ? 'Switch to light mode' : 'Switch to dark mode';
document.querySelectorAll('[data-theme-toggle]').forEach((toggle) => {
toggle.setAttribute('aria-pressed', String(isDark));
toggle.setAttribute('aria-label', label);
toggle.setAttribute('title', label);
});
}
export function initThemeControls() {
const startingTheme = root.getAttribute('data-theme') || resolvePreferredTheme();
applyTheme(startingTheme);
updateToggleMeta(startingTheme);
document.querySelectorAll('[data-theme-toggle]').forEach((toggle) => {
toggle.addEventListener('click', () => {
const current = root.getAttribute('data-theme') === 'dark' ? 'dark' : 'light';
const next = current === 'dark' ? 'light' : 'dark';
applyTheme(next);
setStoredTheme(next);
updateToggleMeta(next);
});
});
if (window.matchMedia) {
const query = window.matchMedia('(prefers-color-scheme: dark)');
const handler = (event) => {
if (getStoredTheme()) {
return;
}
const nextTheme = event.matches ? 'dark' : 'light';
applyTheme(nextTheme);
updateToggleMeta(nextTheme);
};
if (query.addEventListener) {
query.addEventListener('change', handler);
} else if (query.addListener) {
query.addListener(handler);
}
}
}
// Initialize theme controls when DOM is ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initThemeControls);
} else {
initThemeControls();
}