File size: 3,460 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
import {
  DestroyRef,
  Injector,
  NgZone,
  assertInInjectionContext,
  computed,
  inject,
  signal,
} from '@angular/core'
import {
  QueryClient,
  notifyManager,
  replaceEqualDeep,
} from '@tanstack/query-core'
import type { Signal } from '@angular/core'
import type {
  Mutation,
  MutationCache,
  MutationFilters,
  MutationState,
} from '@tanstack/query-core'

type MutationStateOptions<TResult = MutationState> = {
  filters?: MutationFilters
  select?: (mutation: Mutation) => TResult
}

/**
 *
 * @param mutationCache
 * @param options
 */
function getResult<TResult = MutationState>(
  mutationCache: MutationCache,
  options: MutationStateOptions<TResult>,
): Array<TResult> {
  return mutationCache
    .findAll(options.filters)
    .map(
      (mutation): TResult =>
        (options.select ? options.select(mutation) : mutation.state) as TResult,
    )
}

/**
 * @public
 */
export interface InjectMutationStateOptions {
  /**
   * The `Injector` in which to create the mutation state signal.
   *
   * If this is not provided, the current injection context will be used instead (via `inject`).
   */
  injector?: Injector
}

/**
 * Injects a signal that tracks the state of all mutations.
 * @param injectMutationStateFn - A function that returns mutation state options.
 * @param options - The Angular injector to use.
 * @returns The signal that tracks the state of all mutations.
 * @public
 */
export function injectMutationState<TResult = MutationState>(
  injectMutationStateFn: () => MutationStateOptions<TResult> = () => ({}),
  options?: InjectMutationStateOptions,
): Signal<Array<TResult>> {
  !options?.injector && assertInInjectionContext(injectMutationState)
  const injector = options?.injector ?? inject(Injector)
  const destroyRef = injector.get(DestroyRef)
  const ngZone = injector.get(NgZone)
  const queryClient = injector.get(QueryClient)
  const mutationCache = queryClient.getMutationCache()

  /**
   * Computed signal that gets result from mutation cache based on passed options
   * First element is the result, second element is the time when the result was set
   */
  const resultFromOptionsSignal = computed(() => {
    return [
      getResult(mutationCache, injectMutationStateFn()),
      performance.now(),
    ] as const
  })

  /**
   * Signal that contains result set by subscriber
   * First element is the result, second element is the time when the result was set
   */
  const resultFromSubscriberSignal = signal<[Array<TResult>, number] | null>(
    null,
  )

  /**
   * Returns the last result by either subscriber or options
   */
  const effectiveResultSignal = computed(() => {
    const optionsResult = resultFromOptionsSignal()
    const subscriberResult = resultFromSubscriberSignal()
    return subscriberResult && subscriberResult[1] > optionsResult[1]
      ? subscriberResult[0]
      : optionsResult[0]
  })

  const unsubscribe = ngZone.runOutsideAngular(() =>
    mutationCache.subscribe(
      notifyManager.batchCalls(() => {
        const [lastResult] = effectiveResultSignal()
        const nextResult = replaceEqualDeep(
          lastResult,
          getResult(mutationCache, injectMutationStateFn()),
        )
        if (lastResult !== nextResult) {
          ngZone.run(() => {
            resultFromSubscriberSignal.set([nextResult, performance.now()])
          })
        }
      }),
    ),
  )

  destroyRef.onDestroy(unsubscribe)

  return effectiveResultSignal
}