Skip to content

Commit

Permalink
docs(rstream): add undo/redo example to readme
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Jan 31, 2018
1 parent 54cd526 commit 59d2a8a
Showing 1 changed file with 62 additions and 0 deletions.
62 changes: 62 additions & 0 deletions packages/rstream/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,68 @@ new rs.StreamMerge([
// ...
```

### Central app state atom with reactive undo / redo

```typescript
import * as atom from "@thi.ng/atom";
import * as tx from "@thi.ng/transducers";

// central app state / single source of truth
const app = new atom.Atom({ui: {theme: "dark", mode: false}, foo: "bar"});

// define some cursors for different UI params
const theme = new atom.Cursor(app, "ui.theme");
const mode = new atom.Cursor(app, "ui.mode");

// create streams of cursor value changes
rs.fromAtom(theme).subscribe(rs.trace("theme:"));
// with transducer
rs.fromAtom(mode).subscribe(rs.trace("mode:"), tx.map(mode => mode ? "advanced" : "basic"));
// another one for an hitherto unknown value in app state
rs.fromAtom(new atom.Cursor(app, "session.user")).subscribe(rs.trace("user:"));

// attach history only to `ui` branch
// undo/redo will not record/change other keys in the atom
const hist = new atom.History(new atom.Cursor(app, "ui"));

hist.record(); // record current snapshot
theme.reset("light");
// theme: light

hist.record();
mode.swap(mode => !mode); // toggle mode
// mode: advanced

hist.undo(); // 1st
// mode: basic
// { theme: 'light', mode: false }

hist.undo(); // 2nd
// theme: dark
// { theme: 'dark', mode: false }

hist.redo(); // 1st
// theme: light
// { theme: 'light', mode: false }

// update another part of the app state (SPREAD, DON'T MUTATE!)
app.swap((state) => ({...state, session: {user: "asterix"}}));
// user: asterix
// { ui: { theme: 'light', mode: false },
// foo: 'bar',
// session: { user: 'asterix' } }

hist.redo(); // redo 2nd time
// mode: advanced
// { theme: 'light', mode: true }

// verify history redo did not destroy other keys
app.deref();
// { ui: { theme: 'light', mode: true },
// foo: 'bar',
// session: { user: 'asterix' } }
```

TODO more to come... see tests for now!

## Authors
Expand Down

0 comments on commit 59d2a8a

Please sign in to comment.