feat: 深色模式基础设施 (system theme + 跟随系统)
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* 系统深色模式监听 — 提供初始值与变更回调
|
||||
* 旧设备 wx.onThemeChange 失败时退化为只读一次
|
||||
*/
|
||||
|
||||
const STORAGE_KEY = 'dark_mode_pref'
|
||||
|
||||
function _readSystemTheme() {
|
||||
try {
|
||||
const info = wx.getSystemInfoSync()
|
||||
return info.theme === 'dark' ? true : false
|
||||
} catch (e) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function getInitialDarkMode() {
|
||||
const pref = wx.getStorageSync(STORAGE_KEY) || 'system'
|
||||
if (pref === 'system') return _readSystemTheme()
|
||||
return pref === 'dark'
|
||||
}
|
||||
|
||||
function getPref() {
|
||||
return wx.getStorageSync(STORAGE_KEY) || 'system'
|
||||
}
|
||||
|
||||
function setPref(value) {
|
||||
if (!['system', 'light', 'dark'].includes(value)) return
|
||||
wx.setStorageSync(STORAGE_KEY, value)
|
||||
}
|
||||
|
||||
function watchDarkMode(onChange) {
|
||||
if (typeof wx.onThemeChange !== 'function') return
|
||||
try {
|
||||
wx.onThemeChange(({ theme }) => {
|
||||
const pref = getPref()
|
||||
if (pref === 'system') onChange(theme === 'dark')
|
||||
})
|
||||
} catch (e) {
|
||||
// 旧设备不支持,忽略
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
getInitialDarkMode,
|
||||
getPref,
|
||||
setPref,
|
||||
watchDarkMode
|
||||
}
|
||||
Reference in New Issue
Block a user