-
Notifications
You must be signed in to change notification settings - Fork 0
/
dark-theme.ts
43 lines (40 loc) · 1.63 KB
/
dark-theme.ts
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
const getStoredTheme = () => localStorage.getItem("theme");
const setStoredTheme = (theme: string) => localStorage.setItem("theme", theme);
const getPreferredTheme = () =>
getStoredTheme() || (window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light");
const setTheme = (theme: string) =>
document.documentElement.setAttribute(
"data-bs-theme",
theme === "auto" && window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : theme,
);
setTheme(getPreferredTheme());
function showActiveTheme(theme: string, focus = false) {
const themeSwitcher: HTMLElement = document.querySelector(".dark-theme-toggle")!;
const btnToActive: HTMLElement = document.querySelector(`[data-bs-theme-value="${theme}"]`)!;
document.querySelectorAll("[data-bs-theme-value]").forEach((element) => {
element.classList.remove("active");
element.setAttribute("aria-pressed", "false");
});
btnToActive.classList.add("active");
btnToActive.setAttribute("aria-pressed", "true");
const ariaLabel = (themeSwitcher.textContent || "").trim();
themeSwitcher.setAttribute("aria-label", `${ariaLabel} (${btnToActive.dataset.bsThemeValue})`);
if (focus) themeSwitcher.focus();
}
document.addEventListener(
"DOMContentLoaded",
function () {
showActiveTheme(getPreferredTheme());
document.querySelectorAll("[data-bs-theme-value]").forEach((toggle) => {
toggle.addEventListener("click", () => {
const theme = toggle.getAttribute("data-bs-theme-value");
if (theme) {
setStoredTheme(theme);
setTheme(theme);
showActiveTheme(theme, true);
}
});
});
},
false,
);