-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathshared.js
More file actions
61 lines (55 loc) · 2.66 KB
/
Copy pathshared.js
File metadata and controls
61 lines (55 loc) · 2.66 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
// Theme + locale toggle, persisted in localStorage.
(function () {
const root = document.documentElement;
// ----- theme -----
const savedTheme = localStorage.getItem("kb.theme");
const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
const initialTheme = savedTheme || (prefersDark ? "dark" : "light");
root.setAttribute("data-theme", initialTheme);
// Keep the mobile browser address bar in sync with the theme.
function applyThemeColor(theme) {
let m = document.querySelector('meta[name="theme-color"]');
if (!m) { m = document.createElement("meta"); m.setAttribute("name", "theme-color"); document.head.appendChild(m); }
m.setAttribute("content", theme === "dark" ? "#080809" : "#ffffff");
}
applyThemeColor(initialTheme);
// ----- locale -----
const savedLocale = localStorage.getItem("kb.locale");
const browserLocale = (navigator.language || "fr").toLowerCase().startsWith("en") ? "en" : "fr";
const initialLocale = savedLocale || browserLocale;
root.setAttribute("data-locale", initialLocale);
document.documentElement.lang = initialLocale;
function reflectButtons() {
document.querySelectorAll("[data-action='toggle-theme']").forEach((b) => {
const t = root.getAttribute("data-theme");
b.setAttribute("aria-label", t === "dark" ? "Passer en mode clair" : "Passer en mode sombre");
b.querySelector("[data-icon='sun']")?.toggleAttribute("hidden", t !== "dark");
b.querySelector("[data-icon='moon']")?.toggleAttribute("hidden", t === "dark");
});
document.querySelectorAll("[data-action='toggle-locale']").forEach((b) => {
const l = root.getAttribute("data-locale");
b.textContent = l === "fr" ? "EN" : "FR";
b.setAttribute("aria-label", l === "fr" ? "Switch to English" : "Passer en français");
});
}
document.addEventListener("click", (e) => {
const themeBtn = e.target.closest("[data-action='toggle-theme']");
const localeBtn = e.target.closest("[data-action='toggle-locale']");
if (themeBtn) {
const next = root.getAttribute("data-theme") === "dark" ? "light" : "dark";
root.setAttribute("data-theme", next);
localStorage.setItem("kb.theme", next);
applyThemeColor(next);
reflectButtons();
}
if (localeBtn) {
const next = root.getAttribute("data-locale") === "fr" ? "en" : "fr";
root.setAttribute("data-locale", next);
document.documentElement.lang = next;
localStorage.setItem("kb.locale", next);
reflectButtons();
document.dispatchEvent(new CustomEvent("kb:locale-change", { detail: { locale: next } }));
}
});
document.addEventListener("DOMContentLoaded", reflectButtons);
})();