preferences.ts 6.4 KB

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