Skip to content

Commit

Permalink
pref: 优化主题切换按钮逻辑
Browse files Browse the repository at this point in the history
  • Loading branch information
HowieHz committed Jan 3, 2025
1 parent 67cc911 commit c849389
Showing 1 changed file with 27 additions and 15 deletions.
42 changes: 27 additions & 15 deletions templates/fragments/layout.html
Original file line number Diff line number Diff line change
Expand Up @@ -173,19 +173,31 @@
</script>

<script th:if="${theme.config?.styles?.is_dark_mode_switch_show}">
const THEME_DARK = "dark";
const THEME_LIGHT = "light";
const THEME_AUTO = "auto";
const themeColorSchemeMap = {
auto: "auto",
dark: "dark",
light: "light",
"dark-blue": "dark",
"light-blue": "light",
gray: "light",
};

function updateThemeIcon(theme) {
const themeIcon = document.getElementById("theme-toggle-button-icon");
if (theme === "light") {
if (theme === THEME_LIGHT) {
themeIcon.setAttribute("data-icon", "ph:sun-bold");
} else if (theme === "dark") {
} else if (theme === THEME_DARK) {
themeIcon.setAttribute("data-icon", "ph:moon-bold");
} else {
themeIcon.setAttribute("data-icon", "ph:circle-bold");
}
}

function updateTagAttribute(theme) {
document.documentElement.setAttribute("data-color-scheme", theme);
document.documentElement.setAttribute("data-color-scheme", themeColorSchemeMap[theme]);
document.documentElement.setAttribute("theme", theme);
}

Expand All @@ -196,7 +208,7 @@

function applyTheme(theme) {
if (typeof Storage !== "undefined") {
localStorage.setItem("pref-theme", theme);
localStorage.setItem("pref-theme", themeColorSchemeMap[theme]);
} else {
console.log("Sorry, your browser does not support web storage...");
}
Expand All @@ -217,27 +229,27 @@
(function () {
switch (getPreferredTheme()) {
case "dark":
updateTagAttribute("dark");
updateTagAttribute(THEME_DARK);
break;
case "light":
updateTagAttribute("light");
updateTagAttribute(THEME_LIGHT);
break;
case "auto":
updateTagAttribute("auto");
updateTagAttribute(THEME_AUTO);
break;
}
})();

document.addEventListener("DOMContentLoaded", function () {
switch (getPreferredTheme()) {
case "dark":
updateThemeIcon("dark");
updateThemeIcon(THEME_DARK);
break;
case "light":
updateThemeIcon("light");
updateThemeIcon(THEME_LIGHT);
break;
case "auto":
updateThemeIcon("auto");
updateThemeIcon(THEME_AUTO);
break;
}
});
Expand All @@ -247,12 +259,12 @@
const currentTheme = document.documentElement.attributes["theme"].value;
let newTheme;
// light -> dark -> auto -> light
if (currentTheme === "light") {
newTheme = "dark";
} else if (currentTheme === "dark") {
newTheme = "auto";
if (currentTheme === THEME_LIGHT) {
newTheme = THEME_DARK;
} else if (currentTheme === THEME_DARK) {
newTheme = THEME_AUTO;
} else {
newTheme = "light";
newTheme = THEME_LIGHT;
}
applyTheme(newTheme);
}
Expand Down

0 comments on commit c849389

Please sign in to comment.