State History
The stateHistory function provides a convenient way for undo and redo functionality, saving you the trouble of maintaining a history in the app yourself.
First, you need to install the package by using the CLI command elf-cli install and selecting the stat-history package, or via npm:
npm i @ngneat/elf-state-history
Then, call the stateHistory method when you want to start monitoring.
import { createStore } from '@ngneat/elf';
import { stateHistory } from '@ngneat/elf-state-history';
const propsStore = createStore({ name }, withProps<Props>());
export const propsStateHistory = stateHistory(propsStore);
As the second parameter you can pass a StateHistoryOptions object, which can be used to define the store's maximum age and state comparator function.
API
undo
Undo the last change:
propsStateHistory.undo();
redo
redo the last change:
propsStateHistory.redo();
jumpToPast
Jump to the provided index in the past (assuming index is valid):
propsStateHistory.jumpToPast(number);
jumpToFuture
Jump to the provided index in the future (assuming index is valid):
propsStateHistory.jumpToFuture(number);
clear
Clear the history:
propsStateHistory.clear();
propsStateHistory.clear(customUpdateFn);
pause
Stop monitoring the state changes:
propsStateHistory.pause();
resume
Continue monitoring the state changes:
propsStateHistory.resume();
getPast
Get the whole past history:
propsStateHistory.getPast();
hasPast
A boolean flag that returns whether the history is not empty:
propsStateHistory.hasPast;
hasPast$
An observable that returns whether the history is not empty:
propsStateHistory.hasPast$;
getFuture
Get the whole future history:
propsStateHistory.getFuture();
hasFuture
A boolean flag that returns whether you're not in the latest step in the history:
propsStateHistory.hasFuture;
hasFuture$
An observable that returns whether you're not in the latest step in the history:
propsStateHistory.hasFuture$;
resetFutureOnNewState
A boolean flag in the StateHistoryOptions that controls whether the future redo states should be cleared when a new state is added after the user has undone one or more state changes.
If resetFutureOnNewState is set to true, the future states will be cleared when a new state is added. If it's set to false (which is the defalt value), the future states will be preserved.
Here is how you can set resetFutureOnNewState when calling the stateHistory method:
const propsStateHistory = stateHistory(propsStore, {
resetFutureOnNewState: false,
});
In this example, the future states will not be cleared when a new state is added, allowing the user to still redo previously undone state changes even after a new state has been added.