Skip to content

Commit

Permalink
feat(history-plugin): allow custom clear function
Browse files Browse the repository at this point in the history
  • Loading branch information
fma committed Jun 5, 2019
1 parent 5500c15 commit 68ba22e
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 3 deletions.
28 changes: 28 additions & 0 deletions akita/__tests__/stateHistory.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,34 @@ describe('StateHistory', () => {
present: { counter: 5 },
future: [{ counter: 4 }]
});

stateHistory.clear((history) => {
return {
past: history.past,
present: history.present,
future: []
};
});

expect(stateHistory.history).toEqual({
past: [{ counter: 0 }, { counter: 2 }, { counter: 4 }],
present: { counter: 5 },
future: []
});

stateHistory.clear((history) => {
return {
past: [],
present: history.present,
future: history.future
};
});

expect(stateHistory.history).toEqual({
past: [],
present: { counter: 5 },
future: []
});
});
});

Expand Down
28 changes: 25 additions & 3 deletions akita/src/plugins/stateHistory/stateHistoryPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,19 @@ import { toBoolean } from '../../toBoolean';
import { AkitaPlugin, Queries } from '../plugin';
import { EntityParam } from '../entityCollectionPlugin';
import { logAction } from '../../actions';
import { isFunction } from '../../isFunction';

export interface StateHistoryParams {
maxAge?: number;
comparator?: (prevState, currentState) => boolean;
}

export type History<S> = {
past: S[],
present: S | null,
future: S[]
}

export class StateHistoryPlugin<E = any, S = any> extends AkitaPlugin<E, S> {
/** Allow skipping an update from outside */
private skip = false;
Expand Down Expand Up @@ -124,9 +131,24 @@ export class StateHistoryPlugin<E = any, S = any> extends AkitaPlugin<E, S> {
this.update('Redo');
}

clear() {
this.history = {
past: [],
/**
* Clear the history
*
* @param customUpdateFn Callback function for only clearing part of the history
*
* @example
*
* stateHistory.clear((history) => {
* return {
* past: history.past,
* present: history.present,
* future: []
* };
* });
*/
clear(customUpdateFn?: (history: History<S>) => History<S>) {
this.history = isFunction(customUpdateFn) ? customUpdateFn(this.history) : {
past: [],
present: null,
future: []
};
Expand Down

0 comments on commit 68ba22e

Please sign in to comment.