Merge branch 'feat/inda-383-daily-stat' into 'main'
[ProtonMail-WebClient.git] / packages / pass / store / optimistic / utils / transformers.ts
blob7d10ba3eef4fe77c9b98788e450a27caeb6027d8
1 import type { Action } from 'redux';
3 import type { HistoryItem, OptimisticReducersMapObject, WrappedOptimisticState } from '../types';
4 import { isCombinedOptimisticReducer } from './assertions';
6 export const wrapOptimisticState = <T>(state: T): WrappedOptimisticState<T> => ({
7     ...state,
8     optimistic: { history: [] },
9 });
11 export const unwrapOptimisticState = <T>(state: WrappedOptimisticState<T>): T => {
12     const { optimistic, ...inner } = state;
14     /*
15      * TS: 'T' could be instantiated with an arbitrary type which could be unrelated to
16      * 'Omit<WrappedOptimisticState<T>, "optimistic">'
17      *
18      * Impossible, since WrappedOptimisticState<T> is 'T & { optimistic: {...} }'
19      */
20     return inner as any as T;
23 /* Unwraps the underlying actionfrom an OptimisticHistoryItem */
24 export const getActionFromHistoryItem = (item: HistoryItem): Action => item.action;
26 /**
27  * Sanitizes an optimistic reducer map object by recursively
28  * unwrapping any combined optimistic reducer into a sub-map
29  * of the inner reducers (see combineOptimisticReducers)
30  */
31 export const sanitizeOptimisticReducerMapObject = (map: OptimisticReducersMapObject): OptimisticReducersMapObject => {
32     return Object.fromEntries(
33         Object.entries(map).map(([reducerKey, reducer]) => {
34             if (
35                 typeof reducer === 'function' &&
36                 isCombinedOptimisticReducer(reducer) &&
37                 reducer.innerCombinedReducers !== undefined
38             ) {
39                 return [reducerKey, sanitizeOptimisticReducerMapObject(reducer.innerCombinedReducers)];
40             }
42             return [reducerKey, reducer];
43         })
44     );