UNPKG

1.92 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.syncFrom = void 0;
4var rxjs_1 = require("rxjs");
5var operators_1 = require("rxjs/operators");
6function syncFrom(args) {
7 var target = args.target;
8 var parent = (args.parent || '').trim();
9 if (!parent) {
10 var err = "Cannot sync: parent node not specified.";
11 throw new Error(err);
12 }
13 if (!target.query.exists(parent)) {
14 var err = "Cannot sync: the parent node '" + parent + "' does not exist in tree '" + target.id + "'.";
15 throw new Error(err);
16 }
17 var dispose$ = new rxjs_1.Subject();
18 var dispose = function () {
19 dispose$.next();
20 dispose$.complete();
21 };
22 target.dispose$.subscribe(function () { return dispose(); });
23 if (args.until$) {
24 args.until$.subscribe(function () { return dispose(); });
25 }
26 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; }));
27 var change = function (to) {
28 target.change(function (draft, ctx) {
29 var node = ctx.findById(parent);
30 if (node) {
31 ctx.children(node, function (children) {
32 var index = children.findIndex(function (child) { return child.id === to.id; });
33 if (index === -1) {
34 children.push(to);
35 }
36 else {
37 children[index] = to;
38 }
39 });
40 }
41 });
42 };
43 if (args.initial) {
44 change(args.initial);
45 }
46 source$.subscribe(function (e) {
47 change(e.to);
48 });
49 var syncer = {
50 parent: parent,
51 dispose$: dispose$,
52 dispose: dispose,
53 };
54 return syncer;
55}
56exports.syncFrom = syncFrom;