portal_publico/static/js/theme.js

78 lines
2.4 KiB
JavaScript

const PID_THEME_KEY = "pid_theme";
const PID_COLOR_THEME_KEY = "pid_color_theme";
const PID_COLOR_THEMES = [
{ key: "roxo", label: "Roxo", swatch: "#7c4dff" },
{ key: "azul", label: "Azul", swatch: "#3b82f6" },
{ key: "verde", label: "Verde", swatch: "#22c55e" },
{ key: "ambar", label: "Âmbar", swatch: "#f59e0b" },
{ key: "rosa", label: "Rosa", swatch: "#ec4899" },
{ key: "vermelho", label: "Vermelho", swatch: "#ef4444" },
];
// localStorage pode estar bloqueado (janela privada, política do navegador) e
// aí lança: o tema vira só da sessão atual, mas o menu da conta continua funcionando.
function pidLerPreferencia(chave) {
try {
return localStorage.getItem(chave);
} catch (e) {
return null;
}
}
function pidGravarPreferencia(chave, valor) {
try {
localStorage.setItem(chave, valor);
} catch (e) {
// sem armazenamento: a escolha vale só até recarregar a página
}
}
(function applyStoredTheme() {
const stored = pidLerPreferencia(PID_THEME_KEY);
if (stored) {
document.documentElement.setAttribute("data-theme", stored);
}
})();
(function applyStoredColorTheme() {
const stored = pidLerPreferencia(PID_COLOR_THEME_KEY);
if (stored) {
document.documentElement.setAttribute("data-color-theme", stored);
}
})();
function pidToggleTheme() {
const current = document.documentElement.getAttribute("data-theme") || "dark";
const next = current === "dark" ? "light" : "dark";
document.documentElement.setAttribute("data-theme", next);
pidGravarPreferencia(PID_THEME_KEY, next);
document.dispatchEvent(new CustomEvent("pid:theme-changed", { detail: { theme: next } }));
}
function pidGetColorTheme() {
return document.documentElement.getAttribute("data-color-theme") || "roxo";
}
function pidSetColorTheme(themeKey) {
document.documentElement.setAttribute("data-color-theme", themeKey);
pidGravarPreferencia(PID_COLOR_THEME_KEY, themeKey);
}
document.addEventListener("DOMContentLoaded", () => {
const btn = document.getElementById("theme-toggle");
if (!btn) return;
const syncIcon = () => {
const theme = document.documentElement.getAttribute("data-theme") || "dark";
btn.setAttribute("aria-pressed", theme === "light");
btn.setAttribute("aria-label", theme === "dark" ? "Ativar modo claro" : "Ativar modo escuro");
};
syncIcon();
btn.addEventListener("click", () => {
pidToggleTheme();
syncIcon();
});
});