This repository has been archived by the owner on May 4, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 123
/
keshif.js
13369 lines (12191 loc) · 512 KB
/
keshif.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
/*********************************
keshif library
Copyright (c) 2014-2016, University of Maryland
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Maryland nor the names of its contributors
may not be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL MICHAEL BOSTOCK BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
************************************ */
// load google visualization library only if google scripts were included
if(typeof google !== 'undefined'){
google.charts.load('current', {packages: ['corechart']});
//google.load('visualization', '1', {'packages': []});
}
// Temporary: Until I build my own d3 bundle, this is not included in the main bundle
// https://github.com/d3/d3-selection-multi Version 1.0.0. Copyright 2016 Mike Bostock.
!function(t,n){"object"==typeof exports&&"undefined"!=typeof module?n(require("d3-selection"),require("d3-transition")):"function"==typeof define&&define.amd?define(["d3-selection","d3-transition"],n):n(t.d3,t.d3)}(this,function(t,n){"use strict";function r(n,r){return n.each(function(){var n=r.apply(this,arguments),e=t.select(this);for(var i in n)e.attr(i,n[i])})}function e(t,n){for(var r in n)t.attr(r,n[r]);return t}function i(t){return("function"==typeof t?r:e)(this,t)}function o(n,r,e){return n.each(function(){var n=r.apply(this,arguments),i=t.select(this);for(var o in n)i.style(o,n[o],e)})}function f(t,n,r){for(var e in n)t.style(e,n[e],r);return t}function u(t,n){return("function"==typeof t?o:f)(this,t,null==n?"":n)}function s(n,r){return n.each(function(){var n=r.apply(this,arguments),e=t.select(this);for(var i in n)e.property(i,n[i])})}function c(t,n){for(var r in n)t.property(r,n[r]);return t}function a(t){return("function"==typeof t?s:c)(this,t)}function p(n,r){return n.each(function(){var e=r.apply(this,arguments),i=t.select(this).transition(n);for(var o in e)i.attr(o,e[o])})}function l(t,n){for(var r in n)t.attr(r,n[r]);return t}function y(t){return("function"==typeof t?p:l)(this,t)}function h(n,r,e){return n.each(function(){var i=r.apply(this,arguments),o=t.select(this).transition(n);for(var f in i)o.style(f,i[f],e)})}function v(t,n,r){for(var e in n)t.style(e,n[e],r);return t}function d(t,n){return("function"==typeof t?h:v)(this,t,null==n?"":n)}t.selection.prototype.attrs=i,t.selection.prototype.styles=u,t.selection.prototype.properties=a,n.transition.prototype.attrs=y,n.transition.prototype.styles=d});
var kshf = {
browsers: [],
dt: {},
dt_id: {},
maxVisibleItems_Default: 100,
scrollWidth: 19,
attribPanelWidth: 220,
catHeight: 18,
map: {
// http://{s}.tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png
// http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png
// http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png
// http://{s}.tile.stamen.com/toner/{z}/{x}/{y}.png
// http://{s}.tile.stamen.com/toner-lite/{z}/{x}/{y}.png
// http://tile.stamen.com/watercolor/{z}/{x}/{y}.jpg
// http://tile.stamen.com/terrain/{z}/{x}/{y}.jpg
// http://otile{s}.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png
// http://otile{s}.mqcdn.com/tiles/1.0.0/map/{z}/{x}/{y}.png
// http://otile{s}.mqcdn.com/tiles/1.0.0/sat/{z}/{x}/{y}.png
tileTemplate: 'http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png',
wrapLongitude: 170,
config: {
maxBoundsViscosity: 1,
boxZoom: false,
touchZoom: false,
doubleClickZoom: false,
zoomControl: false,
worldcopyjump: true
/*continuousWorld: true, crs: L.CRS.EPSG3857 */
},
tileConfig: {
attribution: '© <a href="http://www.openstreetmap.org/copyright" target="_blank">OpenStreetMap</a>'+
' & <a href="http://cartodb.com/attributions" target="_blank">CartoDB</a>',
subdomains: 'abcd',
maxZoom: 19,
//noWrap: true
},
flyConfig:{
padding: [0,0],
pan: {animate: true, duration: 1.2},
zoom: {animate: true}
},
},
lang: {
en: {
ModifyBrowser: "Modify browser",
OpenDataSource: "Open data source",
ShowInfoCredits: "Powered by Keshif<br>Show info",
ShowFullscreen: "Fullscreen",
RemoveFilter: "Remove filter",
RemoveAllFilters: "Remove all filters",
SaveSelection: "Save Selection",
MinimizeSummary: "Minimize",
OpenSummary: "Open",
MaximizeSummary: "Maximize",
RemoveSummary: "Remove",
ReverseOrder: "Reverse order",
Reorder: "Reorder",
ShowMoreInfo: "Show record info",
Percentiles: "Percentiles",
LockToCompare: "Lock selection",
Unlock: "Unlock",
ChangeMeasureFunc: "Change metric",
Search: "Search",
CreatingBrowser: "Creating Keshif Browser",
Rows: "Rows",
More: "More",
LoadingData: "Loading data sources",
ShowAll: "Show All",
ScrollToTop: "Top",
Percent: "Percent",
Absolute: "Absolute",
AbsoluteSize: "Absolute Size",
PartOfSize: "Relative Size",
Width: "Size",
DragToFilter: "Drag",
And: "And",
Or: "Or",
Not: "Not",
EditTitle: "Rename",
ResizeBrowser: "Resize browser",
RemoveRecords: "Remove record panel",
EditFormula: "Edit formula",
NoData: "(No data)",
ValidData: "(Valid data)",
ZoomToFit: "Zoom to fit",
Close: "Close",
Help: "Help"
},
tr: {
ModifyBrowser: "Tarayıcıyı düzenle",
OpenDataSource: "Veri kaynağını aç",
ShowInfoCredits: "Bilgi",
ShowFullscreen: "Tam ekran",
RemoveFilter: "Filtreyi kaldır",
RemoveAllFilters: "Tüm filtreleri kaldır",
MinimizeSummary: "Ufalt",
OpenSummary: "Aç",
MaximizeSummary: "Büyüt",
RemoveSummary: "Kaldır",
ReverseOrder: "Ters sırala",
Reorder: "Yeniden sırala",
ShowMoreInfo: "Daha fazla bilgi",
Percentiles: "Yüzde",
LockToCompare: "Kilitle ve karşılaştır",
Unlock: "Kilidi kaldır",
Search: "Ara",
LoadingData: "Veriler yükleniyor...",
CreatingBrowser: "Keşif arayüzü oluşturuluyor...",
Rows: "Satır",
More: "Daha",
ShowAll: "Hepsi",
ScrollToTop: "Yukarı",
Absolute: "Net",
Percent: "Yüzde",
PartOfSize: "Görece",
Width: "Genişlik",
DragToFilter: "Sürükle",
And: "Ve",
Or: "Veya",
Not: "Değil",
EditTitle: "Değiştir",
ResizeBrowser: "Boyutlandır",
RemoveRecords: "Kayıtları kaldır",
EditFormula: "Formülü değiştir",
NoData: "(verisiz)",
VelidData: "(veri var)",
ZoomToFit: "Oto-yakınlaş",
Close: "Kapat",
Help: "Yardim"
},
fr: {
ModifyBrowser: "Modifier le navigateur",
OpenDataSource: "Ouvrir la source de données",
ShowInfoCredits: "Afficher les credits",
RemoveFilter: "Supprimer le filtre",
RemoveAllFilters: "Supprimer tous les filtres",
MinimizeSummary: "Réduire le sommaire",
OpenSummary: "Ouvrir le sommaire",
MaximizeSummary: "Agrandir le sommaire",
RemoveSummary: "??",
ReverseOrder: "Inverser l'ordre",
Reorder: "Réorganiser",
ShowMoreInfo: "Plus d'informations",
Percentiles: "Percentiles",
LockToCompare: "Bloquer pour comparer",
Unlock: "Débloquer",
Search: "Rechercher",
CreatingBrowser: "Création du navigateur",
Rows: "Lignes",
More: "Plus",
LoadingData: "Chargement des données",
ShowAll: "Supprimer les filtres",
ScrollToTop: "Début",
Absolute: "Absolue",
Percent: "Pourcentage",
PartOfSize: "Part-Of",
Width: "Largeur",
DragToFilter: "??",
And: "??",
Or: "??",
Not: "??",
EditFormula: "Edit Formula",
NoData: "(No data)",
ValidData: "(Valid data)",
ZoomToFit: "Zoom to fit"
},
// translation by github@nelsonmau
it: {
ModifyBrowser: "Modifica il browser",
OpenDataSource: "Fonte Open Data",
ShowInfoCredits: "Mostra info e crediti",
ShowFullscreen: "Schermo intero",
RemoveFilter: "Rimuovi il filtro",
RemoveAllFilters: "Rimuovi tutti i filtri",
MinimizeSummary: "Chiudi il sommario",
OpenSummary: "Apri il sommario",
MaximizeSummary: "Massimizza il sommario",
RemoveSummary: "Rimuovi il sommario",
ReverseOrder: "Ordine inverso",
Reorder: "Riordina",
ShowMoreInfo: "Mostra più informazioni",
Percentiles: "Percentuali",
LockToCompare: "Blocca per confrontare",
Unlock: "Sblocca",
Search: "Cerca",
CreatingBrowser: "Browser in preparazione - Keshif",
Rows: "Righe",
More: "Di più",
LoadingData: "Carimento delle fonti dati",
ShowAll: "Mostra tutto",
ScrollToTop: "Torna su",
Absolute: "Assoluto",
Percent: "Percentuale",
Relative: "Relativo",
Width: "Larghezza",
DragToFilter: "Trascina",
And: "E",
Or: "O",
Not: "No",
EditTitle: "Modifica",
NoData: "(No data)",
ValidData: "(Valid data)",
ResizeBrowser: "Ridimensiona il browser",
RemoveRecords: "Rimuovi la visualizzazione dei record"
},
cur: null // Will be set to en if not defined before a browser is loaded
},
Util: {
sortFunc_List_String: function(a, b){
return a.localeCompare(b);
},
sortFunc_List_Date: function(a, b){
if(a===null) return -1;
if(b===null) return 1;
return b.getTime() - a.getTime(); // recent first
},
sortFunc_List_Number: function(a, b){
return b - a;
},
/** Given a list of columns which hold multiple IDs, breaks them into an array */
cellToArray: function(dt, columns, splitExpr){
if(splitExpr===undefined) splitExpr = /\b\s+/;
var j;
dt.forEach(function(p){
p = p.data;
columns.forEach(function(column){
var list = p[column];
if(list===null) return;
if(typeof list==="number") {
p[column] = ""+list;
return;
}
var list2 = list.split(splitExpr);
list = [];
// remove empty "" records
for(j=0; j<list2.length; j++){
list2[j] = list2[j].trim();
if(list2[j]!=="") list.push(list2[j]);
}
p[column] = list;
});
});
},
baseMeasureFormat: d3.format(".2s"),
/** You should only display at most 3 digits + k/m/etc */
formatForItemCount: function(n){
if(n<1000) return n;
return kshf.Util.baseMeasureFormat(n);
},
clearArray: function(arr){
while(arr.length > 0) arr.pop();
},
ignoreScrollEvents: false,
scrollToPos_do: function(scrollDom, targetPos){
scrollDom = scrollDom.node();
kshf.Util.ignoreScrollEvents = true;
// scroll to top
var startTime = null;
var scrollInit = scrollDom.scrollTop;
var easeFunc = d3.easeCubicOut;
var scrollTime = 500;
var animateToTop = function(timestamp){
var progress;
if(startTime===null) startTime = timestamp;
// complete animation in 500 ms
progress = (timestamp - startTime)/scrollTime;
var m=easeFunc(progress);
scrollDom.scrollTop = (1-m)*scrollInit+m*targetPos;
if(scrollDom.scrollTop!==targetPos){
window.requestAnimationFrame(animateToTop);
} else {
kshf.Util.ignoreScrollEvents = false;
}
};
window.requestAnimationFrame(animateToTop);
},
toProperCase: function(str){
return str.toLowerCase().replace(/\b[a-z]/g,function(f){return f.toUpperCase()});
},
setTransform: function(dom,transform){
dom.style.webkitTransform = transform;
dom.style.MozTransform = transform;
dom.style.msTransform = transform;
dom.style.OTransform = transform;
dom.style.transform = transform;
},
// http://stackoverflow.com/questions/13627308/add-st-nd-rd-and-th-ordinal-suffix-to-a-number
ordinal_suffix_of: function(i) {
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";
},
},
/** -- */
fontLoaded: false,
loadFont: function(){
if(this.fontLoaded===true) return;
WebFontConfig = {
google: {
families: [
'Roboto:400,500,300,100,700:latin',
'Montserrat:400,700:latin',
'Roboto+Slab:700'
]
}
};
var wf = document.createElement('script');
wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
'://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
wf.type = 'text/javascript';
wf.async = 'true';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(wf, s);
this.fontLoaded = true;
},
handleResize: function(){
this.browsers.forEach(function(browser){ browser.updateLayout(); });
},
activeTipsy: undefined,
colorScale : {
converge: [
d3.rgb('#ffffd9'),
d3.rgb('#edf8b1'),
d3.rgb('#c7e9b4'),
d3.rgb('#7fcdbb'),
d3.rgb('#41b6c4'),
d3.rgb('#1d91c0'),
d3.rgb('#225ea8'),
d3.rgb('#253494'),
d3.rgb('#081d58')],
diverge: [
d3.rgb('#8c510a'),
d3.rgb('#bf812d'),
d3.rgb('#dfc27d'),
d3.rgb('#f6e8c3'),
d3.rgb('#f5f5f5'),
d3.rgb('#c7eae5'),
d3.rgb('#80cdc1'),
d3.rgb('#35978f'),
d3.rgb('#01665e')]
},
/* -- */
intersects: function(d3bound, leafletbound){
if(d3bound[0][0]>leafletbound._northEast.lng) return false;
if(d3bound[0][1]>leafletbound._northEast.lat) return false;
if(d3bound[1][0]<leafletbound._southWest.lng) return false;
if(d3bound[1][1]<leafletbound._southWest.lat) return false;
return true;
},
/** -- */
gistPublic: true,
gistLogin: false,
getGistLogin: function(){
if(this.githubToken===undefined) return;
d3.request('https://api.github.com/user')
.header("Authorization","token "+kshf.githubToken)
.get(function(error, data){ kshf.gistLogin = JSON.parse(data.response).login; });
},
kshfLogo: '<svg class="kshfLogo" viewBox="0 0 200 200">'+
'<rect class="kshfLogo_C1 kshfLogo_B" x="37.2" y="49.1" width="128.5" height="39.7" transform="matrix(-0.7071 0.7071 -0.7071 -0.7071 222.0549 46.0355)" />'+
'<polygon class="kshfLogo_C1 kshfLogo_B" points="42.5,100.6 71,72 163,164.4 134.5,193" />'+
'<polygon class="kshfLogo_C1 " points="132.2,13 53.5,91.3 79.3,117 158,38.7" />'+
'<rect class="kshfLogo_C2 kshfLogo_B" x="55.1" y="6.4" width="38.3" height="188.8" />'+
'</svg>'
};
// tipsy : Modified & simplified version for internal Keshif use
// (c) 2008-2010 jason frame [[email protected]]
// released under the MIT license
function Tipsy(element, options) {
this.jq_element = element;
this.options = options;
if(this.options.className === undefined) this.options.className = null;
if(this.options.gravity === undefined) this.options.gravity = 'n';
};
Tipsy.prototype = {
show: function() {
var maybeCall = function(thing, ctx) {
return (typeof thing == 'function') ? (thing.call(ctx)) : thing;
};
if(kshf.activeTipsy) kshf.activeTipsy.hide();
kshf.activeTipsy = this;
var title = this.getTitle();
if(!title) return;
this.tip();
this.jq_tipsy_inner.html(title);
this.jq_tip.attr("class","tipsy"); // reset classname in case of dynamic gravity
this.jq_tip.styles({top: 0, left: 0, visibility: 'hidden', display: 'block'});
kshf.browser.DOM.root.node().appendChild(this.jq_tip.node());
if(this.options.className) {
this.jq_tip.attr("class", "tipsy "+maybeCall(this.options.className, this.jq_element));
}
var pos = this.jq_element.getBoundingClientRect();
var actualWidth = this.jq_tip.node().offsetWidth,
actualHeight = this.jq_tip.node().offsetHeight,
gravity = maybeCall(this.options.gravity, this.jq_element);
this.tipWidth = actualWidth;
this.tipHeight = actualHeight;
var tp;
switch (gravity.charAt(0)) {
case 'n':
tp = {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2};
break;
case 's':
tp = {top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2};
break;
case 'e':
tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth};
break;
case 'w':
tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width};
break;
}
if (gravity.length == 2) {
if (gravity.charAt(1) == 'w') {
tp.left = pos.left + pos.width / 2 - 15;
} else {
tp.left = pos.left + pos.width / 2 - actualWidth + 15;
}
}
var browserPos = kshf.browser.DOM.root.node().getBoundingClientRect();
tp.left = tp.left - browserPos.left;
tp.top = tp.top - browserPos.top;
this.jq_tip
.style('left',tp.left+"px")
.style('top', tp.top +"px")
.attr("class", this.jq_tip.attr("class")+' tipsy-' + gravity);
this.jq_tipsy_arrow.attr("class", 'tipsy-arrow tipsy-arrow-' + gravity.charAt(0));
this.jq_tip.styles({opacity: 0, visibility: 'visible'}).transition().duration(200).style('opacity',1);
},
hide: function(){
kshf.activeTipsy = undefined;
if(this.jq_tip) this.jq_tip.transition().duration(200).style('opacity',0).remove();
},
getTitle: function() {
var title, o = this.options;
if (typeof o.title == 'string') {
title = o.title;
} else if (typeof o.title == 'function') {
title = o.title.call(this.jq_element);
}
return ('' + title).replace(/(^\s*|\s*$)/, "");
},
tip: function() {
if(this.jq_tip) return this.jq_tip;
this.jq_tip = d3.select(document.createElement("div")).attr("class","tipsy");
this.jq_tipsy_arrow = this.jq_tip.append("div").attr("class","tipsy-arrow");
this.jq_tipsy_inner = this.jq_tip.append("div").attr("class","tipsy-inner");
return this.jq_tip;
}
};
/**
* @constructor
*/
kshf.Record = function(d, idIndex){
this.data = d;
this.idIndex = idIndex; // TODO: Items don't need to have ID index, only one per table is enough??
// By default, each item is aggregated as 1
// You can modify this with a non-negative value
// Note that the aggregation currently works by summation only.
this.measure_Self = 1;
// Wanted item / not filtered out
this.isWanted = true;
// Rank order of the record
this.recordRank = 0;
// The data that's used for mapping this item, used as a cache.
// This is accessed by filterID
// Through this, you can also reach DOM of aggregates
// DOM elements that this item is mapped to
// - If this is a paper, it can be paper type. If this is author, it can be author affiliation.
this._valueCache = []; // caching the values this item was mapped to
// Aggregates which this record falls under
this._aggrCache = [];
this.DOM = { record: undefined };
// If true, filter/wanted state is dirty and needs to be updated.
this._filterCacheIsDirty = true;
// Cacheing filter state per each summary
this._filterCache = [];
this.selectCompared_str = "";
this.selectCompared = {A: false, B: false, C: false};
};
kshf.Record.prototype = {
/** Returns unique ID of the item. */
id: function(){
return this.data[this.idIndex];
},
/** -- */
setFilterCache: function(index,v){
if(this._filterCache[index]===v) return;
this._filterCache[index] = v;
this._filterCacheIsDirty = true;
},
/** Updates isWanted state, and notifies all related aggregates of the change */
updateWanted: function(){
if(!this._filterCacheIsDirty) return false;
var me = this;
var oldWanted = this.isWanted;
this.isWanted = this._filterCache.every(function(f){ return f; });
this._filterCacheIsDirty = false;
if(this.measure_Self && this.isWanted !== oldWanted){ // There is some change that affects computation
var valToAdd = (this.isWanted && !oldWanted) ? this.measure_Self /*add*/ : -this.measure_Self /*remove*/;
var cntToAdd = this.isWanted ? 1 : -1; // more record : less record
this._aggrCache.forEach(function(aggr){
aggr._measure.Active += valToAdd;
aggr.recCnt.Active += cntToAdd;
});
}
return this.isWanted !== oldWanted;
},
/** -- */
setRecordDetails: function(value){
this.showDetails = value;
if(this.DOM.record) d3.select(this.DOM.record).classed('showDetails', this.showDetails);
},
/** Called on mouse-over on a primary item type */
highlightRecord: function(){
if(this.DOM.record) this.DOM.record.setAttribute("selection","onRecord");
// summaries that this item appears in
this._aggrCache.forEach(function(aggr){
if(aggr.DOM.aggrGlyph) aggr.DOM.aggrGlyph.setAttribute("catselect","onRecord");
if(aggr.DOM.matrixRow) aggr.DOM.matrixRow.setAttribute("catselect","onRecord");
if(aggr.summary && aggr.summary.setRecordValue) aggr.summary.setRecordValue(this);
},this);
},
/** -- */
unhighlightRecord: function(){
if(this.DOM.record) this.DOM.record.removeAttribute("selection");
// summaries that this item appears in
this._aggrCache.forEach(function(aggr){
aggr.unselectAggregate();
if(aggr.summary && aggr.summary.hideRecordValue ) aggr.summary.hideRecordValue();
},this);
},
/** -- */
addForHighlight: function(){
if(!this.isWanted || this.highlighted) return;
if(this.DOM.record) {
var x = this.DOM.record;
x.setAttribute("selection","highlighted");
// SVG geo area - move it to the bottom of parent so that border can be displayed nicely.
// TODO: improve the conditional check!
if(x.nodeName==="path") d3.select(x.parentNode.appendChild(x));
}
this._aggrCache.forEach(function(aggr){
if(this.measure_Self===null ||this.measure_Self===0) return;
aggr._measure.Highlight += this.measure_Self;
aggr.recCnt.Highlight++;
}, this);
this.highlighted = true;
},
/** -- */
remForHighlight: function(distribute){
if(!this.isWanted || !this.highlighted) return;
if(this.DOM.record) this.DOM.record.removeAttribute("selection");
if(distribute) this._aggrCache.forEach(function(aggr){
if(this.measure_Self===null || this.measure_Self===0) return;
aggr._measure.Highlight -= this.measure_Self;
aggr.recCnt.Highlight--;
}, this);
this.highlighted = false;
},
/** -- */
setCompared: function(cT){
this.selectCompared_str+=cT+" ";
this.selectCompared[cT] = true;
this.domCompared();
},
/** -- */
unsetCompared: function(cT){
this.selectCompared_str = this.selectCompared_str.replace(cT+" ","");
this.selectCompared[cT] = false;
this.domCompared();
},
domCompared: function(){
if(!this.DOM.record) return;
if(this.selectCompared_str==="") {
this.DOM.record.removeAttribute("rec_compared");
} else {
this.DOM.record.setAttribute("rec_compared",this.selectCompared_str);
}
},
initLinks: function(){
this.DOM.links_To = [];
this.DOM.links_From = [];
this.links_To = [];
this.links_From = [];
}
};
/**
* @constructor
*/
kshf.Aggregate = function(summary){
// Which summary does this aggregate appear in?
this.summary = summary;
// Records which are mapped to this aggregate
this.records = [];
// To signal that this aggregate should not be shown, set this to false;
this.usedAggr = true;
// DOM
this.DOM = { aggrGlyph: undefined };
// Reset
this.resetAggregateMeasures();
};
kshf.Aggregate.prototype = {
/** -- */
resetAggregateMeasures: function(){
this._measure = {
Total : 0,
Active : 0,
Highlight : 0,
Compare_A : 0,
Compare_B : 0,
Compare_C : 0
};
this.recCnt = {
Total : 0,
Active : 0,
Highlight : 0,
Compare_A : 0,
Compare_B : 0,
Compare_C : 0
};
this.records.forEach(function(record){
if(record.measure_Self===null) return;
this._measure.Total += record.measure_Self;
this.recCnt.Total++;
if(record.isWanted) {
this._measure.Active += record.measure_Self;
this.recCnt.Active++;
}
},this);
},
/** -- */
addRecord: function(record){
this.records.push(record);
record._aggrCache.push(this);
if(record.measure_Self===null) return;
this._measure.Total += record.measure_Self;
this.recCnt.Total++;
if(record.isWanted) {
this._measure.Active += record.measure_Self;
this.recCnt.Active++;
}
},
/** -- */
removeRecord: function(record){
this.records.splice(this.records.indexOf(record),1);
record._aggrCache.splice(record._aggrCache.indexOf(this),1);
if(record.measure_Self===null) return;
this._measure.Total -= record.measure_Self;
this.recCnt.Total--;
if(record.isWanted) {
this._measure.Active -= record.measure_Self;
this.recCnt.Active--;
}
},
/** -- */
measure: function(v){
if(kshf.browser.measureFunc==="Avg"){
var r=this.recCnt[v];
return (r===0) ? 0 : this._measure[v]/r ; // avoid division by zero.
}
return this._measure[v];
},
/** -- */
ratioHighlightToTotal: function(){
return this._measure.Highlight / this._measure.Total;
},
/** -- */
ratioHighlightToActive: function(){
return this._measure.Highlight / this._measure.Active;
},
/** -- */
ratioCompareToActive: function(cT){
return this._measure["Compare_"+cT] / this._measure.Active;
},
/** -- */
unselectAggregate: function(){
if(this.DOM.aggrGlyph) {
d3.select(this.DOM.aggrGlyph).attr("catselect",null).classed("showlock",false);
}
if(this.DOM.matrixRow) {
this.DOM.matrixRow.removeAttribute("selection");
this.DOM.matrixRow.removeAttribute("catselect");
}
},
/** -- */
selectCompare: function(cT){
d3.select(this.DOM.aggrGlyph).classed("locked",true);
this.compared = cT;
this.records.forEach(function(record){ record.setCompared(cT); });
},
/** -- */
clearCompare: function(cT){
d3.select(this.DOM.aggrGlyph).classed("locked",false).attr("compare",null);
this.compared = false;
this.records.forEach(function(record){ record.unsetCompared(cT); });
},
/** -- */
selectHighlight: function(){
this.records.forEach(function(record){ record.addForHighlight(); });
},
/** -- */
clearHighlight: function(){
this.records.forEach(function(record){ record.remForHighlight(false); });
},
};
/**
* @constructor
*/
kshf.Aggregate_Category = function(summary, d, idIndex){
kshf.Aggregate.call(this, summary);
// What this aggregate represents
this.data = d;
// Categories can be indexed
this.idIndex = idIndex;
// Selection state
// 1: selected for inclusion (AND)
// 2: selected for inclusion (OR)
// -1: selected for removal (NOT query)
// 0: not selected
this.selected = 0;
};
kshf.Aggregate_Category.prototype = Object.create(kshf.Aggregate.prototype);
kshf.Aggregate_Category.constructor = kshf.Aggregate_Category;
var Aggregate_Category_functions = {
/** Returns unique ID of the aggregate. */
id: function(){
return this.data[this.idIndex];
},
f_selected: function(){ return this.selected!== 0; },
f_included: function(){ return this.selected > 0; },
is_NONE : function(){ return this.selected=== 0; },
is_NOT : function(){ return this.selected===-1; },
is_AND : function(){ return this.selected=== 1; },
is_OR : function(){ return this.selected=== 2; },
set_NONE: function(){
if(this.inList!==undefined) {
this.inList.splice(this.inList.indexOf(this),1);
}
this.inList = undefined;
this.selected = 0; this._refreshCatDOMSelected();
},
set_NOT: function(l){
if(this.is_NOT()) return;
this._insertToList(l);
this.selected =-1; this._refreshCatDOMSelected();
},
set_AND: function(l){
if(this.is_AND()) return;
this._insertToList(l);
this.selected = 1; this._refreshCatDOMSelected();
},
set_OR: function(l){
if(this.is_OR()) return;
this._insertToList(l);
this.selected = 2; this._refreshCatDOMSelected();
},
/** Internal */
_insertToList: function(l){
if(this.inList!==undefined) {
this.inList.splice(this.inList.indexOf(this),1);
}
this.inList = l;
l.push(this);
},
/** Internal */
_refreshCatDOMSelected: function(){
if(this.DOM.aggrGlyph) {
if(this.selected===0) {
this.DOM.aggrGlyph.removeAttribute("cFiltered"); return;
}
var v = "?";
switch(this.selected){
case 1: v="AND"; break;
case 2: v="OR"; break;
case -1:v="NOT"; break;
}
this.DOM.aggrGlyph.setAttribute("cFiltered",v);
}
},
}
for(var index in Aggregate_Category_functions){
kshf.Aggregate_Category.prototype[index] = Aggregate_Category_functions[index];
}
/**
* @constructor
*/
kshf.Aggregate_Interval = function(summary, minV, maxV){
kshf.Aggregate.call(this, summary);
this.minV = minV;
this.maxV = maxV;
};
kshf.Aggregate_Interval.prototype = Object.create(kshf.Aggregate.prototype);
kshf.Aggregate_Interval.constructor = kshf.Aggregate_Interval;
/**
* @constructor
*/
kshf.Aggregate_Set = function(summary, set_1, set_2){
kshf.Aggregate.call(this, summary);
this.set_1 = set_1;
this.set_2 = set_2;
};
kshf.Aggregate_Set.prototype = Object.create(kshf.Aggregate.prototype);
kshf.Aggregate_Set.constructor = kshf.Aggregate_Set;
/**
* @constructor
*/
kshf.Aggregate_EmptyRecords = function(summary){
kshf.Aggregate_Category.call(this, summary, {id:null}, 'id');
this.isVisible = true;
this.emptyRecordsAggregate = true;
};
kshf.Aggregate_EmptyRecords.prototype = Object.create(kshf.Aggregate_Category.prototype);
/**
* @constructor
*/
kshf.BreadCrumb = function(browser, selectType, _filter){
this.browser = browser;
this.DOM = null;
this.selectType = selectType;
this.filter = _filter;
};
kshf.BreadCrumb.prototype = {
isCompareSelection: function(){
return this.selectType.substr(0,7)==="Compare";
},
/** -- */
showCrumb: function(summary){
var _pre = this.browser.getHeight_PanelBasic();
var _pre_ = parseInt(this.browser.DOM.panelsTop.style('margin-top'));
if(this.DOM===null) {
this._insertDOM_crumb();
}
var details;
if(this.selectType==="Filter"){
this.DOM.select(".crumbHeader").html(this.filter.getTitle());
details = this.filter.filterView_Detail();
} else {
this.DOM.select(".crumbHeader").html(summary.summaryName);
var selectedAggr = this.browser.selectedAggr[this.selectType];
if(selectedAggr instanceof kshf.Aggregate_EmptyRecords){
details = kshf.lang.cur.NoData;
} else if(summary.printAggrSelection){
details = summary.printAggrSelection(selectedAggr);
} else {
return;
}
}
details = "" + details; // convert to string, in case the return value is a number...
if(details) this.DOM.select(".crumbDetails").html(details.replace(/<br>/gi," "));
if(this.selectType==="Highlight"){
var _post = this.browser.getHeight_PanelBasic();
this.browser.DOM.panelsTop.style('margin-top',(_pre_+_pre-_post)+"px");
} else {
this.browser.DOM.panelsTop.style('margin-top',"0px");
}
},
/** -- */
removeCrumb: function(noAnim){
if(this.DOM === null) return;
var me=this;
if(noAnim){
this.DOM.remove();
} else {
var _pre = this.browser.getHeight_PanelBasic();
var _pre_ = parseInt(me.browser.DOM.panelsTop.style('margin-top'));
this.DOM.style("opacity",0)
.transition().delay(300).remove()
.on("end",function(){
var _post = me.browser.getHeight_PanelBasic();
var v = _pre_+_pre-_post;
if(me.selectType!=="Highlight") v=0;
me.browser.DOM.panelsTop.style('margin-top',v+"px");
});
}
this.DOM = null;
},
/** -- */
_insertDOM_crumb: function(){
var me=this;
this.DOM = this.browser.DOM.breadcrumbs.append("span")
.attr("class","breadCrumb crumbMode_"+this.selectType)
.each(function(){
if(me.selectType!=="Highlight"){
var l=this.parentNode.childNodes.length;
if(l>1) this.parentNode.insertBefore(this, this.parentNode.childNodes[l-2] );
}
this.tipsy = new Tipsy(this, {
gravity: 'n',
title: function(){
switch(me.selectType){
case "Filter": return kshf.lang.cur.RemoveFilter;
case "Highlight": return "Remove Highlight";
default: return kshf.lang.cur.Unlock; // Compare_A, Compare_B, Compare_C
}
}
});
})
.on("mouseenter",function(){