Repository navigation
Expand file tree
/
Copy paththeme.ts
More file actions
67 lines (57 loc) · 1.85 KB
/
Copy paththeme.ts
File metadata and controls
67 lines (57 loc) · 1.85 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
export type Theme = "dark" | "light";
const THEME_COLORS: Record<Theme, string> = {
dark: "#080a0d",
light: "#f4f7f5",
};
export function initializeThemeToggle(): void {
const toggle =
document.querySelector<HTMLButtonElement>(".nav__theme-toggle");
const themeColor = document.querySelector<HTMLMetaElement>("#theme-color");
if (!toggle) return;
applyTheme(toggle, themeColor, getCurrentTheme());
toggle.addEventListener("click", () => {
const theme = getCurrentTheme() === "dark" ? "light" : "dark";
document.documentElement.dataset.theme = theme;
saveTheme(theme);
applyTheme(toggle, themeColor, theme);
});
}
export function updateProjectImages(theme: Theme): void {
const images = document.querySelectorAll<HTMLImageElement>(
"[data-dark-src][data-light-src]",
);
images.forEach((image) => {
const source =
theme === "light" ? image.dataset.lightSrc : image.dataset.darkSrc;
if (source && image.getAttribute("src") !== source) image.src = source;
});
}
function applyTheme(
toggle: HTMLButtonElement,
themeColor: HTMLMetaElement | null,
theme: Theme,
): void {
updateThemeControls(toggle, themeColor, theme);
updateProjectImages(theme);
}
function getCurrentTheme(): Theme {
return document.documentElement.dataset.theme === "light" ? "light" : "dark";
}
function saveTheme(theme: Theme): void {
try {
localStorage.setItem("theme", theme);
} catch {
// The selected theme still applies when storage is unavailable.
}
}
function updateThemeControls(
toggle: HTMLButtonElement,
themeColor: HTMLMetaElement | null,
theme: Theme,
): void {
const nextTheme = theme === "dark" ? "light" : "dark";
const label = `Switch to ${nextTheme} theme`;
toggle.setAttribute("aria-label", label);
toggle.setAttribute("title", label);
themeColor?.setAttribute("content", THEME_COLORS[theme]);
}