localstate.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { Ref } from "@nuxtjs/composition-api"
  2. import { distinctUntilChanged, pluck } from "rxjs"
  3. import DispatchingStore, { defineDispatchers } from "./DispatchingStore"
  4. import { useStream } from "~/helpers/utils/composables"
  5. type LocalState = {
  6. REMEMBERED_TEAM_ID: string | undefined
  7. }
  8. const defaultLocalState: LocalState = {
  9. REMEMBERED_TEAM_ID: undefined,
  10. }
  11. const dispatchers = defineDispatchers({
  12. bulkApplyState(_currentState: LocalState, payload: Partial<LocalState>) {
  13. return payload
  14. },
  15. applyState<K extends keyof LocalState>(
  16. _currentState: LocalState,
  17. { key, value }: { key: K; value: LocalState[K] }
  18. ) {
  19. const result: Partial<LocalState> = {
  20. [key]: value,
  21. }
  22. return result
  23. },
  24. })
  25. export const localStateStore = new DispatchingStore(
  26. defaultLocalState,
  27. dispatchers
  28. )
  29. export const localState$ = localStateStore.subject$.asObservable()
  30. export function bulkApplyLocalState(obj: Partial<LocalState>) {
  31. localStateStore.dispatch({
  32. dispatcher: "bulkApplyState",
  33. payload: obj,
  34. })
  35. }
  36. export function applyLocalState<K extends keyof LocalState>(
  37. key: K,
  38. value: LocalState[K]
  39. ) {
  40. localStateStore.dispatch({
  41. dispatcher: "applyState",
  42. payload: { key, value },
  43. })
  44. }
  45. export function useLocalState<K extends keyof LocalState>(
  46. key: K
  47. ): Ref<LocalState[K]> {
  48. return useStream(
  49. localStateStore.subject$.pipe(pluck(key), distinctUntilChanged()),
  50. localStateStore.value[key],
  51. (value: LocalState[K]) => {
  52. localStateStore.dispatch({
  53. dispatcher: "applyState",
  54. payload: { key, value },
  55. })
  56. }
  57. )
  58. }