Skip to content

Commit

Permalink
feat(atom): update History.record(), add IHistory interface
Browse files Browse the repository at this point in the history
- check changed() from record() if called without arg
- add IHistory for alt implementations
  • Loading branch information
postspectacular committed Apr 15, 2018
1 parent 3c92f7e commit cf42260
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
11 changes: 11 additions & 0 deletions packages/atom/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,15 @@ export interface CursorOpts<T> {
path: Path | [(s: any) => T, (s: any, v: T) => any];
validate?: api.Predicate<T>;
id?: string;
}

export interface IHistory<T> extends IAtom<T> {
canUndo(): boolean;
canRedo(): boolean;

undo(): T;
redo(): T;
clear(): void;

record(): void;
}
19 changes: 14 additions & 5 deletions packages/atom/src/history.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Predicate2, Watch } from "@thi.ng/api/api";
import { equiv } from "@thi.ng/api/equiv";
import { Path, getIn, setIn, updateIn } from "@thi.ng/paths";

import { IAtom, SwapFn, IView, ViewTransform } from "./api";
import { IAtom, IHistory, IView, SwapFn, ViewTransform } from "./api";
import { View } from "./view";

/**
Expand All @@ -13,7 +13,7 @@ import { View } from "./view";
* `record()` directly.
*/
export class History<T> implements
IAtom<T> {
IHistory<T> {

state: IAtom<T>;
maxLen: number;
Expand Down Expand Up @@ -137,12 +137,21 @@ export class History<T> implements
* @param state
*/
record(state?: T) {
if (this.history.length >= this.maxLen) {
this.history.shift();
const history = this.history;
const n = history.length;
if (n >= this.maxLen) {
history.shift();
}
// check for arg given and not if `state == null` we want to
// allow null/undefined as possible values
this.history.push(arguments.length > 0 ? state : this.state.deref());
if (!arguments.length) {
state = this.state.deref();
if (!n || this.changed(history[n - 1], state)) {
history.push(state);
}
} else {
history.push(state);
}
this.future.length = 0;
}

Expand Down

0 comments on commit cf42260

Please sign in to comment.