@platform/state
Version:
A small, simple, strongly typed, [rx/observable] state-machine.
92 lines (91 loc) • 3.35 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Store = void 0;
var tslib_1 = require("tslib");
var immer_1 = require("immer");
var rxjs_1 = require("rxjs");
var operators_1 = require("rxjs/operators");
var Store = (function () {
function Store(args) {
var _this = this;
this._dispose$ = new rxjs_1.Subject();
this._changing$ = new rxjs_1.Subject();
this._changed$ = new rxjs_1.Subject();
this._ = {
state: undefined,
};
this.dispose$ = this._dispose$.pipe((0, operators_1.share)());
this.changing$ = this._changing$.pipe((0, operators_1.share)());
this.changed$ = this._changed$.pipe((0, operators_1.share)());
this._.state = tslib_1.__assign({}, args.initial);
this._event$ = args.event$ || new rxjs_1.Subject();
this.event$ = this._event$.pipe((0, operators_1.takeUntil)(this.dispose$), (0, operators_1.map)(function (e) { return _this.toDispatchEvent(e); }), (0, operators_1.share)());
}
Store.create = function (args) {
return new Store(args);
};
Store.prototype.dispose = function () {
this._dispose$.next();
this._dispose$.complete();
};
Object.defineProperty(Store.prototype, "isDisposed", {
get: function () {
return this._dispose$.isStopped;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Store.prototype, "state", {
get: function () {
return tslib_1.__assign({}, this._.state);
},
enumerable: false,
configurable: true
});
Store.prototype.dispatch = function (event) {
this._event$.next(event);
return this;
};
Store.prototype.on = function (type) {
return this.event$.pipe((0, operators_1.filter)(function (e) { return e.type === type; }), (0, operators_1.map)(function (e) { return e; }));
};
Store.prototype.toDispatchEvent = function (event) {
var _this = this;
var type = event.type, payload = event.payload;
var from = this.state;
var result = {
type: type,
payload: payload,
get state() {
return tslib_1.__assign({}, from);
},
change: function (next) {
var to = typeof next !== 'function'
? tslib_1.__assign({}, next) : (0, immer_1.default)(from, function (draft) {
next(draft);
return undefined;
});
var isCancelled = false;
var change = { type: type, event: event, from: from, to: to };
_this._changing$.next({
change: change,
isCancelled: isCancelled,
cancel: function () { return (isCancelled = true); },
});
if (isCancelled) {
return result;
}
_this._.state = to;
_this._changed$.next(change);
return result;
},
dispatch: function (event) {
_this.dispatch(event);
return result;
},
};
return result;
};
return Store;
}());
exports.Store = Store;