From 8d1e04090cfc99bfa7c0958e71e73ecfd597558f Mon Sep 17 00:00:00 2001 From: lifeadventurer Date: Fri, 1 Nov 2024 23:35:40 +0800 Subject: [PATCH] Feat(theme): Save selected theme to localStorage for persistence --- fortune_generator/js/theme.js | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/fortune_generator/js/theme.js b/fortune_generator/js/theme.js index f29a419..74d3a10 100644 --- a/fortune_generator/js/theme.js +++ b/fortune_generator/js/theme.js @@ -2,6 +2,9 @@ document.addEventListener("DOMContentLoaded", () => { const themeListContainer = document.querySelector("#themeList"); const root = document.documentElement; + // Apply the saved theme if it exists + applySavedTheme(); + async function fetchThemes() { try { const response = await fetch("./json/themes.json"); @@ -49,7 +52,10 @@ document.addEventListener("DOMContentLoaded", () => { themeItem.appendChild(colorPreivewContainer); // Apply theme on click - themeItem.addEventListener("click", () => applyTheme(theme.properties)); + themeItem.addEventListener("click", () => { + applyTheme(theme.properties); + saveThemeToLocalStorage(theme.name); + }); themeListContainer.appendChild(themeItem); }); @@ -62,5 +68,24 @@ document.addEventListener("DOMContentLoaded", () => { }); } + function saveThemeToLocalStorage(themeName) { + localStorage.setItem("selectedTheme", themeName); + } + + function applySavedTheme() { + const savedThemeName = localStorage.getItem("selectedTheme"); + if (savedThemeName) { + fetch("./json/themes.json") + .then((response) => response.json()) + .then((themes) => { + const theme = themes.themes.find((t) => t.name === savedThemeName); + if (theme) { + applyTheme(theme.properties); + } + }) + .catch((error) => console.error("Error fetching themes:", error)); + } + } + fetchThemes(); });