theme.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import { defineStore } from 'pinia'
  2. import { ref, watch } from 'vue'
  3. export const useThemeStore = defineStore('theme', () => {
  4. // State
  5. const theme = ref('dark') // 'dark' | 'light'
  6. // Load persisted theme on init
  7. function init() {
  8. try {
  9. const saved = uni.getStorageSync('theme')
  10. if (saved === 'light' || saved === 'dark') {
  11. theme.value = saved
  12. } else {
  13. // Follow system preference if available
  14. try {
  15. const sysInfo = uni.getSystemInfoSync()
  16. if (sysInfo.theme && sysInfo.theme === 'light') {
  17. theme.value = 'light'
  18. }
  19. } catch (e) {
  20. // Default to dark (brand identity)
  21. }
  22. }
  23. } catch (e) {
  24. theme.value = 'dark'
  25. }
  26. applyTheme(theme.value)
  27. }
  28. // Toggle theme
  29. function toggle() {
  30. theme.value = theme.value === 'dark' ? 'light' : 'dark'
  31. applyTheme(theme.value)
  32. persistTheme(theme.value)
  33. }
  34. // Set specific theme
  35. function setTheme(t) {
  36. if (t !== 'dark' && t !== 'light') return
  37. theme.value = t
  38. applyTheme(t)
  39. persistTheme(t)
  40. }
  41. // Apply to DOM
  42. function applyTheme(t) {
  43. try {
  44. const pages = getCurrentPages()
  45. const curPage = pages[pages.length - 1]
  46. if (curPage && curPage.$page && curPage.$page.$el) {
  47. curPage.$page.$el.setAttribute('data-theme', t)
  48. }
  49. } catch (e) {
  50. // Silent fallback
  51. }
  52. }
  53. // Persist to storage
  54. function persistTheme(t) {
  55. try {
  56. uni.setStorageSync('theme', t)
  57. } catch (e) {
  58. // Silent
  59. }
  60. }
  61. // Listen for system theme changes
  62. function watchSystemTheme() {
  63. try {
  64. uni.onThemeChange((res) => {
  65. // Optional: auto-follow system
  66. // theme.value = res.theme
  67. // applyTheme(res.theme)
  68. })
  69. } catch (e) {
  70. // onThemeChange not supported on this platform
  71. }
  72. }
  73. return {
  74. theme,
  75. init,
  76. toggle,
  77. setTheme,
  78. watchSystemTheme
  79. }
  80. })