@platform/state
Version:
A small, simple, strongly typed, [rx/observable] state-machine.
57 lines (56 loc) • 1.94 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.syncFrom = void 0;
var rxjs_1 = require("rxjs");
var operators_1 = require("rxjs/operators");
function syncFrom(args) {
var target = args.target;
var parent = (args.parent || '').trim();
if (!parent) {
var err = "Cannot sync: parent node not specified.";
throw new Error(err);
}
if (!target.query.exists(parent)) {
var err = "Cannot sync: the parent node '".concat(parent, "' does not exist in tree '").concat(target.id, "'.");
throw new Error(err);
}
var dispose$ = new rxjs_1.Subject();
var dispose = function () {
dispose$.next();
dispose$.complete();
};
target.dispose$.subscribe(function () { return dispose(); });
if (args.until$) {
args.until$.subscribe(function () { return dispose(); });
}
var source$ = args.source$.pipe((0, operators_1.takeUntil)(dispose$), (0, operators_1.filter)(function (e) { return e.type === 'TreeState/changed'; }), (0, operators_1.map)(function (e) { return e.payload; }));
var change = function (to) {
target.change(function (draft, ctx) {
var node = ctx.findById(parent);
if (node) {
ctx.children(node, function (children) {
var index = children.findIndex(function (child) { return child.id === to.id; });
if (index === -1) {
children.push(to);
}
else {
children[index] = to;
}
});
}
});
};
if (args.initial) {
change(args.initial);
}
source$.subscribe(function (e) {
change(e.to);
});
var syncer = {
parent: parent,
dispose$: dispose$,
dispose: dispose,
};
return syncer;
}
exports.syncFrom = syncFrom;