-
Notifications
You must be signed in to change notification settings - Fork 69
/
json-schema-viewer.js
1368 lines (1148 loc) · 45.4 KB
/
json-schema-viewer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//fix for IE
if (!window.location.origin) {
window.location.origin = window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
}
if (typeof JSV === 'undefined') {
/**
* JSV namespace for JSON Schema Viewer.
* @namespace
*/
JSV = {
/**
* The root schema to load.
*/
schema: '',
/**
* If true, render diagram only on init, without the jQuery Mobile UI.
* The legend and nav tools will be rendered with any event listeners.
*/
plain: false,
/**
* The version of the schema.
*/
version: '',
/**
* Currently focused node
*/
focusNode: false,
/**
* Currently loaded example
*/
example: false,
/**
* @property {object} treeData The diagram nodes
*/
treeData: null,
/**
* The initialization status of the viewer page
*/
viewerInit: false,
/**
* The current viewer height
*/
viewerHeight: 0,
/**
* The current viewer width
*/
viewerWidth: 0,
/**
* The default duration of the node transitions
*/
duration: 750,
/**
* Counter for generating unique ids
*/
counter: 0,
maxLabelLength: 0,
/**
* Default maximum depth for recursive schemas
*/
maxDepth: 20,
/**
* @property {object} labels Nodes to render as non-clickable in the tree. They will auto-expand if child nodes are present.
*/
labels: {
allOf: true,
anyOf: true,
oneOf: true,
'object{ }': true
},
/**
* @property {array} baseSvg The base SVG element for the d3 diagram
*/
baseSvg: null,
/**
* @property {array} svgGroup SVG group which holds all nodes and which the zoom Listener can act upon.
*/
svgGroup: null,
/**
* Initializes the viewer.
*
* @param {object} config The configuration.
* @param {function} callback Function to run after schemas are loaded and
* diagram is created.
*/
init: function(config, callback) {
var i;
//apply config
for (i in config) {
if (JSV.hasOwnProperty(i)) {
JSV[i] = config[i];
}
}
if(JSV.plain) {
JSV.createDiagram(callback);
//setup controls
d3.selectAll('#zoom-controls>a').on('click', JSV.zoomClick);
d3.select('#tree-controls>a#reset-tree').on('click', JSV.resetViewer);
JSV.viewerInit = true;
return;
}
JSV.contentHeight();
JSV.resizeViewer();
$(document).on('pagecontainertransition', this.contentHeight);
$(window).on('throttledresize orientationchange', this.contentHeight);
$(window).on('resize', this.contentHeight);
JSV.resizeBtn();
$(document).on('pagecontainershow', JSV.resizeBtn);
$(window).on('throttledresize', JSV.resizeBtn);
var cb = function() {
callback();
//setup search
var items = [];
JSV.visit(JSV.treeData, function(me) {
if (me.isReal) {
items.push(me.plainName + '|' + JSV.getNodePath(me).join('-'));
}
}, function(me) {
return me.children || me._children;
});
items.sort();
JSV.buildSearchList(items, true);
$('#loading').fadeOut('slow');
};
JSV.createDiagram(cb);
JSV.initValidator();
//initialize error popup
$( '#popup-error' ).enhanceWithin().popup();
///highlight plugin
$.fn.highlight = function (str, className, quote) {
var string = quote ? '\\"\\b'+str+'\\b\\"' : '\\b'+str+'\\b',
regex = new RegExp(string, 'g');
return this.each(function () {
this.innerHTML = this.innerHTML.replace(regex, function(matched) {return '<span class="' + className + '">' + matched + '</span>';});
});
};
//restore info-panel state
$('body').on('pagecontainershow', function(event, ui) {
var page = ui.toPage;
if(page.attr('id') === 'viewer-page' && JSV.viewerInit) {
if(page.jqmData('infoOpen')) {
$('#info-panel'). panel('open');
}
//TODO: add this to 'pagecontainercreate' handler on refactor???
JSV.contentHeight();
if($('svg#jsv-tree').height() === 0) {
$('svg#jsv-tree').attr('width', $('#main-body').width())
.attr('height', $('#main-body').height());
JSV.resizeViewer();
JSV.resetViewer();
}
}
});
//store info-panel state
$('body').on('pagecontainerbeforehide', function(event, ui) {
var page = ui.prevPage;
if(page.attr('id') === 'viewer-page') {
page.jqmData('infoOpen', !!page.find('#info-panel.ui-panel-open').length);
}
});
//resize viewer on panel open/close
$('#info-panel').on('panelopen', function() {
var focus = JSV.focusNode;
JSV.resizeViewer();
if(focus) {
d3.select('#n-' + focus.id).classed('focus',true);
JSV.setPermalink(focus);
}
});
$('#info-panel').on('panelclose', function() {
var focus = JSV.focusNode;
JSV.resizeViewer();
if (focus) {
d3.select('#n-' + focus.id).classed('focus', false);
$('#permalink').html('Select a Node...');
$('#sharelink').val('');
}
});
//scroll example/schema when tab is activated
$('#info-panel').on( 'tabsactivate', function( event, ui ) {
var id = ui.newPanel.attr('id');
if(id === 'info-tab-example' || id === 'info-tab-schema') {
var pre = ui.newPanel.find('pre'),
highEl = pre.find('span.highlight')[0];
if(highEl) {
pre.scrollTo(highEl, 900);
}
}
});
//setup example links
$('.load-example').each(function(idx, link) {
var ljq = $(link);
ljq.on('click', function(evt) {
evt.preventDefault();
JSV.loadInputExample(link.href, ljq.data('target'));
});
});
//setup controls
d3.selectAll('#zoom-controls>a').on('click', JSV.zoomClick);
d3.select('#tree-controls>a#reset-tree').on('click', JSV.resetViewer);
$('#sharelink').on('click', function () {
$(this).select();
});
JSV.viewerInit = true;
},
/**
* (Re)set the viewer page height, set the diagram dimensions.
*/
contentHeight: function() {
var screen = $.mobile.getScreenHeight(),
header = $('.ui-header').hasClass('ui-header-fixed') ? $('.ui-header').outerHeight() - 1 : $('.ui-header').outerHeight(),
footer = $('.ui-footer').hasClass('ui-footer-fixed') ? $('.ui-footer').outerHeight() - 1 : $('.ui-footer').outerHeight(),
contentCurrent = $('#main-body.ui-content').outerHeight() - $('#main-body.ui-content').height(),
content = screen - header - footer - contentCurrent;
$('#main-body.ui-content').css('min-height', content + 'px');
},
/**
* Hides navbar button text on smaller window sizes.
*
* @param {number} minSize The navbar width breakpoint.
*/
resizeBtn: function(minSize) {
var bp = typeof minSize === 'number' ? minSize : 800;
var activePage = $.mobile.pageContainer.pagecontainer('getActivePage');
if ($('.md-navbar', activePage).width() <= bp) {
$('.md-navbar .md-flex-btn.ui-btn-icon-left').toggleClass('ui-btn-icon-notext ui-btn-icon-left');
} else {
$('.md-navbar .md-flex-btn.ui-btn-icon-notext').toggleClass('ui-btn-icon-left ui-btn-icon-notext');
}
},
/**
* Set version of the schema and the content
* of any elemant with the class *schema-version*.
*
* @param {string} version
*/
setVersion: function(version) {
JSV.version = version;
$('.schema-version').text(version);
},
/**
* Display an error message.
*
* @param {string} msg The message to display.
*/
showError: function(msg) {
$('#popup-error .error-message').html(msg);
$('#popup-error').popup('open');
},
initValidator: function() {
var opts = {
readAsDefault: 'Text',
on: {
load: function(e, file) {
var data = e.currentTarget.result;
try {
$.parseJSON(data);
//console.info(data);
$('#textarea-json').val(data);
} catch(err) {
//JSV.showError('Unable to parse JSON: <br/>' + e);
JSV.showError('Failed to load ' + file.name + '. The file is not valid JSON. <br/>The error: <i>' + err + '</i>');
}
},
error: function(e, file) {
var msg = 'Failed to load ' + file.name + '. ' + e.currentTarget.error.message;
JSV.showError(msg);
}
}
};
$('#file-upload, #textarea-json').fileReaderJS(opts);
$('body').fileClipboard(opts);
$('#button-validate').click(function() {
var result = JSV.validate();
if (result) {
JSV.showValResult(result);
}
//console.info(result);
});
},
/**
* Validate using tv4 and currently loaded schema(s).
*/
validate: function() {
var data;
try {
data = $.parseJSON($('#textarea-json').val());
} catch(e) {
JSV.showError('Unable to parse JSON: <br/>' + e);
}
if (data) {
var stop = $('#checkbox-stop').is(':checked'),
strict = $('#checkbox-strict').is(':checked'),
schema = tv4.getSchemaMap()[JSV.schema],
result;
if (stop) {
var r = tv4.validate(data, schema, false, strict);
result = {
valid: r,
errors: !r ? [tv4.error] : []
};
} else {
result = tv4.validateMultiple(data, schema, false, strict);
}
return result;
}
},
/**
* Display the validation result
*
* @param {object} result A result object, ouput from [validate]{@link JSV.validate}
*/
showValResult: function(result) {
var cont = $('#validation-results'), ui;
if(cont.children().length) {
cont.css('opacity', 0);
}
if(result.valid) {
cont.html('<p class=ui-content>JSON is valid!</p>');
} else {
ui = cont.html('<div class=ui-content>JSON is <b>NOT</b> valid!</div>');
$.each(result.errors, function(i, err){
var me = JSV.buildValError(err, 'Error ' + (i+1) + ': ');
if(err.subErrors) {
$.each(err.subErrors, function(i, sub){
me.append(JSV.buildValError(sub, 'SubError ' + (i+1) + ': '));
});
}
ui.children('.ui-content').first().append(me).enhanceWithin();
});
}
cont.toggleClass('error', !result.valid);
$('#validator-page').animate({
scrollTop: $('#validation-results').offset().top + 20
}, 1000);
cont.fadeTo(350, 1);
},
/**
* Build a collapsible validation block.
*
* @param {object} err The error object
* @param {string} title The title for the error block
*/
buildValError: function(err, title) {
var main = '<div data-role="collapsible" data-collapsed="true" data-mini="true">' +
'<h4>' + (title || 'Error: ') + err.message + '</h4>' +
'<ul><li>Message: '+ err.message + '</li>' +
'<li>Data Path: '+ err.dataPath + '</li>' +
'<li>Schema Path: '+ err.schemaPath + '</li></ul></div>';
return $(main);
},
/**
* Set the content for the info panel.
*
* @param {object} node The d3 tree node.
*/
setInfo: function(node) {
var schema = $('#info-tab-schema');
var def = $('#info-tab-def');
var ex = $('#info-tab-example');
var height = ($('#info-panel').innerHeight() - $('#info-panel .ui-panel-inner').outerHeight() + $('#info-panel #info-tabs').height()) -
$('#info-panel #info-tabs-navbar').height() - (schema.outerHeight(true) - schema.height());
$.each([schema, def, ex], function(i, e){
e.height(height);
});
$('#info-definition').html(node.description || 'No definition provided.');
$('#info-type').html(node.displayType.toString());
if(node.translation) {
var trans = $('<ul></ul>');
$.each(node.translation, function(p, v) {
var li = $('<li>' + p + '</li>');
var ul = $('<ul></ul>');
$.each(v, function(i, e) {
ul.append('<li>' + e + '</li>');
});
trans.append(li.append(ul));
});
$('#info-translation').html(trans);
} else {
$('#info-translation').html('No translations available.');
}
JSV.createPre(schema, tv4.getSchema(node.schema), false, node.plainName);
var example = (!node.example && node.parent && node.parent.example && node.parent.type === 'object' ? node.parent.example : node.example);
if(example) {
if(example !== JSV.example) {
$.getJSON(node.schema.match( /^(.*?)(?=[^\/]*\.json)/g ) + example, function(data) {
var pointer = example.split('#')[1];
if(pointer) {
data = jsonpointer.get(data, pointer);
}
JSV.createPre(ex, data, false, node.plainName);
JSV.example = example;
}).fail(function() {
ex.html('<h3>No example found.</h3>');
JSV.example = false;
});
} else {
var pre = ex.find('pre'),
highEl;
pre.find('span.highlight').removeClass('highlight');
if(node.plainName) {
pre.highlight(node.plainName, 'highlight', true);
}
//scroll to highlighted property
highEl = pre.find('span.highlight')[0];
if (highEl) {
pre.scrollTo(highEl, 900);
}
}
} else {
ex.html('<h3>No example available.</h3>');
JSV.example = false;
}
},
/**
* Create a *pre* block and append it to the passed element.
*
* @param {object} el jQuery element
* @param {object} obj The obj to stringify and display
* @param {string} title The title for the new window
* @param {string} exp The string to highlight
*/
createPre: function(el, obj, title, exp) {
var pre = $('<pre><code class="language-json">' + JSON.stringify(obj, null, ' ') + '</code></pre>');
var btn = $('<a href="#" class="ui-btn ui-mini ui-icon-action ui-btn-icon-right">Open in new window</a>').click(function() {
var w = window.open('', 'pre', null, true);
$(w.document.body).html($('<div>').append(pre.clone().height('95%')).html());
hljs.highlightBlock($(w.document.body).children('pre')[0]);
$(w.document.body).append('<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.1/styles/default.min.css">');
w.document.title = title || 'JSON Schema Viewer';
w.document.close();
});
el.html(btn);
if(exp) {
pre.highlight(exp, 'highlight', true);
}
el.append(pre);
pre.height(el.height() - btn.outerHeight(true) - (pre.outerHeight(true) - pre.height()));
//scroll to highlighted property
var highEl = pre.find('span.highlight')[0];
if(highEl) {
pre.scrollTo(highEl, 900);
}
},
/**
* Create a "breadcrumb" for the node.
*/
compilePath: function(node, path) {
var p;
if(node.parent) {
p = path ? node.name + ' > ' + path : node.name;
return JSV.compilePath(node.parent, p);
} else {
p = path ? node.name + ' > ' + path : node.name;
}
return p;
},
/**
* Load an example in the specified input field.
*/
loadInputExample: function(uri, target) {
$.getJSON(uri).done(function(fetched) {
$('#' + target).val(JSON.stringify(fetched, null, ' '));
}).fail(function(jqXHR, textStatus, errorThrown) {
JSV.showError('Failed to load example: ' + errorThrown);
});
},
/**
* Create a "permalink" for the node.
*/
setPermalink: function(node) {
var uri = new URI(),
path = JSV.getNodePath(node).join('-');
//uri.search({ v: path});
uri.hash($.mobile.activePage.attr('id') + '?v=' + path);
$('#permalink').html(JSV.compilePath(node));
$('#sharelink').val(uri.toString());
},
/**
* Create an index-based path for the node from the root.
*/
getNodePath: function(node, path) {
var p = path || [],
parent = node.parent;
if(parent) {
var children = parent.children || parent._children;
p.unshift(children.indexOf(node));
return JSV.getNodePath(parent, p);
} else {
return p;
}
},
/**
* Expand an index-based path for the node from the root.
*/
expandNodePath: function(path) {
var i,
node = JSV.treeData; //start with root
for (i = 0; i < path.length; i++) {
if(node._children) {
JSV.expand(node);
}
node = node.children[path[i]];
}
JSV.update(JSV.treeData);
JSV.centerNode(node);
return node;
},
/**
* Build Search.
*/
buildSearchList: function(items, init) {
var ul = $('ul#search-result');
$.each(items, function(i,v) {
var data = v.split('|');
var li = $('<li/>').attr('data-icon', 'false').appendTo(ul);
$('<a/>').attr('data-path', data[1]).text(data[0]).appendTo(li);
});
if(init) {
ul.filterable();
}
ul.filterable('refresh');
ul.on('click', function(e) {
var path = $(e.target).attr('data-path');
var node = JSV.expandNodePath(path.split('-'));
JSV.flashNode(node);
});
},
/**
* Flash node text
*/
flashNode: function(node, times) {
var t = times || 4,
text = $('#n-' + node.id + ' text');
//flash node text
while (t--) {
text.fadeTo(350, 0).fadeTo(350, 1);
}
},
/**
* A recursive helper function for performing some setup by walking
* through all nodes
*/
visit: function (parent, visitFn, childrenFn) {
if (!parent) {
return;
}
visitFn(parent);
var children = childrenFn(parent);
if (children) {
var count = children.length, i;
for ( i = 0; i < count; i++) {
JSV.visit(children[i], visitFn, childrenFn);
}
}
},
/**
* Create the tree data object from the schema(s)
*/
compileData: function (schema, parent, name, real, depth) {
// Ensure healthy amount of recursion
depth = depth || 0;
if (depth > this.maxDepth) {
return;
}
var key, node,
s = schema.$ref ? tv4.getSchema(schema.$ref) : schema,
props = s.properties,
items = s.items,
owns = Object.prototype.hasOwnProperty,
all = {},
parentSchema = function(node) {
var schema = node.id || node.$ref || node.schema;
if (schema) {
return schema;
} else if (node.parentSchema) {
return parentSchema(node.parentSchema);
} else {
return null;
}
};
if (s.allOf) {
all.allOf = s.allOf;
}
if (s.oneOf) {
all.oneOf = s.oneOf;
}
if (s.anyOf) {
all.anyOf = s.anyOf;
}
node = {
description: schema.description || s.description,
name: (schema.$ref && real ? name : false) || s.title || name || 'schema',
isReal: real,
plainName: name,
type: s.type,
displayType: s.type || (s['enum'] ? 'enum: ' + s['enum'].join(', ') : s.items ? 'array' : s.properties ? 'object' : 'ambiguous'),
translation: schema.translation || s.translation,
example: schema.example || s.example,
opacity: real ? 1 : 0.5,
required: s.required,
schema: s.id || schema.$ref || parentSchema(parent),
parentSchema: parent,
deprecated: schema.deprecated || s.deprecated
};
node.require = parent && parent.required ? parent.required.indexOf(node.name) > -1 : false;
if (parent) {
if (node.name === 'item') {
node.parent = parent;
if(node.type) {
node.name = node.type;
parent.children.push(node);
}
} else if (parent.name === 'item') {
parent.parent.children.push(node);
} else {
parent.children.push(node);
}
} else {
JSV.treeData = node;
}
if(node.type === 'array') {
node.name += '[' + (s.minItems || ' ') + ']';
node.minItems = s.minItems;
}
if(node.type === 'object' && node.name !== 'item') {
node.name += '{ }';
}
if(props || items || all) {
node.children = [];
}
for (key in props) {
if (!owns.call(props, key)) {
continue;
}
JSV.compileData(props[key], node, key, true, depth + 1);
}
for (key in all) {
if (!owns.call(all, key)) {
continue;
}
if (!all[key]) {
continue;
}
var allNode = {
name: key,
children: [],
opacity: 0.5,
parentSchema: parent,
schema: schema.$ref || parentSchema(parent)
};
if (node.name === 'item') {
node.parent.children.push(allNode);
} else {
node.children.push(allNode);
}
for (var i = 0; i < all[key].length; i++) {
JSV.compileData(all[key][i], allNode, s.title || all[key][i].type, false, depth + 1);
}
}
if (Object.prototype.toString.call(items) === '[object Object]') {
JSV.compileData(items, node, 'item', false, depth + 1);
} else if (Object.prototype.toString.call(items) === '[object Array]') {
items.forEach(function(itm, idx, arr) {
JSV.compileData(itm, node, idx.toString(), false, depth + 1);
});
}
},
/**
* Resize the diagram
*/
resizeViewer: function() {
JSV.viewerWidth = $('#main-body').width();
JSV.viewerHeight = $('#main-body').height();
if(JSV.focusNode) {
JSV.centerNode(JSV.focusNode);
}
},
/**
* Reset the tree starting from the passed source.
*/
resetTree: function (source, level) {
JSV.visit(source, function(d) {
if (d.children && d.children.length > 0 && d.depth > level && !JSV.labels[d.name]) {
JSV.collapse(d);
//d._children = d.children;
//d.children = null;
}else if(JSV.labels[d.name]){
JSV.expand(d);
}
}, function(d) {
if (d.children && d.children.length > 0) {
return d.children;
} else if (d._children && d._children.length > 0) {
return d._children;
} else {
return null;
}
});
},
/**
* Reset and center the tree.
*/
resetViewer: function () {
//Firefox will choke if the viewer-page is not visible
//TODO: fix on refactor to use pagecontainer event
var page = $('#viewer-page');
page.css('display','block');
// Define the root
var root = JSV.treeData;
root.x0 = JSV.viewerHeight / 2;
root.y0 = 0;
// Layout the tree initially and center on the root node.
// Call visit function to set initial depth
JSV.tree.nodes(root);
JSV.resetTree(root, 1);
JSV.update(root);
//reset the style for viewer-page
page.css('display', '');
JSV.centerNode(root, 4);
},
/**
* Function to center node when clicked so node doesn't get lost when collapsing with large amount of children.
*/
centerNode: function (source, ratioX) {
var rX = ratioX ? ratioX : 2,
zl = JSV.zoomListener,
scale = zl.scale(),
x = -source.y0 * scale + JSV.viewerWidth / rX,
y = -source.x0 * scale + JSV.viewerHeight / 2;
d3.select('g#node-group').transition()
.duration(JSV.duration)
.attr('transform', 'translate(' + x + ',' + y + ')scale(' + scale + ')');
zl.scale(scale);
zl.translate([x, y]);
},
/**
* Helper functions for collapsing nodes.
*/
collapse: function (d) {
if (d.children) {
d._children = d.children;
//d._children.forEach(collapse);
d.children = null;
}
},
/**
* Helper functions for expanding nodes.
*/
expand: function (d) {
if (d._children) {
d.children = d._children;
//d.children.forEach(expand);
d._children = null;
}
if (d.children) {
var count = d.children.length, i;
for (i = 0; i < count; i++) {
if(JSV.labels[d.children[i].name]) {
JSV.expand(d.children[i]);
}
}
}
},
/**
* Toggle children function
*/
toggleChildren: function (d) {
if (d.children) {
JSV.collapse(d);
} else if (d._children) {
JSV.expand(d);
}
return d;
},
/**
* Toggle children on node click.
*/
click: function (d) {
if(!JSV.labels[d.name]) {
if (d3.event && d3.event.defaultPrevented) {return;} // click suppressed
d = JSV.toggleChildren(d);
JSV.update(d);
JSV.centerNode(d);
}
},
/**
* Show info on node title click.
*/
clickTitle: function (d) {
if(!JSV.labels[d.name]) {
if (d3.event && d3.event.defaultPrevented) {return;} // click suppressed
var panel = $( '#info-panel' );
if(JSV.focusNode) {
d3.select('#n-' + JSV.focusNode.id).classed('focus',false);
}
JSV.focusNode = d;
JSV.centerNode(d);
d3.select('#n-' + d.id).classed('focus',true);
if(!JSV.plain) {
JSV.setPermalink(d);
$('#info-title')
.text('Info: ' + d.name)
.toggleClass('deprecated', !!d.deprecated);
JSV.setInfo(d);
panel.panel( 'open' );
}
}
},
/**
* Zoom the tree
*/
zoom: function () {
JSV.svgGroup.attr('transform', 'translate(' + JSV.zoomListener.translate() + ')' + 'scale(' + JSV.zoomListener.scale() + ')');
},
/**
* Perform the d3 zoom based on position and scale
*/
interpolateZoom: function (translate, scale) {
return d3.transition().duration(350).tween('zoom', function () {
var iTranslate = d3.interpolate(JSV.zoomListener.translate(), translate),
iScale = d3.interpolate(JSV.zoomListener.scale(), scale);
return function (t) {
JSV.zoomListener
.scale(iScale(t))
.translate(iTranslate(t));
JSV.zoom();
};
});
},
/**
* Click handler for the zoom control
*/
zoomClick: function () {
var clicked = d3.event.target,