| 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915 |
1
1
1
1
1
628
628
65
1
303
33
11
33
33
22
66
264
303
1
1000
303
1000
1000
697
1000
1
277
277
897
897
897
277
1
174
174
174
174
174
1
172
172
172
169
169
169
169
1
65
1
16
16
119
119
46
1
383
383
383
175
2
173
173
319
319
121
121
319
1
9
1
8
4
5
1
6
4
2
2
2
2
2
2
2
1
689
689
689
689
689
689
689
511
178
686
686
1
110
110
110
110
110
1
511
511
511
507
368
390
390
390
390
511
508
1
2093
1
148
4
144
3
141
141
601
140
141
1
48
48
4
44
22
22
63
18
45
22
48
44
156
20
44
1
557
557
557
16
1
541
551
2042
29
2039
1492
25
551
551
21
21
551
1
2007
2007
1
13
13
1
19
3
19
19
1
25
4
25
25
25
25
1
424
1
22
1
20
1
2
1
5
5
5
5
5
5
5
5
1
5
5
5
5
5
5
5
5
1
6
6
6
6
6
6
6
6
1
8
8
8
8
8
1
134
1
8
8
8
8
8
1
1100
1100
1100
1
411
411
409
407
407
372
372
407
1
235
179
56
56
6
6
50
50
50
50
50
50
50
50
1
3694
1
56
1
300
1
55
1
15
15
15
15
15
6
6
6
6
9
9
9
9
9
9
9
9
9
1
23
23
8
8
8
8
14
14
14
14
10
10
10
10
10
10
1
271
1
20
1
19
19
8
8
8
8
11
11
11
11
11
11
11
11
11
1
6
6
6
6
4
4
4
4
4
2
2
2
3
2
2
2
2
2
2
1
1
| /*
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/* jshint -W071 */
/* global define */
// [UMD/returnExports.js](https://github.com/umdjs/umd/blob/master/returnExports.js)
// setup for AMD, Node.js, and Global usages.
(function (root, factory) {
'use strict';
Eif (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['underscore'], factory);
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like enviroments that support module.exports,
// like Node.
/* global module, require */
module.exports = factory(require('underscore'));
} else {
// Browser globals (root is window)
root._tree = factory(root._);
}
}(this, function (_) {
'use strict';
var _tree = {}, Tree, Node, __defaults;
function __callback(tree, event) {
var args = Array.prototype.slice.call(arguments, 2);
_.each(tree.defaults.callbacks[event], function(cb) {
_.partial(cb, tree).apply(null, args);
});
}
function __preFinalizeTree(tree) {
// engage mixins before calling the tree pre-finalized
_.each(tree.defaults.mixins, function(mix) {
if (mix.tree) {
_.each(mix.tree, function(f, key) {
tree[key] = f;
});
}
if (mix.node) {
_.each(mix.node, function(f, key) {
tree.walk(function(visitNode) {
visitNode[key] = f;
});
});
}
});
__setupAncestry(tree);
}
// Since tree and nodes are not set until this point, a
// meaningful ancestry needs to be setup here at this last
// step.
function __setupAncestry(tree, node, parent) {
if (!node) {
node = tree.root();
}
node.__tree = tree;
if (parent) {
node.__parent = parent;
}
_.each(node.children(), function(c) {__setupAncestry(tree, c, node); });
}
// Before returning a mutable cloned tree, it needs to be properly
// frozen to maintain its immutability guarantee. Also, since
// trees aren't immutable until all node modifications are done,
// all nodes need to be given this last-stage reference to the
// tree.
function __finalizeMutableTreeClone(tree) {
// Environments that don't support `Object.freeze` will still
// work, but without guaranteed tree immutability.
try { Object.freeze(tree); } catch (e) {}
// finalizeMutableChildNodes
tree.walk(function(node) {
try {
Object.freeze(node);
Object.freeze(node.__children);
} catch (e) {}
});
// call each afterUpdate callback with the new tree
__callback(tree, 'afterUpdate');
}
function __cloneDefaults(defaults) {
defaults = defaults ? _.clone(defaults) : {};
defaults.callbacks = _.defaults(_.clone(defaults.callbacks || {}), __defaults.callbacks);
defaults.mixins = _.union((defaults.mixins || []), __defaults.mixins);
defaults = _.defaults(defaults, __defaults);
return defaults;
}
// # Public API
// `_tree.inflate` parses tree-like data into an immutable `Tree`
// object for you to work with. It does so without modifying your
// object whatsoever, and it can handle any tree data structure
// you define.
//
// You can specify the default behaviour of your tree via the
// `defaults` argument. Anything you don't specify will take the
// standard default options.
//
// `_tree.inflate` handles all forms of tree-like data by making
// the object parsing logic fully pluggable. You can define your
// own `inflateMethod`, or use one of the handful of built-ins.
_tree.inflate = function (obj, inflateMethod, defaults) {
defaults = __cloneDefaults(defaults);
inflateMethod = defaults.inflate = inflateMethod || defaults.inflate;
var tree = new Tree(defaults, obj, inflateMethod);
__preFinalizeTree(tree);
__callback(tree, 'beforeFreeze');
__finalizeMutableTreeClone(tree);
return tree;
};
// `_tree.create` creates an empty tree from scratch. Tree-wide
// `defaults` can also be set here.
_tree.create = function (defaults) {
return _tree.inflate(null, null, defaults);
};
// Maybe the most natural representation of trees in Javascript
// can be parsed by this `_tree.inflate` method. It inflates
// objects that have child arrays bound to some property of the
// parent object (usually 'children')
//
// For example, it parses an object like this:
//
// {'name': parent,
// 'children': [
// {'name': 'child1'},
// {'name': 'child2', 'children': [
// {'name': 'child3'}]
// }]
// }
//
// into a tree like this:
//
// parent
// child1
// child2
// child3
_tree.inflate.byKey = function (Key) {
Key = Key || 'children';
return function (Obj) {
this.emit(Obj);
if (_.has(Obj, Key)) {
this.children(Obj[Key]);
}
};
};
// `_tree.inflate.byAdjacencyList` parses a wonky sort of array,
// wherein every entry is either a node, or an array containing
// the children of the previous node. An example to clarify:
//
// It parses an array like this:
//
// ['parent', ['child1', 'child2', ['child3']]]
//
// into a tree like this:
//
// parent
// child1
// child2
// child3
_tree.inflate.byAdjacencyList = function (Obj) {
var kids, tmpObj, i;
this.emit(_.first(Obj));
if (Obj.length > 1) {
if (!_.isArray(Obj[1]) || Obj.length > 2) {
throw 'invalid adjacency list';
}
kids = Obj[1];
for (i = 0; i < kids.length; i++) {
tmpObj = [kids[i]];
if (kids.length > 1 && _.isArray(kids[i + 1])) {
tmpObj.push(kids[i + 1]);
i++;
}
this.children([tmpObj]);
}
}
};
// If your tree only keeps data for leaf nodes, you can use `_tree.inflate.onlyLeavesList`
// inflation method to parse arrays like this:
//
// [[child1, [child3]]]
//
// into trees like this:
//
// <no data>
// child1
// <no data>
// child3
//
_tree.inflate.onlyLeavesList = function (Obj) {
if (!_.isArray(Obj) || Obj.length > 1) {
throw 'invalid leaves list';
}
if (_.isArray(_.first(Obj))) {
this.children(_.map(_.first(Obj), function (n) {return [n];}));
} else {
this.emit(_.first(Obj));
}
};
// `_tree.fromNode`, allows the creation of a new tree from an
// existing `Node`. The new tree is considered to *not* be a clone
// of the node's original tree.
_tree.fromNode = function (node, defaults) {
if (! (node instanceof Node)) {
throw new Error('invalid node: ' + JSON.stringify(node));
}
defaults = __cloneDefaults(defaults);
var tree = new Tree(defaults);
tree.__root = Node.clone(tree, node);
__preFinalizeTree(tree);
__callback(tree, 'beforeFreeze');
__finalizeMutableTreeClone(tree);
return tree;
};
// # Tree
// This is the `Tree` constructor. It is intended to be used
// internally, and so it returns a mutable object that must be
// frozen before it's returned. For the sake of IE8, and all other
// environments that don't support Object.definePropert(y|ies),
// the nasty bit of try/catch here allows those environments to
// work without guaranteed immutability.
Tree = function (defaults, obj, inflateMethod, nextNodeId) {
this.defaults = defaults;
var __id, __nextNodeId, __root;
__id = _.uniqueId();
__nextNodeId = nextNodeId || 0;
try {
Object.defineProperties(this, {
'__id': {
value: __id,
writable: true,
enumerable: false,
configurable: false
},
'__nextNodeId': {
value: __nextNodeId,
writable: true,
enumerable: false,
configurable: false
},
'__batch': {
value: 0,
writable: true,
enumerable: false,
configurable: false
}
});
} catch (e) {
this.__id = __id;
this.__nextNodeId = __nextNodeId;
}
if (!!obj && !!inflateMethod) {
__root = Tree.inflate(this, obj, inflateMethod);
} else {
__root = new Node(this);
}
try {
Object.defineProperties(this, {
'__root': {
writable: true,
enumerable: false,
configurable: false,
value: __root
}
});
} catch (e) {
this.__root = __root;
}
};
// ## Internal Static Tree Methods
// To facilitate immutability, `Tree.clone` provides a static copy
// constructor that takes a(n) (im)mutable tree and returns a
// mutable clone. This method provides the base for all Tree
// modifications.
Tree.clone = function (tree) {
var newTree = new Tree(tree.defaults);
newTree.__root = Node.clone(newTree, tree.root());
newTree.__nextNodeId = tree.__nextNodeId;
newTree.__id = tree.__id;
return newTree;
};
// `Tree.inflate` provides the general logic behind object
// inflation/parsing/deserialization.
Tree.inflate = function(tree, obj, inflateMethod) {
var thisnode = new Node(tree), _this;
tree.__root = thisnode;
// When `inflateMethod` is called to navigate `obj`, `this` is
// bound to the following object:
//
// * `this.emit(data)`: Sets the data for the current node.
// * `this.children([child])`: Calling this immediately
// processes and inflates a set of child node objects.
//
_this = {
emit: function (Data) {
thisnode.__data = Data;
},
children: function (Nodes) {
_.each(Nodes, function (kidObj) {
var kidTree = new Tree(tree.defaults, kidObj, inflateMethod, tree.__nextNodeId);
thisnode.__children.push(kidTree.root());
kidTree.root().__parent = thisnode;
tree.__nextNodeId = kidTree.__nextNodeId;
});
}
};
inflateMethod.call(_this, obj);
return thisnode;
};
// ## Tree Instance Methods
// A getter for the root `Node` of the tree.
Tree.prototype.root = function () {
return this.__root;
};
// Find a node in a tree by internal id correlation, and return
// the Node or `false` if no match was found. This can be used to
// find a matching node in a cloned tree, since ids are designed
// to be invariant across clones.
Tree.prototype.findNode = function (fromNode, walkMethod, startNode) {
if (! (fromNode instanceof Node)) {
throw 'not a node';
}
if (!this.equals(fromNode.__tree)) {
return false;
}
var found = false;
this.walk(function (visitNode) {
if (!found && fromNode.equals(visitNode)) {
found = visitNode;
}
}, walkMethod, startNode);
return found;
};
// Matches a node by its data using deep comparison, without
// requiring object equality, via `_.isEqual(node.data(), data)`
Tree.prototype.findNodeByData = function (data, walkMethod, startNode) {
var isMatch, keys, found = false;
if (_.isUndefined(data)) {
return false;
}
if (_.isObject(data) && !_.isArray(data)) {
keys = _.keys(data);
isMatch = function(nodeData) {
if (!_.isObject(nodeData) || _.isArray(nodeData)) {
return false;
}
return _.isEqual(data, _.partial(_.pick, nodeData).apply(_, keys));
};
} else {
isMatch = function(nodeData) {
return _.isEqual(data, nodeData);
};
}
this.walk(function (visitNode) {
if (!found && isMatch(visitNode.__data)) {
found = visitNode;
}
}, walkMethod, startNode);
return found;
};
// This method is the workhorse of the library. It allows you to
// walk the tree in arbitrary ways (specified by `walkMethod`), and
// execute `Callback` for every node in the order you specify.
Tree.prototype.walk = function (Callback, walkMethod, startNode) {
walkMethod = walkMethod || this.defaults.walk;
var _this, qs = [], recurList = [], tmpNode;
if (startNode) {
if (!this.containsNode(startNode)) {
throw new Error('startNode does not exist in the tree');
}
} else {
startNode = this.root();
}
// In `walkMethod`, `this` will be bound to the following
// object. To see how it's used, scan the built-in walk
// methods below. Briefly, the binding provides:
//
// * `queue`: Adds nodes to the end of the callback list.
// * `push`: Adds nodes to the front of the callback list.
// * `recurse`: Recurses immediately on the set of nodes.
// * `queueRecurse`: Adds a set of nodes to the end of a list of nodes to recurse on next.
_this = {
'queue': function (Nodes) {
qs = qs.concat(Nodes);
},
'push': function (Nodes) {
qs = Nodes.concat(qs);
},
'recurse': function (Nodes) {
_.each(Nodes, function (n) {
walkMethod.call(_this, n);
});
},
'queueRecurse': function (Nodes) {
recurList = recurList.concat(Nodes);
}
};
// Before executing any callbacks, an ordered list of nodes
// (`qs`) is generated. In some cases, `walkMethod` many not be
// able to evaluate all nodes in one pass, so `recurList` is
// used to track which nodes to visit in the next pass. It
// can take as many passes as required.
walkMethod.call(_this, startNode);
while (recurList.length > 0) {
tmpNode = recurList.shift();
walkMethod.call(_this, tmpNode);
}
// Finally, `Callback` is called for each node, in order.
_.each(qs, Callback);
};
// The is the implementation of the built-in depth-first,
// pre-order traversal algorithm. It is setup as the default walk
// method.
Tree.prototype.walk.dfpre = function (Node) {
this.queue(Node);
this.recurse(Node.children());
};
// Depth-first, post-order traversal algorithm.
Tree.prototype.walk.dfpost = function (Node) {
this.recurse(Node.children());
this.queue(Node);
};
// Breadth-first, pre-order traversal algorithm.
Tree.prototype.walk.bfpre = function (Node) {
if (!Node.parent()) {
this.queue([Node]);
}
this.queue(Node.children());
this.recurse(Node.children());
};
// Breadth-first, post-order traversal algorithm.
Tree.prototype.walk.bfpost = function (Node) {
if (!Node.parent()) {
this.push([Node]);
}
this.push(Node.children());
var rev = _.clone(Node.children());
rev.reverse();
this.queueRecurse(rev);
};
// Tests for equality of trees across clone
// lines. Returns `boolean`, whether trees share any clone
// lineage.
Tree.prototype.equals = function (otherTree) {
return (otherTree instanceof Tree) && this.__id === otherTree.__id;
};
// A shorthand method to test whether a `Node` exists in the
// `Tree`. `someNode` can be from any tree clone.
Tree.prototype.containsNode = function (someNode) {
return (this.findNode(someNode) instanceof Node);
};
// A shorthand method to test whether a node containing this data
// exists in the `Tree`.
Tree.prototype.containsData = function(someData) {
return (this.findNodeByData(someData) instanceof Node);
};
// Returns a new `Tree` created by
//
// * deleting the `movingNode`,
// * finding the destination parent node in the new `Tree` context, and
// * adding the `movingNode` as a child
Tree.prototype.moveNode = function (movingNode, toParent) {
return this.batch()
.findNode(movingNode).remove()
.findNode(toParent)
.addChildNode(movingNode)
.end();
};
// Registers callbacks for tree events. Currently, `event` can
// only be 'afterUpdate', and `callback` can either be a single
// function or an array of functions.
//
// Note that adding callbacks generates a new tree, much as any
// other tree modification
Tree.prototype.on = function(event, callback) {
var newTree, cb;
newTree = Tree.clone(this);
cb = _.isArray(callback) ? callback : [callback];
newTree.defaults.callbacks[event] = newTree.defaults.callbacks[event].concat(cb);
__preFinalizeTree(newTree);
__callback(newTree, 'beforeFreeze');
__finalizeMutableTreeClone(newTree);
return newTree;
};
// Unregisters callbacks for tree events. Currently, `event` can
// only be 'afterUpdate', and `callback` can either be a single
// function or an array of functions. This also generates a new
// tree.
Tree.prototype.off = function(event, callback) {
var newTree, cb;
newTree = Tree.clone(this);
cb = _.isArray(callback) ? callback : [callback];
newTree.defaults.callbacks[event] = _.partial(_.without, newTree.defaults.callbacks[event]).apply(_, cb);
__preFinalizeTree(newTree);
__callback(newTree, 'beforeFreeze');
__finalizeMutableTreeClone(newTree);
return newTree;
};
// Adds mixin properties and functions to the tree. These mixins
// are preserved across all tree operations. Be careful, you can
// overwrite core _tree methods with mixins. No effort is made to
// protect you there. Namespacing your mixins is probably good
// practice.
Tree.prototype.mixin = function(mixin) {
var newTree;
newTree = Tree.clone(this);
Eif (!_.contains(newTree.defaults.mixins, mixin)) {
newTree.defaults.mixins.push(mixin);
}
__preFinalizeTree(newTree);
__callback(newTree, 'beforeFreeze');
__finalizeMutableTreeClone(newTree);
return newTree;
};
Tree.prototype.batch = function() {
var batchTree;
batchTree = Tree.clone(this);
batchTree.__batch++;
__preFinalizeTree(batchTree);
return batchTree;
};
Tree.prototype.isBatch = function() {
return this.__batch > 0;
};
Tree.prototype.end = function() {
Iif (!this.isBatch()) {
throw 'Called `tree.end` when not in batch mode.';
}
this.__batch--;
Eif (!this.isBatch()) {
__finalizeMutableTreeClone(this);
}
return this;
};
// # Node
// This defines the `Node` constructor, and much like `Tree`, the
// resulting object is mutable until just before being exposed to
// the external world.
Node = function (tree) {
try {
Object.defineProperties(this, {
'__tree': {
value: tree,
writable: true,
enumerable: false,
configurable: false
},
'__data': {
writable: true,
enumerable: false,
configurable: false
},
'__children': {
value: [],
writable: true,
enumerable: false,
configurable: false
},
'__id': {
value: tree.__nextNodeId,
writable: true,
enumerable: false,
configurable: false
}
});
} catch (e) {
this.__tree = tree;
this.__data = undefined;
this.__children = [];
this.__id = tree.__nextNodeId;
}
tree.__nextNodeId = tree.__nextNodeId + 1;
};
// A static copy constructor for `Node` objects, much like
// `Tree.clone`, but recursive. All child nodes are cloned as
// well.
Node.clone = function (newTree, node, differentId) {
var newNode = new Node(newTree);
newNode.__data = node.__data;
newNode.__children = _.map(node.children(), function(c) { return Node.clone(newTree, c, differentId); });
_.each(newNode.__children, function(c) {c.__parent = newNode;});
if (!differentId) {
newNode.__id = node.__id;
newTree.__nextNodeId--;
}
return newNode;
};
// The `Node.data` method is both a getter and setter, depending
// on how it's used.
//
// If `Obj` isn't submitted, it's used as a getter.
//
// Otherwise, it's used as a setter. Setting the data on a node
// triggers the creation of a complete tree clone. Modifications
// are done to the mutable clone, and the entire tree is returned
// after being made immutable.
Node.prototype.data = function (Obj) {
if (!Obj) {
return this.__data;
}
var newTree, newNode;
if (this.tree().isBatch()) {
this.__data = Obj;
return this.tree();
}
newTree = Tree.clone(this.tree());
newNode = newTree.findNode(this);
newNode.__data = Obj;
__preFinalizeTree(newTree);
__callback(newTree, 'beforeFreeze');
__callback(newTree, 'beforeFreeze.data', newNode);
__finalizeMutableTreeClone(newTree);
return newTree;
};
// A simple getter for node children.
Node.prototype.children = function () {
return this.__children;
};
// A simple getter for the node's parent. Returns `undefined` if
// no parent is set.
Node.prototype.parent = function () {
return this.__parent;
};
// A simple getter for the node's tree. `_tree` is intended for
// internal use. Presumably, client code will know which tree a
// node is in, but it may be useful to client code.
Node.prototype.tree = function () {
return this.__tree;
};
// A simple getter for the node's id. `__id` is intended for
// internal use, but may also be valuable to client code.
Node.prototype.id = function () {
return this.__id;
};
// To add a child node, an object representing the node data is
// parsed as if it were a new tree and then appended to the end of
// the children array. Remember that a newly-cloned tree is
// returned, *not* a `Node`.
Node.prototype.parseAndAddChild = function (childObj, inflateMethod) {
inflateMethod = inflateMethod || this.__tree.defaults.inflate;
var childTree, newTree, newNode, tree;
tree = this.tree();
childTree = new Tree(tree.defaults, childObj, inflateMethod, tree.__nextNodeId);
if (tree.isBatch()) {
this.__children.push(childTree.root());
tree.__nextNodeId = childTree.__nextNodeId;
__preFinalizeTree(tree);
return tree;
}
newTree = Tree.clone(tree);
newNode = newTree.findNode(this);
newNode.__children.push(childTree.root());
newTree.__nextNodeId = childTree.__nextNodeId;
__preFinalizeTree(newTree);
__callback(newTree, 'beforeFreeze');
__callback(newTree, 'beforeFreeze.parseAndAddChild', childTree.root());
__finalizeMutableTreeClone(newTree);
return newTree;
};
Node.prototype.addChildNode = function(node) {
var newTree, newParentNode, nodeClone;
if (this.tree().isBatch()) {
nodeClone = Node.clone(this.tree(), node, true);
this.__children.push(nodeClone);
__preFinalizeTree(this.tree());
return this.tree();
}
newTree = Tree.clone(this.tree());
newParentNode = newTree.findNode(this);
newTree.__nextNodeId = this.tree().__nextNodeId;
nodeClone = Node.clone(newTree, node, true);
newParentNode.__children.push(nodeClone);
__preFinalizeTree(newTree);
__callback(newTree, 'beforeFreeze');
__callback(newTree, 'beforeFreeze.addChildNode', nodeClone);
__finalizeMutableTreeClone(newTree);
return newTree;
};
// `Node.equals` works across clone lines, determining if both
// nodes *represent* the same node regardless of whether they're
// the same object in memory.
Node.prototype.equals = function(otherNode) {
return this.__tree.equals(otherNode.__tree) &&
this.__id === otherNode.__id;
};
Node.prototype.remove = function () {
if (this === this.tree().root()) {
throw new Error('cannot delete the root node');
}
var newTree, newNode, parNode;
if (this.tree().isBatch()) {
parNode = this.parent();
parNode.__children = _.without(parNode.__children, this);
__preFinalizeTree(this.tree());
return parNode.tree();
}
newTree = Tree.clone(this.__tree);
newNode = newTree.findNode(this);
parNode = newTree.findNode(this.__parent);
parNode.__children = _.without(parNode.__children, newNode);
__preFinalizeTree(newTree);
__callback(newTree, 'beforeFreeze');
__callback(newTree, 'beforeFreeze.remove', parNode);
__finalizeMutableTreeClone(newTree);
return newTree;
};
// removes all immediate children of this node specified in
// `kidsToRemove`.
Node.prototype.removeAll = function (kidsToRemove) {
var tree, self, newTree, newNode, newKids;
tree = this.tree();
self = this;
if (this.tree().isBatch()) {
newKids = _.map(kidsToRemove, function(k) {
return tree.findNode(k, undefined, self);
});
this.__children = _.difference(this.__children, newKids);
__preFinalizeTree(this.tree());
return this.tree();
}
newTree = Tree.clone(this.__tree);
newNode = newTree.findNode(this);
newKids = _.map(kidsToRemove, function(k) {
return newTree.findNode(k, undefined, newNode);
});
newNode.__children = _.difference(newNode.__children, newKids);
__preFinalizeTree(newTree);
__callback(newTree, 'beforeFreeze');
__callback(newTree, 'beforeFreeze.removeAll', newNode);
__finalizeMutableTreeClone(newTree);
return newTree;
};
// Finally, we setup some library-wide defaults.
__defaults = {
'inflate': _tree.inflate.byKey(),
'walk': Tree.prototype.walk.dfpre,
'deleteRecursive': true,
'callbacks': {'afterUpdate': [],
'beforeFreeze': [],
'beforeFreeze.data': [],
'beforeFreeze.parseAndAddChild': [],
'beforeFreeze.addChildNode': [],
'beforeFreeze.remove': []
},
'mixins': []
};
// And we're done.
return _tree;
}));
|