launch.io
Version:
Launch.IO is an Ultra Hip, Simple, and Fast, Time Traveling React State Management Library
44 lines (43 loc) • 2.22 kB
JavaScript
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
/* eslint-disable @typescript-eslint/no-explicit-any */
import getNewState from "../utils/getNewState";
const initialState = {
initialGlobalState: null,
past: [],
future: [],
};
const actions = {
stepBack: ({ state }, { serviceActions, boundActions }) => {
if (state._history.past.length === 0) {
return state;
}
const previous = state._history.past[state._history.past.length - 1], newPast = state._history.past.slice(0, state._history.past.length - 1), newState = getNewState(Object.assign({}, state._history.initialGlobalState), newPast, serviceActions, boundActions);
return Object.assign(Object.assign({}, newState), { _history: Object.assign(Object.assign({}, state._history), { past: newPast, future: [previous, ...state._history.future] }) });
},
stepForward: ({ state }, { serviceActions, boundActions }) => {
if (state._history.future.length === 0) {
return state;
}
const next = state._history.future[0], newFuture = state._history.future.slice(1), newPast = [...state._history.past, next], newState = getNewState(Object.assign({}, state._history.initialGlobalState), newPast, serviceActions, boundActions);
return Object.assign(Object.assign({}, newState), { _history: Object.assign(Object.assign({}, state._history), { past: newPast, future: newFuture }) });
},
add: ({ state }, newAction) => {
return {
initialGlobalState: state._history.initialGlobalState
? state._history.past.length === newAction.timeTravelHistoryLimit
? getNewState(state._history.initialGlobalState, [state._history.past[0]], newAction.timeTravelActionContext.serviceActions, newAction.timeTravelActionContext.boundActions)
: state._history.initialGlobalState
: state,
past: [
...state._history.past.slice(-1 * (newAction.timeTravelHistoryLimit - 1)),
newAction.action,
],
future: [],
};
},
};
export default {
name: "_history",
initialState,
actions,
};