theme.js (1.5 KB)


 1 // Theme: theme selection, cycling, and persistence
 2 
 3 function cycleTheme() {
 4 	state.currentThemeIndex = (state.currentThemeIndex + 1) % state.themes.length;
 5 	var newTheme = state.themes[state.currentThemeIndex];
 6 	setTheme(newTheme);
 7 	saveThemeToLocalStorage(newTheme);
 8 }
 9 
10 function saveThemeToLocalStorage(theme) {
11 	localStorage.setItem('currentTheme', theme);
12 }
13 
14 function updateFavicon() {
15 	var iconEmoji = getComputedStyle(document.documentElement).getPropertyValue('--icon').trim().replace(/'/g, '');
16 	var faviconLink = document.querySelector('link[rel="icon"]');
17 	if (faviconLink && iconEmoji) {
18 		faviconLink.href = `data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>${iconEmoji}</text></svg>`;
19 	}
20 }
21 
22 function setTheme(theme) {
23 	document.documentElement.setAttribute('data-theme', theme);
24 	var backgroundColor = getComputedStyle(document.documentElement).getPropertyValue('--background').trim();
25 	document.getElementById('themeColor').setAttribute('content', backgroundColor);
26 	updateFavicon();
27 }
28 
29 function setInitialTheme() {
30 	var savedTheme = localStorage.getItem('currentTheme');
31 	var defaultTheme = document.documentElement.getAttribute('data-theme');
32 
33 	if (savedTheme && state.themes.includes(savedTheme)) {
34 		state.currentThemeIndex = state.themes.indexOf(savedTheme);
35 	} else if (state.themes.includes(defaultTheme)) {
36 		state.currentThemeIndex = state.themes.indexOf(defaultTheme);
37 	} else {
38 		state.currentThemeIndex = 0;
39 	}
40 
41 	setTheme(state.themes[state.currentThemeIndex]);
42 }