1 import type { Reducer } from 'redux';
3 import { arrayRemove } from '@proton/pass/utils/array/remove';
5 import type { OptimisticState } from '../types';
6 import { isOptimisticHistoryItemWithId } from './assertions';
7 import { splitHistoryOnFirstOptimisticItem } from './split-history';
8 import { getActionFromHistoryItem } from './transformers';
11 * Removes an history item from the optimistic item by its optimisticId.
12 * - If optimisticId is not found in history, early return
13 * - If the item matched by optimisticId is the first in the history list, we can safely remove it and recaculate
14 * the next checkpoint as being the state resulting from applying every action up until the NEXT optimistic
15 * item in history (if any). The next history can be then re-computed as the remaining actions starting FROM
16 * this NEXT optimistic item in history.
17 * - If the matched item is anywhere else in the optimistic history, remove it.
19 export const removeHistoryItem = <T>(
21 optimistic: OptimisticState<T>,
23 ): OptimisticState<T> => {
24 const { history, checkpoint } = optimistic;
25 const historyItemIndex = history.findIndex(isOptimisticHistoryItemWithId(optimisticId));
27 if (historyItemIndex === -1) {
31 if (historyItemIndex === 0) {
32 const [, ...other] = history;
33 const [removableHistory, nextHistory] = splitHistoryOnFirstOptimisticItem(other);
34 const nextCheckpoint = removableHistory.map(getActionFromHistoryItem).reduce(reducer, checkpoint);
36 return { checkpoint: nextCheckpoint, history: nextHistory };
39 return { checkpoint, history: arrayRemove(history, historyItemIndex) };