configStore.tsx 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import moment from 'moment-timezone';
  2. import Reflux from 'reflux';
  3. import {Config} from 'app/types';
  4. type ConfigStoreInterface = {
  5. get<K extends keyof Config>(key: K): Config[K];
  6. set<K extends keyof Config>(key: K, value: Config[K]): void;
  7. getConfig(): Config;
  8. updateTheme(theme: 'light' | 'dark'): void;
  9. loadInitialData(config: Config): void;
  10. };
  11. type Internals = {
  12. config: Config;
  13. };
  14. const storeConfig: Reflux.StoreDefinition & Internals & ConfigStoreInterface = {
  15. // When the app is booted we will _immediately_ hydrate the config store,
  16. // effecively ensureing this is not empty.
  17. config: {} as Config,
  18. init(): void {
  19. this.config = {} as Config;
  20. },
  21. get(key) {
  22. return this.config[key];
  23. },
  24. set(key, value) {
  25. this.config = {
  26. ...this.config,
  27. [key]: value,
  28. };
  29. this.trigger({[key]: value});
  30. },
  31. /**
  32. * This is only called by media query listener so that we can control
  33. * the auto switching of color schemes without affecting manual toggle
  34. */
  35. updateTheme(theme) {
  36. if (this.config.user?.options.theme !== 'system') {
  37. return;
  38. }
  39. this.set('theme', theme);
  40. },
  41. getConfig() {
  42. return this.config;
  43. },
  44. loadInitialData(config): void {
  45. const shouldUseDarkMode = config.user?.options.theme === 'dark';
  46. this.config = {
  47. ...config,
  48. features: new Set(config.features || []),
  49. theme: shouldUseDarkMode ? 'dark' : 'light',
  50. };
  51. // TODO(dcramer): abstract this out of ConfigStore
  52. if (config.user) {
  53. config.user.permissions = new Set(config.user.permissions);
  54. moment.tz.setDefault(config.user.options.timezone);
  55. }
  56. this.trigger(config);
  57. },
  58. };
  59. const ConfigStore = Reflux.createStore(storeConfig) as Reflux.Store &
  60. ConfigStoreInterface;
  61. export default ConfigStore;