| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- import { defineStore } from 'pinia'
- import { ref, watch } from 'vue'
- export const useThemeStore = defineStore('theme', () => {
- // State
- const theme = ref('dark') // 'dark' | 'light'
- // Load persisted theme on init
- function init() {
- try {
- const saved = uni.getStorageSync('theme')
- if (saved === 'light' || saved === 'dark') {
- theme.value = saved
- } else {
- // Follow system preference if available
- try {
- const sysInfo = uni.getSystemInfoSync()
- if (sysInfo.theme && sysInfo.theme === 'light') {
- theme.value = 'light'
- }
- } catch (e) {
- // Default to dark (brand identity)
- }
- }
- } catch (e) {
- theme.value = 'dark'
- }
- applyTheme(theme.value)
- }
- // Toggle theme
- function toggle() {
- theme.value = theme.value === 'dark' ? 'light' : 'dark'
- applyTheme(theme.value)
- persistTheme(theme.value)
- }
- // Set specific theme
- function setTheme(t) {
- if (t !== 'dark' && t !== 'light') return
- theme.value = t
- applyTheme(t)
- persistTheme(t)
- }
- // Apply to DOM
- function applyTheme(t) {
- // Update page data-theme (CSS fallback)
- try {
- const pages = getCurrentPages()
- const curPage = pages[pages.length - 1]
- if (curPage && curPage.$page && curPage.$page.$el) {
- curPage.$page.$el.setAttribute('data-theme', t)
- }
- } catch (e) {
- // Silent fallback
- }
- // Update the native bottom tab bar (outside Vue component tree)
- try {
- uni.setTabBarStyle({
- color: t === 'light' ? '#4A5568' : '#A0AEC0',
- selectedColor: '#C9A84C',
- backgroundColor: t === 'light' ? '#FFFFFF' : '#1E3A5F',
- borderStyle: t === 'light' ? 'black' : 'white',
- })
- } catch (e) {
- // Tab bar not configured — skip
- }
- }
- // Persist to storage
- function persistTheme(t) {
- try {
- uni.setStorageSync('theme', t)
- } catch (e) {
- // Silent
- }
- }
- // Listen for system theme changes
- function watchSystemTheme() {
- try {
- uni.onThemeChange((res) => {
- // Optional: auto-follow system
- // theme.value = res.theme
- // applyTheme(res.theme)
- })
- } catch (e) {
- // onThemeChange not supported on this platform
- }
- }
- return {
- theme,
- init,
- toggle,
- setTheme,
- watchSystemTheme
- }
- })
|