@platform/state
Version:
A small, simple, strongly typed, [rx/observable] state-machine.
60 lines (59 loc) • 2 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 '" + parent + "' does not exist in tree '" + 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(operators_1.takeUntil(dispose$), operators_1.filter(function (e) { return e.type === 'TreeState/changed'; }), 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,
get isDisposed() {
return dispose$.isStopped;
},
dispose$: dispose$,
dispose: dispose,
};
return syncer;
}
exports.syncFrom = syncFrom;