From e2186b2502fee2b92fe8f9579a5027479a5abd1f Mon Sep 17 00:00:00 2001 From: cnliucheng Date: Thu, 4 Jun 2026 16:43:32 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20theme=20persistence=20=E2=80=94=20error?= =?UTF-8?q?=20handling,=20backup,=20stale=20highlight?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bug 1 (critical): setTheme lacked try/catch around wx.setStorageSync. If storage write throws (full / permission), the theme silently fails to persist but UI has already changed → on next cold start getCurrentTheme falls back to orange. → Wrap in try/catch; still apply UI change even if storage fails (better to see the right color now than revert immediately). Bug 2 (display): settings onShow called applyThemeToPage (updates 'theme' object) but never refreshed 'currentThemeId'. After tab switching, the radio highlight showed the wrong theme. → Add setData({ currentThemeId }) in onShow. Redundancy: theme now also saved as themeId in user_settings. getCurrentTheme falls back to user_settings.themeId if app_theme key is unexpectedly missing, providing a recovery path. --- pages/settings/settings.js | 2 ++ utils/theme.js | 23 ++++++++++++++++++++--- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/pages/settings/settings.js b/pages/settings/settings.js index 6590502..c839580 100644 --- a/pages/settings/settings.js +++ b/pages/settings/settings.js @@ -39,6 +39,8 @@ Page({ if (tb) tb.setData({ selected: 2 }) } catch (e) {} themeMod.applyThemeToPage(this) + // sync highlighted theme in case it was changed elsewhere + this.setData({ currentThemeId: themeMod.getCurrentTheme().id }) }, onSelectTheme(e) { diff --git a/utils/theme.js b/utils/theme.js index 84d8a2a..0b2015a 100644 --- a/utils/theme.js +++ b/utils/theme.js @@ -50,8 +50,15 @@ let _navColorTimer = null const getThemeById = (id) => THEMES.find(t => t.id === id) || THEMES[0] const getCurrentTheme = () => { - const id = wx.getStorageSync(THEME_KEY) || DEFAULT_THEME_ID - return getThemeById(id) + let id = wx.getStorageSync(THEME_KEY) + if (!id) { + // fallback: try recovering from user_settings backup + try { + const s = wx.getStorageSync('user_settings') + if (s && s.themeId) id = s.themeId + } catch (e) {} + } + return getThemeById(id || DEFAULT_THEME_ID) } const _setNavBarColor = (primary) => { @@ -69,7 +76,17 @@ const _setNavBarColor = (primary) => { } const setTheme = (id) => { - wx.setStorageSync(THEME_KEY, id) + try { + wx.setStorageSync(THEME_KEY, id) + // redundant backup in user_settings + try { + const s = wx.getStorageSync('user_settings') || {} + s.themeId = id + wx.setStorageSync('user_settings', s) + } catch (e) {} + } catch (e) { + console.error('Failed to save theme:', e) + } const theme = getThemeById(id) _setNavBarColor(theme.primary) const app = getApp()