-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrender.js
4811 lines (4412 loc) · 174 KB
/
render.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
/*
Interactive family tree viewer
Written January 2016 by Jeff Epstein in Brno, Czech Republic
Released under GPL3
*/
/*jshint sub:true*/ /*jshint shadow:true*/
"use strict";
// Some formatting options
var verticalMargin = 45;
var horizontalMargin = 35;
var generationLimit = 3;
var nodeBorderMargin = 6;
var mouseClickRadius = 70;
// Global display modes
var print_mode = false;
var compact_mode = false;
var narrative_tree_style = null;
var aesthetic_table =
{"bgcolor": {"m": "#a7cbca",
"f": "#dfa296",
"z": "#d3d3d3" }
};
var aesthetic_table_bw =
{"bgcolor": {"m": "#ffffff",
"f": "#ffffff",
"z": "#ffffff" }
};
// Configure network access
var xhrTimeout = 20000;
var useObjectUrl = false;
var encryptedData = false;
var loadImage = function(src) {
var img = new Image();
img.src = src;
return img;
};
var emptyImage = "data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==";
var loadLazyImage = function(src) {
var img = new Image();
img.src = emptyImage;
img.setAttribute("data-lazy-src", src);
return img;
};
var euclidean_distance = function(touches) {
var x1 = touches[0].clientX;
var y1 = touches[0].clientY;
var x2 = touches[1].clientX;
var y2 = touches[1].clientY;
return euclidean_distance_impl(x1, y1, x2, y2);
};
var euclidean_distance_impl = function(x1, y1, x2, y2) {
return Math.sqrt((y2-y1)*(y2-y1) + (x2-x1)*(x2-x1));
};
var grayscalify = function(image) {
//https://stackoverflow.com/questions/562135/how-do-you-convert-a-color-image-to-black-white-using-javascript
var canvas=document.createElement("canvas");
var ctx=canvas.getContext("2d");
canvas.width= image.width;
canvas.height= image.height;
ctx.drawImage(image,0,0);
var imageData=ctx.getImageData(0,0, image.width, image.height);
for (var i=0;i<imageData.data.length;i+=4) {
//var avg = (imageData.data[i]+imageData.data[i+1]+imageData.data[i+2])/3;
var avg = imageData.data[i] * 0.2126 + imageData.data[i+1] * 0.7152 + imageData.data[i+2] * 0.0722;
imageData.data[i] = avg;
imageData.data[i+1] = avg;
imageData.data[i+2] = avg;
}
ctx.putImageData(imageData, 0, 0, 0, 0, imageData.width, imageData.height);
var newImg = document.createElement("img");
newImg.src = canvas.toDataURL();
return newImg;
};
var isvisible = function(obj) {
// http://stackoverflow.com/questions/4795473/check-visibility-of-an-object-with-javascript
return obj.offsetWidth > 0 && obj.offsetHeight > 0;
};
function ordinal_suffix_of(i) {
// https://stackoverflow.com/questions/13627308/add-st-nd-rd-and-th-ordinal-suffix-to-a-number
var j = i % 10,
k = i % 100;
if (j == 1 && k != 11) {
return i + "st";
}
if (j == 2 && k != 12) {
return i + "nd";
}
if (j == 3 && k != 13) {
return i + "rd";
}
return i + "th";
}
function multiplicative_of(i) {
switch (i) {
case 1:
return "once";
case 2:
return "twice";
case 3:
return "thrice";
default:
return i+"-times";
}
}
var addClass = function(node, className) {
if (node.classList) {
node.classList.add(className);
} else {
var classes = node.className.split(" ");
classes.addonce(className);
node.className = classes.join(" ");
}
};
var hasClass = function(node, className) {
if (node.classList)
return node.classList.contains(className);
else {
var classes = node.className.split(" ");
return classes.indexOf(className) >= 0;
}
};
var removeClass = function(node, className) {
if (node.classList) {
node.classList.remove(className);
} else {
var classes = node.className.split(" ");
classes.splice(classes.indexOf(className), 1);
node.className = classes.join(" ");
}
};
if (typeof CanvasRenderingContext2D != 'undefined')
CanvasRenderingContext2D.prototype.roundRect = function (x, y, w, h, r) {
// from http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
if (w < 2 * r) r = w / 2;
if (h < 2 * r) r = h / 2;
this.beginPath();
this.moveTo(x+r, y);
this.arcTo(x+w, y, x+w, y+h, r);
this.arcTo(x+w, y+h, x, y+h, r);
this.arcTo(x, y+h, x, y, r);
this.arcTo(x, y, x+w, y, r);
this.closePath();
return this;
};
// https://developer.mozilla.org/pl/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
// workaround for old versions of Safari
if (!String.prototype.startsWith) {
String.prototype.startsWith = function(searchString, position){
position = position || 0;
return this.substr(position, searchString.length) === searchString;
};
}
if (!String.prototype.endsWith) {
String.prototype.endsWith = function(searchString, position) {
var subjectString = this.toString();
if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
position = subjectString.length;
}
position -= searchString.length;
var lastIndex = subjectString.indexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
};
}
var java_hashcode = function(s){
// http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/
var hash = 0;
if (s.length == 0) return hash;
for (var i = 0; i < s.length; i++) {
var char = s.charCodeAt(i);
hash = ((hash<<5)-hash)+char;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
};
var resources = {};
var loadResources = function() {
resources = {
hiddenParentsImage: (loadImage('images/uparrow.png')),
personImage: (loadImage('images/person.png')),
hiddenParentsAndChildrenImage: (loadImage('images/doublearrow.png')),
hiddenChildrenImage: (loadImage('images/downarrow.png')),
};
};
var screenWidth = function() {
return Math.min(window.outerWidth || window.innerWidth, window.innerWidth);
};
var screenHeight = function() {
return Math.min(window.outerHeight || window.innerHeight, window.innerHeight);
};
var fetchStaticJsonWithLoadingWindow = function(addr, callback, timeout) {
var loadingwindow = document.getElementById("loadingwindow");
var to = setTimeout(function() {
loadingwindow.style.display = "block";
}, 500);
fetchStaticJson(addr, function(js) {
clearTimeout(to);
loadingwindow.style.display="none";
callback(js);
}, timeout);
};
var fetchStaticJsonWithLoadingPanel = function(addr, callback, timeout) {
var myloadingscreen = document.createElement("div");
myloadingscreen.className = "loadingpanel infoflex";
var msgdiv = document.createElement("div"); msgdiv.className='detailcontentcontainer';
msgdiv.appendChild(document.createTextNode("Loading, please wait."));
myloadingscreen.appendChild(msgdiv);
showInfoWindow({"text": myloadingscreen});
fetchStaticJson(addr, function(js) {
if (js == null) {
var myerrorscreen = document.createElement("div");
myerrorscreen.className = "loadingpanel infoflex";
var msgdiv = document.createElement("div"); msgdiv.className='detailcontentcontainer';
msgdiv.appendChild(document.createTextNode("Detailed data isn't accessible right now. Make sure you are connected to the internet."));
myerrorscreen.appendChild(msgdiv);
showInfoWindow({"text": myerrorscreen});
}
else
callback(js);
}, timeout);
};
var fetchStaticJsonDelay = function(addr, callback, timeout) {
setTimeout(function() {
fetchStaticJson(addr, callback, timeout);
},3000);
};
var fetchStaticJson = function(addr, callback, timeout) {
var conditional_decrypt =
encryptedData ? decrypt : function(x) {return x;};
var xhr = new XMLHttpRequest();
var called = false;
var started = false;
var readystatechange = function(evt) {
var ret = null;
if (xhr.status && xhr.status != 200) {
called = true;
callback(null);
return;
}
// if (xhr.readyState == 2 || xhr.readyState == 3)
// started = true;
if (xhr.readyState == 4) {
if (xhr.responseText.length < 2 || (xhr.responseText[0]!='[' && xhr.responseText[0]!='{')) {
callback(null);
return;
}
try {
ret = JSON.parse(conditional_decrypt(xhr.responseText));
}
catch (err) {
}
if (!called) {
called = true;
callback(ret);
}
}
};
if (timeout)
setTimeout(function(){
if (! called && ! started) {
called=true;
callback(null);
}
},timeout);
xhr.addEventListener("readystatechange", readystatechange);
xhr.open("GET", addr, true);
if (xhr.overrideMimeType) //IE9 does not have this property
xhr.overrideMimeType("application/json");
xhr.send(null);
};
var onDemandLoad = function(data, category, callback) {
var categories = {
"birthdays": "data/birthdays.json"
};
if (data[category])
callback(data[category]);
else
fetchStaticJson(categories[category], function(val) {
if (val) {
data[category] = val;
callback(val);
}
else {
displayError("Can't load data from server. Try refreshing the page.", true);
}
}, xhrTimeout);
};
var dynamicLoadJavaScript = function(filename, callback) {
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", filename);
fileref.setAttribute("async", false);
fileref.addEventListener("load", callback);
document.getElementsByTagName("head")[0].appendChild(fileref);
};
var loadData = function(callback) {
var files1 = {
"config": "data/config.json" };
var files2 = {
"structure_raw": "data/structure.json",
"narratives": "data/narratives.json",
"pictures": "data/pictures.json" };
loadDataImpl(files1, function(ret) {
if (ret!=null) {
var nextBatch = function() { loadDataImpl(files2, function (ret2) {
if (ret2!=null) {
var files={};
var retkeys = Object.keys(ret);
for (var i=0; i<retkeys.length; i++)
files[retkeys[i]] = ret[retkeys[i]];
var ret2keys = Object.keys(ret2);
for (var i=0; i<ret2keys.length; i++)
files[ret2keys[i]] = ret2[ret2keys[i]];
var structure = {};
for (var i=0; i<files["structure_raw"].length;i++)
structure[files["structure_raw"][i]["id"]]=files["structure_raw"][i];
files["structure"] = structure;
files["details"] = {};
callback(files);
} else callback(null);
}); };
if (ret["config"] && ret["config"]["encrypted"]==true) {
encryptedData = true;
dynamicLoadJavaScript("../app/sjcl.js", function() {
dynamicLoadJavaScript("../app/login.js", nextBatch);
});
} else nextBatch();
} else callback(null);
});
};
var loadDataImpl = function(files, callback) {
var files_keys = Object.keys(files);
var answers = files_keys.length;
var errors = 0;
for (var i=0; i<files_keys.length; i++) {
var src = files[files_keys[i]];
(function() {
var myii = i;
fetchStaticJson(src, function(js) {
answers --;
if (js == null) {
errors ++;
}
files[files_keys[myii]] = js;
if (answers == 0) {
if (errors == 0)
callback(files);
else
callback(null);
}
},xhrTimeout);
})();
}
};
var jmap = function(fn, arr) {
var result = [];
for (var i = 0; i < arr.length; i ++) {
result.push(fn(arr[i]));
}
return result;
};
String.prototype.trim = function()
{
return String(this).replace(/^\s+|\s+$/g, '');
};
Array.prototype.remove = function(val) {
var i = this.indexOf(val);
if (i>=0)
this.splice(i,1);
};
Array.prototype.addonce = function(val) {
for (var i = 0, l=this.length; i < l; i++) {
if (this[i] == val)
return;
}
this.push(val);
};
Array.prototype.fillish = function(val) {
for (var i=0; i<this.length; i++)
this[i] = val;
return this;
};
// http://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript
Array.prototype.equals = function(array) {
if (!array)
return false;
if (this.length != array.length)
return false;
for (var i = 0, l=this.length; i < l; i++) {
if (this[i] instanceof Array && array[i] instanceof Array) {
if (!this[i].equals(array[i]))
return false;
}
else if (this[i] != array[i]) {
return false;
}
}
return true;
};
var sortByGender = function(structure, personList) {
return personList.slice().sort(function(a,b){return -structure[a]["sex"].localeCompare(structure[b]["sex"]);});
};
var relationshipToParent = function(person, parent) {
if (person["prel"] != undefined) {
for (var i=0; i<person["prel"].length; i++) {
var rel = person["prel"][i];
if (rel[0] == parent)
return " (" + rel[1] + ")";
}
}
return "";
};
var displayName = function(n) {
return n.replace(/\//g,"");
};
var displaySurname = function(n) {
var names = n.split(" ");
var surnames = [];
var insurname = false;
for (var i=0; i<names.length; i++) {
if (names[i].startsWith("/"))
insurname = true;
if (insurname)
surnames.push(names[i]);
if (names[i].endsWith("/"))
return surnames.join(" ").replace(/\//g, "");
}
return "UNKNOWN";
};
var flattenTree = function(node) {
var all = [];
var flattenTreeHelper = function(node) {
var rels = [node].concat(node.ascendents_down).concat(node.descendents_down).concat(node.ascendents_up).concat(node.descendents_up);
for (var i=0; i<rels.length; i++)
{
if (all.indexOf(rels[i]) < 0) {
all.push(rels[i]);
flattenTreeHelper(rels[i]);
}
}
};
flattenTreeHelper(node);
return all;
};
var findConnection = function(structure, fromid, toid) {
var tagup = function(items, tag) {
var newlist = [];
for (var i=0; i<items.length; i++) {
newlist.push([items[i], tag]);
}
return newlist;
};
var upConnections = function(person) {
return sortByGender(structure, structure[person].parents);
};
var horizConnections = function(person) {
return structure[person].spouses;
};
var downConnections = function(person) {
var children = [];
var spouses = horizConnections(person);
for (var i=0; i<structure[person].children.length; i++)
if (structure[structure[person].children[i]].parents.length==1)
children.push(structure[person].children[i]);
for (var i = 0; i < spouses.length; i++) {
for (var j = 0; j < structure[person].children.length; j++) {
if (structure[spouses[i]].children.indexOf(structure[person].children[j]) >= 0) {
children.push(structure[person].children[j]);
}
}
}
return children;
};
var seen = [];
var queue = [{"c":[fromid], "p":["0"]}];
while (!queue.equals([])) {
var next = queue.shift();
var lastvisited = next["c"].slice(-1);
if (lastvisited == toid) {
return next;
}
var connections = [].concat(tagup(downConnections(lastvisited),"C"),
tagup(upConnections(lastvisited),"P"),
tagup(horizConnections(lastvisited),"S"));
for (var i = 0; i<connections.length; i++) {
var connection=connections[i];
if (seen.indexOf(connection[0]) < 0) {
seen.push(connection[0]);
var vv = {"c":next["c"].concat([connection[0]]),
"p":next["p"].concat([connection[1]])};
queue.push(vv);
}
}
}
return null;
};
var translateConnection = function(structure, connection) {
var s = "";
var path = connection["p"];
var genders = [];
var gend = function(mfi, m, f, z) {
return {"m":m,"f":f,"z":z}[mfi];
};
for (var i=0; i<connection["c"].length; i++) {
genders.push(structure[connection["c"][i]]["sex"]);
}
//sibling simplification phase
for (var i=1; i<path.length; i++) {
if (path.slice(i,2+i).equals(["P","C"])) {
path.splice(i,2,"SIB");
genders.splice(i,1);
}
}
//grandparent and grandchild simplification phase
for (var i=1; i<path.length; i++) {
if (path[i] == "C" || path[i]=="P") {
var count = 1;
var prefix="";
while (count+i<path.length) {
if (path[i+count]!=path[i])
break;
count+=1;
if (count>2)
prefix+="great-";
}
if (path[i+count]=="SIB" && path[i]=="P") {
for (var j=i+count+1; j<path.length; j++)
if (path[j]!="C")
break;
var cousins_up = count;
var cousins_down = j-i-count-1;
if (cousins_up >0 && cousins_down >0) {
var out = "the "+ ordinal_suffix_of(Math.min(cousins_up, cousins_down)) + " cousin";
if (cousins_up!=cousins_down)
out+=" "+multiplicative_of(Math.abs(cousins_up-cousins_down))+" removed";
path.splice(i,j-i,out+" of ");
genders.splice(i,j-i-1);
continue;
}
}
if (count > 1) {
if (count >4)
prefix = ordinal_suffix_of(count-2)+" great-";
var relation = {"C":gend(genders[i-1],"father","mother","parent"),
"P":gend(genders[i-1],"son","daughter","child")}[path[i]];
var newf = "the "+prefix+"grand"+relation+" of ";
path.splice(i,count,newf);
genders.splice(i,count-1);
continue;
}
}
}
var rels = [
[["S","C"], "the step-father of ", "the step-mother of ", "the step-parent of "],
[["P","S"], "the step-son of ", "the step-daughter of ", "the step-child of "],
[["C","S"], "the father-in-law of ", "the mother-in-law of ", "the parent-in-law of "],
[["S", "SIB"], "the brother-in-law of ", "the sister-in-law of ", "the sibling-in-law of "],
[["SIB", "C"], "the uncle of ", "the aunt of ", "the sibling of the parent of "],
[["P", "SIB"], "the nephew of ", "the niece of ", "the child of the sibling of "]
];
//additional relationship simplification phase
for (var i=1; i<path.length; i++) {
for (var rel=0; rel<rels.length; rel++) {
if (path.slice(i,2+i).equals(rels[rel][0])) {
path.splice(i,2,gend(genders[i-1],rels[rel][1], rels[rel][2], rels[rel][3]));
genders.splice(i,1);
break;
}
}
}
// final translation phase
var g="z";
while (path.length > 0) {
var step = path.shift();
switch (step) {
case "0":
s+=displayName(structure[connection["c"][0]]["name"])+" is ";
break;
case "C":
s+=gend(g,"the father of ","the mother of ","the parent of ");
break;
case "P":
s+=gend(g,"the son of ", "the daughter of ", "the child of ");
break;
case "S":
s+=gend(g, "the husband of ", "the wife of ", "the spouse of ");
break;
case "SIB":
s+=gend(g,"the brother of ","the sister of ","the sibling of ");
break;
default:
s+=step;
break;
}
g = genders.shift() || "z";
}
return s+displayName(structure[connection["c"][connection["c"].length-1]]["name"]);
};
var Layout = function(layout_style, person, structure, view) {
/*Based on tree drawing code from here
https://rachel53461.wordpress.com/2014/04/20/algorithm-for-drawing-trees/ */
var getSiblings = function(person) {
var generation = [];
var parents = structure[person].parents;
for (var i = 0; i < parents.length; i++) {
var parentid = parents[i];
for (var j = 0; j < structure[parentid].children.length; j++) {
var child = structure[parentid].children[j];
if (structure[child].parents.slice().sort().equals(structure[person].parents.slice().sort()))
generation.addonce(child);
}
}
generation.addonce(person);
return generation;
};
var getSpouses = function(person) {
// TODO sort m-f
return structure[person].spouses;
};
var getParents = function(person) {
return sortByGender(structure, structure[person].parents);
};
var getChildren = function(person) {
var children = [];
var spouses = getSpouses(person);
for (var i=0; i<structure[person].children.length; i++)
if (structure[structure[person].children[i]].parents.length==1)
children.push(structure[person].children[i]);
for (var i = 0; i < spouses.length; i++) {
for (var j = 0; j < structure[person].children.length; j++) {
if (structure[spouses[i]].children.indexOf(structure[person].children[j]) >= 0) {
children.push(structure[person].children[j]);
}
}
}
return children;
};
var mappedNodes = {};
var makeNodePedigree = function(person, generation) {
var newnode = Node(structure[person]);
newnode.generation=generation;
var parents = getParents(person);
for (var i=0; i<parents.length; i++) {
if (parents[i] in mappedNodes)
continue;
var aparent = makeNodePedigree(parents[i], generation - 1);
aparent.descendents_down.addonce(newnode);
newnode.ascendents_down.addonce(aparent);
}
mappedNodes[person] = newnode;
nodeCount++;
return newnode;
};
var makeNodeConnections = function(person, target) {
var connection = findConnection(structure, person, target);
var visited = [];
if (connection == null) {
displayError("I can't find out how to connect these people", true);
return null;
}
var relationship=translateConnection(structure, connection);
displayNotification(relationship);
connection = connection["c"];
var topid = connection.shift();
var top;
var interiorNodes={};
var topspouses = getSpouses(topid);
top = Node(structure[topid]);
mappedNodes[topid]=top;
interiorNodes[topid] = top;
top.generation = 0;
top.ascendents_down=[];
top.descendents_down=[];
var lastid = topid;
var last = top;
var lastlast = null;
while (!connection.equals([])) {
var nextid = connection.shift();
visited.push(nextid);
var spouses = getSpouses(lastid);
var children = getChildren(lastid);
var parents = getParents(lastid);
var nextspouses = getSpouses(nextid);
var nextspouses2 = [];
/* for (var i=0; i<nextspouses.length; i++) {
var ns = nextspouses[i];
if (connection.length>0) {
var nextnext = connection[0];
var rels = [].concat(getChildren(ns),getParents(ns));
if ((rels.indexOf(lastid) >= 0 &&
rels.indexOf(nextnext) >= 0) ||
nextnext == ns)
nextspouses2.push(ns);
}
}*/
var next;
next = Node(structure[nextid]);
mappedNodes[nextid]=next;
interiorNodes[nextid]=next;
next.ascendents_down=[];
next.descendents_down=[];
if (spouses.indexOf(nextid) >= 0) {
var allspouses = last.getIds().concat([nextid]);
var tempnext = nextid;
while (connection.length > 0 && getSpouses(connection[0]).indexOf(tempnext)>=0 ) {
tempnext = connection.shift();
allspouses.push(tempnext);
}
var allspouses_obj=[];
for (var i=0; i<allspouses.length; i++) {
var spouse=allspouses[i];
var obj = Node(structure[spouse]);
interiorNodes[spouse] = obj;
obj.generation=last.generation;
allspouses_obj.push(obj);
next = obj;
}
var newnext = NodeGroup(allspouses_obj);
newnext.generation = last.generation;
for (var i=0; i<allspouses.length; i++)
{
mappedNodes[allspouses[i]] = newnext;
}
if (lastlast) {
var obj = mappedNodes[lastlast.getId()];
if (lastlast.ascendents_down.indexOf(last)>=0) {
obj.ascendents_down.remove(last);
obj.ascendents_down.addonce(newnext);
lastlast.ascendents_down.remove(last);
lastlast.ascendents_down.addonce(newnext);
}
if (lastlast.descendents_down.indexOf(last)>=0) {
obj.descendents_down.remove(last);
obj.descendents_down.addonce(newnext);
lastlast.descendents_down.remove(last);
lastlast.descendents_down.addonce(newnext);
}
}
newnext.descendents_down = last.descendents_down.slice();
newnext.ascendents_down = last.ascendents_down.slice();
nextid = next.getId();
} else if (children.indexOf(nextid) >= 0) {
if (mappedNodes[last.getId()] != interiorNodes[last.getId()]) {
mappedNodes[last.getId()].descendents_down.addonce(next);
next.ascendents_down.addonce(mappedNodes[last.getId()]);
}
last.descendents_down.addonce(next);
next.ascendents_down.addonce(last);
next.generation = last.generation+1;
} else if (parents.indexOf(nextid) >= 0) {
if (mappedNodes[last.getId()] != last) {
mappedNodes[last.getId()].ascendents_down.addonce(next);
next.descendents_down.addonce(mappedNodes[last.getId()]);
}
last.ascendents_down.addonce(next);
next.descendents_down.addonce(last);
next.generation = last.generation-1;
} else {
displayError("Bad connection", true);
return null;
}
if (next.generation < top.generation) {
top = next;
topid = nextid;
}
lastlast = last;
lastid = nextid;
last = next;
}
};
var nodeCount = 0;
var makeNode = function(person, generation, generation_limit) {
if (person in mappedNodes)
return mappedNodes[person];
var newNode = null;
if (getSpouses(person).length == 0 || (render_opt("omit_spouses")&&generation!=0)) {
newNode = Node(structure[person]);
mappedNodes[person] = newNode;
} else {
var plist = [person].concat(getSpouses(person));
newNode = NodeGroup(jmap(function(p){return Node(structure[p]);}, plist));
for (var i=0; i<plist.length; i++)
mappedNodes[plist[i]] = newNode;
}
newNode.generation = generation;
if (getParents(person).length == 0)
newNode.ascendents_down = [];
else {
var padres = getParents(person);
newNode.ascendents_down = [];
for (var i=0; i<padres.length; i++)
if (padres[i] in mappedNodes)
newNode.ascendents_down.addonce(makeNode(padres[i], generation -1,generation_limit ));
}
var childs = getChildren(person);
if (childs.length > 0) {
if (Math.abs(generation) < generation_limit) {
newNode.descendents_down = [];
for (var i=0; i<childs.length; i++) {
var temp = makeNode(childs[i],generation+1, generation_limit);
if (temp.ascendents_down.indexOf(newNode)<0)
continue;
newNode.descendents_down.push(temp);
}
}
}
nodeCount++;
return newNode;
};
var verticalSpacing = function(view, node_list)
{
var maxheights = {};
var localverticalMargin = verticalMargin;
if (compact_mode)
localverticalMargin *= 0.75;
for (var i = 0; i<node_list.length; i++)
{
var dims = node_list[i].calcDimensions(view);
var w = dims[0]; var h = dims[1];
maxheights[node_list[i].generation] = Math.max(maxheights[node_list[i].generation] || 0, h);
}
var sumHeights = {};
sumHeights[0] = 0;
for (var i = 1; i in maxheights; i++)
sumHeights[i] = sumHeights[i-1] + maxheights[i-1] + localverticalMargin;
for (var i = -1; i in maxheights; i--)
sumHeights[i] = sumHeights[i+1] - maxheights[i] - localverticalMargin;
for (var i = 0; i<node_list.length; i++)
{
var pos = node_list[i].getPos();
var x = pos[0]; var y = pos[1];
node_list[i].setPos(x,sumHeights[node_list[i].generation]);
}
};
var helperIsNodeLeaf = function(node) {
return node.descendents_down.length == 0;
};
var helperIsNodeLeftMost = function(node) {
if (node.ascendents_down.length == 0)
return true;
return node.getIds().indexOf(node.ascendents_down[0].descendents_down[0].getId()) >= 0;
};
var helperGetPreviousSibling = function(node) {
if (node.ascendents_down.length == 0)
debug("No ascendents");
var options = node.ascendents_down[0].descendents_down;
for (var i=0; i<options.length; i++)
if (node.getIds().indexOf(options[i].getId())>=0)
return options[i-1];
debug("inconsistent tree");
return null;
};
var getLeftContour = function(node) {
var getLeftContourHelper = function(node, modSum, values) {
if (node.generation in values)
values[node.generation] = Math.min(values[node.generation], node.getX() + modSum);
else
values[node.generation] = node.getX() + modSum;
modSum += node.mod;
for (var i=0; i<node.descendents_down.length; i++)
getLeftContourHelper(node.descendents_down[i], modSum, values);
};
var values = {};
getLeftContourHelper(node, 0, values);
return values;
};
var getRightContour = function(node) {
var getRightContourHelper = function(node, modSum, values) {
if (node.generation in values)
values[node.generation] = Math.max(values[node.generation], node.getX() + node.getWidth() + modSum);
else
values[node.generation] = node.getX() + node.getWidth() + modSum;
modSum += node.mod;
for (var i=0; i<node.descendents_down.length; i++)
getRightContourHelper(node.descendents_down[i], modSum, values);
};
var values = {};
getRightContourHelper(node, 0, values);
return values;
};
var centerBetweenNodes = function(leftNode, rightNode) {
var leftIndex = leftNode.ascendents_down[0].descendents_down.indexOf(rightNode);
var rightIndex = leftNode.ascendents_down[0].descendents_down.indexOf(leftNode);
var numNodesBetween = (rightIndex - leftIndex) - 1;
if (numNodesBetween > 0) {
var distanceBetweenNodes = (leftNode.getX() - (rightNode.getX()+rightNode.getWidth()) ) / (numNodesBetween + 1);
var count = 1;
for (var i = leftIndex + 1; i < rightIndex; i++)
{
var middleNode = leftNode.ascendents_down[0].descendents_down[i];
var desiredX = rightNode.getX() + rightNode.getWidth() + (distanceBetweenNodes * count);
var offset = desiredX - middleNode.getX();
middleNode.setX(middleNode.getX()+offset);
middleNode.mod += offset;
count++;
}
checkForConflicts(leftNode);
}
};
var checkForConflicts = function(node)
{
var treeDistance = 30; // minimum distance between cousin nodes
var shift = 0;
var nodeCounter = getLeftContour(node);
if (node.ascendents_down.length == 0)
return;
var lefterNodes=[];
for (var j=0; j<node.ascendents_down.length; j++) {
for (var i=0; i<node.ascendents_down[j].descendents_down.length &&
node.ascendents_down[j].descendents_down[i] != node; i++)
lefterNodes.push(node.ascendents_down[j].descendents_down[i]);
if (node.ascendents_down[j].descendents_down.indexOf(node)>=0)