Debian Codegraph @

lib/Devel/NYTProf/js/jit/jit.js

raw
1 (function () {
2
3 /*
4 File: Core.js
5
6 Description:
7
8 Provides common utility functions and the Class object used internally by the library.
9
10 Also provides the <TreeUtil> object for manipulating JSON tree structures
11
12 Some of the Basic utility functions and the Class system are based in the MooTools Framework <http://mootools.net>. Copyright (c) 2006-2009 Valerio Proietti, <http://mad4milk.net/>. MIT license <http://mootools.net/license.txt>.
13
14 Author:
15
16 Nicolas Garcia Belmonte
17
18 Copyright:
19
20 Copyright 2008-2009 by Nicolas Garcia Belmonte.
21
22 Homepage:
23
24 <http://thejit.org>
25
26 Version:
27
28 1.1.3
29
30 License:
31
32 BSD License
33
34 > Redistribution and use in source and binary forms, with or without
35 > modification, are permitted provided that the following conditions are met:
36 > * Redistributions of source code must retain the above copyright
37 > notice, this list of conditions and the following disclaimer.
38 > * Redistributions in binary form must reproduce the above copyright
39 > notice, this list of conditions and the following disclaimer in the
40 > documentation and/or other materials provided with the distribution.
41 > * Neither the name of the organization nor the
42 > names of its contributors may be used to endorse or promote products
43 > derived from this software without specific prior written permission.
44 >
45 > THIS SOFTWARE IS PROVIDED BY Nicolas Garcia Belmonte ``AS IS'' AND ANY
46 > EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
47 > WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
48 > DISCLAIMED. IN NO EVENT SHALL Nicolas Garcia Belmonte BE LIABLE FOR ANY
49 > DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
50 > (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
51 > LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
52 > ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
53 > (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
54 > SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
55 */
56
57
58 function $empty() {};
59
60 function $extend(original, extended){
61 for (var key in (extended || {})) original[key] = extended[key];
62 return original;
63 };
64
65 function $lambda(value){
66 return (typeof value == 'function') ? value : function(){
67 return value;
68 };
69 };
70
71 var $time = Date.now || function(){
72 return +new Date;
73 };
74
75 function $splat(obj){
76 var type = $type(obj);
77 return (type) ? ((type != 'array') ? [obj] : obj) : [];
78 };
79
80 var $type = function(elem) {
81 return $type.s.call(elem).match(/^\[object\s(.*)\]$/)[1].toLowerCase();
82 };
83 $type.s = Object.prototype.toString;
84
85 function $each(iterable, fn){
86 var type = $type(iterable);
87 if(type == 'object') {
88 for (var key in iterable) fn(iterable[key], key);
89 } else {
90 for(var i=0; i < iterable.length; i++) fn(iterable[i], i);
91 }
92 };
93
94 function $merge(){
95 var mix = {};
96 for (var i = 0, l = arguments.length; i < l; i++){
97 var object = arguments[i];
98 if ($type(object) != 'object') continue;
99 for (var key in object){
100 var op = object[key], mp = mix[key];
101 mix[key] = (mp && $type(op) == 'object' && $type(mp) == 'object') ? $merge(mp, op) : $unlink(op);
102 }
103 }
104 return mix;
105 };
106
107 function $unlink(object){
108 var unlinked;
109 switch ($type(object)){
110 case 'object':
111 unlinked = {};
112 for (var p in object) unlinked[p] = $unlink(object[p]);
113 break;
114 case 'array':
115 unlinked = [];
116 for (var i = 0, l = object.length; i < l; i++) unlinked[i] = $unlink(object[i]);
117 break;
118 default: return object;
119 }
120 return unlinked;
121 };
122
123 function $rgbToHex(srcArray, array){
124 if (srcArray.length < 3) return null;
125 if (srcArray.length == 4 && srcArray[3] == 0 && !array) return 'transparent';
126 var hex = [];
127 for (var i = 0; i < 3; i++){
128 var bit = (srcArray[i] - 0).toString(16);
129 hex.push((bit.length == 1) ? '0' + bit : bit);
130 }
131 return (array) ? hex : '#' + hex.join('');
132 };
133
134 function $destroy(elem) {
135 $clean(elem);
136 if(elem.parentNode) elem.parentNode.removeChild(elem);
137 if(elem.clearAttributes) elem.clearAttributes();
138 };
139
140 function $clean(elem) {
141 for(var ch = elem.childNodes, i=0; i < ch.length; i++) {
142 $destroy(ch[i]);
143 }
144 };
145
146 function $addEvent(obj, type, fn) {
147 if (obj.addEventListener)
148 obj.addEventListener(type, fn, false);
149 else
150 obj.attachEvent('on' + type, fn);
151 };
152
153 function $hasClass(obj, klass) {
154 return (' ' + obj.className + ' ').indexOf(' ' + klass + ' ') > -1;
155 };
156
157 function $addClass(obj, klass) {
158 if(!$hasClass(obj, klass)) obj.className = (obj.className + " " + klass);
159 };
160
161 function $removeClass(obj, klass) {
162 obj.className = obj.className.replace(new RegExp('(^|\\s)' + klass + '(?:\\s|$)'), '$1');
163 };
164
165 function $get(id) {
166 return document.getElementById(id);
167 };
168
169 var Class = function(properties){
170 properties = properties || {};
171 var klass = function(){
172 // not defining any attributes in Class properties.
173 // for (var key in this){
174 // if (typeof this[key] != 'function') this[key] = $unlink(this[key]);
175 // }
176 this.constructor = klass;
177 if (Class.prototyping) return this;
178 var instance = (this.initialize) ? this.initialize.apply(this, arguments) : this;
179 return instance;
180 };
181
182 for (var mutator in Class.Mutators){
183 if (!properties[mutator]) continue;
184 properties = Class.Mutators[mutator](properties, properties[mutator]);
185 delete properties[mutator];
186 }
187
188 $extend(klass, this);
189 klass.constructor = Class;
190 klass.prototype = properties;
191 return klass;
192 };
193
194 Class.Mutators = {
195
196 Extends: function(self, klass){
197 Class.prototyping = klass.prototype;
198 var subclass = new klass;
199 delete subclass.parent;
200 subclass = Class.inherit(subclass, self);
201 delete Class.prototyping;
202 return subclass;
203 },
204
205 Implements: function(self, klasses){
206 $each($splat(klasses), function(klass){
207 Class.prototying = klass;
208 $extend(self, ($type(klass) == 'function') ? new klass : klass);
209 delete Class.prototyping;
210 });
211 return self;
212 }
213
214 };
215
216 $extend(Class, {
217
218 inherit: function(object, properties){
219 var caller = arguments.callee.caller;
220 for (var key in properties){
221 var override = properties[key];
222 var previous = object[key];
223 var type = $type(override);
224 if (previous && type == 'function'){
225 if (override != previous){
226 if (caller){
227 override.__parent = previous;
228 object[key] = override;
229 } else {
230 Class.override(object, key, override);
231 }
232 }
233 } else if(type == 'object'){
234 object[key] = $merge(previous, override);
235 } else {
236 object[key] = override;
237 }
238 }
239
240 if (caller) object.parent = function(){
241 return arguments.callee.caller.__parent.apply(this, arguments);
242 };
243
244 return object;
245 },
246
247 override: function(object, name, method){
248 var parent = Class.prototyping;
249 if (parent && object[name] != parent[name]) parent = null;
250 var override = function(){
251 var previous = this.parent;
252 this.parent = parent ? parent[name] : object[name];
253 var value = method.apply(this, arguments);
254 this.parent = previous;
255 return value;
256 };
257 object[name] = override;
258 }
259
260 });
261
262
263 Class.prototype.implement = function(){
264 var proto = this.prototype;
265 $each(Array.prototype.slice.call(arguments || []), function(properties){
266 Class.inherit(proto, properties);
267 });
268 return this;
269 };
270
271 /*
272 Object: TreeUtil
273
274 Some common JSON tree manipulation methods.
275 */
276 this.TreeUtil = {
277
278 /*
279 Method: prune
280
281 Clears all tree nodes having depth greater than maxLevel.
282
283 Parameters:
284
285 tree - A JSON tree object. For more information please see <Loader.loadJSON>.
286 maxLevel - An integer specifying the maximum level allowed for this tree. All nodes having depth greater than max level will be deleted.
287
288 */
289 prune: function(tree, maxLevel) {
290 this.each(tree, function(elem, i) {
291 if(i == maxLevel && elem.children) {
292 delete elem.children;
293 elem.children = [];
294 }
295 });
296 },
297
298 /*
299 Method: getParent
300
301 Returns the parent node of the node having _id_ as id.
302
303 Parameters:
304
305 tree - A JSON tree object. See also <Loader.loadJSON>.
306 id - The _id_ of the child node whose parent will be returned.
307
308 Returns:
309
310 A tree JSON node if any, or false otherwise.
311
312 */
313 getParent: function(tree, id) {
314 if(tree.id == id) return false;
315 var ch = tree.children;
316 if(ch && ch.length > 0) {
317 for(var i=0; i<ch.length; i++) {
318 if(ch[i].id == id)
319 return tree;
320 else {
321 var ans = this.getParent(ch[i], id);
322 if(ans) return ans;
323 }
324 }
325 }
326 return false;
327 },
328
329 /*
330 Method: getSubtree
331
332 Returns the subtree that matches the given id.
333
334 Parameters:
335
336 tree - A JSON tree object. See also <Loader.loadJSON>.
337 id - A node *unique* identifier.
338
339 Returns:
340
341 A subtree having a root node matching the given id. Returns null if no subtree matching the id is found.
342
343 */
344 getSubtree: function(tree, id) {
345 if(tree.id == id) return tree;
346 for(var i=0, ch=tree.children; i<ch.length; i++) {
347 var t = this.getSubtree(ch[i], id);
348 if(t != null) return t;
349 }
350 return null;
351 },
352
353 /*
354 Method: getLeaves
355
356 Returns the leaves of the tree.
357
358 Parameters:
359
360 node - A JSON tree node. See also <Loader.loadJSON>.
361 maxLevel - _optional_ A subtree's max level.
362
363 Returns:
364
365 An array having objects with two properties.
366
367 - The _node_ property contains the leaf node.
368 - The _level_ property specifies the depth of the node.
369
370 */
371 getLeaves: function (node, maxLevel) {
372 var leaves = [], levelsToShow = maxLevel || Number.MAX_VALUE;
373 this.each(node, function(elem, i) {
374 if(i < levelsToShow &&
375 (!elem.children || elem.children.length == 0 )) {
376 leaves.push({
377 'node':elem,
378 'level':levelsToShow - i
379 });
380 }
381 });
382 return leaves;
383 },
384
385
386 /*
387 Method: eachLevel
388
389 Iterates on tree nodes with relative depth less or equal than a specified level.
390
391 Parameters:
392
393 tree - A JSON tree or subtree. See also <Loader.loadJSON>.
394 initLevel - An integer specifying the initial relative level. Usually zero.
395 toLevel - An integer specifying a top level. This method will iterate only through nodes with depth less than or equal this number.
396 action - A function that receives a node and an integer specifying the actual level of the node.
397
398 Example:
399 (start code js)
400 TreeUtil.eachLevel(tree, 0, 3, function(node, depth) {
401 alert(node.name + ' ' + depth);
402 });
403 (end code)
404 */
405 eachLevel: function(tree, initLevel, toLevel, action) {
406 if(initLevel <= toLevel) {
407 action(tree, initLevel);
408 for(var i=0, ch = tree.children; i<ch.length; i++) {
409 this.eachLevel(ch[i], initLevel +1, toLevel, action);
410 }
411 }
412 },
413
414 /*
415 Method: each
416
417 A tree iterator.
418
419 Parameters:
420
421 tree - A JSON tree or subtree. See also <Loader.loadJSON>.
422 action - A function that receives a node.
423
424 Example:
425 (start code js)
426 TreeUtil.each(tree, function(node) {
427 alert(node.name);
428 });
429 (end code)
430
431 */
432 each: function(tree, action) {
433 this.eachLevel(tree, 0, Number.MAX_VALUE, action);
434 },
435
436 /*
437 Method: loadSubtrees
438
439 Appends subtrees to leaves by requesting new subtrees
440 with the _request_ method.
441
442 Parameters:
443
444 tree - A JSON tree node. <Loader.loadJSON>.
445 controller - An object that implements a request method.
446
447 Example:
448 (start code js)
449 TreeUtil.loadSubtrees(leafNode, {
450 request: function(nodeId, level, onComplete) {
451 //Pseudo-code to make an ajax request for a new subtree
452 // that has as root id _nodeId_ and depth _level_ ...
453 Ajax.request({
454 'url': 'http://subtreerequesturl/',
455
456 onSuccess: function(json) {
457 onComplete.onComplete(nodeId, json);
458 }
459 });
460 }
461 });
462 (end code)
463 */
464 loadSubtrees: function(tree, controller) {
465 var maxLevel = controller.request && controller.levelsToShow;
466 var leaves = this.getLeaves(tree, maxLevel),
467 len = leaves.length,
468 selectedNode = {};
469 if(len == 0) controller.onComplete();
470 for(var i=0, counter=0; i<len; i++) {
471 var leaf = leaves[i], id = leaf.node.id;
472 selectedNode[id] = leaf.node;
473 controller.request(id, leaf.level, {
474 onComplete: function(nodeId, tree) {
475 var ch = tree.children;
476 selectedNode[nodeId].children = ch;
477 if(++counter == len) {
478 controller.onComplete();
479 }
480 }
481 });
482 }
483 }
484 };
485
486
487
488 /*
489 * File: Canvas.js
490 *
491 * A cross browser Canvas widget.
492 *
493 * Used By:
494 *
495 * <ST>, <Hypertree>, <RGraph>
496 */
497 /*
498 Class: Canvas
499
500 A multi-purpose Canvas Class. This Class can be used with the ExCanvas library to provide
501 cross browser Canvas based visualizations.
502
503 Parameters:
504
505 id - The canvas id. This id will be used as prefix for the canvas widget DOM elements ids.
506 options - An object containing multiple options such as
507
508 - _injectInto_ This property is _required_ and it specifies the id of the DOM element
509 to which the Canvas widget will be appended
510 - _width_ The width of the Canvas widget. Default's to 200px
511 - _height_ The height of the Canvas widget. Default's to 200px
512 - _backgroundColor_ Used for compatibility with IE. The canvas' background color.
513 Default's to '#333'
514 - _styles_ A hash containing canvas specific style properties such as _fillStyle_ and _strokeStyle_ among others.
515
516 Example:
517
518 Suppose we have this HTML
519
520 (start code xml)
521 <div id="infovis"></div>
522 (end code)
523
524 Now we create a new Canvas instance
525
526 (start code js)
527 //Create a new canvas instance
528 var canvas = new Canvas('mycanvas', {
529 //Where to inject the canvas. Any div container will do.
530 'injectInto':'infovis',
531 //width and height for canvas. Default's to 200.
532 'width': 900,
533 'height':500,
534 //Canvas styles
535 'styles': {
536 'fillStyle': '#ccddee',
537 'strokeStyle': '#772277'
538 }
539 });
540 (end code)
541
542 The generated HTML will look like this
543
544 (start code xml)
545 <div id="infovis">
546 <div id="mycanvas" style="position:relative;">
547 <canvas id="mycanvas-canvas" width=900 height=500
548 style="position:absolute; top:0; left:0; width:900px; height:500px;" />
549 <div id="mycanvas-label"
550 style="overflow:visible; position:absolute; top:0; left:0; width:900px; height:0px">
551 </div>
552 </div>
553 </div>
554 (end code)
555
556 As you can see, the generated HTML consists of a canvas DOM element of id _mycanvas-canvas_ and a div label container
557 of id _mycanvas-label_, wrapped in a main div container of id _mycanvas_.
558 You can also add a background canvas, for making background drawings.
559 This is how the <RGraph> background concentric circles are drawn
560
561 Example:
562
563 (start code js)
564 //Create a new canvas instance.
565 var canvas = new Canvas('mycanvas', {
566 //Where to inject the canvas. Any div container will do.
567 'injectInto':'infovis',
568 //width and height for canvas. Default's to 200.
569 'width': 900,
570 'height':500,
571 //Canvas styles
572 'styles': {
573 'fillStyle': '#ccddee',
574 'strokeStyle': '#772277'
575 },
576 //Add a background canvas for plotting
577 //concentric circles.
578 'backgroundCanvas': {
579 //Add Canvas styles for the bck canvas.
580 'styles': {
581 'fillStyle': '#444',
582 'strokeStyle': '#444'
583 },
584 //Add the initialization and plotting functions.
585 'impl': {
586 'init': function() {},
587 'plot': function(canvas, ctx) {
588 var times = 6, d = 100;
589 var pi2 = Math.PI*2;
590 for(var i=1; i<=times; i++) {
591 ctx.beginPath();
592 ctx.arc(0, 0, i * d, 0, pi2, true);
593 ctx.stroke();
594 ctx.closePath();
595 }
596 }
597 }
598 }
599 });
600 (end code)
601
602 The _backgroundCanvas_ object contains a canvas _styles_ property and
603 an _impl_ key to be used for implementing background canvas specific code.
604
605 The _init_ method is only called once, at the instanciation of the background canvas.
606 The _plot_ method is called for plotting a Canvas image.
607 */
608 this.Canvas = (function(){
609 var config = {
610 'injectInto': 'id',
611
612 'width': 200,
613 'height': 200,
614 //deprecated
615 'backgroundColor': '#333333',
616
617 'styles': {
618 'fillStyle': '#000000',
619 'strokeStyle': '#000000'
620 },
621
622 'backgroundCanvas': false
623 };
624
625 function hasCanvas(){
626 hasCanvas.t = hasCanvas.t || typeof(HTMLCanvasElement);
627 return "function" == hasCanvas.t || "object" == hasCanvas.t;
628 };
629
630 function create(tag, prop, styles){
631 var elem = document.createElement(tag);
632 (function(obj, prop){
633 if (prop) {
634 for (var p in prop) {
635 obj[p] = prop[p];
636 }
637 }
638 return arguments.callee;
639 })(elem, prop)(elem.style, styles);
640 //feature check
641 if (tag == "canvas" && !hasCanvas() && G_vmlCanvasManager) {
642 elem = G_vmlCanvasManager.initElement(document.body.appendChild(elem));
643 }
644
645 return elem;
646 };
647
648 function get(id){
649 return document.getElementById(id);
650 };
651
652 function translateToCenter(canvas, ctx, w, h){
653 var width = w ? (canvas.width - w) : canvas.width;
654 var height = h ? (canvas.height - h) : canvas.height;
655 ctx.translate(width / 2, height / 2);
656 };
657
658 return function(id, opt){
659 var ctx, bkctx, mainContainer, labelContainer, canvas, bkcanvas;
660 if (arguments.length < 1)
661 throw "Arguments missing";
662 var idLabel = id + "-label", idCanvas = id + "-canvas", idBCanvas = id + "-bkcanvas";
663 opt = $merge(config, opt || {});
664 //create elements
665 var dim = {
666 'width': opt.width,
667 'height': opt.height
668 };
669 mainContainer = create("div", {
670 'id': id
671 }, $merge(dim, {
672 'position': 'relative'
673 }));
674 labelContainer = create("div", {
675 'id': idLabel
676 }, {
677 'overflow': 'visible',
678 'position': 'absolute',
679 'top': 0,
680 'left': 0,
681 'width': dim.width + 'px',
682 'height': 0
683 });
684 var dimPos = {
685 'position': 'absolute',
686 'top': 0,
687 'left': 0,
688 'width': dim.width + 'px',
689 'height': dim.height + 'px'
690 };
691 canvas = create("canvas", $merge({
692 'id': idCanvas
693 }, dim), dimPos);
694 var bc = opt.backgroundCanvas;
695 if (bc) {
696 bkcanvas = create("canvas", $merge({
697 'id': idBCanvas
698 }, dim), dimPos);
699 //append elements
700 mainContainer.appendChild(bkcanvas);
701 }
702 mainContainer.appendChild(canvas);
703 mainContainer.appendChild(labelContainer);
704 get(opt.injectInto).appendChild(mainContainer);
705
706 //create contexts
707 ctx = canvas.getContext('2d');
708 translateToCenter(canvas, ctx);
709 var st = opt.styles;
710 var s;
711 for (s in st)
712 ctx[s] = st[s];
713 if (bc) {
714 bkctx = bkcanvas.getContext('2d');
715 st = bc.styles;
716 for (s in st) {
717 bkctx[s] = st[s];
718 }
719 translateToCenter(bkcanvas, bkctx);
720 bc.impl.init(bkcanvas, bkctx);
721 bc.impl.plot(bkcanvas, bkctx);
722 }
723 //create methods
724 return {
725 'id': id,
726 /*
727 Method: getCtx
728
729 Returns the main canvas context object
730
731 Returns:
732
733 Main canvas context
734
735 Example:
736
737 (start code js)
738 var ctx = canvas.getCtx();
739 //Now I can use the native canvas context
740 //and for example change some canvas styles
741 ctx.globalAlpha = 1;
742 (end code)
743 */
744 getCtx: function(){
745 return ctx;
746 },
747
748 /*
749 Method: getElement
750 Returns the main Canvas DOM wrapper
751
752 Returns:
753 DOM canvas wrapper generated, (i.e the div wrapper element with id _mycanvas_)
754
755 Example:
756 (start code js)
757 var wrapper = canvas.getElement();
758 //Returns <div id="mycanvas" ... >...</div> as element
759 (end code)
760 */
761 getElement: function(){
762 return mainContainer;
763 },
764
765 /*
766 Method: resize
767
768 Resizes the canvas.
769
770 Parameters:
771
772 width - New canvas width.
773 height - New canvas height.
774
775 This method can be used with the <ST>, <Hypertree> or <RGraph> visualizations to resize
776 the visualizations
777
778 Example:
779
780 (start code js)
781 function resizeViz(width, height) {
782 canvas.resize(width, height);
783 rgraph.refresh(); //ht.refresh or st.refresh() also work.
784 rgraph.onAfterCompute();
785 }
786 (end code)
787
788 */
789 resize: function(width, height){
790 var pwidth = canvas.width, pheight = canvas.height;
791 canvas.width = width;
792 canvas.height = height;
793 canvas.style.width = width + "px";
794 canvas.style.height = height + "px";
795 if (bc) {
796 bkcanvas.width = width;
797 bkcanvas.height = height;
798 bkcanvas.style.width = width + "px";
799 bkcanvas.style.height = height + "px";
800 }
801 //small ExCanvas fix
802 if(!hasCanvas()) {
803 translateToCenter(canvas, ctx, pwidth, pheight);
804 } else {
805 translateToCenter(canvas, ctx);
806 }
807
808 var st = opt.styles;
809 var s;
810 for (s in st) {
811 ctx[s] = st[s];
812 }
813 if (bc) {
814 st = bc.styles;
815 for (s in st)
816 bkctx[s] = st[s];
817 //same ExCanvas fix here
818 if(!hasCanvas()) {
819 translateToCenter(bkcanvas, bkctx, pwidth, pheight);
820 } else {
821 translateToCenter(bkcanvas, bkctx);
822 }
823
824 bc.impl.init(bkcanvas, bkctx);
825 bc.impl.plot(bkcanvas, bkctx);
826 }
827 },
828
829 /*
830 Method: getSize
831
832 Returns canvas dimensions.
833
834 Returns:
835
836 An object with _width_ and _height_ properties.
837 Example:
838 (start code js)
839 canvas.getSize(); //returns { width: 900, height: 500 }
840 (end code)
841 */
842 getSize: function(){
843 return {
844 'width': canvas.width,
845 'height': canvas.height
846 };
847 },
848
849 path: function(type, action){
850 ctx.beginPath();
851 action(ctx);
852 ctx[type]();
853 ctx.closePath();
854 },
855
856 /*
857 Method: clear
858
859 Clears the canvas object.
860 */
861 clear: function(){
862 var size = this.getSize();
863 ctx.clearRect(-size.width / 2, -size.height / 2, size.width, size.height);
864 },
865
866 /*
867 Method: clearReactangle
868
869 Same as <Canvas.clear> but only clears a section of the canvas.
870
871 Parameters:
872
873 top - An integer specifying the top of the rectangle.
874 right - An integer specifying the right of the rectangle.
875 bottom - An integer specifying the bottom of the rectangle.
876 left - An integer specifying the left of the rectangle.
877 */
878 clearRectangle: function(top, right, bottom, left){
879 //if using excanvas
880 if (!hasCanvas()) {
881 var f0 = ctx.fillStyle;
882 ctx.fillStyle = opt.backgroundColor;
883 ctx.fillRect(left, top, Math.abs(right - left), Math.abs(bottom - top));
884 ctx.fillStyle = f0;
885 }
886 else {
887 ctx.clearRect(left, top, Math.abs(right - left), Math.abs(bottom - top));
888 }
889 }
890 };
891 };
892
893 })();
894
895
896
897 /*
898 * File: Polar.js
899 *
900 * Defines the <Polar> class.
901 *
902 * Description:
903 *
904 * The <Polar> class, just like the <Complex> class, is used by the <Hypertree>, <ST> and <RGraph> as a 2D point representation.
905 *
906 * See also:
907 *
908 * <http://en.wikipedia.org/wiki/Polar_coordinates>
909 *
910 */
911
912 /*
913 Class: Polar
914
915 A multi purpose polar representation.
916
917 Description:
918
919 The <Polar> class, just like the <Complex> class, is used by the <Hypertree>, <ST> and <RGraph> as a 2D point representation.
920
921 See also:
922
923 <http://en.wikipedia.org/wiki/Polar_coordinates>
924
925 Parameters:
926
927 theta - An angle.
928 rho - The norm.
929 */
930
931 this.Polar = function(theta, rho) {
932 this.theta = theta;
933 this.rho = rho;
934 };
935
936 Polar.prototype = {
937 /*
938 Method: getc
939
940 Returns a complex number.
941
942 Parameters:
943
944 simple - _optional_ If *true*, this method will return only an object holding x and y properties and not a <Complex> instance. Default's *false*.
945
946 Returns:
947
948 A complex number.
949 */
950 getc: function(simple) {
951 return this.toComplex(simple);
952 },
953
954 /*
955 Method: getp
956
957 Returns a <Polar> representation.
958
959 Returns:
960
961 A variable in polar coordinates.
962 */
963 getp: function() {
964 return this;
965 },
966
967
968 /*
969 Method: set
970
971 Sets a number.
972
973 Parameters:
974
975 v - A <Complex> or <Polar> instance.
976
977 */
978 set: function(v) {
979 v = v.getp();
980 this.theta = v.theta; this.rho = v.rho;
981 },
982
983 /*
984 Method: setc
985
986 Sets a <Complex> number.
987
988 Parameters:
989
990 x - A <Complex> number real part.
991 y - A <Complex> number imaginary part.
992
993 */
994 setc: function(x, y) {
995 this.rho = Math.sqrt(x * x + y * y);
996 this.theta = Math.atan2(y, x);
997 if(this.theta < 0) this.theta += Math.PI * 2;
998 },
999
1000 /*
1001 Method: setp
1002
1003 Sets a polar number.
1004
1005 Parameters:
1006
1007 theta - A <Polar> number angle property.
1008 rho - A <Polar> number rho property.
1009
1010 */
1011 setp: function(theta, rho) {
1012 this.theta = theta;
1013 this.rho = rho;
1014 },
1015
1016 /*
1017 Method: clone
1018
1019 Returns a copy of the current object.
1020
1021 Returns:
1022
1023 A copy of the real object.
1024 */
1025 clone: function() {
1026 return new Polar(this.theta, this.rho);
1027 },
1028
1029 /*
1030 Method: toComplex
1031
1032 Translates from polar to cartesian coordinates and returns a new <Complex> instance.
1033
1034 Parameters:
1035
1036 simple - _optional_ If *true* this method will only return an object with x and y properties (and not the whole <Complex> instance). Default's *false*.
1037
1038 Returns:
1039
1040 A new <Complex> instance.
1041 */
1042 toComplex: function(simple) {
1043 var x = Math.cos(this.theta) * this.rho;
1044 var y = Math.sin(this.theta) * this.rho;
1045 if(simple) return { 'x': x, 'y': y};
1046 return new Complex(x, y);
1047 },
1048
1049 /*
1050 Method: add
1051
1052 Adds two <Polar> instances.
1053
1054 Parameters:
1055
1056 polar - A <Polar> number.
1057
1058 Returns:
1059
1060 A new Polar instance.
1061 */
1062 add: function(polar) {
1063 return new Polar(this.theta + polar.theta, this.rho + polar.rho);
1064 },
1065
1066 /*
1067 Method: scale
1068
1069 Scales a polar norm.
1070
1071 Parameters:
1072
1073 number - A scale factor.
1074
1075 Returns:
1076
1077 A new Polar instance.
1078 */
1079 scale: function(number) {
1080 return new Polar(this.theta, this.rho * number);
1081 },
1082
1083 /*
1084 Method: equals
1085
1086 Comparison method.
1087
1088 Returns *true* if the theta and rho properties are equal.
1089
1090 Parameters:
1091
1092 c - A <Polar> number.
1093
1094 Returns:
1095
1096 *true* if the theta and rho parameters for these objects are equal. *false* otherwise.
1097 */
1098 equals: function(c) {
1099 return this.theta == c.theta && this.rho == c.rho;
1100 },
1101
1102 /*
1103 Method: $add
1104
1105 Adds two <Polar> instances affecting the current object.
1106
1107 Paramters:
1108
1109 polar - A <Polar> instance.
1110
1111 Returns:
1112
1113 The changed object.
1114 */
1115 $add: function(polar) {
1116 this.theta = this.theta + polar.theta; this.rho += polar.rho;
1117 return this;
1118 },
1119
1120 /*
1121 Method: $madd
1122
1123 Adds two <Polar> instances affecting the current object. The resulting theta angle is modulo 2pi.
1124
1125 Parameters:
1126
1127 polar - A <Polar> instance.
1128
1129 Returns:
1130
1131 The changed object.
1132 */
1133 $madd: function(polar) {
1134 this.theta = (this.theta + polar.theta) % (Math.PI * 2); this.rho += polar.rho;
1135 return this;
1136 },
1137
1138
1139 /*
1140 Method: $scale
1141
1142 Scales a polar instance affecting the object.
1143
1144 Parameters:
1145
1146 number - A scaling factor.
1147
1148 Returns:
1149
1150 The changed object.
1151 */
1152 $scale: function(number) {
1153 this.rho *= number;
1154 return this;
1155 },
1156
1157 /*
1158 Method: interpolate
1159
1160 Calculates a polar interpolation between two points at a given delta moment.
1161
1162 Parameters:
1163
1164 elem - A <Polar> instance.
1165 delta - A delta factor ranging [0, 1].
1166
1167 Returns:
1168
1169 A new <Polar> instance representing an interpolation between _this_ and _elem_
1170 */
1171 interpolate: function(elem, delta) {
1172 var pi = Math.PI, pi2 = pi * 2;
1173 var ch = function(t) {
1174 return (t < 0)? (t % pi2) + pi2 : t % pi2;
1175 };
1176 var tt = this.theta, et = elem.theta;
1177 var sum;
1178 if(Math.abs(tt - et) > pi) {
1179 if(tt > et) {
1180 sum =ch((et + ((tt - pi2) - et) * delta)) ;
1181 } else {
1182 sum =ch((et - pi2 + (tt - (et - pi2)) * delta));
1183 }
1184 } else {
1185 sum =ch((et + (tt - et) * delta)) ;
1186 }
1187 var r = (this.rho - elem.rho) * delta + elem.rho;
1188 return {
1189 'theta': sum,
1190 'rho': r
1191 };
1192 }
1193 };
1194
1195
1196 var $P = function(a, b) { return new Polar(a, b); };
1197
1198 Polar.KER = $P(0, 0);
1199
1200
1201
1202 /*
1203 * File: Complex.js
1204 *
1205 * Defines the <Complex> class.
1206 *
1207 * Description:
1208 *
1209 * The <Complex> class, just like the <Polar> class, is used by the <Hypertree>, <ST> and <RGraph> as a 2D point representation.
1210 *
1211 * See also:
1212 *
1213 * <http://en.wikipedia.org/wiki/Complex_number>
1214 *
1215 */
1216
1217 /*
1218 Class: Complex
1219
1220 A multi-purpose Complex Class with common methods.
1221
1222 Description:
1223
1224 The <Complex> class, just like the <Polar> class, is used by the <Hypertree>, <ST> and <RGraph> as a 2D point representation.
1225
1226 See also:
1227
1228 <http://en.wikipedia.org/wiki/Complex_number>
1229
1230 Parameters:
1231
1232 x - _optional_ A Complex number real part.
1233 y - _optional_ A Complex number imaginary part.
1234
1235 */
1236
1237 this.Complex = function(x, y) {
1238 this.x = x;
1239 this.y = y;
1240 };
1241
1242 Complex.prototype = {
1243 /*
1244 Method: getc
1245
1246 Returns a complex number.
1247
1248 Returns:
1249
1250 A complex number.
1251 */
1252 getc: function() {
1253 return this;
1254 },
1255
1256 /*
1257 Method: getp
1258
1259 Returns a <Polar> representation of this number.
1260
1261 Parameters:
1262
1263 simple - _optional_ If *true*, this method will return only an object holding theta and rho properties and not a <Polar> instance. Default's *false*.
1264
1265 Returns:
1266
1267 A variable in <Polar> coordinates.
1268 */
1269 getp: function(simple) {
1270 return this.toPolar(simple);
1271 },
1272
1273
1274 /*
1275 Method: set
1276
1277 Sets a number.
1278
1279 Parameters:
1280
1281 c - A <Complex> or <Polar> instance.
1282
1283 */
1284 set: function(c) {
1285 c = c.getc(true);
1286 this.x = c.x;
1287 this.y = c.y;
1288 },
1289
1290 /*
1291 Method: setc
1292
1293 Sets a complex number.
1294
1295 Parameters:
1296
1297 x - A <Complex> number Real part.
1298 y - A <Complex> number Imaginary part.
1299
1300 */
1301 setc: function(x, y) {
1302 this.x = x;
1303 this.y = y;
1304 },
1305
1306 /*
1307 Method: setp
1308
1309 Sets a polar number.
1310
1311 Parameters:
1312
1313 theta - A <Polar> number theta property.
1314 rho - A <Polar> number rho property.
1315
1316 */
1317 setp: function(theta, rho) {
1318 this.x = Math.cos(theta) * rho;
1319 this.y = Math.sin(theta) * rho;
1320 },
1321
1322 /*
1323 Method: clone
1324
1325 Returns a copy of the current object.
1326
1327 Returns:
1328
1329 A copy of the real object.
1330 */
1331 clone: function() {
1332 return new Complex(this.x, this.y);
1333 },
1334
1335 /*
1336 Method: toPolar
1337
1338 Transforms cartesian to polar coordinates.
1339
1340 Parameters:
1341
1342 simple - _optional_ If *true* this method will only return an object with theta and rho properties (and not the whole <Polar> instance). Default's *false*.
1343
1344 Returns:
1345
1346 A new <Polar> instance.
1347 */
1348
1349 toPolar: function(simple) {
1350 var rho = this.norm();
1351 var atan = Math.atan2(this.y, this.x);
1352 if(atan < 0) atan += Math.PI * 2;
1353 if(simple) return { 'theta': atan, 'rho': rho };
1354 return new Polar(atan, rho);
1355 },
1356 /*
1357 Method: norm
1358
1359 Calculates a <Complex> number norm.
1360
1361 Returns:
1362
1363 A real number representing the complex norm.
1364 */
1365 norm: function () {
1366 return Math.sqrt(this.squaredNorm());
1367 },
1368
1369 /*
1370 Method: squaredNorm
1371
1372 Calculates a <Complex> number squared norm.
1373
1374 Returns:
1375
1376 A real number representing the complex squared norm.
1377 */
1378 squaredNorm: function () {
1379 return this.x*this.x + this.y*this.y;
1380 },
1381
1382 /*
1383 Method: add
1384
1385 Returns the result of adding two complex numbers.
1386
1387 Does not alter the original object.
1388
1389 Parameters:
1390
1391 pos - A <Complex> instance.
1392
1393 Returns:
1394
1395 The result of adding two complex numbers.
1396 */
1397 add: function(pos) {
1398 return new Complex(this.x + pos.x, this.y + pos.y);
1399 },
1400
1401 /*
1402 Method: prod
1403
1404 Returns the result of multiplying two <Complex> numbers.
1405
1406 Does not alter the original object.
1407
1408 Parameters:
1409
1410 pos - A <Complex> instance.
1411
1412 Returns:
1413
1414 The result of multiplying two complex numbers.
1415 */
1416 prod: function(pos) {
1417 return new Complex(this.x*pos.x - this.y*pos.y, this.y*pos.x + this.x*pos.y);
1418 },
1419
1420 /*
1421 Method: conjugate
1422
1423 Returns the conjugate of this <Complex> number.
1424
1425 Does not alter the original object.
1426
1427 Returns:
1428
1429 The conjugate of this <Complex> number.
1430 */
1431 conjugate: function() {
1432 return new Complex(this.x, -this.y);
1433 },
1434
1435
1436 /*
1437 Method: scale
1438
1439 Returns the result of scaling a <Complex> instance.
1440
1441 Does not alter the original object.
1442
1443 Parameters:
1444
1445 factor - A scale factor.
1446
1447 Returns:
1448
1449 The result of scaling this complex to a factor.
1450 */
1451 scale: function(factor) {
1452 return new Complex(this.x * factor, this.y * factor);
1453 },
1454
1455 /*
1456 Method: equals
1457
1458 Comparison method.
1459
1460 Returns *true* if both real and imaginary parts are equal.
1461
1462 Parameters:
1463
1464 c - A <Complex> instance.
1465
1466 Returns:
1467
1468 A boolean instance indicating if both <Complex> numbers are equal.
1469 */
1470 equals: function(c) {
1471 return this.x == c.x && this.y == c.y;
1472 },
1473
1474 /*
1475 Method: $add
1476
1477 Returns the result of adding two <Complex> numbers.
1478
1479 Alters the original object.
1480
1481 Parameters:
1482
1483 pos - A <Complex> instance.
1484
1485 Returns:
1486
1487 The result of adding two complex numbers.
1488 */
1489 $add: function(pos) {
1490 this.x += pos.x; this.y += pos.y;
1491 return this;
1492 },
1493
1494 /*
1495 Method: $prod
1496
1497 Returns the result of multiplying two <Complex> numbers.
1498
1499 Alters the original object.
1500
1501 Parameters:
1502
1503 pos - A <Complex> instance.
1504
1505 Returns:
1506
1507 The result of multiplying two complex numbers.
1508 */
1509 $prod:function(pos) {
1510 var x = this.x, y = this.y;
1511 this.x = x*pos.x - y*pos.y;
1512 this.y = y*pos.x + x*pos.y;
1513 return this;
1514 },
1515
1516 /*
1517 Method: $conjugate
1518
1519 Returns the conjugate for this <Complex>.
1520
1521 Alters the original object.
1522
1523 Returns:
1524
1525 The conjugate for this complex.
1526 */
1527 $conjugate: function() {
1528 this.y = -this.y;
1529 return this;
1530 },
1531
1532 /*
1533 Method: $scale
1534
1535 Returns the result of scaling a <Complex> instance.
1536
1537 Alters the original object.
1538
1539 Parameters:
1540
1541 factor - A scale factor.
1542
1543 Returns:
1544
1545 The result of scaling this complex to a factor.
1546 */
1547 $scale: function(factor) {
1548 this.x *= factor; this.y *= factor;
1549 return this;
1550 },
1551
1552 /*
1553 Method: $div
1554
1555 Returns the division of two <Complex> numbers.
1556
1557 Alters the original object.
1558
1559 Parameters:
1560
1561 pos - A <Complex> number.
1562
1563 Returns:
1564
1565 The result of scaling this complex to a factor.
1566 */
1567 $div: function(pos) {
1568 var x = this.x, y = this.y;
1569 var sq = pos.squaredNorm();
1570 this.x = x * pos.x + y * pos.y; this.y = y * pos.x - x * pos.y;
1571 return this.$scale(1 / sq);
1572 }
1573 };
1574
1575 var $C = function(a, b) { return new Complex(a, b); };
1576
1577 Complex.KER = $C(0, 0);
1578
1579
1580
1581 /*
1582 * File: Graph.js
1583 *
1584 * Generic <Graph>, <Graph.Node> and <Graph.Adjacence> classes.
1585 *
1586 * Used by:
1587 *
1588 * <Hypertree>, <RGraph> and <ST>.
1589 *
1590 */
1591
1592 /*
1593 Class: Graph
1594
1595 A generic Graph class.
1596
1597 Description:
1598
1599 When a json graph/tree structure is loaded by <Loader.loadJSON>, an internal <Graph> representation is created.
1600
1601 In most cases you'll be dealing with an already created <Graph> structure, so methods like <Graph.addNode> or <Graph.addAdjacence> won't
1602 be of many use. However methods like <Graph.getNode> and <Graph.hasNode> are pretty useful.
1603
1604 <Graph.Util> provides also iterators for <Graphs> and advanced and useful graph operations and methods.
1605
1606 Used by:
1607
1608 <Loader.loadJSON>, <Hypertree>, <RGraph> and <ST>.
1609
1610 Access:
1611
1612 An instance of this class can be accessed by using the _graph_ parameter of a <Hypertree>, <RGraph> or <ST> instance
1613
1614 Example:
1615
1616 (start code js)
1617 var st = new ST(canvas, config);
1618 st.graph.getNode //or any other <Graph> method.
1619
1620 var ht = new Hypertree(canvas, config);
1621 ht.graph.getNode //or any other <Graph> method.
1622
1623 var rg = new RGraph(canvas, config);
1624 rg.graph.getNode //or any other <Graph> method.
1625 (end code)
1626
1627 */
1628
1629 this.Graph = new Class({
1630
1631 initialize: function(opt) {
1632 var innerOptions = {
1633 'complex': false,
1634 'Node': {}
1635 };
1636 this.opt = $merge(innerOptions, opt || {});
1637 this.nodes= {};
1638 },
1639
1640 /*
1641 Method: getNode
1642
1643 Returns a <Graph.Node> by _id_.
1644
1645 Parameters:
1646
1647 id - A <Graph.Node> id.
1648
1649 Returns:
1650
1651 A <Graph.Node> having _id_ as id. Returns *false* otherwise.
1652
1653 Example:
1654
1655 (start code js)
1656 var node = graph.getNode('someid');
1657 (end code)
1658 */
1659 getNode: function(id) {
1660 if(this.hasNode(id)) return this.nodes[id];
1661 return false;
1662 },
1663
1664 /*
1665 Method: getAdjacence
1666
1667 Returns an array of <Graph.Adjacence> objects connecting nodes with ids _id_ and _id2_.
1668
1669 Parameters:
1670
1671 id - A <Graph.Node> id.
1672 id2 - A <Graph.Node> id.
1673
1674 Returns:
1675
1676 An Array of <Graph.Adjacence> objects. Returns *false* if there's not a <Graph.Adjacence> connecting those two nodes.
1677 */
1678 getAdjacence: function (id, id2) {
1679 var adjs = [];
1680 if(this.hasNode(id) && this.hasNode(id2)
1681 && this.nodes[id].adjacentTo({ 'id':id2 }) && this.nodes[id2].adjacentTo({ 'id':id })) {
1682 adjs.push(this.nodes[id].getAdjacency(id2));
1683 adjs.push(this.nodes[id2].getAdjacency(id));
1684 return adjs;
1685 }
1686 return false;
1687 },
1688
1689 /*
1690 Method: addNode
1691
1692 Adds a node.
1693
1694 Parameters:
1695
1696 obj - An object containing as properties
1697
1698 - _id_ node's id
1699 - _name_ node's name
1700 - _data_ node's data hash
1701
1702 See also:
1703 <Graph.Node>
1704
1705 */
1706 addNode: function(obj) {
1707 if(!this.nodes[obj.id]) {
1708 this.nodes[obj.id] = new Graph.Node($extend({
1709 'id': obj.id,
1710 'name': obj.name,
1711 'data': obj.data
1712 }, this.opt.Node), this.opt.complex);
1713 }
1714 return this.nodes[obj.id];
1715 },
1716
1717 /*
1718 Method: addAdjacence
1719
1720 Connects nodes specified by _obj_ and _obj2_. If not found, nodes are created.
1721
1722 Parameters:
1723
1724 obj - a <Graph.Node> object.
1725 obj2 - Another <Graph.Node> object.
1726 data - A DataSet object. Used to store some extra information in the <Graph.Adjacence> object created.
1727
1728 See also:
1729
1730 <Graph.Node>, <Graph.Adjacence>
1731 */
1732 addAdjacence: function (obj, obj2, data) {
1733 var adjs = [];
1734 if(!this.hasNode(obj.id)) { this.addNode(obj); }
1735 if(!this.hasNode(obj2.id)) { this.addNode(obj2); }
1736 obj = this.nodes[obj.id]; obj2 = this.nodes[obj2.id];
1737
1738 for(var i in this.nodes) {
1739 if(this.nodes[i].id == obj.id) {
1740 if(!this.nodes[i].adjacentTo(obj2)) {
1741 adjs.push(this.nodes[i].addAdjacency(obj2, data));
1742 }
1743 }
1744
1745 if(this.nodes[i].id == obj2.id) {
1746 if(!this.nodes[i].adjacentTo(obj)) {
1747 adjs.push(this.nodes[i].addAdjacency(obj, data));
1748 }
1749 }
1750 }
1751 return adjs;
1752 },
1753
1754 /*
1755 Method: removeNode
1756
1757 Removes a <Graph.Node> matching the specified _id_.
1758
1759 Parameters:
1760
1761 id - A node's id.
1762
1763 */
1764 removeNode: function(id) {
1765 if(this.hasNode(id)) {
1766 var node = this.nodes[id];
1767 for(var i=0 in node.adjacencies) {
1768 var adj = node.adjacencies[i];
1769 this.removeAdjacence(id, adj.nodeTo.id);
1770 }
1771 delete this.nodes[id];
1772 }
1773 },
1774
1775 /*
1776 Method: removeAdjacence
1777
1778 Removes a <Graph.Adjacence> matching _id1_ and _id2_.
1779
1780 Parameters:
1781
1782 id1 - A <Graph.Node> id.
1783 id2 - A <Graph.Node> id.
1784 */
1785 removeAdjacence: function(id1, id2) {
1786 if(this.hasNode(id1)) this.nodes[id1].removeAdjacency(id2);
1787 if(this.hasNode(id2)) this.nodes[id2].removeAdjacency(id1);
1788 },
1789
1790 /*
1791 Method: hasNode
1792
1793 Returns a Boolean instance indicating if the node belongs to the <Graph> or not.
1794
1795 Parameters:
1796
1797 id - Node id.
1798
1799 Returns:
1800
1801 A Boolean instance indicating if the node belongs to the graph or not.
1802 */
1803 hasNode: function(id) {
1804 return id in this.nodes;
1805 }
1806 });
1807
1808 /*
1809 Class: Graph.Node
1810
1811 A <Graph> node.
1812
1813 Parameters:
1814
1815 obj - An object containing an 'id', 'name' and 'data' properties as described in <Graph.addNode>.
1816 complex - Whether node position properties should contain <Complex> or <Polar> instances.
1817
1818 See also:
1819
1820 <Graph>
1821
1822 Description:
1823
1824 An instance of <Graph.Node> is usually passed as parameter for most configuration/controller methods in the
1825 <Hypertree>, <RGraph> and <ST> classes.
1826
1827 A <Graph.Node> object has as properties
1828
1829 id - Node id.
1830 name - Node name.
1831 data - Node data property containing a hash (i.e {}) with custom options. For more information see <Loader.loadJSON>.
1832 selected - Whether the node is selected or not. Used by <ST> for selecting nodes that are between the root node and the selected node.
1833 angleSpan - For radial layouts such as the ones performed by the <Hypertree> and the <RGraph>. Contains _begin_ and _end_ properties containing angle values describing the angle span for this subtree.
1834 alpha - Current opacity value.
1835 startAlpha - Opacity begin value. Used for interpolation.
1836 endAlpha - Opacity end value. Used for interpolation.
1837 pos - Current position. Can be a <Complex> or <Polar> instance.
1838 startPos - Starting position. Used for interpolation.
1839 endPos - Ending position. Used for interpolation.
1840 */
1841 Graph.Node = new Class({
1842
1843 initialize: function(opt, complex) {
1844 var innerOptions = {
1845 'id': '',
1846 'name': '',
1847 'data': {},
1848 'adjacencies': {},
1849
1850 'selected': false,
1851 'drawn': false,
1852 'exist': false,
1853
1854 'angleSpan': {
1855 'begin': 0,
1856 'end' : 0
1857 },
1858
1859 'alpha': 1,
1860 'startAlpha': 1,
1861 'endAlpha': 1,
1862
1863 'pos': (complex && $C(0, 0)) || $P(0, 0),
1864 'startPos': (complex && $C(0, 0)) || $P(0, 0),
1865 'endPos': (complex && $C(0, 0)) || $P(0, 0)
1866 };
1867
1868 $extend(this, $extend(innerOptions, opt));
1869 },
1870
1871 /*
1872 Method: adjacentTo
1873
1874 Indicates if the node is adjacent to the node specified by id
1875
1876 Parameters:
1877
1878 id - A node id.
1879
1880 Returns:
1881
1882 A Boolean instance indicating whether this node is adjacent to the specified by id or not.
1883
1884 Example:
1885 (start code js)
1886 node.adjacentTo('mynodeid');
1887 (end code)
1888 */
1889 adjacentTo: function(node) {
1890 return node.id in this.adjacencies;
1891 },
1892
1893 /*
1894 Method: getAdjacency
1895
1896 Returns a <Graph.Adjacence> object connecting the current <Graph.Node> and the node having _id_ as id.
1897
1898 Parameters:
1899
1900 id - A node id.
1901
1902 Returns:
1903
1904 A <Graph.Adjacence> object or undefined.
1905 */
1906 getAdjacency: function(id) {
1907 return this.adjacencies[id];
1908 },
1909 /*
1910 Method: addAdjacency
1911
1912 Connects the current node and the given node.
1913
1914 Parameters:
1915
1916 node - A <Graph.Node>.
1917 data - Some custom hash information.
1918 */
1919 addAdjacency: function(node, data) {
1920 var adj = new Graph.Adjacence(this, node, data);
1921 return this.adjacencies[node.id] = adj;
1922 },
1923
1924 /*
1925 Method: removeAdjacency
1926
1927 Removes a <Graph.Adjacence> by _id_.
1928
1929 Parameters:
1930
1931 id - A node id.
1932 */
1933 removeAdjacency: function(id) {
1934 delete this.adjacencies[id];
1935 }
1936 });
1937
1938 /*
1939 Class: Graph.Adjacence
1940
1941 A <Graph> adjacence (or edge). Connects two <Graph.Nodes>.
1942
1943 Parameters:
1944
1945 nodeFrom - A <Graph.Node>.
1946 nodeTo - A <Graph.Node>.
1947 data - Some custom hash data.
1948
1949 See also:
1950
1951 <Graph>
1952
1953 Description:
1954
1955 An instance of <Graph.Adjacence> is usually passed as parameter for some configuration/controller methods in the
1956 <Hypertree>, <RGraph> and <ST> classes.
1957
1958 A <Graph.Adjacence> object has as properties
1959
1960 nodeFrom - A <Graph.Node> connected by this edge.
1961 nodeTo - Another <Graph.Node> connected by this edge.
1962 data - Node data property containing a hash (i.e {}) with custom options. For more information see <Loader.loadJSON>.
1963 alpha - Current opacity value.
1964 startAlpha - Opacity begin value. Used for interpolation.
1965 endAlpha - Opacity end value. Used for interpolation.
1966 */
1967 Graph.Adjacence = function(nodeFrom, nodeTo, data) {
1968 this.nodeFrom = nodeFrom;
1969 this.nodeTo = nodeTo;
1970 this.data = data || {};
1971 this.alpha = 1;
1972 this.startAlpha = 1;
1973 this.endAlpha = 1;
1974 };
1975
1976 /*
1977 Object: Graph.Util
1978
1979 <Graph> traversal and processing utility object.
1980 */
1981 Graph.Util = {
1982 /*
1983 filter
1984
1985 For internal use only. Provides a filtering function based on flags.
1986 */
1987 filter: function(param) {
1988 if(!param || !($type(param) == 'string')) return function() { return true; };
1989 var props = param.split(" ");
1990 return function(elem) {
1991 for(var i=0; i<props.length; i++) {
1992 if(elem[props[i]]) {
1993 return false;
1994 }
1995 }
1996 return true;
1997 };
1998 },
1999 /*
2000 Method: getNode
2001
2002 Returns a <Graph.Node> by _id_.
2003
2004 Parameters:
2005
2006 graph - A <Graph> instance.
2007 id - A <Graph.Node> id.
2008
2009 Returns:
2010
2011 A <Graph> node.
2012
2013 Example:
2014
2015 (start code js)
2016 Graph.Util.getNode(graph, 'nodeid');
2017 (end code)
2018 */
2019 getNode: function(graph, id) {
2020 return graph.getNode(id);
2021 },
2022
2023 /*
2024 Method: eachNode
2025
2026 Iterates over <Graph> nodes performing an _action_.
2027
2028 Parameters:
2029
2030 graph - A <Graph> instance.
2031 action - A callback function having a <Graph.Node> as first formal parameter.
2032
2033 Example:
2034 (start code js)
2035 Graph.Util.each(graph, function(node) {
2036 alert(node.name);
2037 });
2038 (end code)
2039 */
2040 eachNode: function(graph, action, flags) {
2041 var filter = this.filter(flags);
2042 for(var i in graph.nodes) {
2043 if(filter(graph.nodes[i])) action(graph.nodes[i]);
2044 }
2045 },
2046
2047 /*
2048 Method: eachAdjacency
2049
2050 Iterates over <Graph.Node> adjacencies applying the _action_ function.
2051
2052 Parameters:
2053
2054 node - A <Graph.Node>.
2055 action - A callback function having <Graph.Adjacence> as first formal parameter.
2056
2057 Example:
2058 (start code js)
2059 Graph.Util.eachAdjacency(node, function(adj) {
2060 alert(adj.nodeTo.name);
2061 });
2062 (end code)
2063 */
2064 eachAdjacency: function(node, action, flags) {
2065 var adj = node.adjacencies, filter = this.filter(flags);
2066 for(var id in adj) {
2067 if(filter(adj[id])) {
2068 action(adj[id], id);
2069 }
2070 }
2071 },
2072
2073 /*
2074 Method: computeLevels
2075
2076 Performs a BFS traversal setting the correct depth for each node.
2077
2078 The depth of each node can then be accessed by
2079 >node._depth
2080
2081 Parameters:
2082
2083 graph - A <Graph>.
2084 id - A starting node id for the BFS traversal.
2085 startDepth - _optional_ A minimum depth value. Default's 0.
2086
2087 */
2088 computeLevels: function(graph, id, startDepth, flags) {
2089 startDepth = startDepth || 0;
2090 var filter = this.filter(flags);
2091 this.eachNode(graph, function(elem) {
2092 elem._flag = false;
2093 elem._depth = -1;
2094 }, flags);
2095 var root = graph.getNode(id);
2096 root._depth = startDepth;
2097 var queue = [root];
2098 while(queue.length != 0) {
2099 var node = queue.pop();
2100 node._flag = true;
2101 this.eachAdjacency(node, function(adj) {
2102 var n = adj.nodeTo;
2103 if(n._flag == false && filter(n)) {
2104 if(n._depth < 0) n._depth = node._depth + 1 + startDepth;
2105 queue.unshift(n);
2106 }
2107 }, flags);
2108 }
2109 },
2110
2111 /*
2112 Method: eachBFS
2113
2114 Performs a BFS traversal applying _action_ to each <Graph.Node>.
2115
2116 Parameters:
2117
2118 graph - A <Graph>.
2119 id - A starting node id for the BFS traversal.
2120 action - A callback function having a <Graph.Node> as first formal parameter.
2121
2122 Example:
2123 (start code js)
2124 Graph.Util.eachBFS(graph, 'mynodeid', function(node) {
2125 alert(node.name);
2126 });
2127 (end code)
2128 */
2129 eachBFS: function(graph, id, action, flags) {
2130 var filter = this.filter(flags);
2131 this.clean(graph);
2132 var queue = [graph.getNode(id)];
2133 while(queue.length != 0) {
2134 var node = queue.pop();
2135 node._flag = true;
2136 action(node, node._depth);
2137 this.eachAdjacency(node, function(adj) {
2138 var n = adj.nodeTo;
2139 if(n._flag == false && filter(n)) {
2140 n._flag = true;
2141 queue.unshift(n);
2142 }
2143 }, flags);
2144 }
2145 },
2146
2147 /*
2148 Method: eachLevel
2149
2150 Iterates over a node's subgraph applying _action_ to the nodes of relative depth between _levelBegin_ and _levelEnd_.
2151
2152 Parameters:
2153
2154 node - A <Graph.Node>.
2155 levelBegin - A relative level value.
2156 levelEnd - A relative level value.
2157 action - A callback function having a <Graph.Node> as first formal parameter.
2158
2159 */
2160 eachLevel: function(node, levelBegin, levelEnd, action, flags) {
2161 var d = node._depth, filter = this.filter(flags), that = this;
2162 levelEnd = levelEnd === false? Number.MAX_VALUE -d : levelEnd;
2163 (function loopLevel(node, levelBegin, levelEnd) {
2164 var d = node._depth;
2165 if(d >= levelBegin && d <= levelEnd && filter(node)) action(node, d);
2166 if(d < levelEnd) {
2167 that.eachAdjacency(node, function(adj) {
2168 var n = adj.nodeTo;
2169 if(n._depth > d) loopLevel(n, levelBegin, levelEnd);
2170 });
2171 }
2172 })(node, levelBegin + d, levelEnd + d);
2173 },
2174
2175 /*
2176 Method: eachSubgraph
2177
2178 Iterates over a node's children recursively.
2179
2180 Parameters:
2181 node - A <Graph.Node>.
2182 action - A callback function having a <Graph.Node> as first formal parameter.
2183
2184 Example:
2185 (start code js)
2186 Graph.Util.eachSubgraph(node, function(node) {
2187 alert(node.name);
2188 });
2189 (end code)
2190 */
2191 eachSubgraph: function(node, action, flags) {
2192 this.eachLevel(node, 0, false, action, flags);
2193 },
2194
2195 /*
2196 Method: eachSubnode
2197
2198 Iterates over a node's children (without deeper recursion).
2199
2200 Parameters:
2201 node - A <Graph.Node>.
2202 action - A callback function having a <Graph.Node> as first formal parameter.
2203
2204 Example:
2205 (start code js)
2206 Graph.Util.eachSubnode(node, function(node) {
2207 alert(node.name);
2208 });
2209 (end code)
2210 */
2211 eachSubnode: function(node, action, flags) {
2212 this.eachLevel(node, 1, 1, action, flags);
2213 },
2214
2215 /*
2216 Method: anySubnode
2217
2218 Returns *true* if any subnode matches the given condition.
2219
2220 Parameters:
2221 node - A <Graph.Node>.
2222 cond - A callback function returning a Boolean instance. This function has as first formal parameter a <Graph.Node>.
2223
2224 Returns:
2225 A boolean value.
2226
2227 Example:
2228 (start code js)
2229 Graph.Util.anySubnode(node, function(node) { return node.name == "mynodename"; });
2230 (end code)
2231 */
2232 anySubnode: function(node, cond, flags) {
2233 var flag = false;
2234 cond = cond || $lambda(true);
2235 var c = $type(cond) == 'string'? function(n) { return n[cond]; } : cond;
2236 this.eachSubnode(node, function(elem) {
2237 if(c(elem)) flag = true;
2238 }, flags);
2239 return flag;
2240 },
2241
2242 /*
2243 Method: getSubnodes
2244
2245 Collects all subnodes for a specified node. The _level_ parameter filters nodes having relative depth of _level_ from the root node.
2246
2247 Parameters:
2248 node - A <Graph.Node>.
2249 level - _optional_ A starting relative depth for collecting nodes. Default's 0.
2250
2251 Returns:
2252 An array of nodes.
2253
2254 */
2255 getSubnodes: function(node, level, flags) {
2256 var ans = [], that = this;
2257 level = level || 0;
2258 var levelStart, levelEnd;
2259 if($type(level) == 'array') {
2260 levelStart = level[0];
2261 levelEnd = level[1];
2262 } else {
2263 levelStart = level;
2264 levelEnd = Number.MAX_VALUE - node._depth;
2265 }
2266 this.eachLevel(node, levelStart, levelEnd, function(n) {
2267 ans.push(n);
2268 }, flags);
2269 return ans;
2270 },
2271
2272
2273 /*
2274 Method: getParents
2275
2276 Returns an Array of <Graph.Nodes> wich are parents of the given node.
2277
2278 Parameters:
2279 node - A <Graph.Node>.
2280
2281 Returns:
2282 An Array of <Graph.Nodes>.
2283
2284 Example:
2285 (start code js)
2286 var pars = Graph.Util.getParents(node);
2287 if(pars.length > 0) {
2288 //do stuff with parents
2289 }
2290 (end code)
2291 */
2292 getParents: function(node) {
2293 var ans = [];
2294 this.eachAdjacency(node, function(adj) {
2295 var n = adj.nodeTo;
2296 if(n._depth < node._depth) ans.push(n);
2297 });
2298 return ans;
2299 },
2300
2301 /*
2302 Method: isDescendantOf
2303
2304 Returns a Boolean instance indicating if some node is descendant of the node with the given id.
2305
2306 Parameters:
2307 node - A <Graph.Node>.
2308 id - A <Graph.Node> id.
2309
2310 Returns:
2311 Ture if _node_ is descendant of the node with the given _id_. False otherwise.
2312
2313 Example:
2314 (start code js)
2315 var pars = Graph.Util.isDescendantOf(node, "nodeid");
2316 (end code)
2317 */
2318 isDescendantOf: function(node, id) {
2319 if(node.id == id) return true;
2320 var pars = this.getParents(node), ans = false;
2321 for ( var i = 0; !ans && i < pars.length; i++) {
2322 ans = ans || this.isDescendantOf(pars[i], id);
2323 }
2324 return ans;
2325 },
2326
2327 /*
2328 Method: clean
2329
2330 Cleans flags from nodes (by setting the _flag_ property to false).
2331
2332 Parameters:
2333 graph - A <Graph> instance.
2334 */
2335 clean: function(graph) { this.eachNode(graph, function(elem) { elem._flag = false; }); }
2336 };
2337
2338
2339
2340 /*
2341 * File: Graph.Op.js
2342 *
2343 * Defines an abstract class for performing <Graph> Operations.
2344 */
2345
2346 /*
2347 Object: Graph.Op
2348
2349 Generic <Graph> Operations.
2350
2351 Description:
2352
2353 An abstract class holding unary and binary powerful graph operations such as removingNodes, removingEdges, adding two graphs and morphing.
2354
2355 Implemented by:
2356
2357 <Hypertree.Op>, <RGraph.Op> and <ST.Op>.
2358
2359 Access:
2360
2361 The subclasses for this abstract class can be accessed by using the _op_ property of the <Hypertree>, <RGraph> or <ST> instances created.
2362
2363 See also:
2364
2365 <Hypertree.Op>, <RGraph.Op>, <ST.Op>, <Hypertree>, <RGraph>, <ST>, <Graph>.
2366 */
2367 Graph.Op = {
2368
2369 options: {
2370 type: 'nothing',
2371 duration: 2000,
2372 hideLabels: true,
2373 fps:30
2374 },
2375
2376 /*
2377 Method: removeNode
2378
2379 Removes one or more <Graph.Nodes> from the visualization.
2380 It can also perform several animations like fading sequentially, fading concurrently, iterating or replotting.
2381
2382 Parameters:
2383
2384 node - The node's id. Can also be an array having many ids.
2385 opt - Animation options. It's an object with optional properties
2386
2387 - _type_ Type of the animation. Can be "nothing", "replot", "fade:seq", "fade:con" or "iter". Default's "nothing".
2388 - _duration_ Duration of the animation in milliseconds. Default's 2000.
2389 - _fps_ Frames per second for the animation. Default's 30.
2390 - _hideLabels_ Hide labels during the animation. Default's *true*.
2391 - _transition_ Transitions defined in the <Animation> class. Default's the default transition option of the
2392 <RGraph>, <Hypertree> or <ST> instance created.
2393
2394 Example:
2395 (start code js)
2396 var rg = new RGraph(canvas, config); //could be new ST or new Hypertree also.
2397 rg.op.removeNode('nodeid', {
2398 type: 'fade:seq',
2399 duration: 1000,
2400 hideLabels: false,
2401 transition: Trans.Quart.easeOut
2402 });
2403 //or also
2404 rg.op.removeNode(['someid', 'otherid'], {
2405 type: 'fade:con',
2406 duration: 1500
2407 });
2408 (end code)
2409 */
2410
2411 removeNode: function(node, opt) {
2412 var viz = this.viz;
2413 var options = $merge(this.options, viz.controller, opt);
2414 var n = $splat(node);
2415 var i, that, nodeObj;
2416 switch(options.type) {
2417 case 'nothing':
2418 for(i=0; i<n.length; i++) viz.graph.removeNode(n[i]);
2419 break;
2420
2421 case 'replot':
2422 this.removeNode(n, { type: 'nothing' });
2423 viz.fx.clearLabels();
2424 viz.refresh(true);
2425 break;
2426
2427 case 'fade:seq': case 'fade':
2428 that = this;
2429 //set alpha to 0 for nodes to remove.
2430 for(i=0; i<n.length; i++) {
2431 nodeObj = viz.graph.getNode(n[i]);
2432 nodeObj.endAlpha = 0;
2433 }
2434 viz.fx.animate($merge(options, {
2435 modes: ['fade:nodes'],
2436 onComplete: function() {
2437 that.removeNode(n, { type: 'nothing' });
2438 viz.fx.clearLabels();
2439 viz.reposition();
2440 viz.fx.animate($merge(options, {
2441 modes: ['linear']
2442 }));
2443 }
2444 }));
2445 break;
2446
2447 case 'fade:con':
2448 that = this;
2449 //set alpha to 0 for nodes to remove. Tag them for being ignored on computing positions.
2450 for(i=0; i<n.length; i++) {
2451 nodeObj = viz.graph.getNode(n[i]);
2452 nodeObj.endAlpha = 0;
2453 nodeObj.ignore = true;
2454 }
2455 viz.reposition();
2456 viz.fx.animate($merge(options, {
2457 modes: ['fade:nodes', 'linear'],
2458 onComplete: function() {
2459 that.removeNode(n, { type: 'nothing' });
2460 }
2461 }));
2462 break;
2463
2464 case 'iter':
2465 that = this;
2466 viz.fx.sequence({
2467 condition: function() { return n.length != 0; },
2468 step: function() { that.removeNode(n.shift(), { type: 'nothing' }); viz.fx.clearLabels(); },
2469 onComplete: function() { options.onComplete(); },
2470 duration: Math.ceil(options.duration / n.length)
2471 });
2472 break;
2473
2474 default: this.doError();
2475 }
2476 },
2477
2478 /*
2479 Method: removeEdge
2480
2481 Removes one or more edges from the visualization.
2482 It can also perform several animations like fading sequentially, fading concurrently, iterating or replotting.
2483
2484 Parameters:
2485
2486 vertex - An array having two strings which are the ids of the nodes connected by this edge (i.e ['id1', 'id2']). Can also be a two dimensional array holding many edges (i.e [['id1', 'id2'], ['id3', 'id4'], ...]).
2487 opt - Animation options. It's an object with optional properties
2488
2489 - _type_ Type of the animation. Can be "nothing", "replot", "fade:seq", "fade:con" or "iter". Default's "nothing".
2490 - _duration_ Duration of the animation in milliseconds. Default's 2000.
2491 - _fps_ Frames per second for the animation. Default's 30.
2492 - _hideLabels_ Hide labels during the animation. Default's *true*.
2493 - _transition_ Transitions defined in the <Animation> class. Default's the default transition option of the
2494 <RGraph>, <Hypertree> or <ST> instance created.
2495
2496 Example:
2497 (start code js)
2498 var rg = new RGraph(canvas, config); //could be new ST or new Hypertree also.
2499 rg.op.removeEdge(['nodeid', 'otherid'], {
2500 type: 'fade:seq',
2501 duration: 1000,
2502 hideLabels: false,
2503 transition: Trans.Quart.easeOut
2504 });
2505 //or also
2506 rg.op.removeEdge([['someid', 'otherid'], ['id3', 'id4']], {
2507 type: 'fade:con',
2508 duration: 1500
2509 });
2510 (end code)
2511
2512 */
2513 removeEdge: function(vertex, opt) {
2514 var viz = this.viz;
2515 var options = $merge(this.options, viz.controller, opt);
2516 var v = ($type(vertex[0]) == 'string')? [vertex] : vertex;
2517 var i, that, adjs;
2518 switch(options.type) {
2519 case 'nothing':
2520 for(i=0; i<v.length; i++) viz.graph.removeAdjacence(v[i][0], v[i][1]);
2521 break;
2522
2523 case 'replot':
2524 this.removeEdge(v, { type: 'nothing' });
2525 viz.refresh(true);
2526 break;
2527
2528 case 'fade:seq': case 'fade':
2529 that = this;
2530 //set alpha to 0 for edges to remove.
2531 for(i=0; i<v.length; i++) {
2532 adjs = viz.graph.getAdjacence(v[i][0], v[i][1]);
2533 if(adjs) {
2534 adjs[0].endAlpha = 0;
2535 adjs[1].endAlpha = 0;
2536 }
2537 }
2538 viz.fx.animate($merge(options, {
2539 modes: ['fade:vertex'],
2540 onComplete: function() {
2541 that.removeEdge(v, { type: 'nothing' });
2542 viz.reposition();
2543 viz.fx.animate($merge(options, {
2544 modes: ['linear']
2545 }));
2546 }
2547 }));
2548 break;
2549
2550 case 'fade:con':
2551 that = this;
2552 //set alpha to 0 for nodes to remove. Tag them for being ignored when computing positions.
2553 for(i=0; i<v.length; i++) {
2554 adjs = viz.graph.getAdjacence(v[i][0], v[i][1]);
2555 if(adjs) {
2556 adjs[0].endAlpha = 0;
2557 adjs[0].ignore = true;
2558 adjs[1].endAlpha = 0;
2559 adjs[1].ignore = true;
2560 }
2561 }
2562 viz.reposition();
2563 viz.fx.animate($merge(options, {
2564 modes: ['fade:vertex', 'linear'],
2565 onComplete: function() {
2566 that.removeEdge(v, { type: 'nothing' });
2567 }
2568 }));
2569 break;
2570
2571 case 'iter':
2572 that = this;
2573 viz.fx.sequence({
2574 condition: function() { return v.length != 0; },
2575 step: function() { that.removeEdge(v.shift(), { type: 'nothing' }); viz.fx.clearLabels(); },
2576 onComplete: function() { options.onComplete(); },
2577 duration: Math.ceil(options.duration / v.length)
2578 });
2579 break;
2580
2581 default: this.doError();
2582 }
2583 },
2584
2585 /*
2586 Method: sum
2587
2588 Adds a new graph to the visualization.
2589
2590 The json graph (or tree) must at least have a common node with the current graph plotted by the visualization.
2591
2592 The resulting graph can be defined as follows <http://mathworld.wolfram.com/GraphSum.html>
2593
2594 Parameters:
2595
2596 json - A json tree or graph structure. See also <Loader.loadJSON>.
2597 opt - Animation options. It's an object with optional properties
2598
2599 - _type_ Type of the animation. Can be "nothing", "replot", "fade:seq" or "fade:con". Default's "nothing".
2600 - _duration_ Duration of the animation in milliseconds. Default's 2000.
2601 - _fps_ Frames per second for the animation. Default's 30.
2602 - _hideLabels_ Hide labels during the animation. Default's *true*.
2603 - _transition_ Transitions defined in the <Animation> class. Default's the default transition option of the
2604 <RGraph>, <Hypertree> or <ST> instance created.
2605
2606 Example:
2607 (start code js)
2608 //json contains a tree or graph structure.
2609
2610 var rg = new RGraph(canvas, config); //could be new ST or new Hypertree also.
2611 rg.op.sum(json, {
2612 type: 'fade:seq',
2613 duration: 1000,
2614 hideLabels: false,
2615 transition: Trans.Quart.easeOut
2616 });
2617 //or also
2618 rg.op.sum(json, {
2619 type: 'fade:con',
2620 duration: 1500
2621 });
2622 (end code)
2623
2624 */
2625 sum: function(json, opt) {
2626 var viz = this.viz;
2627 var options = $merge(this.options, viz.controller, opt), root = viz.root;
2628 var GUtil, graph;
2629 viz.root = opt.id || viz.root;
2630 switch(options.type) {
2631 case 'nothing':
2632 graph = viz.construct(json);
2633 GUtil = Graph.Util;
2634 GUtil.eachNode(graph, function(elem) {
2635 GUtil.eachAdjacency(elem, function(adj) {
2636 viz.graph.addAdjacence(adj.nodeFrom, adj.nodeTo, adj.data);
2637 });
2638 });
2639 break;
2640
2641 case 'replot':
2642 viz.refresh(true);
2643 this.sum(json, { type: 'nothing' });
2644 viz.refresh(true);
2645 break;
2646
2647 case 'fade:seq': case 'fade': case 'fade:con':
2648 GUtil = Graph.Util;
2649 that = this;
2650 graph = viz.construct(json);
2651
2652 //set alpha to 0 for nodes to add.
2653 var fadeEdges = this.preprocessSum(graph);
2654 var modes = !fadeEdges? ['fade:nodes'] : ['fade:nodes', 'fade:vertex'];
2655 viz.reposition();
2656 if(options.type != 'fade:con') {
2657 viz.fx.animate($merge(options, {
2658 modes: ['linear'],
2659 onComplete: function() {
2660 viz.fx.animate($merge(options, {
2661 modes: modes,
2662 onComplete: function() {
2663 options.onComplete();
2664 }
2665 }));
2666 }
2667 }));
2668 } else {
2669 GUtil.eachNode(viz.graph, function(elem) {
2670 if (elem.id != root && elem.pos.getp().equals(Polar.KER)) {
2671 elem.pos.set(elem.endPos); elem.startPos.set(elem.endPos);
2672 }
2673 });
2674 viz.fx.animate($merge(options, {
2675 modes: ['linear'].concat(modes)
2676 }));
2677 }
2678 break;
2679
2680 default: this.doError();
2681 }
2682 },
2683
2684 /*
2685 Method: morph
2686
2687 This method will _morph_ the current visualized graph into the new _json_ representation passed in the method.
2688
2689 Can also perform multiple animations. The _json_ object must at least have the root node in common with the current visualized graph.
2690
2691 Parameters:
2692
2693 json - A json tree or graph structure. See also <Loader.loadJSON>.
2694 opt - Animation options. It's an object with optional properties
2695
2696 - _type_ Type of the animation. Can be "nothing", "replot", or "fade". Default's "nothing".
2697 - _duration_ Duration of the animation in milliseconds. Default's 2000.
2698 - _fps_ Frames per second for the animation. Default's 30.
2699 - _hideLabels_ Hide labels during the animation. Default's *true*.
2700 - _transition_ Transitions defined in the <Animation> class. Default's the default transition option of the
2701 <RGraph>, <Hypertree> or <ST> instance created.
2702
2703 Example:
2704 (start code js)
2705 //json contains a tree or graph structure.
2706
2707 var rg = new RGraph(canvas, config); //could be new ST or new Hypertree also.
2708 rg.op.morph(json, {
2709 type: 'fade',
2710 duration: 1000,
2711 hideLabels: false,
2712 transition: Trans.Quart.easeOut
2713 });
2714 //or also
2715 rg.op.morph(json, {
2716 type: 'fade',
2717 duration: 1500
2718 });
2719 (end code)
2720
2721 */
2722 morph: function(json, opt) {
2723 var viz = this.viz;
2724 var options = $merge(this.options, viz.controller, opt), root = viz.root;
2725 var GUtil, graph;
2726 viz.root = opt.id || viz.root;
2727 switch(options.type) {
2728 case 'nothing':
2729 graph = viz.construct(json);
2730 GUtil = Graph.Util;
2731 GUtil.eachNode(graph, function(elem) {
2732 GUtil.eachAdjacency(elem, function(adj) {
2733 viz.graph.addAdjacence(adj.nodeFrom, adj.nodeTo, adj.data);
2734 });
2735 });
2736 GUtil.eachNode(viz.graph, function(elem) {
2737 GUtil.eachAdjacency(elem, function(adj) {
2738 if(!graph.getAdjacence(adj.nodeFrom.id, adj.nodeTo.id)) {
2739 viz.graph.removeAdjacence(adj.nodeFrom.id, adj.nodeTo.id);
2740 }
2741 });
2742 if(!graph.hasNode(elem.id)) viz.graph.removeNode(elem.id);
2743 });
2744
2745 break;
2746
2747 case 'replot':
2748 viz.fx.clearLabels(true);
2749 this.morph(json, { type: 'nothing' });
2750 viz.refresh(true);
2751 viz.refresh(true);
2752 break;
2753
2754 case 'fade:seq': case 'fade': case 'fade:con':
2755 GUtil = Graph.Util;
2756 that = this;
2757 graph = viz.construct(json);
2758 //preprocessing for adding nodes.
2759 var fadeEdges = this.preprocessSum(graph);
2760 //preprocessing for nodes to delete.
2761 GUtil.eachNode(viz.graph, function(elem) {
2762 if(!graph.hasNode(elem.id)) {
2763 elem.alpha = 1; elem.startAlpha = 1; elem.endAlpha = 0; elem.ignore = true;
2764 }
2765 });
2766 GUtil.eachNode(viz.graph, function(elem) {
2767 if(elem.ignore) return;
2768 GUtil.eachAdjacency(elem, function(adj) {
2769 if(adj.nodeFrom.ignore || adj.nodeTo.ignore) return;
2770 var nodeFrom = graph.getNode(adj.nodeFrom.id);
2771 var nodeTo = graph.getNode(adj.nodeTo.id);
2772 if(!nodeFrom.adjacentTo(nodeTo)) {
2773 var adjs = viz.graph.getAdjacence(nodeFrom.id, nodeTo.id);
2774 fadeEdges = true;
2775 adjs[0].alpha = 1; adjs[0].startAlpha = 1; adjs[0].endAlpha = 0; adjs[0].ignore = true;
2776 adjs[1].alpha = 1; adjs[1].startAlpha = 1; adjs[1].endAlpha = 0; adjs[1].ignore = true;
2777 }
2778 });
2779 });
2780 var modes = !fadeEdges? ['fade:nodes'] : ['fade:nodes', 'fade:vertex'];
2781 viz.reposition();
2782 GUtil.eachNode(viz.graph, function(elem) {
2783 if (elem.id != root && elem.pos.getp().equals(Polar.KER)) {
2784 elem.pos.set(elem.endPos); elem.startPos.set(elem.endPos);
2785 }
2786 });
2787 viz.fx.animate($merge(options, {
2788 modes: ['polar'].concat(modes),
2789 onComplete: function() {
2790 GUtil.eachNode(viz.graph, function(elem) {
2791 if(elem.ignore) viz.graph.removeNode(elem.id);
2792 });
2793 GUtil.eachNode(viz.graph, function(elem) {
2794 GUtil.eachAdjacency(elem, function(adj) {
2795 if(adj.ignore) viz.graph.removeAdjacence(adj.nodeFrom.id, adj.nodeTo.id);
2796 });
2797 });
2798 options.onComplete();
2799 }
2800 }));
2801 break;
2802
2803 default: this.doError();
2804 }
2805 },
2806
2807 preprocessSum: function(graph) {
2808 var viz = this.viz;
2809 var GUtil = Graph.Util;
2810 GUtil.eachNode(graph, function(elem) {
2811 if(!viz.graph.hasNode(elem.id)) {
2812 viz.graph.addNode(elem);
2813 var n = viz.graph.getNode(elem.id);
2814 n.alpha = 0; n.startAlpha = 0; n.endAlpha = 1;
2815 }
2816 });
2817 var fadeEdges = false;
2818 GUtil.eachNode(graph, function(elem) {
2819 GUtil.eachAdjacency(elem, function(adj) {
2820 var nodeFrom = viz.graph.getNode(adj.nodeFrom.id);
2821 var nodeTo = viz.graph.getNode(adj.nodeTo.id);
2822 if(!nodeFrom.adjacentTo(nodeTo)) {
2823 var adjs = viz.graph.addAdjacence(nodeFrom, nodeTo, adj.data);
2824 if(nodeFrom.startAlpha == nodeFrom.endAlpha
2825 && nodeTo.startAlpha == nodeTo.endAlpha) {
2826 fadeEdges = true;
2827 adjs[0].alpha = 0; adjs[0].startAlpha = 0; adjs[0].endAlpha = 1;
2828 adjs[1].alpha = 0; adjs[1].startAlpha = 0; adjs[1].endAlpha = 1;
2829 }
2830 }
2831 });
2832 });
2833 return fadeEdges;
2834 }
2835 };
2836
2837
2838
2839 /*
2840 * File: Graph.Plot.js
2841 *
2842 * Defines an abstract class for performing <Graph> rendering and animation.
2843 *
2844 */
2845
2846
2847 /*
2848 Object: Graph.Plot
2849
2850 Generic <Graph> rendering and animation methods.
2851
2852 Description:
2853
2854 An abstract class for plotting a generic graph structure.
2855
2856 Implemented by:
2857
2858 <Hypertree.Plot>, <RGraph.Plot>, <ST.Plot>.
2859
2860 Access:
2861
2862 The subclasses for this abstract class can be accessed by using the _fx_ property of the <Hypertree>, <RGraph>, or <ST> instances created.
2863
2864 See also:
2865
2866 <Hypertree.Plot>, <RGraph.Plot>, <ST.Plot>, <Hypertree>, <RGraph>, <ST>, <Graph>.
2867
2868 */
2869 Graph.Plot = {
2870
2871 Interpolator: {
2872 'moebius': function(elem, delta, vector) {
2873 if(delta <= 1 || vector.norm() <= 1) {
2874 var x = vector.x, y = vector.y;
2875 var ans = elem.startPos.getc().moebiusTransformation(vector);
2876 elem.pos.setc(ans.x, ans.y);
2877 vector.x = x; vector.y = y;
2878 }
2879 },
2880
2881 'linear': function(elem, delta) {
2882 var from = elem.startPos.getc(true);
2883 var to = elem.endPos.getc(true);
2884 elem.pos.setc((to.x - from.x) * delta + from.x, (to.y - from.y) * delta + from.y);
2885 },
2886
2887 'fade:nodes': function(elem, delta) {
2888 if(delta <= 1 && (elem.endAlpha != elem.alpha)) {
2889 var from = elem.startAlpha;
2890 var to = elem.endAlpha;
2891 elem.alpha = from + (to - from) * delta;
2892 }
2893 },
2894
2895 'fade:vertex': function(elem, delta) {
2896 var adjs = elem.adjacencies;
2897 for(var id in adjs) this['fade:nodes'](adjs[id], delta);
2898 },
2899
2900 'polar': function(elem, delta) {
2901 var from = elem.startPos.getp(true);
2902 var to = elem.endPos.getp();
2903 var ans = to.interpolate(from, delta);
2904 elem.pos.setp(ans.theta, ans.rho);
2905 }
2906 },
2907
2908 //A flag value indicating if node labels are being displayed or not.
2909 labelsHidden: false,
2910 //Label DOM element
2911 labelContainer: false,
2912 //Label DOM elements hash.
2913 labels: {},
2914
2915 /*
2916 Method: getLabelContainer
2917
2918 Lazy fetcher for the label container.
2919
2920 Returns:
2921
2922 The label container DOM element.
2923
2924 Example:
2925
2926 (start code js)
2927 var rg = new RGraph(canvas, config); //can be also Hypertree or ST
2928 var labelContainer = rg.fx.getLabelContainer();
2929 alert(labelContainer.innerHTML);
2930 (end code)
2931 */
2932 getLabelContainer: function() {
2933 return this.labelContainer? this.labelContainer : this.labelContainer = document.getElementById(this.viz.config.labelContainer);
2934 },
2935
2936 /*
2937 Method: getLabel
2938
2939 Lazy fetcher for the label DOM element.
2940
2941 Parameters:
2942
2943 id - The label id (which is also a <Graph.Node> id).
2944
2945 Returns:
2946
2947 The label DOM element.
2948
2949 Example:
2950
2951 (start code js)
2952 var rg = new RGraph(canvas, config); //can be also Hypertree or ST
2953 var label = rg.fx.getLabel('someid');
2954 alert(label.innerHTML);
2955 (end code)
2956
2957 */
2958 getLabel: function(id) {
2959 return (id in this.labels && this.labels[id] != null)? this.labels[id] : this.labels[id] = document.getElementById(id);
2960 },
2961
2962 /*
2963 Method: hideLabels
2964
2965 Hides all labels (by hiding the label container).
2966
2967 Parameters:
2968
2969 hide - A boolean value indicating if the label container must be hidden or not.
2970
2971 Example:
2972 (start code js)
2973 var rg = new RGraph(canvas, config); //can be also Hypertree or ST
2974 rg.fx.hideLabels(true);
2975 (end code)
2976
2977 */
2978 hideLabels: function (hide) {
2979 var container = this.getLabelContainer();
2980 if(hide) container.style.display = 'none';
2981 else container.style.display = '';
2982 this.labelsHidden = hide;
2983 },
2984
2985 /*
2986 Method: clearLabels
2987
2988 Clears the label container.
2989
2990 Useful when using a new visualization with the same canvas element/widget.
2991
2992 Parameters:
2993
2994 force - Forces deletion of all labels.
2995
2996 Example:
2997 (start code js)
2998 var rg = new RGraph(canvas, config); //can be also Hypertree or ST
2999 rg.fx.clearLabels();
3000 (end code)
3001 */
3002 clearLabels: function(force) {
3003 for(var id in this.labels) {
3004 if (force || !this.viz.graph.hasNode(id)) {
3005 this.disposeLabel(id);
3006 delete this.labels[id];
3007 }
3008 }
3009 },
3010
3011 /*
3012 Method: disposeLabel
3013
3014 Removes a label.
3015
3016 Parameters:
3017
3018 id - A label id (which generally is also a <Graph.Node> id).
3019
3020 Example:
3021 (start code js)
3022 var rg = new RGraph(canvas, config); //can be also Hypertree or ST
3023 rg.fx.disposeLabel('labelid');
3024 (end code)
3025 */
3026 disposeLabel: function(id) {
3027 var elem = this.getLabel(id);
3028 if(elem && elem.parentNode) {
3029 elem.parentNode.removeChild(elem);
3030 }
3031 },
3032
3033 /*
3034 Method: hideLabel
3035
3036 Hides the corresponding <Graph.Node> label.
3037
3038 Parameters:
3039
3040 node - A <Graph.Node>. Can also be an array of <Graph.Nodes>.
3041 flag - If *true*, nodes will be shown. Otherwise nodes will be hidden.
3042
3043 Example:
3044 (start code js)
3045 var rg = new RGraph(canvas, config); //can be also Hypertree or ST
3046 rg.fx.hideLabel(rg.graph.getNode('someid'), false);
3047 (end code)
3048 */
3049 hideLabel: function(node, flag) {
3050 node = $splat(node);
3051 var st = flag? "" : "none", lab, that = this;
3052 $each(node, function(n) {
3053 var lab = that.getLabel(n.id);
3054 if (lab) {
3055 lab.style.display = st;
3056 }
3057 });
3058 },
3059
3060 /*
3061 Method: sequence
3062
3063 Iteratively performs an action while refreshing the state of the visualization.
3064
3065 Parameters:
3066
3067 options - Some sequence options like
3068
3069 - _condition_ A function returning a boolean instance in order to stop iterations.
3070 - _step_ A function to execute on each step of the iteration.
3071 - _onComplete_ A function to execute when the sequence finishes.
3072 - _duration_ Duration (in milliseconds) of each step.
3073
3074 Example:
3075 (start code js)
3076 var rg = new RGraph(canvas, config); //can be also Hypertree or ST
3077 var i = 0;
3078 rg.fx.sequence({
3079 condition: function() {
3080 return i == 10;
3081 },
3082 step: function() {
3083 alert(i++);
3084 },
3085 onComplete: function() {
3086 alert('done!');
3087 }
3088 });
3089 (end code)
3090
3091 */
3092 sequence: function(options) {
3093 var that = this;
3094 options = $merge({
3095 condition: $lambda(false),
3096 step: $empty,
3097 onComplete: $empty,
3098 duration: 200
3099 }, options || {});
3100
3101 var interval = setInterval(function() {
3102 if(options.condition()) {
3103 options.step();
3104 } else {
3105 clearInterval(interval);
3106 options.onComplete();
3107 }
3108 that.viz.refresh(true);
3109 }, options.duration);
3110 },
3111
3112 /*
3113 Method: animate
3114
3115 Animates a <Graph> by interpolating some <Graph.Nodes> properties.
3116
3117 Parameters:
3118
3119 opt - Animation options. This object contains as properties
3120
3121 - _modes_ (required) An Array of animation types. Possible values are "linear", "polar", "moebius", "fade:nodes" and "fade:vertex".
3122
3123 "linear", "polar" and "moebius" animation options will interpolate <Graph.Nodes> "startPos" and "endPos" properties, storing the result in "pos".
3124
3125 "fade:nodes" and "fade:vertex" animation options will interpolate <Graph.Nodes> and/or <Graph.Adjacence> "startAlpha" and "endAlpha" properties, storing the result in "alpha".
3126
3127 - _duration_ Duration (in milliseconds) of the Animation.
3128 - _fps_ Frames per second.
3129 - _hideLabels_ hide labels or not during the animation.
3130
3131 ...and other <Hypertree>, <RGraph> or <ST> controller methods.
3132
3133 Example:
3134 (start code js)
3135 var rg = new RGraph(canvas, config); //can be also Hypertree or ST
3136 rg.fx.animate({
3137 modes: ['linear'],
3138 hideLabels: false
3139 });
3140 (end code)
3141
3142
3143 */
3144 animate: function(opt, versor) {
3145 var that = this,
3146 viz = this.viz,
3147 graph = viz.graph,
3148 GUtil = Graph.Util;
3149 opt = $merge(viz.controller, opt || {});
3150
3151 if(opt.hideLabels) this.hideLabels(true);
3152 this.animation.setOptions($merge(opt, {
3153 $animating: false,
3154 compute: function(delta) {
3155 var vector = versor? versor.scale(-delta) : null;
3156 GUtil.eachNode(graph, function(node) {
3157 for(var i=0; i<opt.modes.length; i++) {
3158 that.Interpolator[opt.modes[i]](node, delta, vector);
3159 }
3160 });
3161 that.plot(opt, this.$animating);
3162 this.$animating = true;
3163 },
3164 complete: function() {
3165 GUtil.eachNode(graph, function(node) {
3166 node.startPos.set(node.pos);
3167 node.startAlpha = node.alpha;
3168 });
3169 if(opt.hideLabels) that.hideLabels(false);
3170 that.plot(opt);
3171 opt.onComplete();
3172 opt.onAfterCompute();
3173 }
3174 })).start();
3175 },
3176
3177 /*
3178 Method: plot
3179
3180 Plots a <Graph>.
3181
3182 Parameters:
3183
3184 opt - _optional_ Plotting options.
3185
3186 Example:
3187
3188 (start code js)
3189 var rg = new RGraph(canvas, config); //can be also Hypertree or ST
3190 rg.fx.plot();
3191 (end code)
3192
3193 */
3194 plot: function(opt, animating) {
3195 var viz = this.viz,
3196 aGraph = viz.graph,
3197 canvas = viz.canvas,
3198 id = viz.root,
3199 that = this,
3200 ctx = canvas.getCtx(),
3201 GUtil = Graph.Util;
3202 opt = opt || this.viz.controller;
3203 opt.clearCanvas && canvas.clear();
3204
3205 var T = !!aGraph.getNode(id).visited;
3206 GUtil.eachNode(aGraph, function(node) {
3207 GUtil.eachAdjacency(node, function(adj) {
3208 var nodeTo = adj.nodeTo;
3209 if(!!nodeTo.visited === T && node.drawn && nodeTo.drawn) {
3210 !animating && opt.onBeforePlotLine(adj);
3211 ctx.save();
3212 ctx.globalAlpha = Math.min(Math.min(node.alpha, nodeTo.alpha), adj.alpha);
3213 that.plotLine(adj, canvas, animating);
3214 ctx.restore();
3215 !animating && opt.onAfterPlotLine(adj);
3216 }
3217 });
3218 ctx.save();
3219 if(node.drawn) {
3220 ctx.globalAlpha = node.alpha;
3221 !animating && opt.onBeforePlotNode(node);
3222 that.plotNode(node, canvas, animating);
3223 !animating && opt.onAfterPlotNode(node);
3224 }
3225 if(!that.labelsHidden && opt.withLabels) {
3226 if(node.drawn && ctx.globalAlpha >= 0.95) {
3227 that.plotLabel(canvas, node, opt);
3228 } else {
3229 that.hideLabel(node, false);
3230 }
3231 }
3232 ctx.restore();
3233 node.visited = !T;
3234 });
3235 },
3236
3237 /*
3238 Method: plotLabel
3239
3240 Plots a label for a given node.
3241
3242 Parameters:
3243
3244 canvas - A <Canvas> instance.
3245 node - A <Graph.Node>.
3246 controller - A configuration object. See also <Hypertree>, <RGraph>, <ST>.
3247
3248 */
3249 plotLabel: function(canvas, node, controller) {
3250 var id = node.id, tag = this.getLabel(id);
3251 if(!tag && !(tag = document.getElementById(id))) {
3252 tag = document.createElement('div');
3253 var container = this.getLabelContainer();
3254 container.appendChild(tag);
3255 tag.id = id;
3256 tag.className = 'node';
3257 tag.style.position = 'absolute';
3258 controller.onCreateLabel(tag, node);
3259 this.labels[node.id] = tag;
3260 }
3261 this.placeLabel(tag, node, controller);
3262 },
3263
3264 /*
3265 Method: plotNode
3266
3267 Plots a <Graph.Node>.
3268
3269 Parameters:
3270
3271 node - A <Graph.Node>.
3272 canvas - A <Canvas> element.
3273
3274 */
3275 plotNode: function(node, canvas, animating) {
3276 var nconfig = this.node, data = node.data;
3277 var cond = nconfig.overridable && data;
3278 var width = cond && data.$lineWidth || nconfig.lineWidth;
3279 var color = cond && data.$color || nconfig.color;
3280 var ctx = canvas.getCtx();
3281
3282 ctx.lineWidth = width;
3283 ctx.fillStyle = color;
3284 ctx.strokeStyle = color;
3285
3286 var f = node.data && node.data.$type || nconfig.type;
3287 this.nodeTypes[f].call(this, node, canvas, animating);
3288 },
3289
3290 /*
3291 Method: plotLine
3292
3293 Plots a line.
3294
3295 Parameters:
3296
3297 adj - A <Graph.Adjacence>.
3298 canvas - A <Canvas> instance.
3299
3300 */
3301 plotLine: function(adj, canvas, animating) {
3302 var econfig = this.edge, data = adj.data;
3303 var cond = econfig.overridable && data;
3304 var width = cond && data.$lineWidth || econfig.lineWidth;
3305 var color = cond && data.$color || econfig.color;
3306 var ctx = canvas.getCtx();
3307
3308 ctx.lineWidth = width;
3309 ctx.fillStyle = color;
3310 ctx.strokeStyle = color;
3311
3312 var f = adj.data && adj.data.$type || econfig.type;
3313 this.edgeTypes[f].call(this, adj, canvas, animating);
3314 },
3315
3316 /*
3317 Method: fitsInCanvas
3318
3319 Returns _true_ or _false_ if the label for the node is contained in the canvas dom element or not.
3320
3321 Parameters:
3322
3323 pos - A <Complex> instance (I'm doing duck typing here so any object with _x_ and _y_ parameters will do).
3324 canvas - A <Canvas> instance.
3325
3326 Returns:
3327
3328 A boolean value specifying if the label is contained in the <Canvas> DOM element or not.
3329
3330 */
3331 fitsInCanvas: function(pos, canvas) {
3332 var size = canvas.getSize();
3333 if(pos.x >= size.width || pos.x < 0
3334 || pos.y >= size.height || pos.y < 0) return false;
3335 return true;
3336 }
3337 };
3338
3339
3340 /*
3341 * File: Loader.js
3342 *
3343 * Provides methods for loading JSON data.
3344 *
3345 * Description:
3346 *
3347 * Provides the <Loader.loadJSON> method implemented by the main visualization classes to load JSON Trees and Graphs.
3348 *
3349 * Implemented By:
3350 *
3351 * <ST>, <TM>, <Hypertree> and <RGraph> classes
3352 *
3353 */
3354
3355 /*
3356 Object: Loader
3357
3358 Provides static methods for loading JSON data.
3359
3360 Description:
3361
3362 This object is extended by the main Visualization classes (<ST>, <Hypertree>, <TM> and <RGraph>)
3363 in order to implement the <Loader.loadJSON> method.
3364
3365 The <Loader.loadJSON> method accepts JSON Trees and Graph objects. This will be explained in detail in the <Loader.loadJSON> method definition.
3366 */
3367 var Loader = {
3368 construct: function(json) {
3369 var isGraph = ($type(json) == 'array');
3370 var ans = new Graph(this.graphOptions);
3371 if(!isGraph)
3372 //make tree
3373 (function (ans, json) {
3374 ans.addNode(json);
3375 for(var i=0, ch = json.children; i<ch.length; i++) {
3376 ans.addAdjacence(json, ch[i]);
3377 arguments.callee(ans, ch[i]);
3378 }
3379 })(ans, json);
3380 else
3381 //make graph
3382 (function (ans, json) {
3383 var getNode = function(id) {
3384 for(var w=0; w<json.length; w++) {
3385 if(json[w].id == id) {
3386 return json[w];
3387 }
3388 }
3389 return undefined;
3390 };
3391
3392 for(var i=0; i<json.length; i++) {
3393 ans.addNode(json[i]);
3394 for(var j=0, adj = json[i].adjacencies; j<adj.length; j++) {
3395 var node = adj[j], data;
3396 if(typeof adj[j] != 'string') {
3397 data = node.data;
3398 node = node.nodeTo;
3399 }
3400 ans.addAdjacence(json[i], getNode(node), data);
3401 }
3402 }
3403 })(ans, json);
3404
3405 return ans;
3406 },
3407
3408 /*
3409 Method: loadJSON
3410
3411 Loads a JSON structure to the visualization. The JSON structure can be a JSON tree or graph structure.
3412
3413 A JSON tree or graph structure consists of nodes, each having as properties
3414 - _id_ A unique identifier for the node
3415 - _name_ A node's name
3416 - _data_ The data property contains a hash (i.e {}) where you can store all
3417 the information you want about this node.
3418
3419 Hash keys prefixed with a dollar sign (i.e $) have special meaning. I will detail those properties below.
3420
3421 For JSON tree structures, there's an extra property _children_ of type Array which contains the node's children.
3422
3423 Example:
3424
3425 (start code js)
3426 var json = {
3427 "id": "aUniqueIdentifier",
3428 "name": "usually a nodes name",
3429 "data": {
3430 "some key": "some value",
3431 "some other key": "some other value"
3432 },
3433 "children": [ 'other nodes or empty' ]
3434 };
3435 (end code)
3436
3437 JSON Graph structures consist of an array of nodes, each specifying the nodes to which the current node is connected.
3438
3439 For JSON Graph structures, the _children_ property is replaced by the _adjacencies_ property.
3440
3441 There are two types of Graph structures, _simple_ and _extended_ graph structures.
3442
3443 For _simple_ Graph structures, the adjacencies property contains an array of strings, each specifying the
3444 id of the node connected to the main node.
3445
3446 Example:
3447
3448 (start code js)
3449 var json = [
3450 {
3451 "id": "aUniqueIdentifier",
3452 "name": "usually a nodes name",
3453 "data": {
3454 "some key": "some value",
3455 "some other key": "some other value"
3456 },
3457 "adjacencies": ["anotherUniqueIdentifier", "yetAnotherUniqueIdentifier", 'etc']
3458 },
3459
3460 'other nodes go here...'
3461 ];
3462 (end code)
3463
3464 For _extended_ Graph structures, the adjacencies property contains an array of Adjacency objects that have as properties
3465 - nodeTo The other node connected by this adjacency.
3466 - data A data property, where we can store custom key/value information.
3467
3468 Example:
3469
3470 (start code js)
3471 var json = [
3472 {
3473 "id": "aUniqueIdentifier",
3474 "name": "usually a nodes name",
3475 "data": {
3476 "some key": "some value",
3477 "some other key": "some other value"
3478 },
3479 "adjacencies": [
3480 {
3481 nodeTo:"aNodeId",
3482 data: {} //put whatever you want here
3483 },
3484 'other adjacencies go here...'
3485 },
3486
3487 'other nodes go here...'
3488 ];
3489 (end code)
3490
3491 Since all visualizations implement this method, this will be the entry point for JSON data for all visualizations. This method could be called like this
3492
3493 Example:
3494
3495 (start code js)
3496 var ht = new Hypertree(canvas, config);
3497 ht.loadJSON(json);
3498
3499 var tm = new TM.Squarified(config);
3500 tm.loadJSON(json);
3501
3502 var st = new ST(canvas, config);
3503 st.loadJSON(json);
3504
3505 var rg = new RGraph(canvas, config);
3506 rg.loadJSON(json);
3507
3508 (end code)
3509
3510 Parameters:
3511
3512 json - A JSON Tree or Graph structure.
3513 i - For Graph structures only. Sets the indexed node as root for the visualization.
3514
3515 */
3516 loadJSON: function(json, i) {
3517 this.json = json;
3518 this.graph = this.construct(json);
3519 if($type(json) != 'array'){
3520 this.root = json.id;
3521 } else {
3522 this.root = json[i? i : 0].id;
3523 }
3524 }
3525 };
3526
3527
3528
3529 /*
3530 * File: Animation.js
3531 *
3532 * Core <Animation> and <Trans> transition classes.
3533 *
3534 */
3535
3536 /*
3537 Object: Trans
3538
3539 An object containing multiple type of transformations.
3540
3541 Based on:
3542
3543 Easing and Transition animation methods are based in the MooTools Framework <http://mootools.net>. Copyright (c) 2006-2009 Valerio Proietti, <http://mad4milk.net/>. MIT license <http://mootools.net/license.txt>.
3544
3545 Used by:
3546
3547 <RGraph>, <Hypertree> and <ST> classes.
3548
3549 Description:
3550
3551 This object is used for specifying different animation transitions in the <RGraph>, <Hypertree> and <ST> classes.
3552
3553 There are many different type of animation transitions.
3554
3555 linear:
3556
3557 Displays a linear transition
3558
3559 >Trans.linear
3560
3561 (see Linear.png)
3562
3563 Quad:
3564
3565 Displays a Quadratic transition.
3566
3567 >Trans.Quad.easeIn
3568 >Trans.Quad.easeOut
3569 >Trans.Quad.easeInOut
3570
3571 (see Quad.png)
3572
3573 Cubic:
3574
3575 Displays a Cubic transition.
3576
3577 >Trans.Cubic.easeIn
3578 >Trans.Cubic.easeOut
3579 >Trans.Cubic.easeInOut
3580
3581 (see Cubic.png)
3582
3583 Quart:
3584
3585 Displays a Quartetic transition.
3586
3587 >Trans.Quart.easeIn
3588 >Trans.Quart.easeOut
3589 >Trans.Quart.easeInOut
3590
3591 (see Quart.png)
3592
3593 Quint:
3594
3595 Displays a Quintic transition.
3596
3597 >Trans.Quint.easeIn
3598 >Trans.Quint.easeOut
3599 >Trans.Quint.easeInOut
3600
3601 (see Quint.png)
3602
3603 Expo:
3604
3605 Displays an Exponential transition.
3606
3607 >Trans.Expo.easeIn
3608 >Trans.Expo.easeOut
3609 >Trans.Expo.easeInOut
3610
3611 (see Expo.png)
3612
3613 Circ:
3614
3615 Displays a Circular transition.
3616
3617 >Trans.Circ.easeIn
3618 >Trans.Circ.easeOut
3619 >Trans.Circ.easeInOut
3620
3621 (see Circ.png)
3622
3623 Sine:
3624
3625 Displays a Sineousidal transition.
3626
3627 >Trans.Sine.easeIn
3628 >Trans.Sine.easeOut
3629 >Trans.Sine.easeInOut
3630
3631 (see Sine.png)
3632
3633 Back:
3634
3635 >Trans.Back.easeIn
3636 >Trans.Back.easeOut
3637 >Trans.Back.easeInOut
3638
3639 (see Back.png)
3640
3641 Bounce:
3642
3643 Bouncy transition.
3644
3645 >Trans.Bounce.easeIn
3646 >Trans.Bounce.easeOut
3647 >Trans.Bounce.easeInOut
3648
3649 (see Bounce.png)
3650
3651 Elastic:
3652
3653 Elastic curve.
3654
3655 >Trans.Elastic.easeIn
3656 >Trans.Elastic.easeOut
3657 >Trans.Elastic.easeInOut
3658
3659 (see Elastic.png)
3660
3661
3662
3663 */
3664 this.Trans = {
3665 linear: function(p) { return p; }
3666 };
3667
3668 (function() {
3669
3670 var makeTrans = function(transition, params){
3671 params = $splat(params);
3672 return $extend(transition, {
3673 easeIn: function(pos){
3674 return transition(pos, params);
3675 },
3676 easeOut: function(pos){
3677 return 1 - transition(1 - pos, params);
3678 },
3679 easeInOut: function(pos){
3680 return (pos <= 0.5) ? transition(2 * pos, params) / 2 : (2 - transition(2 * (1 - pos), params)) / 2;
3681 }
3682 });
3683 };
3684
3685 var transitions = {
3686
3687 Pow: function(p, x){
3688 return Math.pow(p, x[0] || 6);
3689 },
3690
3691 Expo: function(p){
3692 return Math.pow(2, 8 * (p - 1));
3693 },
3694
3695 Circ: function(p){
3696 return 1 - Math.sin(Math.acos(p));
3697 },
3698
3699 Sine: function(p){
3700 return 1 - Math.sin((1 - p) * Math.PI / 2);
3701 },
3702
3703 Back: function(p, x){
3704 x = x[0] || 1.618;
3705 return Math.pow(p, 2) * ((x + 1) * p - x);
3706 },
3707
3708 Bounce: function(p){
3709 var value;
3710 for (var a = 0, b = 1; 1; a += b, b /= 2){
3711 if (p >= (7 - 4 * a) / 11){
3712 value = b * b - Math.pow((11 - 6 * a - 11 * p) / 4, 2);
3713 break;
3714 }
3715 }
3716 return value;
3717 },
3718
3719 Elastic: function(p, x){
3720 return Math.pow(2, 10 * --p) * Math.cos(20 * p * Math.PI * (x[0] || 1) / 3);
3721 }
3722
3723 };
3724
3725 $each(transitions, function(val, key) {
3726 Trans[key] = makeTrans(val);
3727 });
3728
3729 $each(['Quad', 'Cubic', 'Quart', 'Quint'], function(elem, i) {
3730 Trans[elem] = makeTrans(function(p){
3731 return Math.pow(p, [i + 2]);
3732 });
3733 });
3734
3735 })();
3736
3737 /*
3738 Class: Animation
3739
3740 A Class that can perform animations for generic objects.
3741
3742 If you are looking for animation transitions please take a look at the <Trans> object.
3743
3744 Used by:
3745
3746 <Graph.Plot>
3747
3748 Based on:
3749
3750 The Animation class is based in the MooTools Framework <http://mootools.net>. Copyright (c) 2006-2009 Valerio Proietti, <http://mad4milk.net/>. MIT license <http://mootools.net/license.txt>.
3751
3752 */
3753
3754 var Animation = new Class({
3755
3756 initalize: function(options) {
3757 this.setOptions(options);
3758 },
3759
3760 setOptions: function(options) {
3761 var opt = {
3762 duration: 2500,
3763 fps: 40,
3764 transition: Trans.Quart.easeInOut,
3765 compute: $empty,
3766 complete: $empty
3767 };
3768 this.opt = $merge(opt, options || {});
3769 return this;
3770 },
3771
3772 getTime: function() {
3773 return $time();
3774 },
3775
3776 step: function(){
3777 var time = this.getTime(), opt = this.opt;
3778 if (time < this.time + opt.duration){
3779 var delta = opt.transition((time - this.time) / opt.duration);
3780 opt.compute(delta);
3781 } else {
3782 this.timer = clearInterval(this.timer);
3783 opt.compute(1);
3784 opt.complete();
3785 }
3786 },
3787
3788 start: function(){
3789 this.time = 0;
3790 this.startTimer();
3791 return this;
3792 },
3793
3794 startTimer: function(){
3795 var that = this, opt = this.opt;
3796 if (this.timer) return false;
3797 this.time = this.getTime() - this.time;
3798 this.timer = setInterval((function () { that.step(); }), Math.round(1000 / opt.fps));
3799 return true;
3800 }
3801 });
3802
3803
3804
3805 /*
3806 * File: Spacetree.js
3807 *
3808 * Implements the <ST> class and other derived classes.
3809 *
3810 * Description:
3811 *
3812 * The main idea of the spacetree algorithm is to take the most common tree layout, and to expand nodes that are "context-related" .i.e lying on the path between the root node and a selected node. Useful animations to contract and expand nodes are also included.
3813 *
3814 * Inspired by:
3815 *
3816 * SpaceTree: Supporting Exploration in Large Node Link Tree, Design Evolution and Empirical Evaluation (Catherine Plaisant, Jesse Grosjean, Benjamin B. Bederson)
3817 *
3818 * <http://hcil.cs.umd.edu/trs/2002-05/2002-05.pdf>
3819 *
3820 * Disclaimer:
3821 *
3822 * This visualization was built from scratch, taking only the paper as inspiration, and only shares some features with the Spacetree.
3823 *
3824 */
3825
3826 /*
3827 Class: ST
3828
3829 The main ST class
3830
3831 Extends:
3832
3833 <Loader>
3834
3835 Parameters:
3836
3837 canvas - A <Canvas> Class
3838 config - A configuration/controller object.
3839
3840 Configuration:
3841
3842 The configuration object can have the following properties (all properties are optional and have a default value)
3843
3844 *General*
3845
3846 - _levelsToShow_ Depth of the plotted tree. The plotted tree will be pruned in order to fit the specified depth if constrained=true. Default's 2.
3847 - _constrained_ If true, the algorithm will try to plot only the part of the tree that fits the Canvas.
3848 - _subtreeOffset_ Separation offset between subtrees. Default's 8.
3849 - _siblingOffset_ Separation offset between siblings. Default's 5.
3850 - _levelDistance_ Distance between levels. Default's 30.
3851 - _orientation_ Sets the orientation layout. Implemented orientations are _left_ (the root node will be placed on the left side of the screen), _top_ (the root node will be placed on top of the screen), _bottom_ and _right_. Default's "left".
3852 - _align_ Whether the tree alignment is left, center or right.
3853 - _indent_ Used when alignment is left or right and shows an indentation between parent and children. Default's 10.
3854 - _withLabels_ Whether the visualization should use/create labels or not. Default's *true*.
3855
3856 *Node*
3857
3858 Customize the visualization nodes' shape, color, and other style properties.
3859
3860 - _Node_
3861
3862 This object has as properties
3863
3864 - _overridable_ Determine whether or not nodes properties can be overriden by a particular node. Default's false.
3865
3866 If given a JSON tree or graph, a node _data_ property contains properties which are the same as defined here but prefixed with
3867 a dollar sign (i.e $), the node properties will override the global node properties.
3868
3869 - _type_ Node type (shape). Possible options are "none", "square", "rectangle", "ellipse" and "circle". Default's "rectangle".
3870 - _color_ Node color. Default's '#ccb'.
3871 - _lineWidth_ Line width. If nodes aren't drawn with strokes then this property won't be of any use. Default's 1.
3872 - _height_ Node height. Used for plotting rectangular nodes. _Width_ and _height_ properties are also used as bounding box for nodes of different shapes.
3873 This means that for all shapes you'd have to make sure that the node's shape is contained in the bounding box defined by _width_ and _height_ parameters. Default's 20.
3874 - _width_ Node width. Used for plotting rectangular nodes and for calculating a node's bounding box. Default's 90.
3875 - _dim_ An extra parameter used by other complex shapes such as square and circle to determine the shape's diameter.
3876 Please notice that even if these complex shapes (square, circle) only use _dim_ for calculating it's diameter property, the complex shape must be
3877 contained in the bounding box calculated with the _width_ and _height_ parameters. Default's 15.
3878 - _align_ Defines a node's alignment. Possible values are "center", "left", "right". Default's "center".
3879
3880 *Edge*
3881
3882 Customize the visualization edges' shape, color, and other style properties.
3883
3884 - _Edge_
3885
3886 This object has as properties
3887
3888 - _overridable_ Determine whether or not edges properties can be overriden by a particular edge object. Default's false.
3889
3890 If given a JSON _complex_ graph (defined in <Loader.loadJSON>), an adjacency _data_ property contains properties which are the same as defined here but prefixed with
3891 a dollar sign (i.e $), the adjacency properties will override the global edge properties.
3892
3893 - _type_ Edge type (shape). Possible options are "none", "line", "quadratic:begin", "quadratic:end", "bezier" and "arrow". Default's "line".
3894 - _color_ Edge color. Default's '#ccb'.
3895 - _lineWidth_ Line width. If edges aren't drawn with strokes then this property won't be of any use. Default's 1.
3896 - _dim_ An extra parameter used by other complex shapes such as quadratic, arrow and bezier to determine the shape's diameter.
3897
3898 *Animations*
3899
3900 - _duration_ Duration of the animation in milliseconds. Default's 700.
3901 - _fps_ Frames per second. Default's 25.
3902 - _transition_ One of the transitions defined in the <Animation> class. Default's Quart.easeInOut.
3903 - _clearCanvas_ Whether to clear canvas on each animation frame or not. Default's true.
3904
3905 *Controller options*
3906
3907 You can also implement controller functions inside the configuration object. This functions are
3908
3909 - _onBeforeCompute(node)_ This method is called right before performing all computation and animations to the JIT visualization.
3910 - _onAfterCompute()_ This method is triggered right after all animations or computations for the JIT visualizations ended.
3911 - _onCreateLabel(domElement, node)_ This method receives the label dom element as first parameter, and the corresponding <Graph.Node> as second parameter. This method will only be called on label creation. Note that a <Graph.Node> is a node from the input tree/graph you provided to the visualization. If you want to know more about what kind of JSON tree/graph format is used to feed the visualizations, you can take a look at <Loader.loadJSON>. This method proves useful when adding events to the labels used by the JIT.
3912 - _onPlaceLabel(domElement, node)_ This method receives the label dom element as first parameter and the corresponding <Graph.Node> as second parameter. This method is called each time a label has been placed on the visualization, and thus it allows you to update the labels properties, such as size or position. Note that onPlaceLabel will be triggered after updating the labels positions. That means that, for example, the left and top css properties are already updated to match the nodes positions.
3913 - _onBeforePlotNode(node)_ This method is triggered right before plotting a given node. The _node_ parameter is the <Graph.Node> to be plotted.
3914 This method is useful for changing a node style right before plotting it.
3915 - _onAfterPlotNode(node)_ This method is triggered right after plotting a given node. The _node_ parameter is the <Graph.Node> plotted.
3916 - _onBeforePlotLine(adj)_ This method is triggered right before plotting an edge. The _adj_ parameter is a <Graph.Adjacence> object.
3917 This method is useful for adding some styles to a particular edge before being plotted.
3918 - _onAfterPlotLine(adj)_ This method is triggered right after plotting an edge. The _adj_ parameter is the <Graph.Adjacence> plotted.
3919 - _request(nodeId, level, onComplete)_ This method is used for buffering information into the visualization. When clicking on an empty node,
3920 the visualization will make a request for this node's subtree, specifying a given level for this subtree. Once this request is completed the _onComplete_
3921 object must be called with the given result.
3922
3923 Example:
3924
3925 Here goes a complete example. In most cases you won't be forced to implement all properties and methods. In fact,
3926 all configuration properties have the default value assigned.
3927
3928 I won't be instanciating a <Canvas> class here. If you want to know more about instanciating a <Canvas> class
3929 please take a look at the <Canvas> class documentation.
3930
3931 (start code js)
3932 var st = new ST(canvas, {
3933 orientation: "left",
3934 levelsToShow: 2,
3935 subtreeOffset: 8,
3936 siblingOffset: 5,
3937 levelDistance: 30,
3938 withLabels: true,
3939 align: "center",
3940 multitree: false,
3941 indent: 10,
3942 Node: {
3943 overridable: false,
3944 type: 'rectangle',
3945 color: '#ccb',
3946 lineWidth: 1,
3947 height: 20,
3948 width: 90,
3949 dim: 15,
3950 align: "center"
3951 },
3952 Edge: {
3953 overridable: false,
3954 type: 'line',
3955 color: '#ccc',
3956 dim: 15,
3957 lineWidth: 1
3958 },
3959 duration: 700,
3960 fps: 25,
3961 transition: Trans.Quart.easeInOut,
3962 clearCanvas: true,
3963
3964 onBeforeCompute: function(node) {
3965 //do something onBeforeCompute
3966 },
3967 onAfterCompute: function () {
3968 //do something onAfterCompute
3969 },
3970 onCreateLabel: function(domElement, node) {
3971 //do something onCreateLabel
3972 },
3973 onPlaceLabel: function(domElement, node) {
3974 //do something onPlaceLabel
3975 },
3976 onBeforePlotNode:function(node) {
3977 //do something onBeforePlotNode
3978 },
3979 onAfterPlotNode: function(node) {
3980 //do something onAfterPlotNode
3981 },
3982 onBeforePlotLine:function(adj) {
3983 //do something onBeforePlotLine
3984 },
3985 onAfterPlotLine: function(adj) {
3986 //do something onAfterPlotLine
3987 },
3988 request: false
3989
3990 });
3991 (end code)
3992
3993 Instance Properties:
3994
3995 - _graph_ Access a <Graph> instance.
3996 - _op_ Access a <ST.Op> instance.
3997 - _fx_ Access a <ST.Plot> instance.
3998 */
3999
4000 (function () {
4001
4002 //Layout functions
4003 var slice = Array.prototype.slice;
4004
4005 /*
4006 Calculates the max width and height nodes for a tree level
4007 */
4008 function getBoundaries(graph, config, level, orn) {
4009 var dim = config.Node, GUtil = Graph.Util;
4010 var multitree = config.multitree;
4011 if(dim.overridable) {
4012 var w = -1, h = -1;
4013 GUtil.eachNode(graph, function(n) {
4014 if(n._depth == level && (!multitree ||
4015 ('$orn' in n.data) &&
4016 n.data.$orn == orn)) {
4017 var dw = n.data.$width || dim.width;
4018 var dh = n.data.$height || dim.height;
4019 w = (w < dw)? dw : w;
4020 h = (h < dh)? dh : h;
4021 }
4022 });
4023 return {
4024 'width': w < 0? dim.width : w,
4025 'height': h < 0? dim.height : h
4026 };
4027 } else {
4028 return dim;
4029 }
4030 };
4031
4032 function movetree(node, prop, val, orn) {
4033 var p = (orn == "left" || orn == "right")? "y" : "x";
4034 node[prop][p] += val;
4035 };
4036
4037 function moveextent(extent, val) {
4038 var ans = [];
4039 $each(extent, function(elem) {
4040 elem = slice.call(elem);
4041 elem[0] += val;
4042 elem[1] += val;
4043 ans.push(elem);
4044 });
4045 return ans;
4046 };
4047
4048 function merge(ps, qs) {
4049 if(ps.length == 0) return qs;
4050 if(qs.length == 0) return ps;
4051 var p = ps.shift(), q = qs.shift();
4052 return [[p[0], q[1]]].concat(merge(ps, qs));
4053 };
4054
4055 function mergelist(ls, def) {
4056 def = def || [];
4057 if(ls.length == 0) return def;
4058 var ps = ls.pop();
4059 return mergelist(ls, merge(ps, def));
4060 };
4061
4062 function fit(ext1, ext2, subtreeOffset, siblingOffset, i) {
4063 if(ext1.length <= i ||
4064 ext2.length <= i) return 0;
4065
4066 var p = ext1[i][1], q = ext2[i][0];
4067 return Math.max(fit(ext1, ext2, subtreeOffset, siblingOffset, ++i)
4068 + subtreeOffset, p - q + siblingOffset);
4069 };
4070
4071 function fitlistl(es, subtreeOffset, siblingOffset) {
4072 function $fitlistl(acc, es, i) {
4073 if(es.length <= i) return [];
4074 var e = es[i], ans = fit(acc, e, subtreeOffset, siblingOffset, 0);
4075 return [ans].concat($fitlistl(merge(acc, moveextent(e, ans)), es, ++i));
4076 };
4077 return $fitlistl([], es, 0);
4078 };
4079
4080 function fitlistr(es, subtreeOffset, siblingOffset) {
4081 function $fitlistr(acc, es, i) {
4082 if(es.length <= i) return [];
4083 var e = es[i], ans = -fit(e, acc, subtreeOffset, siblingOffset, 0);
4084 return [ans].concat($fitlistr(merge(moveextent(e, ans), acc), es, ++i));
4085 };
4086 es = slice.call(es);
4087 var ans = $fitlistr([], es.reverse(), 0);
4088 return ans.reverse();
4089 };
4090
4091 function fitlist(es, subtreeOffset, siblingOffset, align) {
4092 var esl = fitlistl(es, subtreeOffset, siblingOffset),
4093 esr = fitlistr(es, subtreeOffset, siblingOffset);
4094
4095 if(align == "left")
4096 esr = esl;
4097 else if(align == "right")
4098 esl = esr;
4099
4100 for(var i = 0, ans = []; i < esl.length; i++) {
4101 ans[i] = (esl[i] + esr[i]) / 2;
4102 }
4103 return ans;
4104 };
4105
4106 function design(graph, node, prop, config, orn) {
4107 var multitree = config.multitree;
4108 var auxp = ['x', 'y'], auxs = ['width', 'height'];
4109 var ind = +(orn == "left" || orn == "right");
4110 var p = auxp[ind], notp = auxp[1 - ind];
4111
4112 var cnode = config.Node;
4113 var s = auxs[ind], nots = auxs[1 - ind];
4114
4115 var siblingOffset = config.siblingOffset;
4116 var subtreeOffset = config.subtreeOffset;
4117 var align = config.align;
4118
4119 var GUtil = Graph.Util;
4120
4121 function $design(node, maxsize, acum) {
4122 var sval = (cnode.overridable && node.data["$" + s]) || cnode[s];
4123 var notsval = maxsize || ((cnode.overridable && node.data["$" + nots]) || cnode[nots]);
4124
4125 var trees = [], extents = [], chmaxsize = false;
4126 var chacum = notsval + config.levelDistance;
4127 GUtil.eachSubnode(node, function(n) {
4128 if(n.exist && (!multitree ||
4129 ('$orn' in n.data) &&
4130 n.data.$orn == orn)) {
4131
4132 if(!chmaxsize)
4133 chmaxsize = getBoundaries(graph, config, n._depth, orn);
4134
4135 var s = $design(n, chmaxsize[nots], acum + chacum);
4136 trees.push(s.tree);
4137 extents.push(s.extent);
4138 }
4139 });
4140 var positions = fitlist(extents, subtreeOffset, siblingOffset, align);
4141 for(var i=0, ptrees = [], pextents = []; i < trees.length; i++) {
4142 movetree(trees[i], prop, positions[i], orn);
4143 pextents.push(moveextent(extents[i], positions[i]));
4144 }
4145 var resultextent = [[-sval/2, sval/2]].concat(mergelist(pextents));
4146 node[prop][p] = 0;
4147
4148 if (orn == "top" || orn == "left") {
4149 node[prop][notp] = acum;
4150 } else {
4151 node[prop][notp] = -acum;
4152 }
4153
4154 return {
4155 tree: node,
4156 extent: resultextent
4157 };
4158 };
4159 $design(node, false, 0);
4160 };
4161
4162
4163
4164 this.ST= (function() {
4165 //Define some private methods first...
4166 //Nodes in path
4167 var nodesInPath = [];
4168 //Nodes to contract
4169 function getNodesToHide(node) {
4170 node = node || this.clickedNode;
4171 var Geom = this.geom, GUtil = Graph.Util;
4172 var graph = this.graph;
4173 var canvas = this.canvas;
4174 var level = node._depth, nodeArray = [];
4175 GUtil.eachNode(graph, function(n) {
4176 if(n.exist && !n.selected) {
4177 if(GUtil.isDescendantOf(n, node.id)) {
4178 if(n._depth <= level) nodeArray.push(n);
4179 } else {
4180 nodeArray.push(n);
4181 }
4182 }
4183 });
4184 var leafLevel = Geom.getRightLevelToShow(node, canvas);
4185 GUtil.eachLevel(node, leafLevel, leafLevel, function(n) {
4186 if(n.exist && !n.selected) nodeArray.push(n);
4187 });
4188
4189 for (var i = 0; i < nodesInPath.length; i++) {
4190 var n = this.graph.getNode(nodesInPath[i]);
4191 if(!GUtil.isDescendantOf(n, node.id)) {
4192 nodeArray.push(n);
4193 }
4194 }
4195 return nodeArray;
4196 };
4197 //Nodes to expand
4198 function getNodesToShow(node) {
4199 var nodeArray= [], GUtil = Graph.Util, config = this.config;
4200 node = node || this.clickedNode;
4201 GUtil.eachLevel(this.clickedNode, 0, config.levelsToShow, function(n) {
4202 if(config.multitree && !('$orn' in n.data)
4203 && GUtil.anySubnode(n, function(ch){ return ch.exist && !ch.drawn; })) {
4204 nodeArray.push(n);
4205 } else if(n.drawn && !GUtil.anySubnode(n, "drawn")) {
4206 nodeArray.push(n);
4207 }
4208 });
4209 return nodeArray;
4210 };
4211 //Now define the actual class.
4212 return new Class({
4213
4214 Implements: Loader,
4215
4216 initialize: function(canvas, controller) {
4217 var innerController = {
4218 onBeforeCompute: $empty,
4219 onAfterCompute: $empty,
4220 onCreateLabel: $empty,
4221 onPlaceLabel: $empty,
4222 onComplete: $empty,
4223 onBeforePlotNode:$empty,
4224 onAfterPlotNode: $empty,
4225 onBeforePlotLine:$empty,
4226 onAfterPlotLine: $empty,
4227 request: false
4228 };
4229
4230 var config= {
4231 orientation: "left",
4232 labelContainer: canvas.id + '-label',
4233 levelsToShow: 2,
4234 subtreeOffset: 8,
4235 siblingOffset: 5,
4236 levelDistance: 30,
4237 withLabels: true,
4238 clearCanvas: true,
4239 align: "center",
4240 indent:10,
4241 multitree: false,
4242 constrained: true,
4243
4244 Node: {
4245 overridable: false,
4246 type: 'rectangle',
4247 color: '#ccb',
4248 lineWidth: 1,
4249 height: 20,
4250 width: 90,
4251 dim: 15,
4252 align: "center"
4253 },
4254 Edge: {
4255 overridable: false,
4256 type: 'line',
4257 color: '#ccc',
4258 dim: 15,
4259 lineWidth: 1
4260 },
4261 duration: 700,
4262 fps: 25,
4263 transition: Trans.Quart.easeInOut
4264 };
4265
4266 this.controller = this.config = $merge(config, innerController, controller);
4267 this.canvas = canvas;
4268 this.graphOptions = {
4269 'complex': true
4270 };
4271 this.graph = new Graph(this.graphOptions);
4272 this.fx = new ST.Plot(this);
4273 this.op = new ST.Op(this);
4274 this.group = new ST.Group(this);
4275 this.geom = new ST.Geom(this);
4276 this.clickedNode= null;
4277
4278 },
4279
4280 /*
4281 Method: plot
4282
4283 Plots the tree. Usually this method is called right after computing nodes' positions.
4284
4285 */
4286 plot: function() { this.fx.plot(this.controller); },
4287
4288
4289 /*
4290 Method: switchPosition
4291
4292 Switches the tree orientation.
4293
4294 Parameters:
4295
4296 pos - The new tree orientation. Possible values are "top", "left", "right" and "bottom".
4297 method - Set this to "animate" if you want to animate the tree when switching its position. You can also set this parameter to "replot" to just replot the subtree.
4298 onComplete - _optional_ This callback is called once the "switching" animation is complete.
4299
4300 Example:
4301
4302 (start code js)
4303 st.switchPosition("right", "animate", {
4304 onComplete: function() {
4305 alert('completed!');
4306 }
4307 });
4308 (end code)
4309 */
4310 switchPosition: function(pos, method, onComplete) {
4311 var Geom = this.geom, Plot = this.fx, that = this;
4312 if(!Plot.busy) {
4313 Plot.busy = true;
4314 this.contract({
4315 onComplete: function() {
4316 Geom.switchOrientation(pos);
4317 that.compute('endPos', false);
4318 Plot.busy = false;
4319 if(method == 'animate') {
4320 that.onClick(that.clickedNode.id, onComplete);
4321 } else if(method == 'replot') {
4322 that.select(that.clickedNode.id, onComplete);
4323 }
4324 }
4325 }, pos);
4326 }
4327 },
4328
4329 /*
4330 Method: switchAlignment
4331
4332 Switches the tree alignment.
4333
4334 Parameters:
4335
4336 align - The new tree alignment. Possible values are "left", "center" and "right".
4337 method - Set this to "animate" if you want to animate the tree after aligning its position. You can also set this parameter to "replot" to just replot the subtree.
4338 onComplete - _optional_ This callback is called once the "switching" animation is complete.
4339
4340 Example:
4341
4342 (start code js)
4343 st.switchAlignment("right", "animate", {
4344 onComplete: function() {
4345 alert('completed!');
4346 }
4347 });
4348 (end code)
4349 */
4350 switchAlignment: function(align, method, onComplete) {
4351 this.config.align = align;
4352 if(method == 'animate') {
4353 this.select(this.clickedNode.id, onComplete);
4354 } else if(method == 'replot') {
4355 this.onClick(this.clickedNode.id, onComplete);
4356 }
4357 },
4358
4359 /*
4360 Method: addNodeInPath
4361
4362 Adds a node to the current path as selected node. This node will be visible (as in non-collapsed) at all times.
4363
4364
4365 Parameters:
4366
4367 id - A <Graph.Node> id.
4368
4369 Example:
4370
4371 (start code js)
4372 st.addNodeInPath("somenodeid");
4373 (end code)
4374 */
4375 addNodeInPath: function(id) {
4376 nodesInPath.push(id);
4377 this.select((this.clickedNode && this.clickedNode.id) || this.root);
4378 },
4379
4380 /*
4381 Method: clearNodesInPath
4382
4383 Removes all nodes tagged as selected by the <ST.addNodeInPath> method.
4384
4385 See also:
4386
4387 <ST.addNodeInPath>
4388
4389 Example:
4390
4391 (start code js)
4392 st.clearNodesInPath();
4393 (end code)
4394 */
4395 clearNodesInPath: function(id) {
4396 nodesInPath.length = 0;
4397 this.select((this.clickedNode && this.clickedNode.id) || this.root);
4398 },
4399
4400 /*
4401 Method: refresh
4402
4403 Computes nodes' positions and replots the tree.
4404
4405 */
4406 refresh: function() {
4407 this.reposition();
4408 this.select((this.clickedNode && this.clickedNode.id) || this.root);
4409 },
4410
4411 reposition: function() {
4412 Graph.Util.computeLevels(this.graph, this.root, 0, "ignore");
4413 this.geom.setRightLevelToShow(this.clickedNode, this.canvas);
4414 Graph.Util.eachNode(this.graph, function(n) {
4415 if(n.exist) n.drawn = true;
4416 });
4417 this.compute('endPos');
4418 },
4419
4420 /*
4421 Method: compute
4422
4423 Computes nodes' positions.
4424
4425 */
4426 compute: function (property, computeLevels) {
4427 var prop = property || 'startPos';
4428 var node = this.graph.getNode(this.root);
4429 $extend(node, {
4430 'drawn':true,
4431 'exist':true,
4432 'selected':true
4433 });
4434 if(!!computeLevels || !("_depth" in node))
4435 Graph.Util.computeLevels(this.graph, this.root, 0, "ignore");
4436 this.computePositions(node, prop);
4437 },
4438
4439 computePositions: function(node, prop) {
4440 var config = this.config;
4441 var multitree = config.multitree;
4442 var align = config.align;
4443 var indent = align !== 'center' && config.indent;
4444 var orn = config.orientation;
4445 var orns = multitree? ['top', 'right', 'bottom', 'left'] : [orn];
4446
4447 var that = this;
4448 $each(orns, function(orn) {
4449 //calculate layout
4450 design(that.graph, node, prop, that.config, orn);
4451 var i = ['x', 'y'][+(orn == "left" || orn == "right")];
4452 //absolutize
4453 (function red(node) {
4454 Graph.Util.eachSubnode(node, function(n) {
4455 if(n.exist && (!multitree ||
4456 ('$orn' in n.data) &&
4457 n.data.$orn == orn)) {
4458
4459 n[prop][i] += node[prop][i];
4460 if(indent) {
4461 n[prop][i] += align == 'left'? indent : -indent;
4462 }
4463 red(n);
4464 }
4465 });
4466 })(node);
4467 });
4468 },
4469
4470 requestNodes: function(node, onComplete) {
4471 var handler = $merge(this.controller, onComplete),
4472 lev = this.config.levelsToShow, GUtil = Graph.Util;
4473 if(handler.request) {
4474 var leaves = [], d = node._depth;
4475 GUtil.eachLevel(node, 0, lev, function(n) {
4476 if(n.drawn &&
4477 !GUtil.anySubnode(n)) {
4478 leaves.push(n);
4479 n._level = lev - (n._depth - d);
4480 }
4481 });
4482 this.group.requestNodes(leaves, handler);
4483 }
4484 else
4485 handler.onComplete();
4486 },
4487
4488 contract: function(onComplete, switched) {
4489 var orn = this.config.orientation;
4490 var Geom = this.geom, Group = this.group;
4491 if(switched) Geom.switchOrientation(switched);
4492 var nodes = getNodesToHide.call(this);
4493 if(switched) Geom.switchOrientation(orn);
4494 Group.contract(nodes, $merge(this.controller, onComplete));
4495 },
4496
4497 move: function(node, onComplete) {
4498 this.compute('endPos', false);
4499 var move = onComplete.Move, offset = {
4500 'x': move.offsetX,
4501 'y': move.offsetY
4502 };
4503 if(move.enable) {
4504 this.geom.translate(node.endPos.add(offset).$scale(-1), "endPos");
4505 }
4506 this.fx.animate($merge(this.controller, { modes: ['linear'] }, onComplete));
4507 },
4508
4509
4510 expand: function (node, onComplete) {
4511 var nodeArray = getNodesToShow.call(this, node);
4512 this.group.expand(nodeArray, $merge(this.controller, onComplete));
4513 },
4514
4515
4516 selectPath: function(node) {
4517 var GUtil = Graph.Util, that = this;
4518 GUtil.eachNode(this.graph, function(n) { n.selected = false; });
4519 function path(node) {
4520 if(node == null || node.selected) return;
4521 node.selected = true;
4522 $each(that.group.getSiblings([node])[node.id],
4523 function(n) {
4524 n.exist = true;
4525 n.drawn = true;
4526 });
4527 var parents = GUtil.getParents(node);
4528 parents = (parents.length > 0)? parents[0] : null;
4529 path(parents);
4530 };
4531 for(var i=0, ns = [node.id].concat(nodesInPath); i < ns.length; i++) {
4532 path(this.graph.getNode(ns[i]));
4533 }
4534 },
4535
4536 /*
4537 Method: setRoot
4538
4539 Switches the current root node.
4540
4541 Parameters:
4542 id - The id of the node to be set as root.
4543 method - Set this to "animate" if you want to animate the tree after adding the subtree. You can also set this parameter to "replot" to just replot the subtree.
4544 onComplete - _optional_ An action to perform after the animation (if any).
4545
4546 Example:
4547
4548 (start code js)
4549 st.setRoot('my_node_id', 'animate', {
4550 onComplete: function() {
4551 alert('complete!');
4552 }
4553 });
4554 (end code)
4555 */
4556 setRoot: function(id, method, onComplete) {
4557 var that = this, canvas = this.canvas;
4558 var rootNode = this.graph.getNode(this.root);
4559 var clickedNode = this.graph.getNode(id);
4560 function $setRoot() {
4561 if(this.config.multitree && clickedNode.data.$orn) {
4562 var orn = clickedNode.data.$orn;
4563 var opp = {
4564 'left': 'right',
4565 'right': 'left',
4566 'top': 'bottom',
4567 'bottom': 'top'
4568 }[orn];
4569 rootNode.data.$orn = opp;
4570 (function tag(rootNode) {
4571 Graph.Util.eachSubnode(rootNode, function(n) {
4572 if(n.id != id) {
4573 n.data.$orn = opp;
4574 tag(n);
4575 }
4576 });
4577 })(rootNode);
4578 delete clickedNode.data.$orn;
4579 }
4580 this.root = id;
4581 this.clickedNode = clickedNode;
4582 Graph.Util.computeLevels(this.graph, this.root, 0, "ignore");
4583 }
4584
4585 //delete previous orientations (if any)
4586 delete rootNode.data.$orns;
4587
4588 if(method == 'animate') {
4589 this.onClick(id, {
4590 onBeforeMove: function() {
4591 $setRoot.call(that);
4592 that.selectPath(clickedNode);
4593 }
4594 });
4595 } else if(method == 'replot') {
4596 $setRoot.call(this);
4597 this.select(this.root);
4598 }
4599 },
4600
4601 /*
4602 Method: addSubtree
4603
4604 Adds a subtree, performing optionally an animation.
4605
4606 Parameters:
4607 subtree - A JSON Tree object. See also <Loader.loadJSON>.
4608 method - Set this to "animate" if you want to animate the tree after adding the subtree. You can also set this parameter to "replot" to just replot the subtree.
4609 onComplete - _optional_ An action to perform after the animation (if any).
4610
4611 Example:
4612
4613 (start code js)
4614 st.addSubtree(json, 'animate', {
4615 onComplete: function() {
4616 alert('complete!');
4617 }
4618 });
4619 (end code)
4620 */
4621 addSubtree: function(subtree, method, onComplete) {
4622 if(method == 'replot') {
4623 this.op.sum(subtree, $extend({ type: 'replot' }, onComplete || {}));
4624 } else if (method == 'animate') {
4625 this.op.sum(subtree, $extend({ type: 'fade:seq' }, onComplete || {}));
4626 }
4627 },
4628
4629 /*
4630 Method: removeSubtree
4631
4632 Removes a subtree, performing optionally an animation.
4633
4634 Parameters:
4635 id - The _id_ of the subtree to be removed.
4636 removeRoot - Remove the root of the subtree or only its subnodes.
4637 method - Set this to "animate" if you want to animate the tree after removing the subtree. You can also set this parameter to "replot" to just replot the subtree.
4638 onComplete - _optional_ An action to perform after the animation (if any).
4639
4640 Example:
4641
4642 (start code js)
4643 st.removeSubtree('idOfSubtreeToBeRemoved', false, 'animate', {
4644 onComplete: function() {
4645 alert('complete!');
4646 }
4647 });
4648 (end code)
4649
4650 */
4651 removeSubtree: function(id, removeRoot, method, onComplete) {
4652 var node = this.graph.getNode(id), subids = [];
4653 Graph.Util.eachLevel(node, +!removeRoot, false, function(n) {
4654 subids.push(n.id);
4655 });
4656 if(method == 'replot') {
4657 this.op.removeNode(subids, $extend({ type: 'replot' }, onComplete || {}));
4658 } else if (method == 'animate') {
4659 this.op.removeNode(subids, $extend({ type: 'fade:seq'}, onComplete || {}));
4660 }
4661 },
4662
4663 /*
4664 Method: select
4665
4666 Selects a sepecific node in the Spacetree without performing an animation. Useful when selecting
4667 nodes which are currently hidden or deep inside the tree.
4668
4669 Parameters:
4670 id - The id of the node to select.
4671 onComplete - _optional_ onComplete callback.
4672
4673 Example:
4674 (start code js)
4675 st.select('mynodeid', {
4676 onComplete: function() {
4677 alert('complete!');
4678 }
4679 });
4680 (end code)
4681 */
4682 select: function(id, onComplete) {
4683 var group = this.group, geom = this.geom;
4684 var node= this.graph.getNode(id), canvas = this.canvas;
4685 var root = this.graph.getNode(this.root);
4686 var complete = $merge(this.controller, onComplete);
4687 var that = this;
4688
4689 complete.onBeforeCompute(node);
4690 this.selectPath(node);
4691 this.clickedNode= node;
4692 this.requestNodes(node, {
4693 onComplete: function(){
4694 group.hide(group.prepare(getNodesToHide.call(that)), complete);
4695 geom.setRightLevelToShow(node, canvas);
4696 that.compute("pos");
4697 Graph.Util.eachNode(that.graph, function(n) {
4698 var pos = n.pos.getc(true);
4699 n.startPos.setc(pos.x, pos.y);
4700 n.endPos.setc(pos.x, pos.y);
4701 n.visited = false;
4702 });
4703 that.geom.translate(node.endPos.scale(-1), ["pos", "startPos", "endPos"]);
4704 group.show(getNodesToShow.call(that));
4705 that.plot();
4706 complete.onAfterCompute(that.clickedNode);
4707 complete.onComplete();
4708 }
4709 });
4710 },
4711
4712 /*
4713 Method: onClick
4714
4715 This method is called when clicking on a tree node. It mainly performs all calculations and the animation of contracting, translating and expanding pertinent nodes.
4716
4717
4718 Parameters:
4719
4720 id - A node id.
4721 options - A group of options and callbacks such as
4722
4723 - _onComplete_ an object callback called when the animation finishes.
4724 - _Move_ an object that has as properties _offsetX_ or _offsetY_ for adding some offset position to the centered node.
4725
4726 Example:
4727
4728 (start code js)
4729 st.onClick('mynodeid', {
4730 Move: {
4731 enable: true,
4732 offsetX: 30,
4733 offsetY: 5
4734 },
4735 onComplete: function() {
4736 alert('yay!');
4737 }
4738 });
4739 (end code)
4740
4741 */
4742 onClick: function (id, options) {
4743 var canvas = this.canvas, that = this, Fx = this.fx, Util = Graph.Util, Geom = this.geom;
4744 var innerController = {
4745 Move: {
4746 enable: true,
4747 offsetX: 0,
4748 offsetY: 0
4749 },
4750 onBeforeRequest: $empty,
4751 onBeforeContract: $empty,
4752 onBeforeMove: $empty,
4753 onBeforeExpand: $empty
4754 };
4755 var complete = $merge(this.controller, innerController, options);
4756
4757 if(!this.busy) {
4758 this.busy= true;
4759 var node= this.graph.getNode(id);
4760 this.selectPath(node, this.clickedNode);
4761 this.clickedNode= node;
4762 complete.onBeforeCompute(node);
4763 complete.onBeforeRequest(node);
4764 this.requestNodes(node, {
4765 onComplete: function() {
4766 complete.onBeforeContract(node);
4767 that.contract({
4768 onComplete: function() {
4769 Geom.setRightLevelToShow(node, canvas);
4770 complete.onBeforeMove(node);
4771 that.move(node, {
4772 Move: complete.Move,
4773 onComplete: function() {
4774 complete.onBeforeExpand(node);
4775 that.expand(node, {
4776 onComplete: function() {
4777 that.busy = false;
4778 complete.onAfterCompute(id);
4779 complete.onComplete();
4780 }
4781 }); //expand
4782 }
4783 }); //move
4784 }
4785 });//contract
4786 }
4787 });//request
4788 }
4789 }
4790 });
4791
4792 })();
4793
4794 /*
4795 Class: ST.Op
4796
4797 Performs advanced operations on trees and graphs.
4798
4799 Extends:
4800
4801 All <Graph.Op> methods
4802
4803 Access:
4804
4805 This instance can be accessed with the _op_ parameter of the st instance created.
4806
4807 Example:
4808
4809 (start code js)
4810 var st = new ST(canvas, config);
4811 st.op.morph //or can also call any other <Graph.Op> method
4812 (end code)
4813
4814 */
4815 ST.Op = new Class({
4816 Implements: Graph.Op,
4817
4818 initialize: function(viz) {
4819 this.viz = viz;
4820 }
4821 });
4822
4823 /*
4824
4825 Performs operations on group of nodes.
4826
4827 */
4828 ST.Group = new Class({
4829
4830 initialize: function(viz) {
4831 this.viz = viz;
4832 this.canvas = viz.canvas;
4833 this.config = viz.config;
4834 this.animation = new Animation;
4835 this.nodes = null;
4836 },
4837
4838 /*
4839
4840 Calls the request method on the controller to request a subtree for each node.
4841 */
4842 requestNodes: function(nodes, controller) {
4843 var counter = 0, len = nodes.length, nodeSelected = {};
4844 var complete = function() { controller.onComplete(); };
4845 var viz = this.viz;
4846 if(len == 0) complete();
4847 for(var i=0; i<len; i++) {
4848 nodeSelected[nodes[i].id] = nodes[i];
4849 controller.request(nodes[i].id, nodes[i]._level, {
4850 onComplete: function(nodeId, data) {
4851 if(data && data.children) {
4852 data.id = nodeId;
4853 viz.op.sum(data, { type: 'nothing' });
4854 }
4855 if(++counter == len) {
4856 Graph.Util.computeLevels(viz.graph, viz.root, 0);
4857 complete();
4858 }
4859 }
4860 });
4861 }
4862 },
4863
4864 /*
4865
4866 Collapses group of nodes.
4867 */
4868 contract: function(nodes, controller) {
4869 var GUtil = Graph.Util;
4870 var viz = this.viz;
4871 var that = this;
4872
4873 nodes = this.prepare(nodes);
4874 this.animation.setOptions($merge(controller, {
4875 $animating: false,
4876 compute: function(delta) {
4877 if(delta == 1) delta = 0.99;
4878 that.plotStep(1 - delta, controller, this.$animating);
4879 this.$animating = 'contract';
4880 },
4881
4882 complete: function() {
4883 that.hide(nodes, controller);
4884 }
4885 })).start();
4886 },
4887
4888 hide: function(nodes, controller) {
4889 var GUtil = Graph.Util, viz = this.viz;
4890 for(var i=0; i<nodes.length; i++) {
4891 //TODO nodes are requested on demand, but not
4892 //deleted when hidden. Would that be a good feature?
4893 //Currently that feature is buggy, so I'll turn it off
4894 //Actually this feature is buggy because trimming should take
4895 //place onAfterCompute and not right after collapsing nodes.
4896 if (true || !controller || !controller.request) {
4897 GUtil.eachLevel(nodes[i], 1, false, function(elem){
4898 if (elem.exist) {
4899 $extend(elem, {
4900 'drawn': false,
4901 'exist': false
4902 });
4903 }
4904 });
4905 } else {
4906 var ids = [];
4907 GUtil.eachLevel(nodes[i], 1, false, function(n) {
4908 ids.push(n.id);
4909 });
4910 viz.op.removeNode(ids, { 'type': 'nothing' });
4911 viz.fx.clearLabels();
4912 }
4913 }
4914 controller.onComplete();
4915 },
4916
4917
4918 /*
4919
4920 Expands group of nodes.
4921 */
4922 expand: function(nodes, controller) {
4923 var that = this, GUtil = Graph.Util;
4924 this.show(nodes);
4925 this.animation.setOptions($merge(controller, {
4926 $animating: false,
4927 compute: function(delta) {
4928 that.plotStep(delta, controller, this.$animating);
4929 this.$animating = 'expand';
4930 },
4931
4932 complete: function() {
4933 that.plotStep(undefined, controller, false);
4934 controller.onComplete();
4935 }
4936 })).start();
4937
4938 },
4939
4940 show: function(nodes) {
4941 var GUtil = Graph.Util, config = this.config;
4942 this.prepare(nodes);
4943 $each(nodes, function(n) {
4944 //check for root nodes if multitree
4945 if(config.multitree && !('$orn' in n.data)) {
4946 delete n.data.$orns;
4947 var orns = ' ';
4948 GUtil.eachSubnode(n, function(ch) {
4949 if(('$orn' in ch.data)
4950 && orns.indexOf(ch.data.$orn) < 0
4951 && ch.exist && !ch.drawn) {
4952 orns += ch.data.$orn + ' ';
4953 }
4954 });
4955 n.data.$orns = orns;
4956 }
4957 GUtil.eachLevel(n, 0, config.levelsToShow, function(n) {
4958 if(n.exist) n.drawn = true;
4959 });
4960 });
4961 },
4962
4963 prepare: function(nodes) {
4964 this.nodes = this.getNodesWithChildren(nodes);
4965 return this.nodes;
4966 },
4967
4968 /*
4969 Filters an array of nodes leaving only nodes with children.
4970 */
4971 getNodesWithChildren: function(nodes) {
4972 var ans = [], GUtil = Graph.Util, config = this.config, root = this.viz.root;
4973 nodes.sort(function(a, b) { return (a._depth <= b._depth) - (a._depth >= b._depth); });
4974 for(var i=0; i<nodes.length; i++) {
4975 if(GUtil.anySubnode(nodes[i], "exist")) {
4976 for (var j = i+1, desc = false; !desc && j < nodes.length; j++) {
4977 if(!config.multitree || '$orn' in nodes[j].data) {
4978 desc = desc || GUtil.isDescendantOf(nodes[i], nodes[j].id);
4979 }
4980 }
4981 if(!desc) ans.push(nodes[i]);
4982 }
4983 }
4984 return ans;
4985 },
4986
4987 plotStep: function(delta, controller, animating) {
4988 var viz = this.viz,
4989 config = this.config,
4990 canvas = viz.canvas,
4991 ctx = canvas.getCtx(),
4992 nodes = this.nodes,
4993 GUtil = Graph.Util;
4994 var i, node;
4995 //hide nodes that are meant to be collapsed/expanded
4996 var nds = {};
4997 for(i=0; i<nodes.length; i++) {
4998 node = nodes[i];
4999 nds[node.id] = [];
5000 var root = config.multitree && !('$orn' in node.data);
5001 var orns = root && node.data.$orns;
5002 GUtil.eachSubgraph(node, function(n) {
5003 //TODO(nico): Cleanup
5004 //special check for root node subnodes when
5005 //multitree is checked.
5006 if(root && orns && orns.indexOf(n.data.$orn) > 0
5007 && n.drawn) {
5008 n.drawn = false;
5009 nds[node.id].push(n);
5010 } else if((!root || !orns) && n.drawn) {
5011 n.drawn = false;
5012 nds[node.id].push(n);
5013 }
5014 });
5015 node.drawn = true;
5016 }
5017 //plot the whole (non-scaled) tree
5018 if(nodes.length > 0) viz.fx.plot();
5019 //show nodes that were previously hidden
5020 for(i in nds) {
5021 $each(nds[i], function(n) { n.drawn = true; });
5022 }
5023 //plot each scaled subtree
5024 for(i=0; i<nodes.length; i++) {
5025 node = nodes[i];
5026 ctx.save();
5027 viz.fx.plotSubtree(node, controller, delta, animating);
5028 ctx.restore();
5029 }
5030 },
5031
5032 getSiblings: function(nodes) {
5033 var siblings = {}, GUtil = Graph.Util;
5034 $each(nodes, function(n) {
5035 var par = GUtil.getParents(n);
5036 if (par.length == 0) {
5037 siblings[n.id] = [n];
5038 } else {
5039 var ans = [];
5040 GUtil.eachSubnode(par[0], function(sn) {
5041 ans.push(sn);
5042 });
5043 siblings[n.id] = ans;
5044 }
5045 });
5046 return siblings;
5047 }
5048 });
5049
5050 /*
5051 Class: ST.Geom
5052
5053 Performs low level geometrical computations.
5054
5055 Access:
5056
5057 This instance can be accessed with the _geom_ parameter of the st instance created.
5058
5059 Example:
5060
5061 (start code js)
5062 var st = new ST(canvas, config);
5063 st.geom.translate //or can also call any other <ST.Geom> method
5064 (end code)
5065
5066 */
5067
5068 ST.Geom = new Class({
5069
5070 initialize: function(viz) {
5071 this.viz = viz;
5072 this.config = viz.config;
5073 this.node = viz.config.Node;
5074 this.edge = viz.config.Edge;
5075 },
5076
5077 /*
5078 Method: translate
5079
5080 Applies a translation to the tree.
5081
5082 Parameters:
5083
5084 pos - A <Complex> number specifying translation vector.
5085 prop - A <Graph.Node> position property ('pos', 'startPos' or 'endPos').
5086
5087 Example:
5088
5089 (start code js)
5090 st.geom.translate(new Complex(300, 100), 'endPos');
5091 (end code)
5092 */
5093 translate: function(pos, prop) {
5094 prop = $splat(prop);
5095 Graph.Util.eachNode(this.viz.graph, function(elem) {
5096 $each(prop, function(p) { elem[p].$add(pos); });
5097 });
5098 },
5099
5100 /*
5101 Changes the tree current orientation to the one specified.
5102
5103 You should usually use <ST.switchPosition> instead.
5104 */
5105 switchOrientation: function(orn) {
5106 this.config.orientation = orn;
5107 },
5108
5109 /*
5110 Makes a value dispatch according to the current layout
5111 Works like a CSS property, either _top-right-bottom-left_ or _top|bottom - left|right_.
5112 */
5113 dispatch: function() {
5114 //TODO(nico) should store Array.prototype.slice.call somewhere.
5115 var args = Array.prototype.slice.call(arguments);
5116 var s = args.shift(), len = args.length;
5117 var val = function(a) { return typeof a == 'function'? a() : a; };
5118 if(len == 2) {
5119 return (s == "top" || s == "bottom")? val(args[0]) : val(args[1]);
5120 } else if(len == 4) {
5121 switch(s) {
5122 case "top": return val(args[0]);
5123 case "right": return val(args[1]);
5124 case "bottom": return val(args[2]);
5125 case "left": return val(args[3]);
5126 }
5127 }
5128 return undefined;
5129 },
5130
5131 /*
5132 Returns label height or with, depending on the tree current orientation.
5133 */
5134 getSize: function(n, invert) {
5135 var node = this.node, data = n.data, config = this.config;
5136 var cond = node.overridable, siblingOffset = config.siblingOffset;
5137 var s = (this.config.multitree
5138 && ('$orn' in n.data)
5139 && n.data.$orn) || this.config.orientation;
5140 var w = (cond && data.$width || node.width) + siblingOffset;
5141 var h = (cond && data.$height || node.height) + siblingOffset;
5142 if(!invert)
5143 return this.dispatch(s, h, w);
5144 else
5145 return this.dispatch(s, w, h);
5146 },
5147
5148 /*
5149 Calculates a subtree base size. This is an utility function used by _getBaseSize_
5150 */
5151 getTreeBaseSize: function(node, level, leaf) {
5152 var size = this.getSize(node, true), baseHeight = 0, that = this;
5153 if(leaf(level, node)) return size;
5154 if(level === 0) return 0;
5155 Graph.Util.eachSubnode(node, function(elem) {
5156 baseHeight += that.getTreeBaseSize(elem, level -1, leaf);
5157 });
5158 return (size > baseHeight? size : baseHeight) + this.config.subtreeOffset;
5159 },
5160
5161
5162 /*
5163 Method: getEdge
5164
5165 Returns a Complex instance with the begin or end position of the edge to be plotted.
5166
5167 Parameters:
5168
5169 node - A <Graph.Node> that is connected to this edge.
5170 type - Returns the begin or end edge position. Possible values are 'begin' or 'end'.
5171
5172 Returns:
5173
5174 A <Complex> number specifying the begin or end position.
5175 */
5176 getEdge: function(node, type, s) {
5177 var $C = function(a, b) {
5178 return function(){
5179 return node.pos.add(new Complex(a, b));
5180 };
5181 };
5182 var dim = this.node;
5183 var cond = this.node.overridable, data = node.data;
5184 var w = cond && data.$width || dim.width;
5185 var h = cond && data.$height || dim.height;
5186
5187 if(type == 'begin') {
5188 if(dim.align == "center") {
5189 return this.dispatch(s, $C(0, h/2), $C(-w/2, 0),
5190 $C(0, -h/2),$C(w/2, 0));
5191 } else if(dim.align == "left") {
5192 return this.dispatch(s, $C(0, h), $C(0, 0),
5193 $C(0, 0), $C(w, 0));
5194 } else if(dim.align == "right") {
5195 return this.dispatch(s, $C(0, 0), $C(-w, 0),
5196 $C(0, -h),$C(0, 0));
5197 } else throw "align: not implemented";
5198
5199
5200 } else if(type == 'end') {
5201 if(dim.align == "center") {
5202 return this.dispatch(s, $C(0, -h/2), $C(w/2, 0),
5203 $C(0, h/2), $C(-w/2, 0));
5204 } else if(dim.align == "left") {
5205 return this.dispatch(s, $C(0, 0), $C(w, 0),
5206 $C(0, h), $C(0, 0));
5207 } else if(dim.align == "right") {
5208 return this.dispatch(s, $C(0, -h),$C(0, 0),
5209 $C(0, 0), $C(-w, 0));
5210 } else throw "align: not implemented";
5211 }
5212 },
5213
5214 /*
5215 Adjusts the tree position due to canvas scaling or translation.
5216 */
5217 getScaledTreePosition: function(node, scale) {
5218 var dim = this.node;
5219 var cond = this.node.overridable, data = node.data;
5220 var w = (cond && data.$width || dim.width);
5221 var h = (cond && data.$height || dim.height);
5222 var s = (this.config.multitree
5223 && ('$orn' in node.data)
5224 && node.data.$orn) || this.config.orientation;
5225
5226 var $C = function(a, b) {
5227 return function(){
5228 return node.pos.add(new Complex(a, b)).$scale(1 - scale);
5229 };
5230 };
5231 if(dim.align == "left") {
5232 return this.dispatch(s, $C(0, h), $C(0, 0),
5233 $C(0, 0), $C(w, 0));
5234 } else if(dim.align == "center") {
5235 return this.dispatch(s, $C(0, h / 2), $C(-w / 2, 0),
5236 $C(0, -h / 2),$C(w / 2, 0));
5237 } else if(dim.align == "right") {
5238 return this.dispatch(s, $C(0, 0), $C(-w, 0),
5239 $C(0, -h),$C(0, 0));
5240 } else throw "align: not implemented";
5241 },
5242
5243 /*
5244 Method: treeFitsInCanvas
5245
5246 Returns a Boolean if the current subtree fits in canvas.
5247
5248 Parameters:
5249
5250 node - A <Graph.Node> which is the current root of the subtree.
5251 canvas - The <Canvas> object.
5252 level - The depth of the subtree to be considered.
5253 */
5254 treeFitsInCanvas: function(node, canvas, level) {
5255 var csize = canvas.getSize(node);
5256 var s = (this.config.multitree
5257 && ('$orn' in node.data)
5258 && node.data.$orn) || this.config.orientation;
5259
5260 var size = this.dispatch(s, csize.width, csize.height);
5261 var baseSize = this.getTreeBaseSize(node, level, function(level, node) {
5262 return level === 0 || !Graph.Util.anySubnode(node);
5263 });
5264 return (baseSize < size);
5265 },
5266
5267 /*
5268 Hides levels of the tree until it properly fits in canvas.
5269 */
5270 setRightLevelToShow: function(node, canvas) {
5271 var level = this.getRightLevelToShow(node, canvas), fx = this.viz.fx;
5272 Graph.Util.eachLevel(node, 0, this.config.levelsToShow, function(n) {
5273 var d = n._depth - node._depth;
5274 if(d > level) {
5275 n.drawn = false;
5276 n.exist = false;
5277 fx.hideLabel(n, false);
5278 } else {
5279 n.exist = true;
5280 }
5281 });
5282 node.drawn= true;
5283 },
5284
5285 /*
5286 Returns the right level to show for the current tree in order to fit in canvas.
5287 */
5288 getRightLevelToShow: function(node, canvas) {
5289 var config = this.config;
5290 var level = config.levelsToShow;
5291 var constrained = config.constrained;
5292 if(!constrained) return level;
5293 while(!this.treeFitsInCanvas(node, canvas, level) && level > 1) { level-- ; }
5294 return level;
5295 }
5296
5297 });
5298
5299 /*
5300 Object: ST.Plot
5301
5302 Performs plotting operations.
5303
5304 Extends:
5305
5306 All <Graph.Plot> methods
5307
5308 Access:
5309
5310 This instance can be accessed with the _fx_ parameter of the st instance created.
5311
5312 Example:
5313
5314 (start code js)
5315 var st = new ST(canvas, config);
5316 st.fx.placeLabel //or can also call any other <ST.Plot> method
5317 (end code)
5318
5319
5320 */
5321 ST.Plot = new Class({
5322
5323 Implements: Graph.Plot,
5324
5325 initialize: function(viz) {
5326 this.viz = viz;
5327 this.config = viz.config;
5328 this.node = this.config.Node;
5329 this.edge = this.config.Edge;
5330 this.animation = new Animation;
5331 this.nodeTypes = new ST.Plot.NodeTypes;
5332 this.edgeTypes = new ST.Plot.EdgeTypes;
5333 },
5334
5335 /*
5336 Plots a subtree from the spacetree.
5337 */
5338 plotSubtree: function(node, opt, scale, animating) {
5339 var viz = this.viz, canvas = viz.canvas;
5340 scale = Math.min(Math.max(0.001, scale), 1);
5341 if(scale >= 0) {
5342 node.drawn = false;
5343 var ctx = canvas.getCtx();
5344 var diff = viz.geom.getScaledTreePosition(node, scale);
5345 ctx.translate(diff.x, diff.y);
5346 ctx.scale(scale, scale);
5347 }
5348 this.plotTree(node, !scale, opt, animating);
5349 if(scale >= 0) node.drawn = true;
5350 },
5351 /*
5352 Plots a Subtree.
5353 */
5354 plotTree: function(node, plotLabel, opt, animating) {
5355 var that = this,
5356 viz = this.viz,
5357 canvas = viz.canvas,
5358 config = this.config,
5359 ctx = canvas.getCtx();
5360 var root = config.multitree && !('$orn' in node.data);
5361 var orns = root && node.data.$orns;
5362 Graph.Util.eachSubnode(node, function(elem) {
5363 //multitree root node check
5364 if((!root || orns.indexOf(elem.data.$orn) > 0)
5365 && elem.exist && elem.drawn) {
5366 var adj = node.getAdjacency(elem.id);
5367 !animating && opt.onBeforePlotLine(adj);
5368 ctx.globalAlpha = Math.min(node.alpha, elem.alpha);
5369 that.plotLine(adj, canvas, animating);
5370 !animating && opt.onAfterPlotLine(adj);
5371 that.plotTree(elem, plotLabel, opt, animating);
5372 }
5373 });
5374
5375 if(node.drawn) {
5376 ctx.globalAlpha = node.alpha;
5377 !animating && opt.onBeforePlotNode(node);
5378 this.plotNode(node, canvas, animating);
5379 !animating && opt.onAfterPlotNode(node);
5380 if(plotLabel && ctx.globalAlpha >= 0.95)
5381 this.plotLabel(canvas, node, opt);
5382 else
5383 this.hideLabel(node, false);
5384 } else {
5385 this.hideLabel(node, true);
5386 }
5387 },
5388
5389 /*
5390 Method: placeLabel
5391
5392 Overrides abstract method placeLabel in <Graph.Plot>.
5393
5394 Parameters:
5395
5396 tag - A DOM label element.
5397 node - A <Graph.Node>.
5398 controller - A configuration/controller object passed to the visualization.
5399
5400 */
5401 placeLabel: function(tag, node, controller) {
5402 var pos = node.pos.getc(true), dim = this.node, canvas = this.viz.canvas;
5403 var w = dim.overridable && node.data.$width || dim.width;
5404 var h = dim.overridable && node.data.$height || dim.height;
5405 var radius = canvas.getSize();
5406 var labelPos, orn;
5407 if(dim.align == "center") {
5408 labelPos= {
5409 x: Math.round(pos.x - w / 2 + radius.width/2),
5410 y: Math.round(pos.y - h / 2 + radius.height/2)
5411 };
5412 } else if (dim.align == "left") {
5413 orn = this.config.orientation;
5414 if(orn == "bottom" || orn == "top") {
5415 labelPos= {
5416 x: Math.round(pos.x - w / 2 + radius.width/2),
5417 y: Math.round(pos.y + radius.height/2)
5418 };
5419 } else {
5420 labelPos= {
5421 x: Math.round(pos.x + radius.width/2),
5422 y: Math.round(pos.y - h / 2 + radius.height/2)
5423 };
5424 }
5425 } else if(dim.align == "right") {
5426 orn = this.config.orientation;
5427 if(orn == "bottom" || orn == "top") {
5428 labelPos= {
5429 x: Math.round(pos.x - w / 2 + radius.width/2),
5430 y: Math.round(pos.y - h + radius.height/2)
5431 };
5432 } else {
5433 labelPos= {
5434 x: Math.round(pos.x - w + radius.width/2),
5435 y: Math.round(pos.y - h / 2 + radius.height/2)
5436 };
5437 }
5438 } else throw "align: not implemented";
5439
5440 var style = tag.style;
5441 style.left = labelPos.x + 'px';
5442 style.top = labelPos.y + 'px';
5443 style.display = this.fitsInCanvas(labelPos, canvas)? '' : 'none';
5444 controller.onPlaceLabel(tag, node);
5445 },
5446
5447
5448 getAlignedPos: function(pos, width, height) {
5449 var nconfig = this.node;
5450 var square, orn;
5451 if(nconfig.align == "center") {
5452 square = {
5453 x: pos.x - width / 2,
5454 y: pos.y - height / 2
5455 };
5456 } else if (nconfig.align == "left") {
5457 orn = this.config.orientation;
5458 if(orn == "bottom" || orn == "top") {
5459 square = {
5460 x: pos.x - width / 2,
5461 y: pos.y
5462 };
5463 } else {
5464 square = {
5465 x: pos.x,
5466 y: pos.y - height / 2
5467 };
5468 }
5469 } else if(nconfig.align == "right") {
5470 orn = this.config.orientation;
5471 if(orn == "bottom" || orn == "top") {
5472 square = {
5473 x: pos.x - width / 2,
5474 y: pos.y - height
5475 };
5476 } else {
5477 square = {
5478 x: pos.x - width,
5479 y: pos.y - height / 2
5480 };
5481 }
5482 } else throw "align: not implemented";
5483
5484 return square;
5485 },
5486
5487 getOrientation: function(adj) {
5488 var config = this.config;
5489 var orn = config.orientation;
5490
5491 if(config.multitree) {
5492 var nodeFrom = adj.nodeFrom;
5493 var nodeTo = adj.nodeTo;
5494 orn = (('$orn' in nodeFrom.data)
5495 && nodeFrom.data.$orn)
5496 || (('$orn' in nodeTo.data)
5497 && nodeTo.data.$orn);
5498 }
5499
5500 return orn;
5501 }
5502 });
5503
5504 /*
5505 Class: ST.Plot.NodeTypes
5506
5507 Here are implemented all kinds of node rendering functions.
5508 Rendering functions implemented are 'none', 'circle', 'ellipse', 'rectangle' and 'square'.
5509
5510 You can add new Node types by implementing a new method in this class
5511
5512 Example:
5513
5514 (start code js)
5515 ST.Plot.NodeTypes.implement({
5516 'newnodetypename': function(node, canvas) {
5517 //Render my node here.
5518 }
5519 });
5520 (end code)
5521
5522 */
5523 ST.Plot.NodeTypes = new Class({
5524 'none': function() {},
5525
5526 'circle': function(node, canvas) {
5527 var pos = node.pos.getc(true), nconfig = this.node, data = node.data;
5528 var cond = nconfig.overridable && data;
5529 var dim = cond && data.$dim || nconfig.dim;
5530 var algnPos = this.getAlignedPos(pos, dim * 2, dim * 2);
5531 canvas.path('fill', function(context) {
5532 context.arc(algnPos.x + dim, algnPos.y + dim, dim, 0, Math.PI * 2, true);
5533 });
5534 },
5535
5536 'square': function(node, canvas) {
5537 var pos = node.pos.getc(true), nconfig = this.node, data = node.data;
5538 var cond = nconfig.overridable && data;
5539 var dim = cond && data.$dim || nconfig.dim;
5540 var algnPos = this.getAlignedPos(pos, dim, dim);
5541 canvas.getCtx().fillRect(algnPos.x, algnPos.y, dim, dim);
5542 },
5543
5544 'ellipse': function(node, canvas) {
5545 var pos = node.pos.getc(true), nconfig = this.node, data = node.data;
5546 var cond = nconfig.overridable && data;
5547 var width = (cond && data.$width || nconfig.width) / 2;
5548 var height = (cond && data.$height || nconfig.height) / 2;
5549 var algnPos = this.getAlignedPos(pos, width * 2, height * 2);
5550 var ctx = canvas.getCtx();
5551 ctx.save();
5552 ctx.scale(width / height, height / width);
5553 canvas.path('fill', function(context) {
5554 context.arc((algnPos.x + width) * (height / width), (algnPos.y + height) * (width / height), height, 0, Math.PI * 2, true);
5555 });
5556 ctx.restore();
5557 },
5558
5559 'rectangle': function(node, canvas) {
5560 var pos = node.pos.getc(true), nconfig = this.node, data = node.data;
5561 var cond = nconfig.overridable && data;
5562 var width = cond && data.$width || nconfig.width;
5563 var height = cond && data.$height || nconfig.height;
5564 var algnPos = this.getAlignedPos(pos, width, height);
5565 canvas.getCtx().fillRect(algnPos.x, algnPos.y, width, height);
5566 }
5567 });
5568
5569 /*
5570 Class: ST.Plot.EdgeTypes
5571
5572 Here are implemented all kinds of edge rendering functions.
5573 Rendering functions implemented are 'none', 'line', 'quadratic:begin', 'quadratic:end', 'bezier' and 'arrow'.
5574
5575 You can add new Edge types by implementing a new method in this class
5576
5577 Example:
5578
5579 (start code js)
5580 ST.Plot.EdgeTypes.implement({
5581 'newedgetypename': function(adj, canvas) {
5582 //Render my edge here.
5583 }
5584 });
5585 (end code)
5586
5587 */
5588 ST.Plot.EdgeTypes = new Class({
5589 'none': function() {},
5590
5591 'line': function(adj, canvas) {
5592 var orn = this.getOrientation(adj);
5593 var nodeFrom = adj.nodeFrom, nodeTo = adj.nodeTo;
5594 var begin = this.viz.geom.getEdge(nodeFrom._depth < nodeTo._depth? nodeFrom:nodeTo, 'begin', orn);
5595 var end = this.viz.geom.getEdge(nodeFrom._depth < nodeTo._depth? nodeTo:nodeFrom, 'end', orn);
5596 canvas.path('stroke', function(ctx) {
5597 ctx.moveTo(begin.x, begin.y);
5598 ctx.lineTo(end.x, end.y);
5599 });
5600 },
5601
5602 'quadratic:begin': function(adj, canvas) {
5603 var orn = this.getOrientation(adj);
5604 var data = adj.data, econfig = this.edge;
5605 var nodeFrom = adj.nodeFrom, nodeTo = adj.nodeTo;
5606 var begin = this.viz.geom.getEdge(nodeFrom._depth < nodeTo._depth? nodeFrom:nodeTo, 'begin', orn);
5607 var end = this.viz.geom.getEdge(nodeFrom._depth < nodeTo._depth? nodeTo:nodeFrom, 'end', orn);
5608 var cond = econfig.overridable && data;
5609 var dim = cond && data.$dim || econfig.dim;
5610 switch(orn) {
5611 case "left":
5612 canvas.path('stroke', function(ctx){
5613 ctx.moveTo(begin.x, begin.y);
5614 ctx.quadraticCurveTo(begin.x + dim, begin.y, end.x, end.y);
5615 });
5616 break;
5617 case "right":
5618 canvas.path('stroke', function(ctx){
5619 ctx.moveTo(begin.x, begin.y);
5620 ctx.quadraticCurveTo(begin.x - dim, begin.y, end.x, end.y);
5621 });
5622 break;
5623 case "top":
5624 canvas.path('stroke', function(ctx){
5625 ctx.moveTo(begin.x, begin.y);
5626 ctx.quadraticCurveTo(begin.x, begin.y + dim, end.x, end.y);
5627 });
5628 break;
5629 case "bottom":
5630 canvas.path('stroke', function(ctx){
5631 ctx.moveTo(begin.x, begin.y);
5632 ctx.quadraticCurveTo(begin.x, begin.y - dim, end.x, end.y);
5633 });
5634 break;
5635 }
5636 },
5637
5638 'quadratic:end': function(adj, canvas) {
5639 var orn = this.getOrientation(adj);
5640 var data = adj.data, econfig = this.edge;
5641 var nodeFrom = adj.nodeFrom, nodeTo = adj.nodeTo;
5642 var begin = this.viz.geom.getEdge(nodeFrom._depth < nodeTo._depth? nodeFrom:nodeTo, 'begin', orn);
5643 var end = this.viz.geom.getEdge(nodeFrom._depth < nodeTo._depth? nodeTo:nodeFrom, 'end', orn);
5644 var cond = econfig.overridable && data;
5645 var dim = cond && data.$dim || econfig.dim;
5646 switch(orn) {
5647 case "left":
5648 canvas.path('stroke', function(ctx){
5649 ctx.moveTo(begin.x, begin.y);
5650 ctx.quadraticCurveTo(end.x - dim, end.y, end.x, end.y);
5651 });
5652 break;
5653 case "right":
5654 canvas.path('stroke', function(ctx){
5655 ctx.moveTo(begin.x, begin.y);
5656 ctx.quadraticCurveTo(end.x + dim, end.y, end.x, end.y);
5657 });
5658 break;
5659 case "top":
5660 canvas.path('stroke', function(ctx){
5661 ctx.moveTo(begin.x, begin.y);
5662 ctx.quadraticCurveTo(end.x, end.y - dim, end.x, end.y);
5663 });
5664 break;
5665 case "bottom":
5666 canvas.path('stroke', function(ctx){
5667 ctx.moveTo(begin.x, begin.y);
5668 ctx.quadraticCurveTo(end.x, end.y + dim, end.x, end.y);
5669 });
5670 break;
5671 }
5672 },
5673
5674 'bezier': function(adj, canvas) {
5675 var data = adj.data, econfig = this.edge;
5676 var orn = this.getOrientation(adj);
5677 var nodeFrom = adj.nodeFrom, nodeTo = adj.nodeTo;
5678 var begin = this.viz.geom.getEdge(nodeFrom._depth < nodeTo._depth? nodeFrom:nodeTo, 'begin', orn);
5679 var end = this.viz.geom.getEdge(nodeFrom._depth < nodeTo._depth? nodeTo:nodeFrom, 'end', orn);
5680 var cond = econfig.overridable && data;
5681 var dim = cond && data.$dim || econfig.dim;
5682 switch(orn) {
5683 case "left":
5684 canvas.path('stroke', function(ctx) {
5685 ctx.moveTo(begin.x, begin.y);
5686 ctx.bezierCurveTo(begin.x + dim, begin.y, end.x - dim, end.y, end.x, end.y);
5687 });
5688 break;
5689 case "right":
5690 canvas.path('stroke', function(ctx) {
5691 ctx.moveTo(begin.x, begin.y);
5692 ctx.bezierCurveTo(begin.x - dim, begin.y, end.x + dim, end.y, end.x, end.y);
5693 });
5694 break;
5695 case "top":
5696 canvas.path('stroke', function(ctx) {
5697 ctx.moveTo(begin.x, begin.y);
5698 ctx.bezierCurveTo(begin.x, begin.y + dim, end.x, end.y - dim, end.x, end.y);
5699 });
5700 break;
5701 case "bottom":
5702 canvas.path('stroke', function(ctx) {
5703 ctx.moveTo(begin.x, begin.y);
5704 ctx.bezierCurveTo(begin.x, begin.y - dim, end.x, end.y + dim, end.x, end.y);
5705 });
5706 break;
5707 }
5708 },
5709
5710 'arrow': function(adj, canvas) {
5711 var orn = this.getOrientation(adj);
5712 var node = adj.nodeFrom, child = adj.nodeTo;
5713 var data = adj.data, econfig = this.edge;
5714 //get edge dim
5715 var cond = econfig.overridable && data;
5716 var edgeDim = cond && data.$dim || econfig.dim;
5717 //get edge direction
5718 if(cond && data.$direction && data.$direction.length > 1) {
5719 var nodeHash = {};
5720 nodeHash[node.id] = node;
5721 nodeHash[child.id] = child;
5722 var sense = data.$direction;
5723 node = nodeHash[sense[0]];
5724 child = nodeHash[sense[1]];
5725 }
5726 var posFrom = this.viz.geom.getEdge(node, 'begin', orn);
5727 var posTo = this.viz.geom.getEdge(child, 'end', orn);
5728 var vect = new Complex(posTo.x - posFrom.x, posTo.y - posFrom.y);
5729 vect.$scale(edgeDim / vect.norm());
5730 var intermediatePoint = new Complex(posTo.x - vect.x, posTo.y - vect.y);
5731 var normal = new Complex(-vect.y / 2, vect.x / 2);
5732 var v1 = intermediatePoint.add(normal), v2 = intermediatePoint.$add(normal.$scale(-1));
5733 canvas.path('stroke', function(context) {
5734 context.moveTo(posFrom.x, posFrom.y);
5735 context.lineTo(posTo.x, posTo.y);
5736 });
5737 canvas.path('fill', function(context) {
5738 context.moveTo(v1.x, v1.y);
5739 context.lineTo(v2.x, v2.y);
5740 context.lineTo(posTo.x, posTo.y);
5741 });
5742 }
5743 });
5744
5745
5746 })();
5747
5748
5749
5750 /*
5751 * File: AngularWidth.js
5752 *
5753 * Provides utility methods for calculating angular widths.
5754 *
5755 * Implemented by:
5756 *
5757 * <RGraph>, <Hypertree>
5758 *
5759 */
5760
5761 /*
5762 Object: AngularWidth
5763
5764 Provides utility methods for calculating angular widths.
5765 */
5766 var AngularWidth = {
5767 /*
5768 Method: setAngularWidthForNodes
5769
5770 Sets nodes angular widths.
5771 */
5772 setAngularWidthForNodes: function() {
5773 var config = this.config.Node;
5774 var overridable = config.overridable;
5775 var dim = config.dim;
5776
5777 Graph.Util.eachBFS(this.graph, this.root, function(elem, i) {
5778 var diamValue = (overridable
5779 && elem.data
5780 && elem.data.$aw) || dim;
5781 elem._angularWidth = diamValue / i;
5782 }, "ignore");
5783 },
5784
5785 /*
5786 Method: setSubtreesAngularWidth
5787
5788 Sets subtrees angular widths.
5789 */
5790 setSubtreesAngularWidth: function() {
5791 var that = this;
5792 Graph.Util.eachNode(this.graph, function(elem) {
5793 that.setSubtreeAngularWidth(elem);
5794 }, "ignore");
5795 },
5796
5797 /*
5798 Method: setSubtreeAngularWidth
5799
5800 Sets the angular width for a subtree.
5801 */
5802 setSubtreeAngularWidth: function(elem) {
5803 var that = this, nodeAW = elem._angularWidth, sumAW = 0;
5804 Graph.Util.eachSubnode(elem, function(child) {
5805 that.setSubtreeAngularWidth(child);
5806 sumAW += child._treeAngularWidth;
5807 }, "ignore");
5808 elem._treeAngularWidth = Math.max(nodeAW, sumAW);
5809 },
5810
5811 /*
5812 Method: computeAngularWidths
5813
5814 Computes nodes and subtrees angular widths.
5815 */
5816 computeAngularWidths: function () {
5817 this.setAngularWidthForNodes();
5818 this.setSubtreesAngularWidth();
5819 }
5820
5821 };
5822
5823
5824 /*
5825 * File: RGraph.js
5826 *
5827 * Implements the <RGraph> class and other derived classes.
5828 *
5829 * Description:
5830 *
5831 * A radial layout of a tree puts the root node on the center of the canvas, places its children on the first concentric ring away from the root node, its grandchildren on a second concentric ring, and so on...
5832 *
5833 * Ka-Ping Yee, Danyel Fisher, Rachna Dhamija and Marti Hearst introduced a very interesting paper called "Animated Exploration of Dynamic Graphs with Radial Layout". In this paper they describe a way to animate a radial layout of a tree with ease-in and ease-out transitions, which make transitions from a graph's state to another easier to understand for the viewer.
5834 *
5835 * Inspired by:
5836 *
5837 * Animated Exploration of Dynamic Graphs with Radial Layout (Ka-Ping Yee, Danyel Fisher, Rachna Dhamija, Marti Hearst)
5838 *
5839 * <http://bailando.sims.berkeley.edu/papers/infovis01.htm>
5840 *
5841 * Disclaimer:
5842 *
5843 * This visualization was built from scratch, taking only the paper as inspiration, and only shares some features with this paper.
5844 *
5845 *
5846 */
5847
5848 /*
5849 Class: RGraph
5850
5851 The main RGraph class
5852
5853 Extends:
5854
5855 <Loader>, <AngularWidth>
5856
5857 Parameters:
5858
5859 canvas - A <Canvas> Class
5860 config - A configuration/controller object.
5861
5862 Configuration:
5863
5864 The configuration object can have the following properties (all properties are optional and have a default value)
5865
5866 *General*
5867
5868 - _interpolation_ Interpolation type used for animations. Possible options are 'polar' and 'linear'. Default's 'linear'.
5869 - _levelDistance_ Distance between a parent node and its children. Default's 100.
5870 - _withLabels_ Whether the visualization should use/create labels or not. Default's *true*.
5871
5872 *Node*
5873
5874 Customize the visualization nodes' shape, color, and other style properties.
5875
5876 - _Node_
5877
5878 This object has as properties
5879
5880 - _overridable_ Determine whether or not nodes properties can be overriden by a particular node. Default's false.
5881
5882 If given a JSON tree or graph, a node _data_ property contains properties which are the same as defined here but prefixed with
5883 a dollar sign (i.e $), the node properties will override the global node properties.
5884
5885 - _type_ Node type (shape). Possible options are "none", "square", "rectangle", "circle", "triangle", "star". Default's "circle".
5886 - _color_ Node color. Default's '#ccb'.
5887 - _lineWidth_ Line width. If nodes aren't drawn with strokes then this property won't be of any use. Default's 1.
5888 - _height_ Node height. Used for plotting rectangular nodes. Default's 5.
5889 - _width_ Node width. Used for plotting rectangular nodes. Default's 5.
5890 - _dim_ An extra parameter used by other complex shapes such as square and circle to determine the shape's diameter. Default's 3.
5891
5892 *Edge*
5893
5894 Customize the visualization edges' shape, color, and other style properties.
5895
5896 - _Edge_
5897
5898 This object has as properties
5899
5900 - _overridable_ Determine whether or not edges properties can be overriden by a particular edge object. Default's false.
5901
5902 If given a JSON _complex_ graph (defined in <Loader.loadJSON>), an adjacency _data_ property contains properties which are the same as defined here but prefixed with
5903 a dollar sign (i.e $), the adjacency properties will override the global edge properties.
5904
5905 - _type_ Edge type (shape). Possible options are "none", "line" and "arrow". Default's "line".
5906 - _color_ Edge color. Default's '#ccb'.
5907 - _lineWidth_ Line width. If edges aren't drawn with strokes then this property won't be of any use. Default's 1.
5908
5909 *Animations*
5910
5911 - _duration_ Duration of the animation in milliseconds. Default's 2500.
5912 - _fps_ Frames per second. Default's 40.
5913 - _transition_ One of the transitions defined in the <Animation> class. Default's Quart.easeInOut.
5914 - _clearCanvas_ Whether to clear canvas on each animation frame or not. Default's true.
5915
5916 *Controller options*
5917
5918 You can also implement controller functions inside the configuration object. This functions are
5919
5920 - _onBeforeCompute(node)_ This method is called right before performing all computation and animations to the JIT visualization.
5921 - _onAfterCompute()_ This method is triggered right after all animations or computations for the JIT visualizations ended.
5922 - _onCreateLabel(domElement, node)_ This method receives the label dom element as first parameter, and the corresponding <Graph.Node> as second parameter. This method will only be called on label creation. Note that a <Graph.Node> is a node from the input tree/graph you provided to the visualization. If you want to know more about what kind of JSON tree/graph format is used to feed the visualizations, you can take a look at <Loader.loadJSON>. This method proves useful when adding events to the labels used by the JIT.
5923 - _onPlaceLabel(domElement, node)_ This method receives the label dom element as first parameter and the corresponding <Graph.Node> as second parameter. This method is called each time a label has been placed on the visualization, and thus it allows you to update the labels properties, such as size or position. Note that onPlaceLabel will be triggered after updating the labels positions. That means that, for example, the left and top css properties are already updated to match the nodes positions.
5924 - _onBeforePlotNode(node)_ This method is triggered right before plotting a given node. The _node_ parameter is the <Graph.Node> to be plotted.
5925 This method is useful for changing a node style right before plotting it.
5926 - _onAfterPlotNode(node)_ This method is triggered right after plotting a given node. The _node_ parameter is the <Graph.Node> plotted.
5927 - _onBeforePlotLine(adj)_ This method is triggered right before plotting an edge. The _adj_ parameter is a <Graph.Adjacence> object.
5928 This method is useful for adding some styles to a particular edge before being plotted.
5929 - _onAfterPlotLine(adj)_ This method is triggered right after plotting an edge. The _adj_ parameter is the <Graph.Adjacence> plotted.
5930
5931 Example:
5932
5933 Here goes a complete example. In most cases you won't be forced to implement all properties and methods. In fact,
5934 all configuration properties have the default value assigned.
5935
5936 I won't be instanciating a <Canvas> class here. If you want to know more about instanciating a <Canvas> class
5937 please take a look at the <Canvas> class documentation.
5938
5939 (start code js)
5940 var rgraph = new RGraph(canvas, {
5941 interpolation: 'linear',
5942 levelDistance: 100,
5943 withLabels: true,
5944 Node: {
5945 overridable: false,
5946 type: 'circle',
5947 color: '#ccb',
5948 lineWidth: 1,
5949 height: 5,
5950 width: 5,
5951 dim: 3
5952 },
5953 Edge: {
5954 overridable: false,
5955 type: 'line',
5956 color: '#ccb',
5957 lineWidth: 1
5958 },
5959 duration: 2500,
5960 fps: 40,
5961 transition: Trans.Quart.easeInOut,
5962 clearCanvas: true,
5963 onBeforeCompute: function(node) {
5964 //do something onBeforeCompute
5965 },
5966 onAfterCompute: function () {
5967 //do something onAfterCompute
5968 },
5969 onCreateLabel: function(domElement, node) {
5970 //do something onCreateLabel
5971 },
5972 onPlaceLabel: function(domElement, node) {
5973 //do something onPlaceLabel
5974 },
5975 onBeforePlotNode:function(node) {
5976 //do something onBeforePlotNode
5977 },
5978 onAfterPlotNode: function(node) {
5979 //do something onAfterPlotNode
5980 },
5981 onBeforePlotLine:function(adj) {
5982 //do something onBeforePlotLine
5983 },
5984 onAfterPlotLine: function(adj) {
5985 //do something onAfterPlotLine
5986 }
5987 });
5988 (end code)
5989
5990 Instance Properties:
5991
5992 - _graph_ Access a <Graph> instance.
5993 - _op_ Access a <RGraph.Op> instance.
5994 - _fx_ Access a <RGraph.Plot> instance.
5995 */
5996
5997 this.RGraph = new Class({
5998
5999 Implements: [Loader, AngularWidth],
6000
6001 initialize: function(canvas, controller) {
6002 var config= {
6003 labelContainer: canvas.id + '-label',
6004
6005 interpolation: 'linear',
6006 levelDistance: 100,
6007 withLabels: true,
6008
6009 Node: {
6010 overridable: false,
6011 type: 'circle',
6012 dim: 3,
6013 color: '#ccb',
6014 width: 5,
6015 height: 5,
6016 lineWidth: 1
6017 },
6018
6019 Edge: {
6020 overridable: false,
6021 type: 'line',
6022 color: '#ccb',
6023 lineWidth: 1
6024 },
6025
6026 fps:40,
6027 duration: 2500,
6028 transition: Trans.Quart.easeInOut,
6029 clearCanvas: true
6030 };
6031
6032 var innerController = {
6033 onBeforeCompute: $empty,
6034 onAfterCompute: $empty,
6035 onCreateLabel: $empty,
6036 onPlaceLabel: $empty,
6037 onComplete: $empty,
6038 onBeforePlotLine:$empty,
6039 onAfterPlotLine: $empty,
6040 onBeforePlotNode:$empty,
6041 onAfterPlotNode: $empty
6042 };
6043
6044 this.controller = this.config = $merge(config, innerController, controller);
6045 this.graphOptions = {
6046 'complex': false,
6047 'Node': {
6048 'selected': false,
6049 'exist': true,
6050 'drawn': true
6051 }
6052 };
6053 this.graph = new Graph(this.graphOptions);
6054 this.fx = new RGraph.Plot(this);
6055 this.op = new RGraph.Op(this);
6056 this.json = null;
6057 this.canvas = canvas;
6058 this.root = null;
6059 this.busy = false;
6060 this.parent = false;
6061 },
6062 /*
6063 Method: refresh
6064
6065 Computes nodes' positions and replots the tree.
6066
6067 */
6068 refresh: function() {
6069 this.compute();
6070 this.plot();
6071 },
6072
6073 /*
6074 Method: reposition
6075
6076 An alias for computing new positions to _endPos_
6077
6078 See also:
6079
6080 <RGraph.compute>
6081
6082 */
6083 reposition: function() {
6084 this.compute('endPos');
6085 },
6086
6087
6088 /*
6089 Method: plot
6090
6091 Plots the RGraph
6092 */
6093 plot: function() {
6094 this.fx.plot();
6095 },
6096 /*
6097 Method: compute
6098
6099 Computes nodes' positions.
6100
6101 Parameters:
6102
6103 property - _optional_ A <Graph.Node> position property to store the new positions. Possible values are 'pos', 'endPos' or 'startPos'.
6104
6105 */
6106 compute: function(property) {
6107 var prop = property || ['pos', 'startPos', 'endPos'];
6108 var node = this.graph.getNode(this.root);
6109 node._depth = 0;
6110 Graph.Util.computeLevels(this.graph, this.root, 0, "ignore");
6111 this.computeAngularWidths();
6112 this.computePositions(prop);
6113 },
6114
6115 /*
6116 computePositions
6117
6118 Performs the main algorithm for computing node positions.
6119 */
6120 computePositions: function(property) {
6121 var propArray = $splat(property);
6122 var aGraph = this.graph;
6123 var GUtil = Graph.Util;
6124 var root = this.graph.getNode(this.root);
6125 var parent = this.parent;
6126 var config = this.config;
6127
6128 for(var i=0; i<propArray.length; i++)
6129 root[propArray[i]] = $P(0, 0);
6130
6131 root.angleSpan = {
6132 begin: 0,
6133 end: 2 * Math.PI
6134 };
6135 root._rel = 1;
6136
6137 GUtil.eachBFS(this.graph, this.root, function (elem) {
6138 var angleSpan = elem.angleSpan.end - elem.angleSpan.begin;
6139 var rho = (elem._depth + 1) * config.levelDistance;
6140 var angleInit = elem.angleSpan.begin;
6141
6142 var totalAngularWidths = 0, subnodes = [];
6143 GUtil.eachSubnode(elem, function(sib) {
6144 totalAngularWidths += sib._treeAngularWidth;
6145 subnodes.push(sib);
6146 }, "ignore");
6147
6148 if(parent && parent.id == elem.id && subnodes.length > 0 && subnodes[0].dist) {
6149 subnodes.sort(function(a, b) {
6150 return (a.dist >= b.dist) - (a.dist <= b.dist);
6151 });
6152 }
6153 for(var k=0; k < subnodes.length; k++) {
6154 var child = subnodes[k];
6155 if(!child._flag) {
6156 child._rel = child._treeAngularWidth / totalAngularWidths;
6157 var angleProportion = child._rel * angleSpan;
6158 var theta = angleInit + angleProportion / 2;
6159
6160 for(var i=0; i<propArray.length; i++)
6161 child[propArray[i]] = $P(theta, rho);
6162
6163 child.angleSpan = {
6164 begin: angleInit,
6165 end: angleInit + angleProportion
6166 };
6167 angleInit += angleProportion;
6168 }
6169 }
6170 }, "ignore");
6171 },
6172
6173 /*
6174 getNodeAndParentAngle
6175
6176 Returns the _parent_ of the given node, also calculating its angle span.
6177 */
6178 getNodeAndParentAngle: function(id) {
6179 var theta = false;
6180 var n = this.graph.getNode(id);
6181 var ps = Graph.Util.getParents(n);
6182 var p = (ps.length > 0)? ps[0] : false;
6183 if(p) {
6184 var posParent = p.pos.getc(), posChild = n.pos.getc();
6185 var newPos = posParent.add(posChild.scale(-1));
6186 theta = Math.atan2(newPos.y, newPos.x);
6187 if(theta < 0) theta += 2 * Math.PI;
6188 }
6189 return {parent: p, theta: theta};
6190 },
6191
6192 /*
6193 tagChildren
6194
6195 Enumerates the children in order to mantain child ordering (second constraint of the paper).
6196 */
6197 tagChildren: function(par, id) {
6198 if(par.angleSpan) {
6199 var adjs = [];
6200 Graph.Util.eachAdjacency(par, function(elem) {
6201 adjs.push(elem.nodeTo);
6202 }, "ignore");
6203 var len = adjs.length;
6204 for(var i=0; i < len && id != adjs[i].id; i++);
6205 for(var j= (i+1) % len, k = 0; id != adjs[j].id; j = (j+1) % len) {
6206 adjs[j].dist = k++;
6207 }
6208 }
6209 },
6210
6211 /*
6212 Method: onClick
6213
6214 Performs all calculations and animations to center the node specified by _id_.
6215
6216 Parameters:
6217
6218 id - A <Graph.Node> id.
6219 opt - _optional_ An object containing some extra properties like
6220
6221 - _hideLabels_ Hide labels when performing the animation. Default's *true*.
6222
6223 Example:
6224
6225 (start code js)
6226 rgraph.onClick('someid');
6227 //or also...
6228 rgraph.onClick('someid', {
6229 hideLabels: false
6230 });
6231 (end code)
6232
6233 */
6234 onClick: function(id, opt) {
6235 if(this.root != id && !this.busy) {
6236 this.busy = true;
6237 this.root = id;
6238 that = this;
6239 this.controller.onBeforeCompute(this.graph.getNode(id));
6240 var obj = this.getNodeAndParentAngle(id);
6241
6242 //second constraint
6243 this.tagChildren(obj.parent, id);
6244 this.parent = obj.parent;
6245 this.compute('endPos');
6246
6247 //first constraint
6248 var thetaDiff = obj.theta - obj.parent.endPos.theta;
6249 Graph.Util.eachNode(this.graph, function(elem) {
6250 elem.endPos.set(elem.endPos.getp().add($P(thetaDiff, 0)));
6251 });
6252
6253 var mode = this.config.interpolation;
6254 opt = $merge({ onComplete: $empty }, opt || {});
6255
6256 this.fx.animate($merge({
6257 hideLabels: true,
6258 modes: [mode]
6259 }, opt, {
6260 onComplete: function() {
6261 that.busy = false;
6262 opt.onComplete();
6263 }
6264 }));
6265 }
6266 }
6267 });
6268
6269 /*
6270 Class: RGraph.Op
6271
6272 Performs advanced operations on trees and graphs.
6273
6274 Extends:
6275
6276 All <Graph.Op> methods
6277
6278 Access:
6279
6280 This instance can be accessed with the _op_ parameter of the <RGraph> instance created.
6281
6282 Example:
6283
6284 (start code js)
6285 var rgraph = new RGraph(canvas, config);
6286 rgraph.op.morph //or can also call any other <Graph.Op> method
6287 (end code)
6288
6289 */
6290 RGraph.Op = new Class({
6291
6292 Implements: Graph.Op,
6293
6294 initialize: function(viz) {
6295 this.viz = viz;
6296 }
6297 });
6298
6299 /*
6300 Class: RGraph.Plot
6301
6302 Performs plotting operations.
6303
6304 Extends:
6305
6306 All <Graph.Plot> methods
6307
6308 Access:
6309
6310 This instance can be accessed with the _fx_ parameter of the <RGraph> instance created.
6311
6312 Example:
6313
6314 (start code js)
6315 var rgraph = new RGraph(canvas, config);
6316 rgraph.fx.placeLabel //or can also call any other <RGraph.Plot> method
6317 (end code)
6318
6319 */
6320 RGraph.Plot = new Class({
6321
6322 Implements: Graph.Plot,
6323
6324 initialize: function(viz) {
6325 this.viz = viz;
6326 this.config = viz.config;
6327 this.node = viz.config.Node;
6328 this.edge = viz.config.Edge;
6329 this.animation = new Animation;
6330 this.nodeTypes = new RGraph.Plot.NodeTypes;
6331 this.edgeTypes = new RGraph.Plot.EdgeTypes;
6332 },
6333
6334 /*
6335 Method: placeLabel
6336
6337 Overrides abstract method placeLabel in <Graph.Plot>.
6338
6339 Parameters:
6340
6341 tag - A DOM label element.
6342 node - A <Graph.Node>.
6343 controller - A configuration/controller object passed to the visualization.
6344
6345 */
6346 placeLabel: function(tag, node, controller) {
6347 var pos = node.pos.getc(true), canvas = this.viz.canvas;
6348 var radius= canvas.getSize();
6349 var labelPos= {
6350 x: Math.round(pos.x + radius.width/2),
6351 y: Math.round(pos.y + radius.height/2)
6352 };
6353 var style = tag.style;
6354 style.left = labelPos.x + 'px';
6355 style.top = labelPos.y + 'px';
6356 style.display = this.fitsInCanvas(labelPos, canvas)? '' : 'none';
6357 controller.onPlaceLabel(tag, node);
6358 }
6359 });
6360
6361 /*
6362 Class: RGraph.Plot.NodeTypes
6363
6364 Here are implemented all kinds of node rendering functions.
6365 Rendering functions implemented are 'none', 'circle', 'triangle', 'rectangle', 'star' and 'square'.
6366
6367 You can add new Node types by implementing a new method in this class
6368
6369 Example:
6370
6371 (start code js)
6372 RGraph.Plot.NodeTypes.implement({
6373 'newnodetypename': function(node, canvas) {
6374 //Render my node here.
6375 }
6376 });
6377 (end code)
6378
6379 */
6380 RGraph.Plot.NodeTypes = new Class({
6381 'none': function() {},
6382
6383 'circle': function(node, canvas) {
6384 var pos = node.pos.getc(true), nconfig = this.node, data = node.data;
6385 var nodeDim = nconfig.overridable && data && data.$dim || nconfig.dim;
6386 canvas.path('fill', function(context) {
6387 context.arc(pos.x, pos.y, nodeDim, 0, Math.PI*2, true);
6388 });
6389 },
6390
6391 'square': function(node, canvas) {
6392 var pos = node.pos.getc(true), nconfig = this.node, data = node.data;
6393 var nodeDim = nconfig.overridable && data && data.$dim || nconfig.dim;
6394 var nodeDim2 = 2 * nodeDim;
6395 canvas.getCtx().fillRect(pos.x - nodeDim, pos.y - nodeDim, nodeDim2, nodeDim2);
6396 },
6397
6398 'rectangle': function(node, canvas) {
6399 var pos = node.pos.getc(true), nconfig = this.node, data = node.data;
6400 var width = nconfig.overridable && data && data.$width || nconfig.width;
6401 var height = nconfig.overridable && data && data.$height || nconfig.height;
6402 canvas.getCtx().fillRect(pos.x - width / 2, pos.y - height / 2, width, height);
6403 },
6404
6405 'triangle': function(node, canvas) {
6406 var pos = node.pos.getc(true), nconfig = this.node, data = node.data;
6407 var nodeDim = nconfig.overridable && data && data.$dim || nconfig.dim;
6408 var c1x = pos.x, c1y = pos.y - nodeDim,
6409 c2x = c1x - nodeDim, c2y = pos.y + nodeDim,
6410 c3x = c1x + nodeDim, c3y = c2y;
6411 canvas.path('fill', function(ctx) {
6412 ctx.moveTo(c1x, c1y);
6413 ctx.lineTo(c2x, c2y);
6414 ctx.lineTo(c3x, c3y);
6415 });
6416 },
6417
6418 'star': function(node, canvas) {
6419 var pos = node.pos.getc(true), nconfig = this.node, data = node.data;
6420 var nodeDim = nconfig.overridable && data && data.$dim || nconfig.dim;
6421 var ctx = canvas.getCtx(), pi5 = Math.PI / 5;
6422 ctx.save();
6423 ctx.translate(pos.x, pos.y);
6424 ctx.beginPath();
6425 ctx.moveTo(nodeDim, 0);
6426 for (var i=0; i<9; i++){
6427 ctx.rotate(pi5);
6428 if(i % 2 == 0) {
6429 ctx.lineTo((nodeDim / 0.525731) * 0.200811, 0);
6430 } else {
6431 ctx.lineTo(nodeDim, 0);
6432 }
6433 }
6434 ctx.closePath();
6435 ctx.fill();
6436 ctx.restore();
6437 }
6438 });
6439
6440 /*
6441 Class: RGraph.Plot.EdgeTypes
6442
6443 Here are implemented all kinds of edge rendering functions.
6444 Rendering functions implemented are 'none', 'line' and 'arrow'.
6445
6446 You can add new Edge types by implementing a new method in this class
6447
6448 Example:
6449
6450 (start code js)
6451 RGraph.Plot.EdgeTypes.implement({
6452 'newedgetypename': function(adj, canvas) {
6453 //Render my edge here.
6454 }
6455 });
6456 (end code)
6457
6458 */
6459 RGraph.Plot.EdgeTypes = new Class({
6460 'none': function() {},
6461
6462 'line': function(adj, canvas) {
6463 var pos = adj.nodeFrom.pos.getc(true);
6464 var posChild = adj.nodeTo.pos.getc(true);
6465 canvas.path('stroke', function(context) {
6466 context.moveTo(pos.x, pos.y);
6467 context.lineTo(posChild.x, posChild.y);
6468 });
6469 },
6470
6471 'arrow': function(adj, canvas) {
6472 var node = adj.nodeFrom, child = adj.nodeTo;
6473 var data = adj.data, econfig = this.edge;
6474 //get edge dim
6475 var cond = econfig.overridable && data;
6476 var edgeDim = cond && data.$dim || 14;
6477 //get edge direction
6478 if(cond && data.$direction && data.$direction.length > 1) {
6479 var nodeHash = {};
6480 nodeHash[node.id] = node;
6481 nodeHash[child.id] = child;
6482 var sense = data.$direction;
6483 node = nodeHash[sense[0]];
6484 child = nodeHash[sense[1]];
6485 }
6486 var posFrom = node.pos.getc(true), posTo = child.pos.getc(true);
6487 var vect = new Complex(posTo.x - posFrom.x, posTo.y - posFrom.y);
6488 vect.$scale(edgeDim / vect.norm());
6489 var intermediatePoint = new Complex(posTo.x - vect.x, posTo.y - vect.y);
6490 var normal = new Complex(-vect.y / 2, vect.x / 2);
6491 var v1 = intermediatePoint.add(normal), v2 = intermediatePoint.$add(normal.$scale(-1));
6492 canvas.path('stroke', function(context) {
6493 context.moveTo(posFrom.x, posFrom.y);
6494 context.lineTo(posTo.x, posTo.y);
6495 });
6496 canvas.path('fill', function(context) {
6497 context.moveTo(v1.x, v1.y);
6498 context.lineTo(v2.x, v2.y);
6499 context.lineTo(posTo.x, posTo.y);
6500 });
6501 }
6502 });
6503
6504
6505 /*
6506 * File: Hypertree.js
6507 *
6508 * Implements the <Hypertree> class and other derived classes.
6509 *
6510 * Description:
6511 *
6512 * A Hyperbolic Tree (HT) is a focus+context information visualization technique used to display large amount of inter-related data. This technique was originally developed at Xerox PARC.
6513 *
6514 * The HT algorithm plots a tree in what's called the Poincare Disk model of Hyperbolic Geometry, a kind of non-Euclidean geometry. By doing this, the HT algorithm applies a moebius transformation to the tree in order to display it with a magnifying glass effect.
6515 *
6516 * Inspired by:
6517 *
6518 * A Focus+Context Technique Based on Hyperbolic Geometry for Visualizing Large Hierarchies (John Lamping, Ramana Rao, and Peter Pirolli).
6519 *
6520 * <http://www.cs.tau.ac.il/~asharf/shrek/Projects/HypBrowser/startree-chi95.pdf>
6521 *
6522 * Disclaimer:
6523 *
6524 * This visualization was built from scratch, taking only the paper as inspiration, and only shares some features with the Hypertree.
6525 *
6526
6527 */
6528
6529 /*
6530 Complex
6531
6532 A multi-purpose Complex Class with common methods. Exetended for the Hypertree.
6533
6534 */
6535 /*
6536 moebiusTransformation
6537
6538 Calculates a moebius transformation for this point / complex.
6539 For more information go to:
6540 http://en.wikipedia.org/wiki/Moebius_transformation.
6541
6542 Parameters:
6543
6544 c - An initialized Complex instance representing a translation Vector.
6545 */
6546
6547 Complex.prototype.moebiusTransformation = function(c) {
6548 var num = this.add(c);
6549 var den = c.$conjugate().$prod(this); den.x++;
6550 return num.$div(den);
6551 };
6552
6553 /*
6554 Method: getClosestNodeToOrigin
6555
6556 Extends <Graph.Util>. Returns the closest node to the center of canvas.
6557
6558 Parameters:
6559
6560 graph - A <Graph> instance.
6561 prop - _optional_ a <Graph.Node> position property. Possible properties are 'startPos', 'pos' or 'endPos'. Default's 'pos'.
6562
6563 Returns:
6564
6565 Closest node to origin. Returns *null* otherwise.
6566
6567 */
6568 Graph.Util.getClosestNodeToOrigin = function(graph, prop, flags) {
6569 return this.getClosestNodeToPos(graph, Polar.KER, prop, flags);
6570 };
6571
6572 /*
6573 Method: getClosestNodeToPos
6574
6575 Extends <Graph.Util>. Returns the closest node to the given position.
6576
6577 Parameters:
6578
6579 graph - A <Graph> instance.
6580 p[os - A <Complex> or <Polar> instance.
6581 prop - _optional_ a <Graph.Node> position property. Possible properties are 'startPos', 'pos' or 'endPos'. Default's 'pos'.
6582
6583 Returns:
6584
6585 Closest node to the given position. Returns *null* otherwise.
6586
6587 */
6588 Graph.Util.getClosestNodeToPos = function(graph, pos, prop, flags) {
6589 var node = null; prop = prop || 'pos'; pos = pos && pos.getc(true) || Complex.KER;
6590 var distance = function(a, b) {
6591 var d1 = a.x - b.x, d2 = a.y - b.y;
6592 return d1 * d1 + d2 * d2;
6593 };
6594 this.eachNode(graph, function(elem) {
6595 node = (node == null || distance(elem[prop].getc(true), pos) < distance(node[prop].getc(true), pos))? elem : node;
6596 }, flags);
6597 return node;
6598 };
6599
6600 /*
6601 moebiusTransformation
6602
6603 Calculates a moebius transformation for the hyperbolic tree.
6604
6605 <http://en.wikipedia.org/wiki/Moebius_transformation>
6606
6607 Parameters:
6608
6609 graph - A <Graph> instance.
6610 pos - A <Complex>.
6611 prop - A property array.
6612 theta - Rotation angle.
6613 startPos - _optional_ start position.
6614 */
6615 Graph.Util.moebiusTransformation = function(graph, pos, prop, startPos, flags) {
6616 this.eachNode(graph, function(elem) {
6617 for(var i=0; i<prop.length; i++) {
6618 var p = pos[i].scale(-1), property = startPos? startPos : prop[i];
6619 elem[prop[i]].set(elem[property].getc().moebiusTransformation(p));
6620 }
6621 }, flags);
6622 };
6623
6624 /*
6625 Class: Hypertree
6626
6627 The main Hypertree class
6628
6629 Extends:
6630
6631 <Loader>, <AngularWidth>
6632
6633 Parameters:
6634
6635 canvas - A <Canvas> Class
6636 config - A configuration/controller object.
6637
6638 Configuration:
6639
6640 The configuration object can have the following properties (all properties are optional and have a default value)
6641
6642 *General*
6643 - _withLabels_ Whether the visualization should use/create labels or not. Default's *true*.
6644
6645 *Node*
6646
6647 Customize the visualization nodes' shape, color, and other style properties.
6648
6649 - _Node_
6650
6651 This object has as properties
6652
6653 - _overridable_ Determine whether or not nodes properties can be overriden by a particular node. Default's false.
6654
6655 If given a JSON tree or graph, a node _data_ property contains properties which are the same as defined here but prefixed with
6656 a dollar sign (i.e $), the node properties will override the global node properties.
6657
6658 - _type_ Node type (shape). Possible options are "none", "square", "rectangle", "circle", "triangle", "star". Default's "circle".
6659 - _color_ Node color. Default's '#ccb'.
6660 - _lineWidth_ Line width. If nodes aren't drawn with strokes then this property won't be of any use. Default's 1.
6661 - _height_ Node height. Used for plotting rectangular nodes. Default's 5.
6662 - _width_ Node width. Used for plotting rectangular nodes. Default's 5.
6663 - _dim_ An extra parameter used by other complex shapes such as square and circle to determine the shape's diameter. Default's 7.
6664 - _transform_ Whether to apply the moebius transformation to the nodes or not. Default's true.
6665
6666 *Edge*
6667
6668 Customize the visualization edges' shape, color, and other style properties.
6669
6670 - _Edge_
6671
6672 This object has as properties
6673
6674 - _overridable_ Determine whether or not edges properties can be overriden by a particular edge object. Default's false.
6675
6676 If given a JSON _complex_ graph (defined in <Loader.loadJSON>), an adjacency _data_ property contains properties which are the same as defined here but prefixed with
6677 a dollar sign (i.e $), the adjacency properties will override the global edge properties.
6678
6679 - _type_ Edge type (shape). Possible options are "none", "line" and "hyperline". Default's "hyperline".
6680 - _color_ Edge color. Default's '#ccb'.
6681 - _lineWidth_ Line width. If edges aren't drawn with strokes then this property won't be of any use. Default's 1.
6682
6683 *Animations*
6684
6685 - _duration_ Duration of the animation in milliseconds. Default's 1500.
6686 - _fps_ Frames per second. Default's 40.
6687 - _transition_ One of the transitions defined in the <Animation> class. Default's Quart.easeInOut.
6688 - _clearCanvas_ Whether to clear canvas on each animation frame or not. Default's true.
6689
6690 *Controller options*
6691
6692 You can also implement controller functions inside the configuration object. This functions are
6693
6694 - _onBeforeCompute(node)_ This method is called right before performing all computation and animations to the JIT visualization.
6695 - _onAfterCompute()_ This method is triggered right after all animations or computations for the JIT visualizations ended.
6696 - _onCreateLabel(domElement, node)_ This method receives the label dom element as first parameter, and the corresponding <Graph.Node> as second parameter. This method will only be called on label creation. Note that a <Graph.Node> is a node from the input tree/graph you provided to the visualization. If you want to know more about what kind of JSON tree/graph format is used to feed the visualizations, you can take a look at <Loader.loadJSON>. This method proves useful when adding events to the labels used by the JIT.
6697 - _onPlaceLabel(domElement, node)_ This method receives the label dom element as first parameter and the corresponding <Graph.Node> as second parameter. This method is called each time a label has been placed on the visualization, and thus it allows you to update the labels properties, such as size or position. Note that onPlaceLabel will be triggered after updating the labels positions. That means that, for example, the left and top css properties are already updated to match the nodes positions.
6698 - _onBeforePlotNode(node)_ This method is triggered right before plotting a given node. The _node_ parameter is the <Graph.Node> to be plotted.
6699 This method is useful for changing a node style right before plotting it.
6700 - _onAfterPlotNode(node)_ This method is triggered right after plotting a given node. The _node_ parameter is the <Graph.Node> plotted.
6701 - _onBeforePlotLine(adj)_ This method is triggered right before plotting an edge. The _adj_ parameter is a <Graph.Adjacence> object.
6702 This method is useful for adding some styles to a particular edge before being plotted.
6703 - _onAfterPlotLine(adj)_ This method is triggered right after plotting an edge. The _adj_ parameter is the <Graph.Adjacence> plotted.
6704
6705 Example:
6706
6707 Here goes a complete example. In most cases you won't be forced to implement all properties and methods. In fact,
6708 all configuration properties have the default value assigned.
6709
6710 I won't be instanciating a <Canvas> class here. If you want to know more about instanciating a <Canvas> class
6711 please take a look at the <Canvas> class documentation.
6712
6713 (start code js)
6714 var ht = new Hypertree(canvas, {
6715
6716 Node: {
6717 overridable: false,
6718 type: 'circle',
6719 color: '#ccb',
6720 lineWidth: 1,
6721 height: 5,
6722 width: 5,
6723 dim: 7,
6724 transform: true
6725 },
6726 Edge: {
6727 overridable: false,
6728 type: 'hyperline',
6729 color: '#ccb',
6730 lineWidth: 1
6731 },
6732 duration: 1500,
6733 fps: 40,
6734 transition: Trans.Quart.easeInOut,
6735 clearCanvas: true,
6736 withLabels: true,
6737
6738 onBeforeCompute: function(node) {
6739 //do something onBeforeCompute
6740 },
6741 onAfterCompute: function () {
6742 //do something onAfterCompute
6743 },
6744 onCreateLabel: function(domElement, node) {
6745 //do something onCreateLabel
6746 },
6747 onPlaceLabel: function(domElement, node) {
6748 //do something onPlaceLabel
6749 },
6750 onBeforePlotNode:function(node) {
6751 //do something onBeforePlotNode
6752 },
6753 onAfterPlotNode: function(node) {
6754 //do something onAfterPlotNode
6755 },
6756 onBeforePlotLine:function(adj) {
6757 //do something onBeforePlotLine
6758 },
6759 onAfterPlotLine: function(adj) {
6760 //do something onAfterPlotLine
6761 }
6762 });
6763 (end code)
6764
6765 Instance Properties:
6766
6767 - _graph_ Access a <Graph> instance.
6768 - _op_ Access a <Hypertree.Op> instance.
6769 - _fx_ Access a <Hypertree.Plot> instance.
6770 */
6771
6772 this.Hypertree = new Class({
6773
6774 Implements: [Loader, AngularWidth],
6775
6776 initialize: function(canvas, controller) {
6777
6778 var config = {
6779 labelContainer: canvas.id + '-label',
6780
6781 withLabels: true,
6782
6783 Node: {
6784 overridable: false,
6785 type: 'circle',
6786 dim: 7,
6787 color: '#ccb',
6788 width: 5,
6789 height: 5,
6790 lineWidth: 1,
6791 transform: true
6792 },
6793
6794 Edge: {
6795 overridable: false,
6796 type: 'hyperline',
6797 color: '#ccb',
6798 lineWidth: 1
6799 },
6800 clearCanvas: true,
6801 fps:40,
6802 duration: 1500,
6803 transition: Trans.Quart.easeInOut
6804 };
6805
6806 var innerController = {
6807 onBeforeCompute: $empty,
6808 onAfterCompute: $empty,
6809 onCreateLabel: $empty,
6810 onPlaceLabel: $empty,
6811 onComplete: $empty,
6812 onBeforePlotLine:$empty,
6813 onAfterPlotLine: $empty,
6814 onBeforePlotNode:$empty,
6815 onAfterPlotNode: $empty
6816 };
6817
6818 this.controller = this.config = $merge(config, innerController, controller);
6819 this.graphOptions = {
6820 'complex': false,
6821 'Node': {
6822 'selected': false,
6823 'exist': true,
6824 'drawn': true
6825 }
6826 };
6827 this.graph = new Graph(this.graphOptions);
6828 this.fx = new Hypertree.Plot(this);
6829 this.op = new Hypertree.Op(this);
6830 this.json = null;
6831 this.canvas = canvas;
6832
6833 this.root = null;
6834 this.busy = false;
6835 },
6836
6837 /*
6838 Method: refresh
6839
6840 Computes nodes' positions and replots the tree.
6841
6842 Parameters:
6843
6844 reposition - _optional_ Set this to *true* to force repositioning.
6845
6846 See also:
6847
6848 <Hypertree.reposition>
6849
6850 */
6851 refresh: function(reposition) {
6852 if(reposition) {
6853 this.reposition();
6854 Graph.Util.eachNode(this.graph, function(node) {
6855 node.startPos.rho = node.pos.rho = node.endPos.rho;
6856 node.startPos.theta = node.pos.theta = node.endPos.theta;
6857 });
6858 } else {
6859 this.compute();
6860 }
6861 this.plot();
6862 },
6863
6864 /*
6865 Method: reposition
6866
6867 Computes nodes' positions and restores the tree to its previous position.
6868
6869 For calculating nodes' positions the root must be placed on its origin. This method does this
6870 and then attemps to restore the hypertree to its previous position.
6871
6872 */
6873 reposition: function() {
6874 this.compute('endPos');
6875 var vector = this.graph.getNode(this.root).pos.getc().scale(-1);
6876 Graph.Util.moebiusTransformation(this.graph, [vector], ['endPos'], 'endPos', "ignore");
6877 Graph.Util.eachNode(this.graph, function(node) {
6878 if (node.ignore) {
6879 node.endPos.rho = node.pos.rho;
6880 node.endPos.theta = node.pos.theta;
6881 }
6882 });
6883 },
6884
6885 /*
6886 Method: plot
6887
6888 Plots the Hypertree
6889
6890 */
6891 plot: function() {
6892 this.fx.plot();
6893 },
6894
6895 /*
6896 Method: compute
6897
6898 Computes nodes' positions.
6899
6900 Parameters:
6901
6902 property - _optional_ A <Graph.Node> position property to store the new positions. Possible values are 'pos', 'endPos' or 'startPos'.
6903
6904
6905 */
6906 compute: function(property) {
6907 var prop = property || ['pos', 'startPos'];
6908 var node = this.graph.getNode(this.root);
6909 node._depth = 0;
6910 Graph.Util.computeLevels(this.graph, this.root, 0, "ignore");
6911 this.computeAngularWidths();
6912 this.computePositions(prop);
6913 },
6914
6915 /*
6916 computePositions
6917
6918 Performs the main algorithm for computing node positions.
6919
6920 Parameters:
6921
6922 property - A <Graph.Node> position property to store the new positions. Possible values are 'pos', 'endPos' or 'startPos'.
6923
6924 */
6925 computePositions: function(property) {
6926 var propArray = $splat(property);
6927 var aGraph = this.graph, GUtil = Graph.Util;
6928 var root = this.graph.getNode(this.root), that = this, config = this.config;
6929 var size = this.canvas.getSize();
6930 var scale = Math.min(size.width, size.height)/ 2;
6931
6932
6933 //Set default values for the root node
6934 for(var i=0; i<propArray.length; i++)
6935 root[propArray[i]] = $P(0, 0);
6936 root.angleSpan = {
6937 begin: 0,
6938 end: 2 * Math.PI
6939 };
6940 root._rel = 1;
6941
6942 //Estimate better edge length.
6943 var edgeLength = (function() {
6944 var depth = 0;
6945 GUtil.eachNode(aGraph, function(node) {
6946 depth = (node._depth > depth)? node._depth : depth;
6947 node._scale = scale;
6948 }, "ignore");
6949 for(var i=0.51; i<=1; i+=0.01) {
6950 var valSeries = (function(a, n) {
6951 return (1 - Math.pow(a, n)) / (1 - a);
6952 })(i, depth + 1);
6953 if(valSeries >= 2) return i - 0.01;
6954 }
6955 return 0.5;
6956 })();
6957
6958 GUtil.eachBFS(this.graph, this.root, function (elem) {
6959 var angleSpan = elem.angleSpan.end - elem.angleSpan.begin;
6960 var angleInit = elem.angleSpan.begin;
6961 var totalAngularWidths = (function (element){
6962 var total = 0;
6963 GUtil.eachSubnode(element, function(sib) {
6964 total += sib._treeAngularWidth;
6965 }, "ignore");
6966 return total;
6967 })(elem);
6968
6969 for(var i=1, rho = 0, lenAcum = edgeLength, depth = elem._depth; i<=depth+1; i++) {
6970 rho += lenAcum;
6971 lenAcum *= edgeLength;
6972 }
6973
6974 GUtil.eachSubnode(elem, function(child) {
6975 if(!child._flag) {
6976 child._rel = child._treeAngularWidth / totalAngularWidths;
6977 var angleProportion = child._rel * angleSpan;
6978 var theta = angleInit + angleProportion / 2;
6979
6980 for(var i=0; i<propArray.length; i++)
6981 child[propArray[i]] = $P(theta, rho);
6982
6983 child.angleSpan = {
6984 begin: angleInit,
6985 end: angleInit + angleProportion
6986 };
6987 angleInit += angleProportion;
6988 }
6989 }, "ignore");
6990
6991 }, "ignore");
6992 },
6993
6994 /*
6995 Method: onClick
6996
6997 Performs all calculations and animations to center the node specified by _id_.
6998
6999 Parameters:
7000
7001 id - A <Graph.Node> id.
7002 opt - _optional_ An object containing some extra properties like
7003
7004 - _hideLabels_ Hide labels when performing the animation. Default's *true*.
7005
7006 Example:
7007
7008 (start code js)
7009 ht.onClick('someid');
7010 //or also...
7011 ht.onClick('someid', {
7012 hideLabels: false
7013 });
7014 (end code)
7015
7016 */
7017 onClick: function(id, opt) {
7018 var pos = this.graph.getNode(id).pos.getc(true);
7019 this.move(pos, opt);
7020 },
7021
7022 /*
7023 Method: move
7024
7025 Translates the tree to the given position.
7026
7027 Parameters:
7028
7029 pos - A <Complex> number determining the position to move the tree to.
7030 opt - _optional_ An object containing some extra properties defined in <Hypertree.onClick>
7031
7032
7033 */
7034 move: function(pos, opt) {
7035 var versor = $C(pos.x, pos.y);
7036 if(this.busy === false && versor.norm() < 1) {
7037 var GUtil = Graph.Util;
7038 this.busy = true;
7039 var root = GUtil.getClosestNodeToPos(this.graph, versor), that = this;
7040 GUtil.computeLevels(this.graph, root.id, 0);
7041 this.controller.onBeforeCompute(root);
7042 if (versor.norm() < 1) {
7043 opt = $merge({ onComplete: $empty }, opt || {});
7044 this.fx.animate($merge({
7045 modes: ['moebius'],
7046 hideLabels: true
7047 }, opt, {
7048 onComplete: function(){
7049 that.busy = false;
7050 opt.onComplete();
7051 }
7052 }), versor);
7053 }
7054 }
7055 }
7056 });
7057
7058 /*
7059 Class: Hypertree.Op
7060
7061 Performs advanced operations on trees and graphs.
7062
7063 Extends:
7064
7065 All <Graph.Op> methods
7066
7067 Access:
7068
7069 This instance can be accessed with the _op_ parameter of the hypertree instance created.
7070
7071 Example:
7072
7073 (start code js)
7074 var ht = new Hypertree(canvas, config);
7075 ht.op.morph //or can also call any other <Graph.Op> method
7076 (end code)
7077
7078 */
7079 Hypertree.Op = new Class({
7080
7081 Implements: Graph.Op,
7082
7083 initialize: function(viz) {
7084 this.viz = viz;
7085 }
7086 });
7087
7088 /*
7089 Class: Hypertree.Plot
7090
7091 Performs plotting operations.
7092
7093 Extends:
7094
7095 All <Graph.Plot> methods
7096
7097 Access:
7098
7099 This instance can be accessed with the _fx_ parameter of the hypertree instance created.
7100
7101 Example:
7102
7103 (start code js)
7104 var ht = new Hypertree(canvas, config);
7105 ht.fx.placeLabel //or can also call any other <Hypertree.Plot> method
7106 (end code)
7107
7108 */
7109 Hypertree.Plot = new Class({
7110
7111 Implements: Graph.Plot,
7112
7113 initialize: function(viz) {
7114 this.viz = viz;
7115 this.config = viz.config;
7116 this.node = this.config.Node;
7117 this.edge = this.config.Edge;
7118 this.animation = new Animation;
7119 this.nodeTypes = new Hypertree.Plot.NodeTypes;
7120 this.edgeTypes = new Hypertree.Plot.EdgeTypes;
7121 },
7122
7123 /*
7124 Method: hyperline
7125
7126 Plots a hyperline between two nodes. A hyperline is an arc of a circle which is orthogonal to the main circle.
7127
7128 Parameters:
7129
7130 adj - A <Graph.Adjacence> object.
7131 canvas - A <Canvas> instance.
7132 */
7133 hyperline: function(adj, canvas) {
7134 var node = adj.nodeFrom, child = adj.nodeTo, data = adj.data;
7135 var pos = node.pos.getc(), posChild = child.pos.getc();
7136 var centerOfCircle = this.computeArcThroughTwoPoints(pos, posChild);
7137 var size = canvas.getSize();
7138 var scale = Math.min(size.width, size.height)/2;
7139 if (centerOfCircle.a > 1000 || centerOfCircle.b > 1000 || centerOfCircle.ratio > 1000) {
7140 canvas.path('stroke', function(ctx) {
7141 ctx.moveTo(pos.x * scale, pos.y * scale);
7142 ctx.lineTo(posChild.x * scale, posChild.y * scale);
7143 });
7144 } else {
7145 var angleBegin = Math.atan2(posChild.y - centerOfCircle.y, posChild.x - centerOfCircle.x);
7146 var angleEnd = Math.atan2(pos.y - centerOfCircle.y, pos.x - centerOfCircle.x);
7147 var sense = this.sense(angleBegin, angleEnd);
7148 var context = canvas.getCtx();
7149 canvas.path('stroke', function(ctx) {
7150 ctx.arc(centerOfCircle.x*scale, centerOfCircle.y*scale, centerOfCircle.ratio*scale, angleBegin, angleEnd, sense);
7151 });
7152 }
7153 },
7154
7155 /*
7156 computeArcThroughTwoPoints
7157
7158 Calculates the arc parameters through two points.
7159
7160 More information in <http://en.wikipedia.org/wiki/Poincar%C3%A9_disc_model#Analytic_geometry_constructions_in_the_hyperbolic_plane>
7161
7162 Parameters:
7163
7164 p1 - A <Complex> instance.
7165 p2 - A <Complex> instance.
7166
7167 Returns:
7168
7169 An object containing some arc properties.
7170 */
7171 computeArcThroughTwoPoints: function(p1, p2) {
7172 var aDen = (p1.x * p2.y - p1.y * p2.x), bDen = aDen;
7173 var sq1 = p1.squaredNorm(), sq2 = p2.squaredNorm();
7174 //Fall back to a straight line
7175 if (aDen == 0) return { x:0, y:0, ratio: 1001 };
7176
7177 var a = (p1.y * sq2 - p2.y * sq1 + p1.y - p2.y) / aDen;
7178 var b = (p2.x * sq1 - p1.x * sq2 + p2.x - p1.x) / bDen;
7179 var x = -a / 2;
7180 var y = -b / 2;
7181 var squaredRatio = (a * a + b * b) / 4 -1;
7182 //Fall back to a straight line
7183 if(squaredRatio < 0) return { x:0, y:0, ratio: 1001 };
7184 var ratio = Math.sqrt(squaredRatio);
7185 var out= {
7186 x: x,
7187 y: y,
7188 ratio: ratio,
7189 a: a,
7190 b: b
7191 };
7192
7193 return out;
7194 },
7195
7196 /*
7197 sense
7198
7199 Sets angle direction to clockwise (true) or counterclockwise (false).
7200
7201 Parameters:
7202
7203 angleBegin - Starting angle for drawing the arc.
7204 angleEnd - The HyperLine will be drawn from angleBegin to angleEnd.
7205
7206 Returns:
7207
7208 A Boolean instance describing the sense for drawing the HyperLine.
7209 */
7210 sense: function(angleBegin, angleEnd) {
7211 return (angleBegin < angleEnd)? ((angleBegin + Math.PI > angleEnd)? false : true) :
7212 ((angleEnd + Math.PI > angleBegin)? true : false);
7213 },
7214
7215
7216 /*
7217 Method: placeLabel
7218
7219 Overrides abstract method placeLabel in <Graph.Plot>.
7220
7221 Parameters:
7222
7223 tag - A DOM label element.
7224 node - A <Graph.Node>.
7225 controller - A configuration/controller object passed to the visualization.
7226
7227 */
7228 placeLabel: function(tag, node, controller) {
7229 var pos = node.pos.getc(true), canvas = this.viz.canvas;
7230 var radius= canvas.getSize();
7231 var scale = node._scale;
7232 var labelPos= {
7233 x: Math.round(pos.x * scale + radius.width/2),
7234 y: Math.round(pos.y * scale + radius.height/2)
7235 };
7236 var style = tag.style;
7237 style.left = labelPos.x + 'px';
7238 style.top = labelPos.y + 'px';
7239 style.display = '';
7240 controller.onPlaceLabel(tag, node);
7241 }
7242 });
7243
7244 /*
7245 Class: Hypertree.Plot.NodeTypes
7246
7247 Here are implemented all kinds of node rendering functions.
7248 Rendering functions implemented are 'none', 'circle', 'triangle', 'rectangle', 'star' and 'square'.
7249
7250 You can add new Node types by implementing a new method in this class
7251
7252 Example:
7253
7254 (start code js)
7255 Hypertree.Plot.NodeTypes.implement({
7256 'newnodetypename': function(node, canvas) {
7257 //Render my node here.
7258 }
7259 });
7260 (end code)
7261
7262 */
7263 Hypertree.Plot.NodeTypes = new Class({
7264 'none': function() {},
7265
7266 'circle': function(node, canvas) {
7267 var nconfig = this.node, data = node.data;
7268 var nodeDim = nconfig.overridable && data && data.$dim || nconfig.dim;
7269 var p = node.pos.getc(), pos = p.scale(node._scale);
7270 var prod = nconfig.transform? nodeDim * (1 - p.squaredNorm()) : nodeDim;
7271 if(prod >= nodeDim / 4) {
7272 canvas.path('fill', function(context) {
7273 context.arc(pos.x, pos.y, prod, 0, Math.PI * 2, true);
7274 });
7275 }
7276 },
7277
7278 'square': function(node, canvas) {
7279 var nconfig = this.node, data = node.data;
7280 var nodeDim = nconfig.overridable && data && data.$dim || nconfig.dim;
7281 var p = node.pos.getc(), pos = p.scale(node._scale);
7282 var prod = nconfig.transform? nodeDim * (1 - p.squaredNorm()) : nodeDim;
7283 var nodeDim2 = 2 * prod;
7284 if (prod >= nodeDim / 4) {
7285 canvas.getCtx().fillRect(pos.x - prod, pos.y - prod, nodeDim2, nodeDim2);
7286 }
7287 },
7288
7289 'rectangle': function(node, canvas) {
7290 var nconfig = this.node, data = node.data;
7291 var width = nconfig.overridable && data && data.$width || nconfig.width;
7292 var height = nconfig.overridable && data && data.$height || nconfig.height;
7293 var p = node.pos.getc(), pos = p.scale(node._scale);
7294 var prod = 1 - p.squaredNorm();
7295 width = nconfig.transform? width * prod : width;
7296 height = nconfig.transform? height * prod : height;
7297 if(prod >= 0.25) {
7298 canvas.getCtx().fillRect(pos.x - width / 2, pos.y - height / 2, width, height);
7299 }
7300
7301 },
7302
7303 'triangle': function(node, canvas) {
7304 var nconfig = this.node, data = node.data;
7305 var nodeDim = nconfig.overridable && data && data.$dim || nconfig.dim;
7306 var p = node.pos.getc(), pos = p.scale(node._scale);
7307 var prod = nconfig.transform? nodeDim * (1 - p.squaredNorm()) : nodeDim;
7308 if (prod >= nodeDim / 4) {
7309 var c1x = pos.x,
7310 c1y = pos.y - prod,
7311 c2x = c1x - prod,
7312 c2y = pos.y + prod,
7313 c3x = c1x + prod,
7314 c3y = c2y;
7315 canvas.path('fill', function(ctx){
7316 ctx.moveTo(c1x, c1y);
7317 ctx.lineTo(c2x, c2y);
7318 ctx.lineTo(c3x, c3y);
7319 });
7320 }
7321 },
7322
7323 'star': function(node, canvas) {
7324 var nconfig = this.node, data = node.data;
7325 var nodeDim = nconfig.overridable && data && data.$dim || nconfig.dim;
7326 var p = node.pos.getc(), pos = p.scale(node._scale);
7327 var prod = nconfig.transform? nodeDim * (1 - p.squaredNorm()) : nodeDim;
7328 if (prod >= nodeDim / 4) {
7329 var ctx = canvas.getCtx(), pi5 = Math.PI / 5;
7330 ctx.save();
7331 ctx.translate(pos.x, pos.y);
7332 ctx.beginPath();
7333 ctx.moveTo(nodeDim, 0);
7334 for (var i = 0; i < 9; i++) {
7335 ctx.rotate(pi5);
7336 if (i % 2 == 0) {
7337 ctx.lineTo((prod / 0.525731) * 0.200811, 0);
7338 }
7339 else {
7340 ctx.lineTo(prod, 0);
7341 }
7342 }
7343 ctx.closePath();
7344 ctx.fill();
7345 ctx.restore();
7346 }
7347 }
7348 });
7349
7350 /*
7351 Class: Hypertree.Plot.EdgeTypes
7352
7353 Here are implemented all kinds of edge rendering functions.
7354 Rendering functions implemented are 'none', 'line' and 'hyperline'.
7355
7356 You can add new Edge types by implementing a new method in this class
7357
7358 Example:
7359
7360 (start code js)
7361 Hypertree.Plot.EdgeTypes.implement({
7362 'newedgetypename': function(adj, canvas) {
7363 //Render my edge here.
7364 }
7365 });
7366 (end code)
7367
7368 */
7369 Hypertree.Plot.EdgeTypes = new Class({
7370 'none': function() {},
7371
7372 'line': function(adj, canvas) {
7373 var s = adj.nodeFrom._scale;
7374 var pos = adj.nodeFrom.pos.getc(true);
7375 var posChild = adj.nodeTo.pos.getc(true);
7376 canvas.path('stroke', function(context) {
7377 context.moveTo(pos.x * s, pos.y * s);
7378 context.lineTo(posChild.x * s, posChild.y * s);
7379 });
7380 },
7381
7382 'hyperline': function(adj, canvas) {
7383 this.hyperline(adj, canvas);
7384 }
7385 });
7386
7387
7388 /*
7389 * File: Treemap.js
7390 *
7391 * Implements the <TM> class and other derived classes.
7392 *
7393 * Description:
7394 *
7395 * A Treemap is an information visualization technique, proven very useful when displaying large hierarchical structures on a constrained space. The idea behind a Treemap is to describe hierarchical relations as 'containment'. That means that if node B is child of node A, then B 'is contained' in A.
7396 *
7397 * Inspired by:
7398 *
7399 * Squarified Treemaps (Mark Bruls, Kees Huizing, and Jarke J. van Wijk)
7400 *
7401 * <http://www.win.tue.nl/~vanwijk/stm.pdf>
7402 *
7403 * Tree visualization with tree-maps: 2-d space-filling approach (Ben Shneiderman)
7404 *
7405 * <http://hcil.cs.umd.edu/trs/91-03/91-03.html>
7406 *
7407 * Disclaimer:
7408 *
7409 * This visualization was built from scratch, taking only these papers as inspiration, and only shares some features with the Treemap papers mentioned above.
7410 *
7411 */
7412
7413 /*
7414 Object: TM
7415
7416 Abstract Treemap object.
7417
7418 Implemented By:
7419
7420 <TM.Squarified>, <TM.Strip> and <TM.SliceAndDice>.
7421
7422 Description:
7423
7424 Implements layout and configuration options inherited by <TM.Squarified>, <TM.Strip> and <TM.SliceAndDice>.
7425
7426 All Treemap constructors take the same configuration object as parameter.
7427
7428 Two special _data_ keys are read from the JSON tree structure loaded by <Loader.loadJSON> to calculate
7429 node's color and dimensions. These properties are $area (for nodes dimensions) and $color. Both of these properties are floats.
7430
7431 This means that the tree structure defined in <Loader.loadJSON> should now look more like this
7432
7433 (start code js)
7434 var json = {
7435 "id": "aUniqueIdentifier",
7436 "name": "usually a nodes name",
7437 "data": {
7438 "$area": 33, //some float value
7439 "$color": 36, //-optional- some float value
7440 "some key": "some value",
7441 "some other key": "some other value"
7442 },
7443 "children": [ 'other nodes or empty' ]
7444 };
7445 (end code)
7446
7447 If you want to know more about JSON tree structures and the _data_ property please read <Loader.loadJSON>.
7448
7449 Configuration:
7450
7451 *General*
7452
7453 - _rootId_ The id of the div container where the Treemap will be injected. Default's 'infovis'.
7454 - _orientation_ For <TM.Strip> and <TM.SliceAndDice> only. The layout algorithm orientation. Possible values are 'h' or 'v'.
7455 - _levelsToShow_ Max depth of the plotted tree. Useful when using the request method.
7456 - _addLeftClickHandler_ Add a left click event handler to zoom in the Treemap view when clicking a node. Default's *false*.
7457 - _addRightClickHandler_ Add a right click event handler to zoom out the Treemap view. Default's *false*.
7458 - _selectPathOnHover_ If setted to *true* all nodes contained in the path between the hovered node and the root node will have an *in-path* CSS class. Default's *false*.
7459
7460 *Nodes*
7461
7462 There are two kinds of Treemap nodes.
7463
7464 (see treemapnode.png)
7465
7466 Inner nodes are nodes having children, like _Pearl Jam_.
7467
7468 These nodes are represented by three div elements. A _content_ element, a _head_ element (where the title goes) and a _body_ element, where the children are laid out.
7469
7470 (start code xml)
7471 <div class="content">
7472 <div class="head">Pearl Jam</div>
7473 <div class="body">...other nodes here...</div>
7474 </div>
7475 (end code)
7476
7477 Leaves are optionally colored nodes laying at the "bottom" of the tree. For example, _Yield_, _Vs._ and _Riot Act_ are leaves.
7478
7479 These nodes are represented by two div elements. A _content_ element and a wrapped _leaf_ element
7480
7481 (start code xml)
7482 <div class="content">
7483 <div class="leaf">Yield</div>
7484 </div>
7485 (end code)
7486
7487 There are some configuration properties regarding Treemap nodes
7488
7489 - _titleHeight_ The height of the title (_head_) div container. Default's 13.
7490 - _offset_ The separation offset between the _content_ div element and its contained div(s). Default's 4.
7491
7492 *Color*
7493
7494 _Color_ is an object containing as properties
7495
7496 - _allow_ If *true*, the algorithm will check for the JSON node data _$color_ property to add some color to the Treemap leaves.
7497 This color is calculated by interpolating a node's $color value range with a real RGB color range.
7498 By specifying min|maxValues for the $color property and min|maxColorValues for the RGB counterparts, the visualization is able to
7499 interpolate color values and assign a proper color to the leaf node. Default's *false*.
7500 - _minValue_ The minimum value expected for the $color value property. Used for interpolating. Default's -100.
7501 - _maxValue_ The maximum value expected for the $color value property. Used for interpolating. Default's 100.
7502 - _minColorValue_ A three-element RGB array defining the color to be assigned to the _$color_ having _minValue_ as value. Default's [255, 0, 50].
7503 - _maxColorValue_ A three-element RGB array defining the color to be assigned to the _$color_ having _maxValue_ as value. Default's [0, 255, 50].
7504
7505 *Tips*
7506
7507 _Tips_ is an object containing as properties
7508
7509 - _allow_ If *true*, a tooltip will be shown when a node is hovered. The tooltip is a div DOM element having "tip" as CSS class. Default's *false*.
7510 - _offsetX_ An offset added to the current tooltip x-position (which is the same as the current mouse position). Default's 20.
7511 - _offsetY_ An offset added to the current tooltip y-position (which is the same as the current mouse position). Default's 20.
7512 - _onShow(tooltip, node, isLeaf, domElement)_ Implement this method to change the HTML content of the tooltip when hovering a node.
7513
7514 Parameters:
7515 tooltip - The tooltip div element.
7516 node - The corresponding JSON tree node (See also <Loader.loadJSON>).
7517 isLeaf - Whether is a leaf or inner node.
7518 domElement - The current hovered DOM element.
7519
7520 *Controller options*
7521
7522 You can also implement controller functions inside the configuration object. These functions are
7523
7524 - _onBeforeCompute(node)_ This method is called right before performing all computation and animations to the JIT visualization.
7525 - _onAfterCompute()_ This method is triggered right after all animations or computations for the JIT visualizations ended.
7526 - _onCreateElement(content, node, isLeaf, elem1, elem2)_ This method is called on each newly created node.
7527
7528 Parameters:
7529 content - The div wrapper element with _content_ className.
7530 node - The corresponding JSON tree node (See also <Loader.loadJSON>).
7531 isLeaf - Whether is a leaf or inner node. If the node's an inner tree node, elem1 and elem2 will become the _head_ and _body_ div elements respectively.
7532 If the node's a _leaf_, then elem1 will become the div leaf element.
7533
7534 - _onDestroyElement(content, node, isLeaf, elem1, elem2)_ This method is called before collecting each node. Takes the same parameters as onCreateElement.
7535 - _request(nodeId, level, onComplete)_ This method is used for buffering information into the visualization. When clicking on an empty node,
7536 the visualization will make a request for this node's subtrees, specifying a given level for this subtree (defined by _levelsToShow_). Once the request is completed, the _onComplete_
7537 object should be called with the given result.
7538
7539 See also <TM.Squarified>, <TM.SliceAndDice> and <TM.Strip>.
7540
7541
7542 */
7543 this.TM = {
7544
7545 layout: {
7546 orientation: "h",
7547 vertical: function() {
7548 return this.orientation == "v";
7549 },
7550 horizontal: function() {
7551 return this.orientation == "h";
7552 },
7553 change: function() {
7554 this.orientation = this.vertical()? "h" : "v";
7555 }
7556 },
7557
7558 innerController: {
7559 onBeforeCompute: $empty,
7560 onAfterCompute: $empty,
7561 onComplete: $empty,
7562 onCreateElement: $empty,
7563 onDestroyElement: $empty,
7564 request: false
7565 },
7566
7567 config: {
7568 orientation: "h",
7569 titleHeight: 13,
7570 rootId: 'infovis',
7571 offset:4,
7572 levelsToShow: 3,
7573 addLeftClickHandler: false,
7574 addRightClickHandler: false,
7575 selectPathOnHover: false,
7576
7577 Color: {
7578 allow: false,
7579 minValue: -100,
7580 maxValue: 100,
7581 minColorValue: [255, 0, 50],
7582 maxColorValue: [0, 255, 50]
7583 },
7584
7585 Tips: {
7586 allow: false,
7587 offsetX: 20,
7588 offsetY: 20,
7589 onShow: $empty
7590 }
7591 },
7592
7593
7594 initialize: function(controller) {
7595 this.tree = null;
7596 this.shownTree = null;
7597 this.controller = this.config = $merge(this.config,
7598 this.innerController,
7599 controller);
7600 this.rootId = this.config.rootId;
7601 this.layout.orientation = this.config.orientation;
7602 //add tooltip
7603 if(this.config.Tips.allow && document.body) {
7604 var tip = document.getElementById('_tooltip') || document.createElement('div');
7605 tip.id = '_tooltip';
7606 tip.className = 'tip';
7607 var style = tip.style;
7608 style.position = 'absolute';
7609 style.display = 'none';
7610 style.zIndex = 13000;
7611 document.body.appendChild(tip);
7612 this.tip = tip;
7613 }
7614
7615 //purge
7616 var that = this;
7617 var fn = function() {
7618 that.empty();
7619 if(window.CollectGarbage) window.CollectGarbage();
7620 delete fn;
7621 };
7622 if(window.addEventListener) {
7623 window.addEventListener('unload', fn, false);
7624 } else {
7625 window.attachEvent('onunload', fn);
7626 }
7627 },
7628
7629 /*
7630 Method: each
7631
7632 Traverses head and leaf nodes applying a given function
7633
7634 Parameters:
7635
7636 f - A function that takes as parameters the same as the onCreateElement and onDestroyElement methods described in <TM>.
7637 */
7638 each: function(f) {
7639 (function rec(elem) {
7640 if(!elem) return;
7641 var ch = elem.childNodes, len = ch.length;
7642 if(len > 0) {
7643 f.apply(this, [elem, len === 1, ch[0], ch[1]]);
7644 }
7645 if (len > 1) {
7646 for(var chi = ch[1].childNodes, i=0; i<chi.length; i++) {
7647 rec(chi[i]);
7648 }
7649 }
7650 })($get(this.rootId).firstChild);
7651 },
7652
7653 /*
7654 toStyle
7655
7656 Transforms a JSON into a CSS style string.
7657 */
7658 toStyle: function(obj) {
7659 var ans = "";
7660 for(var s in obj) ans += s + ":" + obj[s] + ";";
7661 return ans;
7662 },
7663
7664 /*
7665 leaf
7666
7667 Returns a boolean value specifying if the node is a tree leaf or not.
7668
7669 Parameters:
7670
7671 tree - A tree node (which is also a JSON tree object of course). <http://blog.thejit.org>
7672
7673 Returns:
7674
7675 A boolean value specifying if the node is a tree leaf or not.
7676
7677 */
7678 leaf: function(tree) {
7679 return tree.children == 0;
7680 },
7681
7682 /*
7683 Method: createBox
7684
7685 Constructs the proper DOM layout from a json node.
7686
7687 If the node's an _inner node_,
7688 this method calls <TM.contentBox>, <TM.bodyBox> and <TM.leafBox>
7689 to create the following HTML structure
7690
7691 (start code xml)
7692 <div class="content">
7693 <div class="head">[Node name]</div>
7694 <div class="body">[Node's children]</div>
7695 </div>
7696 (end code)
7697
7698 If the node's a leaf node, it creates the following structure
7699 by calling <TM.contentBox>, <TM.leafBox>
7700
7701 (start code xml)
7702 <div class="content">
7703 <div class="leaf">[Node name]</div>
7704 </div>
7705 (end code)
7706
7707
7708 Parameters:
7709
7710 json - A JSON subtree. See also <Loader.loadJSON>.
7711 coord - A coordinates object specifying width, height, left and top style properties.
7712 html - html to inject into the _body_ element if the node is an inner Tree node.
7713
7714 Returns:
7715
7716 The HTML structure described above.
7717
7718 See also:
7719
7720 <TM>, <TM.contentBox>, <TM.bodyBox>, <TM.headBox>, <TM.leafBox>.
7721
7722 */
7723 createBox: function(json, coord, html) {
7724 var box;
7725 if(!this.leaf(json)) {
7726 box = this.headBox(json, coord) + this.bodyBox(html, coord);
7727 } else {
7728 box = this.leafBox(json, coord);
7729 }
7730 return this.contentBox(json, coord, box);
7731 },
7732
7733 /*
7734 Method: plot
7735
7736 Renders the Treemap.
7737
7738 Parameters:
7739
7740 json - A JSON tree structure preprocessed by some Treemap layout algorithm.
7741
7742 Returns:
7743
7744 The HTML to inject to the main visualization container.
7745
7746 See also:
7747
7748 <TM.createBox>.
7749
7750
7751 */
7752 plot: function(json) {
7753 var coord = json.coord, html = "";
7754
7755 if(this.leaf(json))
7756 return this.createBox(json, coord, null);
7757
7758 for(var i=0, ch=json.children; i<ch.length; i++) {
7759 var chi = ch[i], chcoord = chi.coord;
7760 //skip tiny nodes
7761 if(chcoord.width * chcoord.height > 1) {
7762 html+= this.plot(chi);
7763 }
7764 }
7765 return this.createBox(json, coord, html);
7766 },
7767
7768
7769 /*
7770 Method: headBox
7771
7772 Creates the _head_ div dom element that usually contains the name of a parent JSON tree node.
7773
7774 Parameters:
7775
7776 json - A JSON subtree. See also <Loader.loadJSON>.
7777 coord - width and height base coordinate object.
7778
7779 Returns:
7780
7781 A new _head_ div dom element that has _head_ as class name.
7782
7783 See also:
7784
7785 <TM.createBox>.
7786
7787 */
7788 headBox: function(json, coord) {
7789 var config = this.config, offst = config.offset;
7790 var c = {
7791 'height': config.titleHeight + "px",
7792 'width': (coord.width - offst) + "px",
7793 'left': offst / 2 + "px"
7794 };
7795 return "<div class=\"head\" style=\"" + this.toStyle(c) + "\">"
7796 + json.name + "</div>";
7797 },
7798
7799 /*
7800 Method: bodyBox
7801
7802 Creates the _body_ div dom element that usually contains a subtree dom element layout.
7803
7804 Parameters:
7805
7806 html - html that should be contained in the body html.
7807 coord - width and height base coordinate object.
7808
7809 Returns:
7810
7811 A new _body_ div dom element that has _body_ as class name.
7812
7813 See also:
7814
7815 <TM.createBox>.
7816
7817 */
7818 bodyBox: function(html, coord) {
7819 var config = this.config,
7820 th = config.titleHeight,
7821 offst = config.offset;
7822 var c = {
7823 'width': (coord.width - offst) + "px",
7824 'height':(coord.height - offst - th) + "px",
7825 'top': (th + offst / 2) + "px",
7826 'left': (offst / 2) + "px"
7827 };
7828 return "<div class=\"body\" style=\""
7829 + this.toStyle(c) +"\">" + html + "</div>";
7830 },
7831
7832
7833
7834 /*
7835 Method: contentBox
7836
7837 Creates the _content_ div dom element that usually contains a _leaf_ div dom element or _head_ and _body_ div dom elements.
7838
7839 Parameters:
7840
7841 json - A JSON node. See also <Loader.loadJSON>.
7842 coord - An object containing width, height, left and top coordinates.
7843 html - input html wrapped by this tag.
7844
7845 Returns:
7846
7847 A new _content_ div dom element that has _content_ as class name.
7848
7849 See also:
7850
7851 <TM.createBox>.
7852
7853 */
7854 contentBox: function(json, coord, html) {
7855 var c = {};
7856 for(var i in coord) c[i] = coord[i] + "px";
7857 return "<div class=\"content\" style=\"" + this.toStyle(c)
7858 + "\" id=\"" + json.id + "\">" + html + "</div>";
7859 },
7860
7861
7862 /*
7863 Method: leafBox
7864
7865 Creates the _leaf_ div dom element that usually contains nothing else.
7866
7867 Parameters:
7868
7869 json - A JSON subtree. See also <Loader.loadJSON>.
7870 coord - base with and height coordinate object.
7871
7872 Returns:
7873
7874 A new _leaf_ div dom element having _leaf_ as class name.
7875
7876 See also:
7877
7878 <TM.createBox>.
7879
7880
7881 */
7882 leafBox: function(json, coord) {
7883 var config = this.config;
7884 var backgroundColor = config.Color.allow && this.setColor(json),
7885 offst = config.offset,
7886 width = coord.width - offst,
7887 height = coord.height - offst;
7888 var c = {
7889 'top': (offst / 2) + "px",
7890 'height':height + "px",
7891 'width': width + "px",
7892 'left': (offst / 2) + "px"
7893 };
7894 if(backgroundColor) c['background-color'] = backgroundColor;
7895 return "<div class=\"leaf\" style=\"" + this.toStyle(c) + "\">"
7896 + json.name + "</div>";
7897 },
7898
7899
7900 /*
7901 Method: setColor
7902
7903 Calculates an hexa color string based on the _$color_ data node property.
7904
7905 This method is called by <TM.leafBox> to assign an hexadecimal color to each leaf node.
7906
7907 This color is calculated by making a linear interpolation between _$color_ max and min values and
7908 RGB max and min values so that
7909
7910 > hex = (maxColorValue - minColorValue) / (maxValue - minValue) * (x - minValue) + minColorValue
7911
7912 where _x_ range is [minValue, maxValue] and
7913
7914 - _minValue_
7915 - _maxValue_
7916 - _minColorValue_
7917 - _maxColorValue_
7918
7919 are defined in the <TM> configuration object.
7920
7921 This method is called by <TM.leafBox> iif _Color.allow_ is setted to _true_.
7922
7923 Sometimes linear interpolation for coloring is just not enough. In that case you can re-implement this
7924 method so that it fits your coloring needs.
7925
7926 Some people might find useful to implement their own coloring interpolation method and to assign the resulting hex string
7927 to the _$color_ property. In that case we could re-implement the <TM.setColor> method like this
7928
7929 (start code js)
7930 //TM.Strip, TM.SliceAndDice also work
7931 TM.Squarified.implement({
7932 'setColor': function(json) {
7933 return json.data.$color;
7934 }
7935 });
7936 (end code)
7937
7938 So that it returns the previously assigned hex string.
7939
7940 Parameters:
7941
7942 json - A JSON tree node.
7943
7944 Returns:
7945
7946 A String that represents a color in hex value.
7947
7948 */
7949 setColor: function(json) {
7950 var c = this.config.Color,
7951 maxcv = c.maxColorValue,
7952 mincv = c.minColorValue,
7953 maxv = c.maxValue,
7954 minv = c.minValue,
7955 diff = maxv - minv,
7956 x = (json.data.$color - 0);
7957 //linear interpolation
7958 var comp = function(i, x) {
7959 return Math.round((((maxcv[i] - mincv[i]) / diff) * (x - minv) + mincv[i]));
7960 };
7961
7962 return $rgbToHex([ comp(0, x), comp(1, x), comp(2, x) ]);
7963 },
7964
7965 /*
7966 Method: enter
7967
7968 Sets the _elem_ parameter as root and performs the layout.
7969
7970 Parameters:
7971
7972 elem - A JSON Tree node. See also <Loader.loadJSON>.
7973 */
7974 enter: function(elem) {
7975 this.view(elem.parentNode.id);
7976 },
7977
7978 /*
7979 Method: onLeftClick
7980
7981 Sets the _elem_ parameter as root and performs the layout.
7982 This method is called when _addLeftClickHandler_ is *true* and a
7983 node is left-clicked. You can override this method to add some custom behavior
7984 when the node is left clicked though.
7985
7986 An Example for overriding this method could be
7987 (start code js)
7988 //TM.Strip or TM.SliceAndDice also work
7989 TM.Squarified.implement({
7990 'onLeftClick': function(elem) {
7991 //some custom code...
7992 }
7993 });
7994 (end code)
7995
7996
7997 Parameters:
7998
7999 elem - A JSON Tree node. See also <Loader.loadJSON>.
8000
8001 See also:
8002
8003 <TM.enter>
8004 */
8005 onLeftClick: function(elem) {
8006 this.enter(elem);
8007 },
8008
8009 /*
8010 Method: out
8011
8012 Sets the _parent_ node of the currently shown subtree as root and performs the layout.
8013
8014 */
8015 out: function() {
8016 var parent = TreeUtil.getParent(this.tree, this.shownTree.id);
8017 if(parent) {
8018 if(this.controller.request)
8019 TreeUtil.prune(parent, this.config.levelsToShow);
8020 this.view(parent.id);
8021 }
8022 },
8023
8024 /*
8025 Method: onRightClick
8026
8027 Sets the _parent_ node of the currently shown subtree as root and performs the layout.
8028 This method is called when _addRightClickHandler_ is *true* and a
8029 node is right-clicked. You can override this method to add some custom behavior
8030 when the node is right-clicked though.
8031
8032 An Example for overriding this method could be
8033 (start code js)
8034 //TM.Strip or TM.SliceAndDice also work
8035 TM.Squarified.implement({
8036 'onRightClick': function() {
8037 //some custom code...
8038 }
8039 });
8040 (end code)
8041
8042 See also:
8043
8044 <TM.out>
8045
8046 */
8047 onRightClick: function() {
8048 this.out();
8049 },
8050
8051 /*
8052 Method: view
8053
8054 Sets the root of the treemap to the specified node id and performs the layout.
8055
8056 Parameters:
8057
8058 id - A node identifier
8059 */
8060 view: function(id) {
8061 var config = this.config, that = this;
8062 var post = {
8063 onComplete: function() {
8064 that.loadTree(id);
8065 $get(config.rootId).focus();
8066 }
8067 };
8068
8069 if (this.controller.request) {
8070 var TUtil = TreeUtil;
8071 TUtil.loadSubtrees(TUtil.getSubtree(this.tree, id),
8072 $merge(this.controller, post));
8073 } else {
8074 post.onComplete();
8075 }
8076 },
8077
8078 /*
8079 Method: resetPath
8080
8081 Sets an 'in-path' className for _leaf_ and _head_ elements which belong to the path between the given tree node
8082 and the visualization's root node.
8083
8084 Parameters:
8085
8086 tree - A JSON tree node. See also <Loader.loadJSON>.
8087 */
8088 resetPath: function(tree) {
8089 var root = this.rootId, previous = this.resetPath.previous;
8090 this.resetPath.previous = tree || false;
8091 function getParent(c) {
8092 var p = c.parentNode;
8093 return p && (p.id != root) && p;
8094 };
8095 function toggleInPath(elem, remove) {
8096 if(elem) {
8097 var container = $get(elem.id);
8098 if(container) {
8099 var parent = getParent(container);
8100 while(parent) {
8101 elem = parent.childNodes[0];
8102 if($hasClass(elem, 'in-path')) {
8103 if(remove == undefined || !!remove) $removeClass(elem, 'in-path');
8104 } else {
8105 if(!remove) $addClass(elem, 'in-path');
8106 }
8107 parent = getParent(parent);
8108 }
8109 }
8110 }
8111 };
8112 toggleInPath(previous, true);
8113 toggleInPath(tree, false);
8114 },
8115
8116
8117 /*
8118 Method: initializeElements
8119
8120 Traverses the DOM tree applying the onCreateElement method.
8121
8122 The onCreateElement controller method should attach events and add some behavior to the DOM element
8123 node created. *By default, the Treemap wont add any event to its elements.*
8124 */
8125 initializeElements: function() {
8126 var cont = this.controller, that = this;
8127 var ff = $lambda(false), tipsAllow = cont.Tips.allow;
8128 this.each(function(content, isLeaf, elem1, elem2) {
8129 var tree = TreeUtil.getSubtree(that.tree, content.id);
8130 cont.onCreateElement(content, tree, isLeaf, elem1, elem2);
8131
8132 //eliminate context menu when right clicking
8133 if(cont.addRightClickHandler) elem1.oncontextmenu = ff;
8134
8135 //add click handlers
8136 if(cont.addLeftClickHandler || cont.addRightClickHandler) {
8137 $addEvent(elem1, 'mouseup', function(e) {
8138 var rightClick = (e.which == 3 || e.button == 2);
8139 if (rightClick) {
8140 if(cont.addRightClickHandler) that.onRightClick();
8141 }
8142 else {
8143 if(cont.addLeftClickHandler) that.onLeftClick(elem1);
8144 }
8145
8146 //prevent default
8147 if (e.preventDefault)
8148 e.preventDefault();
8149 else
8150 e.returnValue = false;
8151 });
8152 }
8153
8154 //add path selection on hovering nodes
8155 if(cont.selectPathOnHover || tipsAllow) {
8156 $addEvent(elem1, 'mouseover', function(e){
8157 if(cont.selectPathOnHover) {
8158 if (isLeaf) {
8159 $addClass(elem1, 'over-leaf');
8160 }
8161 else {
8162 $addClass(elem1, 'over-head');
8163 $addClass(content, 'over-content');
8164 }
8165 if (content.id)
8166 that.resetPath(tree);
8167 }
8168 if(tipsAllow)
8169 cont.Tips.onShow(that.tip, tree, isLeaf, elem1);
8170 });
8171
8172 $addEvent(elem1, 'mouseout', function(e){
8173 if(cont.selectPathOnHover) {
8174 if (isLeaf) {
8175 $removeClass(elem1, 'over-leaf');
8176 }
8177 else {
8178 $removeClass(elem1, 'over-head');
8179 $removeClass(content, 'over-content');
8180 }
8181 that.resetPath();
8182 }
8183 if(tipsAllow)
8184 that.tip.style.display = 'none';
8185 });
8186
8187 if(tipsAllow) {
8188 //Add mousemove event handler
8189 $addEvent(elem1, 'mousemove', function(e, win){
8190 var tip = that.tip;
8191 //get mouse position
8192 win = win || window;
8193 e = e || win.event;
8194 var doc = win.document;
8195 doc = doc.html || doc.body;
8196 var page = {
8197 x: e.pageX || e.clientX + doc.scrollLeft,
8198 y: e.pageY || e.clientY + doc.scrollTop
8199 };
8200 tip.style.display = '';
8201 //get window dimensions
8202 win = {
8203 'height': document.body.clientHeight,
8204 'width': document.body.clientWidth
8205 };
8206 //get tooltip dimensions
8207 var obj = {
8208 'width': tip.offsetWidth,
8209 'height': tip.offsetHeight
8210 };
8211 //set tooltip position
8212 var style = tip.style, x = cont.Tips.offsetX, y = cont.Tips.offsetY;
8213 style.top = ((page.y + y + obj.height > win.height)?
8214 (page.y - obj.height - y) : page.y + y) + 'px';
8215 style.left = ((page.x + obj.width + x > win.width)?
8216 (page.x - obj.width - x) : page.x + x) + 'px';
8217 });
8218 }
8219 }
8220 });
8221 },
8222
8223 /*
8224 Method: destroyElements
8225
8226 Traverses the tree applying the onDestroyElement method.
8227
8228 The onDestroyElement controller method should detach events and garbage collect the element.
8229 *By default, the Treemap adds some garbage collect facilities for IE.*
8230 */
8231 destroyElements: function() {
8232 if(this.controller.onDestroyElement != $empty) {
8233 var cont = this.controller, that = this;
8234 this.each(function(content, isLeaf, elem1, elem2) {
8235 cont.onDestroyElement(content, TreeUtil.getSubtree(that.tree, content.id), isLeaf, elem1, elem2);
8236 });
8237 }
8238 },
8239
8240 /*
8241 Method: empty
8242
8243 Empties the Treemap container (trying also to garbage collect things).
8244 */
8245 empty: function() {
8246 this.destroyElements();
8247 $clean($get(this.rootId));
8248 },
8249
8250 /*
8251 Method: loadTree
8252
8253 Loads the subtree specified by _id_ and plots it on the layout container.
8254
8255 Parameters:
8256
8257 id - A subtree id.
8258 */
8259 loadTree: function(id) {
8260 this.empty();
8261 this.loadJSON(TreeUtil.getSubtree(this.tree, id));
8262 }
8263
8264 };
8265
8266 /*
8267 Class: TM.SliceAndDice
8268
8269 A JavaScript implementation of the Slice and Dice Treemap algorithm.
8270
8271 The <TM.SliceAndDice> constructor takes an _optional_ configuration object described in <TM>.
8272
8273 This visualization (as all other Treemap visualizations) is fed with JSON Tree structures.
8274
8275 The _$area_ node data key is required for calculating rectangles dimensions.
8276
8277 The _$color_ node data key is required if _Color_ _allow_ is *true* and is used for calculating
8278 leaves colors.
8279
8280 Extends:
8281 <TM>
8282
8283 Parameters:
8284
8285 config - Configuration defined in <TM>.
8286
8287 Example:
8288
8289
8290 Here's a way of instanciating the <TM.SliceAndDice> will all its _optional_ configuration features
8291
8292 (start code js)
8293
8294 var tm = new TM.SliceAndDice({
8295 orientation: "h",
8296 titleHeight: 13,
8297 rootId: 'infovis',
8298 offset:4,
8299 levelsToShow: 3,
8300 addLeftClickHandler: false,
8301 addRightClickHandler: false,
8302 selectPathOnHover: false,
8303
8304 Color: {
8305 allow: false,
8306 minValue: -100,
8307 maxValue: 100,
8308 minColorValue: [255, 0, 50],
8309 maxColorValue: [0, 255, 50]
8310 },
8311
8312 Tips: {
8313 allow: false,
8314 offsetX; 20,
8315 offsetY: 20,
8316 onShow: function(tooltip, node, isLeaf, domElement) {}
8317 },
8318
8319 onBeforeCompute: function(node) {
8320 //Some stuff on before compute...
8321 },
8322 onAfterCompute: function() {
8323 //Some stuff on after compute...
8324 },
8325 onCreateElement: function(content, node, isLeaf, head, body) {
8326 //Some stuff onCreateElement
8327 },
8328 onDestroyElement: function(content, node, isLeaf, head, body) {
8329 //Some stuff onDestroyElement
8330 },
8331 request: false
8332 });
8333 tm.loadJSON(json);
8334
8335 (end code)
8336
8337 */
8338 TM.SliceAndDice = new Class({
8339 Implements: TM,
8340 /*
8341 Method: loadJSON
8342
8343 Loads the specified JSON tree and lays it on the main container.
8344
8345 Parameters:
8346
8347 json - A JSON Tree. See also <Loader.loadJSON>.
8348 */
8349 loadJSON: function (json) {
8350 this.controller.onBeforeCompute(json);
8351 var container = $get(this.rootId),
8352 config = this.config,
8353 width = container.offsetWidth,
8354 height = container.offsetHeight;
8355
8356 var p = {
8357 'coord': {
8358 'top': 0,
8359 'left': 0,
8360 'width': width,
8361 'height': height + config.titleHeight + config.offset
8362 }
8363 };
8364
8365 if(this.tree == null) this.tree = json;
8366 this.shownTree = json;
8367 this.compute(p, json, this.layout.orientation);
8368 container.innerHTML = this.plot(json);
8369 this.initializeElements();
8370 this.controller.onAfterCompute(json);
8371 },
8372
8373 /*
8374 Method: compute
8375
8376 Called by loadJSON to calculate recursively all node positions and lay out the tree.
8377
8378 Parameters:
8379
8380 par - The parent node of the json subtree.
8381 json - A JSON subtree. See also <Loader.loadJSON>.
8382 orientation - The current orientation. This value is switched recursively.
8383 */
8384 compute: function(par, json, orientation) {
8385 var config = this.config,
8386 coord = par.coord,
8387 offst = config.offset,
8388 width = coord.width - offst,
8389 height = coord.height - offst - config.titleHeight,
8390 pdata = par.data,
8391 fact = (pdata && ("$area" in pdata))? json.data.$area / pdata.$area : 1;
8392 var otherSize, size, dim, pos, pos2;
8393
8394 var horizontal = (orientation == "h");
8395 if(horizontal) {
8396 orientation = 'v';
8397 otherSize = height;
8398 size = Math.round(width * fact);
8399 dim = 'height';
8400 pos = 'top';
8401 pos2 = 'left';
8402 } else {
8403 orientation = 'h';
8404 otherSize = Math.round(height * fact);
8405 size = width;
8406 dim = 'width';
8407 pos = 'left';
8408 pos2 = 'top';
8409 }
8410 json.coord = {
8411 'width':size,
8412 'height':otherSize,
8413 'top':0,
8414 'left':0
8415 };
8416 var offsetSize = 0, tm = this;
8417 $each(json.children, function(elem){
8418 tm.compute(json, elem, orientation);
8419 elem.coord[pos] = offsetSize;
8420 elem.coord[pos2] = 0;
8421 offsetSize += Math.floor(elem.coord[dim]);
8422 });
8423 }
8424 });
8425
8426
8427 /*
8428 Class: TM.Area
8429
8430 Abstract Treemap class containing methods that are common to
8431 aspect ratio related algorithms such as <TM.Squarified> and <TM.Strip>.
8432
8433 Implemented by:
8434
8435 <TM.Squarified>, <TM.Strip>
8436 */
8437 TM.Area = new Class({
8438
8439 /*
8440 Method: loadJSON
8441
8442 Loads the specified JSON tree and lays it on the main container.
8443
8444 Parameters:
8445
8446 json - A JSON tree. See also <Loader.loadJSON>.
8447 */
8448 loadJSON: function (json) {
8449 this.controller.onBeforeCompute(json);
8450 var container = $get(this.rootId),
8451 width = container.offsetWidth,
8452 height = container.offsetHeight,
8453 offst = this.config.offset,
8454 offwdth = width - offst,
8455 offhght = height - offst - this.config.titleHeight;
8456
8457 json.coord = {
8458 'height': height,
8459 'width': width,
8460 'top': 0,
8461 'left': 0
8462 };
8463 var coord = $merge(json.coord, {
8464 'width': offwdth,
8465 'height': offhght
8466 });
8467
8468 this.compute(json, coord);
8469 container.innerHTML = this.plot(json);
8470 if(this.tree == null) this.tree = json;
8471 this.shownTree = json;
8472 this.initializeElements();
8473 this.controller.onAfterCompute(json);
8474 },
8475
8476 /*
8477 Method: computeDim
8478
8479 Computes dimensions and positions of a group of nodes
8480 according to a custom layout row condition.
8481
8482 Parameters:
8483
8484 tail - An array of nodes.
8485 initElem - An array of nodes (containing the initial node to be laid).
8486 w - A fixed dimension where nodes will be layed out.
8487 coord - A coordinates object specifying width, height, left and top style properties.
8488 comp - A custom comparison function
8489 */
8490 computeDim: function(tail, initElem, w, coord, comp) {
8491 if(tail.length + initElem.length == 1) {
8492 var l = (tail.length == 1)? tail : initElem;
8493 this.layoutLast(l, w, coord);
8494 return;
8495 }
8496 if(tail.length >= 2 && initElem.length == 0) {
8497 initElem = [tail[0]];
8498 tail = tail.slice(1);
8499 }
8500 if(tail.length == 0) {
8501 if(initElem.length > 0) this.layoutRow(initElem, w, coord);
8502 return;
8503 }
8504 var c = tail[0];
8505 if(comp(initElem, w) >= comp([c].concat(initElem), w)) {
8506 this.computeDim(tail.slice(1), initElem.concat([c]), w, coord, comp);
8507 } else {
8508 var newCoords = this.layoutRow(initElem, w, coord);
8509 this.computeDim(tail, [], newCoords.dim, newCoords, comp);
8510 }
8511 },
8512
8513
8514 /*
8515 Method: worstAspectRatio
8516
8517 Calculates the worst aspect ratio of a group of rectangles.
8518
8519 See also:
8520
8521 <http://en.wikipedia.org/wiki/Aspect_ratio>
8522
8523 Parameters:
8524
8525 ch - An array of nodes.
8526 w - The fixed dimension where rectangles are being laid out.
8527
8528 Returns:
8529
8530 The worst aspect ratio.
8531
8532
8533 */
8534 worstAspectRatio: function(ch, w) {
8535 if(!ch || ch.length == 0) return Number.MAX_VALUE;
8536 var areaSum = 0, maxArea = 0, minArea = Number.MAX_VALUE;
8537 for(var i=0; i<ch.length; i++) {
8538 var area = ch[i]._area;
8539 areaSum += area;
8540 minArea = (minArea < area)? minArea : area;
8541 maxArea = (maxArea > area)? maxArea : area;
8542 }
8543 var sqw = w * w, sqAreaSum = areaSum * areaSum;
8544 return Math.max(sqw * maxArea / sqAreaSum,
8545 sqAreaSum / (sqw * minArea));
8546 },
8547
8548 /*
8549 Method: avgAspectRatio
8550
8551 Calculates the average aspect ratio of a group of rectangles.
8552
8553 See also:
8554
8555 <http://en.wikipedia.org/wiki/Aspect_ratio>
8556
8557 Parameters:
8558
8559 ch - An array of nodes.
8560 w - The fixed dimension where rectangles are being laid out.
8561
8562 Returns:
8563
8564 The average aspect ratio.
8565
8566
8567 */
8568 avgAspectRatio: function(ch, w) {
8569 if(!ch || ch.length == 0) return Number.MAX_VALUE;
8570 var arSum = 0;
8571 for(var i=0; i<ch.length; i++) {
8572 var area = ch[i]._area;
8573 var h = area / w;
8574 arSum += (w > h)? w / h : h / w;
8575 }
8576 return arSum / ch.length;
8577 },
8578
8579 /*
8580 layoutLast
8581
8582 Performs the layout of the last computed sibling.
8583
8584 Parameters:
8585
8586 ch - An array of nodes.
8587 w - A fixed dimension where nodes will be layed out.
8588 coord - A coordinates object specifying width, height, left and top style properties.
8589 */
8590 layoutLast: function(ch, w, coord) {
8591 ch[0].coord = coord;
8592 }
8593
8594 });
8595
8596
8597
8598
8599 /*
8600 Class: TM.Squarified
8601
8602 A JavaScript implementation of the Squarified Treemap algorithm.
8603
8604 The <TM.Squarified> constructor takes an _optional_ configuration object described in <TM>.
8605
8606 This visualization (as all other Treemap visualizations) is fed with JSON Tree structures.
8607
8608 The _$area_ node data key is required for calculating rectangles dimensions.
8609
8610 The _$color_ node data key is required if _Color_ _allow_ is *true* and is used for calculating
8611 leaves colors.
8612
8613 Extends:
8614 <TM> and <TM.Area>
8615
8616 Parameters:
8617
8618 config - Configuration defined in <TM>.
8619
8620 Example:
8621
8622
8623 Here's a way of instanciating the <TM.Squarified> will all its _optional_ configuration features
8624
8625 (start code js)
8626
8627 var tm = new TM.Squarified({
8628 titleHeight: 13,
8629 rootId: 'infovis',
8630 offset:4,
8631 levelsToShow: 3,
8632 addLeftClickHandler: false,
8633 addRightClickHandler: false,
8634 selectPathOnHover: false,
8635
8636 Color: {
8637 allow: false,
8638 minValue: -100,
8639 maxValue: 100,
8640 minColorValue: [255, 0, 50],
8641 maxColorValue: [0, 255, 50]
8642 },
8643
8644 Tips: {
8645 allow: false,
8646 offsetX: 20,
8647 offsetY: 20,
8648 onShow: function(tooltip, node, isLeaf, domElement) {}
8649 },
8650
8651 onBeforeCompute: function(node) {
8652 //Some stuff on before compute...
8653 },
8654 onAfterCompute: function() {
8655 //Some stuff on after compute...
8656 },
8657 onCreateElement: function(content, node, isLeaf, head, body) {
8658 //Some stuff onCreateElement
8659 },
8660 onDestroyElement: function(content, node, isLeaf, head, body) {
8661 //Some stuff onDestroyElement
8662 },
8663 request: false
8664 });
8665
8666 tm.loadJSON(json);
8667
8668 (end code)
8669
8670 */
8671
8672 TM.Squarified = new Class({
8673 Implements: [TM, TM.Area],
8674
8675 /*
8676 Method: compute
8677
8678 Called by loadJSON to calculate recursively all node positions and lay out the tree.
8679
8680 Parameters:
8681
8682 json - A JSON tree. See also <Loader.loadJSON>.
8683 coord - A coordinates object specifying width, height, left and top style properties.
8684 */
8685 compute: function(json, coord) {
8686 if (!(coord.width >= coord.height && this.layout.horizontal()))
8687 this.layout.change();
8688 var ch = json.children, config = this.config;
8689 if(ch.length > 0) {
8690 this.processChildrenLayout(json, ch, coord);
8691 for(var i=0; i<ch.length; i++) {
8692 var chcoord = ch[i].coord,
8693 offst = config.offset,
8694 height = chcoord.height - (config.titleHeight + offst),
8695 width = chcoord.width - offst;
8696 coord = {
8697 'width':width,
8698 'height':height,
8699 'top':0,
8700 'left':0
8701 };
8702 this.compute(ch[i], coord);
8703 }
8704 }
8705 },
8706
8707 /*
8708 Method: processChildrenLayout
8709
8710 Computes children real areas and other useful parameters for performing the Squarified algorithm.
8711
8712 Parameters:
8713
8714 par - The parent node of the json subtree.
8715 ch - An Array of nodes
8716 coord - A coordinates object specifying width, height, left and top style properties.
8717 */
8718 processChildrenLayout: function(par, ch, coord) {
8719 //compute children real areas
8720 var parentArea = coord.width * coord.height;
8721 var i, totalChArea=0, chArea = [];
8722 for(i=0; i < ch.length; i++) {
8723 chArea[i] = parseFloat(ch[i].data.$area);
8724 totalChArea += chArea[i];
8725 }
8726 for(i=0; i<chArea.length; i++) {
8727 ch[i]._area = parentArea * chArea[i] / totalChArea;
8728 }
8729 var minimumSideValue = (this.layout.horizontal())? coord.height : coord.width;
8730 ch.sort(function(a, b) { return (a._area <= b._area) - (a._area >= b._area); });
8731 var initElem = [ch[0]];
8732 var tail = ch.slice(1);
8733 this.squarify(tail, initElem, minimumSideValue, coord);
8734 },
8735
8736 /*
8737 Method: squarify
8738
8739 Performs an heuristic method to calculate div elements sizes in order to have a good aspect ratio.
8740
8741 Parameters:
8742
8743 tail - An array of nodes.
8744 initElem - An array of nodes, containing the initial node to be laid out.
8745 w - A fixed dimension where nodes will be laid out.
8746 coord - A coordinates object specifying width, height, left and top style properties.
8747 */
8748 squarify: function(tail, initElem, w, coord) {
8749 this.computeDim(tail, initElem, w, coord, this.worstAspectRatio);
8750 },
8751
8752 /*
8753 Method: layoutRow
8754
8755 Performs the layout of an array of nodes.
8756
8757 Parameters:
8758
8759 ch - An array of nodes.
8760 w - A fixed dimension where nodes will be laid out.
8761 coord - A coordinates object specifying width, height, left and top style properties.
8762 */
8763 layoutRow: function(ch, w, coord) {
8764 if(this.layout.horizontal()) {
8765 return this.layoutV(ch, w, coord);
8766 } else {
8767 return this.layoutH(ch, w, coord);
8768 }
8769 },
8770
8771 layoutV: function(ch, w, coord) {
8772 var totalArea = 0, rnd = Math.round;
8773 $each(ch, function(elem) { totalArea += elem._area; });
8774 var width = rnd(totalArea / w), top = 0;
8775 for(var i=0; i<ch.length; i++) {
8776 var h = rnd(ch[i]._area / width);
8777 ch[i].coord = {
8778 'height': h,
8779 'width': width,
8780 'top': coord.top + top,
8781 'left': coord.left
8782 };
8783 top += h;
8784 }
8785 var ans = {
8786 'height': coord.height,
8787 'width': coord.width - width,
8788 'top': coord.top,
8789 'left': coord.left + width
8790 };
8791 //take minimum side value.
8792 ans.dim = Math.min(ans.width, ans.height);
8793 if(ans.dim != ans.height) this.layout.change();
8794 return ans;
8795 },
8796
8797 layoutH: function(ch, w, coord) {
8798 var totalArea = 0, rnd = Math.round;
8799 $each(ch, function(elem) { totalArea += elem._area; });
8800 var height = rnd(totalArea / w),
8801 top = coord.top,
8802 left = 0;
8803
8804 for(var i=0; i<ch.length; i++) {
8805 ch[i].coord = {
8806 'height': height,
8807 'width': rnd(ch[i]._area / height),
8808 'top': top,
8809 'left': coord.left + left
8810 };
8811 left += ch[i].coord.width;
8812 }
8813 var ans = {
8814 'height': coord.height - height,
8815 'width': coord.width,
8816 'top': coord.top + height,
8817 'left': coord.left
8818 };
8819 ans.dim = Math.min(ans.width, ans.height);
8820 if(ans.dim != ans.width) this.layout.change();
8821 return ans;
8822 }
8823 });
8824
8825
8826 /*
8827 Class: TM.Strip
8828
8829 A JavaScript implementation of the Strip Treemap algorithm.
8830
8831 The <TM.Strip> constructor takes an _optional_ configuration object described in <TM>.
8832
8833 This visualization (as all other Treemap visualizations) is fed with JSON Tree structures.
8834
8835 The _$area_ node data key is required for calculating rectangles dimensions.
8836
8837 The _$color_ node data key is required if _Color_ _allow_ is *true* and is used for calculating
8838 leaves colors.
8839
8840 Extends:
8841 <TM> and <TM.Area>
8842
8843 Parameters:
8844
8845 config - Configuration defined in <TM>.
8846
8847 Example:
8848
8849
8850 Here's a way of instanciating the <TM.Strip> will all its _optional_ configuration features
8851
8852 (start code js)
8853
8854 var tm = new TM.Strip({
8855 titleHeight: 13,
8856 orientation: "h",
8857 rootId: 'infovis',
8858 offset:4,
8859 levelsToShow: 3,
8860 addLeftClickHandler: false,
8861 addRightClickHandler: false,
8862 selectPathOnHover: false,
8863
8864 Color: {
8865 allow: false,
8866 minValue: -100,
8867 maxValue: 100,
8868 minColorValue: [255, 0, 50],
8869 maxColorValue: [0, 255, 50]
8870 },
8871
8872 Tips: {
8873 allow: false,
8874 offsetX: 20,
8875 offsetY: 20,
8876 onShow: function(tooltip, node, isLeaf, domElement) {}
8877 },
8878
8879 onBeforeCompute: function(node) {
8880 //Some stuff on before compute...
8881 },
8882 onAfterCompute: function() {
8883 //Some stuff on after compute...
8884 },
8885 onCreateElement: function(content, node, isLeaf, head, body) {
8886 //Some stuff onCreateElement
8887 },
8888 onDestroyElement: function(content, node, isLeaf, head, body) {
8889 //Some stuff onDestroyElement
8890 },
8891 request: false
8892 });
8893 tm.loadJSON(json);
8894
8895 (end code)
8896
8897 */
8898
8899 TM.Strip = new Class({
8900 Implements: [ TM, TM.Area ],
8901
8902 /*
8903 Method: compute
8904
8905 Called by loadJSON to calculate recursively all node positions and lay out the tree.
8906
8907 Parameters:
8908
8909 json - A JSON subtree. See also <Loader.loadJSON>.
8910 coord - A coordinates object specifying width, height, left and top style properties.
8911 */
8912 compute: function(json, coord) {
8913 var ch = json.children, config = this.config;
8914 if(ch.length > 0) {
8915 this.processChildrenLayout(json, ch, coord);
8916 for(var i=0; i<ch.length; i++) {
8917 var chcoord = ch[i].coord,
8918 offst = config.offset,
8919 height = chcoord.height - (config.titleHeight + offst),
8920 width = chcoord.width - offst;
8921 coord = {
8922 'width':width,
8923 'height':height,
8924 'top':0,
8925 'left':0
8926 };
8927 this.compute(ch[i], coord);
8928 }
8929 }
8930 },
8931
8932 /*
8933 Method: processChildrenLayout
8934
8935 Computes children real areas and other useful parameters for performing the Strip algorithm.
8936
8937 Parameters:
8938
8939 par - The parent node of the json subtree.
8940 ch - An Array of nodes
8941 coord - A coordinates object specifying width, height, left and top style properties.
8942 */
8943 processChildrenLayout: function(par, ch, coord) {
8944 //compute children real areas
8945 var area = coord.width * coord.height;
8946 var dataValue = parseFloat(par.data.$area);
8947 $each(ch, function(elem) {
8948 elem._area = area * parseFloat(elem.data.$area) / dataValue;
8949 });
8950 var side = (this.layout.horizontal())? coord.width : coord.height;
8951 var initElem = [ch[0]];
8952 var tail = ch.slice(1);
8953 this.stripify(tail, initElem, side, coord);
8954 },
8955
8956 /*
8957 Method: stripify
8958
8959 Performs an heuristic method to calculate div elements sizes in order to have
8960 a good compromise between aspect ratio and order.
8961
8962 Parameters:
8963
8964 tail - An array of nodes.
8965 initElem - An array of nodes.
8966 w - A fixed dimension where nodes will be layed out.
8967 coord - A coordinates object specifying width, height, left and top style properties.
8968 */
8969 stripify: function(tail, initElem, w, coord) {
8970 this.computeDim(tail, initElem, w, coord, this.avgAspectRatio);
8971 },
8972
8973 /*
8974 Method: layoutRow
8975
8976 Performs the layout of an array of nodes.
8977
8978 Parameters:
8979
8980 ch - An array of nodes.
8981 w - A fixed dimension where nodes will be laid out.
8982 coord - A coordinates object specifying width, height, left and top style properties.
8983 */
8984 layoutRow: function(ch, w, coord) {
8985 if(this.layout.horizontal()) {
8986 return this.layoutH(ch, w, coord);
8987 } else {
8988 return this.layoutV(ch, w, coord);
8989 }
8990 },
8991
8992 layoutV: function(ch, w, coord) {
8993 //TODO(nico): handle node dimensions properly
8994 var totalArea = 0, rnd = function(x) { return x; }; //Math.round;
8995 $each(ch, function(elem) { totalArea += elem._area; });
8996 var width = rnd(totalArea / w), top = 0;
8997 for(var i=0; i<ch.length; i++) {
8998 var h = rnd(ch[i]._area / width);
8999 ch[i].coord = {
9000 'height': h,
9001 'width': width,
9002 'top': coord.top + (w - h - top),
9003 'left': coord.left
9004 };
9005 top += h;
9006 }
9007
9008 var ans = {
9009 'height': coord.height,
9010 'width': coord.width - width,
9011 'top': coord.top,
9012 'left': coord.left + width,
9013 'dim': w
9014 };
9015 return ans;
9016 },
9017
9018 layoutH: function(ch, w, coord) {
9019 var totalArea = 0, rnd = function(x) { return x; }; //Math.round;
9020 $each(ch, function(elem) { totalArea += elem._area; });
9021 var height = rnd(totalArea / w),
9022 top = coord.height - height,
9023 left = 0;
9024
9025 for(var i=0; i<ch.length; i++) {
9026 ch[i].coord = {
9027 'height': height,
9028 'width': rnd(ch[i]._area / height),
9029 'top': top,
9030 'left': coord.left + left
9031 };
9032 left += ch[i].coord.width;
9033 }
9034 var ans = {
9035 'height': coord.height - height,
9036 'width': coord.width,
9037 'top': coord.top,
9038 'left': coord.left,
9039 'dim': w
9040 };
9041 return ans;
9042 }
9043 });
9044
9045
9046
9047
9048
9049 })();