Files
anidev-design-system/components/theme-control.js
T

31 lines
1.5 KiB
JavaScript

import { iconSvg } from "../icons/icons.js";
export function themeControlMarkup({ theme = "light", t = (ru) => ru } = {}) {
return `<div class="account-theme-row"><span>${t("Тема", "Theme")}</span><div class="account-theme-options" role="group" aria-label="${t("Цветовая тема", "Color theme")}">${["light", "dark"].map((mode) => `<button type="button" data-account-theme="${mode}" aria-pressed="${mode === theme}" aria-label="${mode === "light" ? t("Светлая тема", "Light theme") : t("Тёмная тема", "Dark theme")}" title="${mode === "light" ? t("Светлая тема", "Light theme") : t("Тёмная тема", "Dark theme")}">${iconSvg(mode === "light" ? "sun" : "moon", { size: 16 })}</button>`).join("")}</div></div>`;
}
export function mountThemeControl(root, { theme = "light", onChange } = {}) {
const abort = new AbortController();
function update(mode) {
root
.querySelectorAll("[data-account-theme]")
.forEach((button) =>
button.setAttribute(
"aria-pressed",
String(button.dataset.accountTheme === mode),
),
);
}
root.addEventListener(
"click",
(event) => {
const button = event.target.closest("[data-account-theme]");
if (!button) return;
event.stopPropagation();
update(button.dataset.accountTheme);
onChange?.(button.dataset.accountTheme);
},
{ signal: abort.signal },
);
update(theme);
return { update, dispose: () => abort.abort() };
}