| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- 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) {
- 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
- }
- }
- // 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
- }
- })
|