preferences.ts 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. import type { DeepPartial } from '@vben-core/typings';
  2. import type { InitialOptions, Preferences } from './types';
  3. import { markRaw, reactive, readonly, watch } from 'vue';
  4. import { isMacOs, merge, StorageManager } from '@vben-core/shared';
  5. import {
  6. breakpointsTailwind,
  7. useBreakpoints,
  8. useDebounceFn,
  9. } from '@vueuse/core';
  10. import { defaultPreferences } from './config';
  11. import { updateCSSVariables } from './update-css-variables';
  12. const STORAGE_KEY = 'preferences';
  13. const STORAGE_KEY_LOCALE = `${STORAGE_KEY}-locale`;
  14. const STORAGE_KEY_THEME = `${STORAGE_KEY}-theme`;
  15. class PreferenceManager {
  16. private cache: null | StorageManager = null;
  17. // private flattenedState: Flatten<Preferences>;
  18. private initialPreferences: Preferences = defaultPreferences;
  19. private isInitialized: boolean = false;
  20. private savePreferences: (preference: Preferences) => void;
  21. private state: Preferences = reactive<Preferences>({
  22. ...this.loadPreferences(),
  23. });
  24. constructor() {
  25. this.cache = new StorageManager();
  26. // 避免频繁的操作缓存
  27. this.savePreferences = useDebounceFn(
  28. (preference: Preferences) => this._savePreferences(preference),
  29. 150,
  30. );
  31. }
  32. /**
  33. * 保存偏好设置
  34. * @param {Preferences} preference - 需要保存的偏好设置
  35. */
  36. private _savePreferences(preference: Preferences) {
  37. this.cache?.setItem(STORAGE_KEY, preference);
  38. this.cache?.setItem(STORAGE_KEY_LOCALE, preference.app.locale);
  39. this.cache?.setItem(STORAGE_KEY_THEME, preference.theme.mode);
  40. }
  41. /**
  42. * 处理更新的键值
  43. * 根据更新的键值执行相应的操作。
  44. * @param {DeepPartial<Preferences>} updates - 部分更新的偏好设置
  45. */
  46. private handleUpdates(updates: DeepPartial<Preferences>) {
  47. const themeUpdates = updates.theme || {};
  48. const appUpdates = updates.app || {};
  49. if (themeUpdates && Object.keys(themeUpdates).length > 0) {
  50. updateCSSVariables(this.state);
  51. }
  52. if (
  53. Reflect.has(appUpdates, 'colorGrayMode') ||
  54. Reflect.has(appUpdates, 'colorWeakMode')
  55. ) {
  56. this.updateColorMode(this.state);
  57. }
  58. }
  59. private initPlatform() {
  60. const dom = document.documentElement;
  61. dom.dataset.platform = isMacOs() ? 'macOs' : 'window';
  62. }
  63. /**
  64. * 从缓存中加载偏好设置。如果缓存中没有找到对应的偏好设置,则返回默认偏好设置。
  65. */
  66. private loadCachedPreferences() {
  67. return this.cache?.getItem<Preferences>(STORAGE_KEY);
  68. }
  69. /**
  70. * 加载偏好设置
  71. * @returns {Preferences} 加载的偏好设置
  72. */
  73. private loadPreferences(): Preferences {
  74. return this.loadCachedPreferences() || { ...defaultPreferences };
  75. }
  76. /**
  77. * 监听状态和系统偏好设置的变化。
  78. */
  79. private setupWatcher() {
  80. if (this.isInitialized) {
  81. return;
  82. }
  83. // 监听断点,判断是否移动端
  84. const breakpoints = useBreakpoints(breakpointsTailwind);
  85. const isMobile = breakpoints.smaller('md');
  86. watch(
  87. () => isMobile.value,
  88. (val) => {
  89. this.updatePreferences({
  90. app: { isMobile: val },
  91. });
  92. },
  93. { immediate: true },
  94. );
  95. // 监听系统主题偏好设置变化
  96. window
  97. .matchMedia('(prefers-color-scheme: dark)')
  98. .addEventListener('change', ({ matches: isDark }) => {
  99. this.updatePreferences({
  100. theme: { mode: isDark ? 'dark' : 'light' },
  101. });
  102. // updateCSSVariables(this.state);
  103. });
  104. }
  105. /**
  106. * 更新页面颜色模式(灰色、色弱)
  107. * @param preference
  108. */
  109. private updateColorMode(preference: Preferences) {
  110. if (preference.app) {
  111. const { colorGrayMode, colorWeakMode } = preference.app;
  112. const dom = document.documentElement;
  113. const COLOR_WEAK = 'invert-mode';
  114. const COLOR_GRAY = 'grayscale-mode';
  115. colorWeakMode
  116. ? dom.classList.add(COLOR_WEAK)
  117. : dom.classList.remove(COLOR_WEAK);
  118. colorGrayMode
  119. ? dom.classList.add(COLOR_GRAY)
  120. : dom.classList.remove(COLOR_GRAY);
  121. }
  122. }
  123. clearCache() {
  124. [STORAGE_KEY, STORAGE_KEY_LOCALE, STORAGE_KEY_THEME].forEach((key) => {
  125. this.cache?.removeItem(key);
  126. });
  127. }
  128. public getInitialPreferences() {
  129. return this.initialPreferences;
  130. }
  131. public getPreferences() {
  132. return readonly(this.state);
  133. }
  134. /**
  135. * 覆盖偏好设置
  136. * overrides 要覆盖的偏好设置
  137. * namespace 命名空间
  138. */
  139. public async initPreferences({ namespace, overrides }: InitialOptions) {
  140. // 是否初始化过
  141. if (this.isInitialized) {
  142. return;
  143. }
  144. // 初始化存储管理器
  145. this.cache = new StorageManager({ prefix: namespace });
  146. // 合并初始偏好设置
  147. this.initialPreferences = merge({}, overrides, defaultPreferences);
  148. // 加载并合并当前存储的偏好设置
  149. const mergedPreference = merge(
  150. {},
  151. overrides,
  152. this.loadCachedPreferences() || defaultPreferences,
  153. );
  154. // 更新偏好设置
  155. this.updatePreferences(mergedPreference);
  156. this.setupWatcher();
  157. this.initPlatform();
  158. // 标记为已初始化
  159. this.isInitialized = true;
  160. }
  161. /**
  162. * 重置偏好设置
  163. * 偏好设置将被重置为初始值,并从 localStorage 中移除。
  164. *
  165. * @example
  166. * 假设 initialPreferences 为 { theme: 'light', language: 'en' }
  167. * 当前 state 为 { theme: 'dark', language: 'fr' }
  168. * this.resetPreferences();
  169. * 调用后,state 将被重置为 { theme: 'light', language: 'en' }
  170. * 并且 localStorage 中的对应项将被移除
  171. */
  172. resetPreferences() {
  173. // 将状态重置为初始偏好设置
  174. Object.assign(this.state, this.initialPreferences);
  175. // 保存重置后的偏好设置
  176. this.savePreferences(this.state);
  177. // 从存储中移除偏好设置项
  178. [STORAGE_KEY, STORAGE_KEY_THEME, STORAGE_KEY_LOCALE].forEach((key) => {
  179. this.cache?.removeItem(key);
  180. });
  181. this.updatePreferences(this.state);
  182. }
  183. /**
  184. * 更新偏好设置
  185. * @param updates - 要更新的偏好设置
  186. */
  187. public updatePreferences(updates: DeepPartial<Preferences>) {
  188. const mergedState = merge({}, updates, markRaw(this.state));
  189. Object.assign(this.state, mergedState);
  190. // 根据更新的键值执行相应的操作
  191. this.handleUpdates(updates);
  192. this.savePreferences(this.state);
  193. }
  194. }
  195. const preferencesManager = new PreferenceManager();
  196. export { PreferenceManager, preferencesManager };