@thi.ng/atom
@thi.ng/atom
This project is part of the @thi.ng/umbrella monorepo.
About
Clojure inspired mutable wrappers for (usually) immutable values, with infrastructure support for:
- watches
- derived view subscriptions
- cursors (direct R/W access to nested values)
- undo/redo history
Together these types act as building blocks for various application state handling patterns, specifically aimed (though not exclusively) at the concept of using a nested, immutable, centralized atom as single source of truth within an application.
Status
Stable, used in production and in active development.
Note: On 2018-03-17 this package was split to remain more focused. Path based getters/setters have been moved into the new @thi.ng/paths package. Likewise, all interceptor based event handling functionality now lives in the @thi.ng/interceptors package.
Installation
yarn add @thi.ng/atom
New since 2018-03-15: You can now create a preconfigured app skeleton using @thi.ng/atom, @thi.ng/hdom & @thi.ng/router using the create-hdom-app project generator:
yarn create hdom-app my-app cd my-appyarn installyarn start
Dependencies
Usage examples
Several projects in the /examples directory make heavy use of this library.
Atom
An Atom
is a mutable wrapper for immutable values. The wrapped value
can be obtained via deref()
, replaced via reset()
and updated using
swap()
. An atom too supports the concept of watches, essentially
onchange
event handlers which are called from reset
/swap
and
receive both the old and new atom values.
; ; // obtain value via deref()a.deref;// 23 // add watch to observe value changesa.addWatch"foo",console.log`: -> `;// true // example update function; // apply given function to current value// (incl. any additional arguments passed to swap)// this is the same as:// a.reset(adder(a.deref(), 1))a.swapadd, 1;// foo: 23 -> 24 // reset atom's valuea.reset42;// foo: 24 -> 42
Cursor
Cursors provide direct & immutable access to a nested value within a structured atom. The path to the desired value must be provided when the cursor is created and cannot be changed later. The path is then compiled into a getter and setter to allow cursors to be used like atoms and update the parent state in an immutable manner (i.e. producing an optimized copy with structural sharing of the original (as much as possible)) - see further details below.
It's important to remember that cursors also cause their parent state (atom or another cursor) to reflect their updated local state. I.e. any change to a cursor's value propagates up the hierarchy of parent states.
a = new atom.Atom// cursor to `b` valueb=new atom.Cursora, "a.b"// cursor to `c` value, relative to `b`c=new atom.Cursorb, "c" c.reset2; b.deref;// { c: 2 } a.deref;// { a: { b: { c: 2 } } }
For that reason, it's recommended to design the overall data layout rather wide than deep (my personal limit is 3-4 levels) to minimize the length of the propagation chain and maximize structural sharing.
// main statemain = new atom.Atom; // cursor to `c` valuecursor = new atom.Cursormain, "a.b.c";// orcursor = new atom.Cursormain, ; // alternatively provide path implicitly via lookup & update functions// both fns will be called with cursor's parent state// this allows the cursor implementation to work with any data structure// as long as the updater DOES NOT mutate in placecursor = new atom.Cursor main,s.a.b.c,; // add watch just as with Atomcursor.addWatch"foo", console.log; cursor.deref// 23 cursor.swapx + 1;// foo 23 24 main.deref// { a: { b: { c: 24 }, d: { e: 42 } }, f: 66 }
Derived views
Whereas cursors provide read/write access to nested key paths within a
state atom, there are many situations when one only requires read access
and the ability to (optionally) produce transformed versions of such a
value. The View
type provides exactly this functionality:
db = new atom.Atom; // create a view for a's valueviewA = db.addView"a"; // create a view for c's value w/ transformerviewC = db.addView"b.c",x * 10; viewA.deref// 1 viewC.deref// 20 // update the atomdb.swapatom.setInstate, "b.c", 3 // views can indicate if their value has changed// (will be reset to `false` after each deref) // here viewA hasn't changed (we only updated `c`)viewA.changed// falseviewC.changed// true // the transformer function is only executed once per value changeviewC.deref// 30 // just returns current cached transformed valueviewC.deref// 30 // discard viewsviewA.releaseviewC.release
Since v1.1.0 views can also be configured to be eager, instead of the
"lazy" default behavior. If the optional lazy
arg is true (default),
the view's transformer will only be executed with the first deref()
after each value change. If lazy
is false, the transformer function
will be executed immediately after a value change occurred and so can be
used like a selective watch which only triggers if there was an actual
value change (in contrast to normal watches, which execute with each
update, regardless of value change).
Related, the actual value change predicate can be customized. If not
given, the default @thi.ng/equiv
will be used.
; // create an eager view by passing `false` as last argview = a.addView"value",x = y, y * 10, false; // check `x` to verify that transformer already has runx === 1// true // reset xx = null // verify transformed valueview.deref === 10// true // verify transformer hasn't rerun because of deref()x === null// true
Atoms & views are useful tools for keeping state outside UI components. Here's an example of a tiny @thi.ng/hdom web app, demonstrating how to use derived views to switch the UI for different application states / modules.
Note: The constrained nature of this next example doesn't really do
justice to the powerful nature of the approach. Also stylistically, in a
larger app we'd want to avoid the use of global variables (apart from
db
) as done here...
For a more advanced / realworld usage pattern, check the related event handling package and bundled examples.
This example is also available in standalone form:
;; // central immutable app state; // define views for different state values;;// specify a view transformer for the username value; // state update functions;;;;;; // components for different app states// note how the value views are used here; // finally define another derived view for the app state value// including a transformer, which maps the current app state value// to its correct UI component (incl. a fallback for illegal app states); // app root component; startdocument.body, app;
Undo history
The History
type can be used with & behaves like an Atom or Cursor,
but creates snapshots of the current state before applying the new
state. By default history has length of 100 steps, but this is
configurable.
db = new atom.Historynew atom.Atomdb.deref// {a: 1} db.resetdb.reset db.undo// {a: 2, b: 3} db.undo// {a: 1} db.undo// undefined (no more undo possible)db.canUndo// false db.redo// {a: 2, b: 3} db.redo// {b: 4} db.redo// undefined (no more redo possible) db.canRedo// false
Authors
- Karsten Schmidt
License
© 2018 Karsten Schmidt // Apache Software License 2.0