1 import type { Selector } from '@reduxjs/toolkit';
3 import isDeepEqual from '@proton/shared/lib/helpers/isDeepEqual';
6 MaybeOptimisticStateObject,
7 OptimisticReducersMapObject,
8 StateFromOptimisticReducersMapObject,
10 WrappedOptimisticState,
12 import { isOptimisticReducer, isOptimisticState } from '../utils/assertions';
13 import { getReducerMapEntries } from '../utils/combine-optimistic-reducers';
14 import getWithoutOptimistic from '../utils/get-without-optimistic';
15 import { sanitizeOptimisticReducerMapObject } from '../utils/transformers';
17 export const asIfNotOptimistic = <T extends {}, M extends OptimisticReducersMapObject<T>>(
20 ): StateFromOptimisticReducersMapObject<M> => {
21 const entries = getReducerMapEntries(sanitizeOptimisticReducerMapObject(reducerMap));
23 const stateWithOptimistics = state as MaybeOptimisticStateObject;
24 const newState = {} as any;
26 for (const [name, maybeReducer] of entries) {
27 const subState = stateWithOptimistics[name];
29 if (typeof maybeReducer === 'function') {
30 if (isOptimisticState(subState) && isOptimisticReducer(maybeReducer)) {
31 newState[name] = getWithoutOptimistic(subState, maybeReducer);
33 newState[name] = subState;
36 newState[name] = asIfNotOptimistic(subState, maybeReducer);
43 export const asIfNotOptimisticSubSelector =
44 <T extends {}, Optimistics extends WrappedOptimisticState<T>>(reducer: WithOptimisticReducer<T>) =>
45 (subState: Optimistics) =>
46 getWithoutOptimistic(subState, reducer);
48 const selectIsOptimistic =
49 <T extends object>(state: T) =>
50 <M extends OptimisticReducersMapObject<T>>(reducerMap: M) =>
51 (selector: Selector<StateFromOptimisticReducersMapObject<M>>): boolean => {
52 const stateWithoutOptimistic = selector(asIfNotOptimistic(state, reducerMap));
53 const stateWithOptimistic = selector(state as StateFromOptimisticReducersMapObject<M>);
55 return !isDeepEqual(stateWithOptimistic, stateWithoutOptimistic);
58 export default selectIsOptimistic;