UNPKG

@thi.ng/atom

Version:

Mutable wrappers for nested immutable values with optional undo/redo history and transaction support

85 lines (84 loc) 2.16 kB
var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __decorateClass = (decorators, target, key, kind) => { var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target; for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result; if (kind && result) __defProp(target, key, result); return result; }; import { IWatchMixin } from "@thi.ng/api/mixins/iwatch"; import { illegalState } from "@thi.ng/errors/illegal-state"; import { setInUnsafe } from "@thi.ng/paths/set-in"; import { updateInUnsafe } from "@thi.ng/paths/update-in"; const defAtom = (value, valid) => new Atom(value, valid); let Atom = class { _value; valid; _watches; constructor(val, valid) { if (valid && !valid(val)) { illegalState("initial state value did not validate"); } this._value = val; this.valid = valid; } get value() { return this._value; } set value(val) { this.reset(val); } deref() { return this._value; } equiv(o) { return this === o; } reset(val) { const old = this._value; if (this.valid && !this.valid(val)) { return old; } this._value = val; this.notifyWatches(old, val); return val; } resetIn(path, val) { return this.reset(setInUnsafe(this._value, path, val)); } resetInUnsafe(path, val) { return this.reset(setInUnsafe(this._value, path, val)); } swap(fn, ...args) { return this.reset(fn.apply(null, [this._value, ...args])); } swapIn(path, fn, ...args) { return this.reset(updateInUnsafe(this._value, path, fn, ...args)); } swapInUnsafe(path, fn, ...args) { return this.reset(updateInUnsafe(this._value, path, fn, ...args)); } // @ts-ignore: mixin addWatch(id, fn) { } // @ts-ignore: mixin removeWatch(id) { } // @ts-ignore: mixin notifyWatches(old, prev) { } release() { delete this._watches; delete this._value; return true; } }; Atom = __decorateClass([ IWatchMixin ], Atom); export { Atom, defAtom };